diff --git a/build/check-bundle-size.ts b/build/check-bundle-size.ts index 5985b40f..31b03412 100644 --- a/build/check-bundle-size.ts +++ b/build/check-bundle-size.ts @@ -47,8 +47,11 @@ import { join } from "node:path"; // measured in the Update Mouse Protocol workflow); main grew 27.7 kB to // 1,413,917 bytes, below its cap. 3.95 MB leaves room for one more release. export const BUDGET_BYTES: Record = { - ".css": 170_000, - ".js": 3_950_000, + // G6 HE/receiver panels, travel charts, battery tooltips and OLED theme, + // with protocol 0.60.0: measured 177,450 bytes CSS and 3,992,589 bytes JS. + // Main stays at 1,459,853 bytes, below its existing separate cap. + ".css": 178_000, + ".js": 4_000_000, }; // main-*.js measured 1,511,619 bytes right after the split (posthog ~377 kB diff --git a/package-lock.json b/package-lock.json index e2a0690e..e0772250 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,12 +10,13 @@ "license": "AGPL-3.0-or-later", "dependencies": { "@openmouse/keyboard-protocol": "1.6.1", - "@openmouse/protocol": "0.59.0", + "@openmouse/protocol": "0.60.0", "lucide-react": "^1.43.0", "posthog-js": "^1.438.17", "preact": "^10.29.8" }, "devDependencies": { + "picomatch": "file:vendor/picomatch-safe", "typescript": "^5.8.3", "vite": "^6.3.5" } @@ -492,9 +493,9 @@ } }, "node_modules/@openmouse/protocol": { - "version": "0.59.0", - "resolved": "https://registry.npmjs.org/@openmouse/protocol/-/protocol-0.59.0.tgz", - "integrity": "sha512-AfAqtxZyKRoS9U1Ta4U3zEA/gPgSsYKxmlmvkHdf2iidwVUx4bSGjg5P7eEdoaKR9O0ta0q1kkHXATEWCkT9NQ==", + "version": "0.60.0", + "resolved": "https://registry.npmjs.org/@openmouse/protocol/-/protocol-0.60.0.tgz", + "integrity": "sha512-XD9SarFVsNVeYkJWUkm7Pa+0nmJkpCIChz8woaQPDbg8aKqfw++VyjonvabAubQ2hqfNFP4ZlxfVLNkDyTZpbA==", "license": "AGPL-3.0-or-later", "engines": { "node": ">=20" @@ -1069,17 +1070,8 @@ "license": "ISC" }, "node_modules/picomatch": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", - "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } + "resolved": "vendor/picomatch-safe", + "link": true }, "node_modules/postcss": { "version": "8.5.28", @@ -1262,9 +1254,9 @@ } }, "node_modules/vite": { - "version": "6.4.4", - "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.4.tgz", - "integrity": "sha512-xGjU/SyjeNyb0E4KxXBvYz/1C+3JXuujvf2hXNOtnlcE+58o5ajd9N2/n2VhkiJvpCP2qQasnUpx5PXNeI+p1Q==", + "version": "6.4.6", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.6.tgz", + "integrity": "sha512-RtsraAwEG68idOA6iUOoIpOlcSKROnf815aIq9qHTSrDNpLoBrBa12suyfcEd8qn0xwOVQI1Yhm1GbmTjF600A==", "dev": true, "license": "MIT", "dependencies": { @@ -1348,6 +1340,15 @@ "resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-6.2.1.tgz", "integrity": "sha512-rLcLXA2sx6+9dE88NHFubwTtGxpK4yYBLj6qHPdFoCaLr0cXGb4efOqtKLlm4loGA4OEKHIQKMKzZkKyOh5ctw==", "license": "Apache-2.0" + }, + "vendor/picomatch-safe": { + "name": "@openmouse/picomatch-safe", + "version": "4.0.7", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } } } } diff --git a/package.json b/package.json index a1c4fbca..475e8311 100644 --- a/package.json +++ b/package.json @@ -15,13 +15,17 @@ }, "dependencies": { "@openmouse/keyboard-protocol": "1.6.1", - "@openmouse/protocol": "0.59.0", + "@openmouse/protocol": "0.60.0", "lucide-react": "^1.43.0", "posthog-js": "^1.438.17", "preact": "^10.29.8" }, "devDependencies": { + "picomatch": "file:vendor/picomatch-safe", "typescript": "^5.8.3", "vite": "^6.3.5" + }, + "overrides": { + "picomatch": "$picomatch" } } diff --git a/public/devices/README.md b/public/devices/README.md index ce8f7107..6a9c501b 100644 --- a/public/devices/README.md +++ b/public/devices/README.md @@ -28,6 +28,11 @@ image file — it has nowhere to go. Instead: ## Maintainer upload steps +For the G6 HE use `keychron-g6-he.png`; for a separate TurboLink receiver render +use `keychron-turbolink-8k.png`. Upload at the bucket root. Both name mappings are +in `src/shared/device-images.ts`; the G6 mapping precedes the generic HE keyboard +fallback. These mappings are ready for upload and do not imply the files exist. + 1. Save a **transparent** PNG or WebP named after the model in kebab-case, e.g. `razer-viper-v3-pro.png`. The panel sits on a dark background, so an image with a white backdrop shows as a white block. diff --git a/src/device/controller.ts b/src/device/controller.ts index fedcaac1..abcd588f 100644 --- a/src/device/controller.ts +++ b/src/device/controller.ts @@ -4754,6 +4754,7 @@ function stageMagneticButton( const name = `${MAGNETIC_SIDE[button]} click ${label}`; stageChange({ key: `magnetic-${setting}-${button}`, + priority: latestDeviceStatus?.brand === "Keychron" && setting === "trigger" ? -1 : 0, label: name, command: `Set the ${name.toLowerCase()}`, progress: `Setting the ${name.toLowerCase()}…`, @@ -4815,7 +4816,19 @@ export function applyMagneticSwitchType(button: 0 | 1, type: "magnetic" | "optic } export function subscribeButtonDepth(listener: (left: number, right: number) => void): () => void { - return magneticClient()?.onButtonDepth?.(listener) ?? (() => {}); + let current: MagneticButtonClient | null = null; + let stop = () => {}; + const bind = () => { + const next = magneticClient(); + if (next === current) return; + stop(); + current = next; + listener(NaN, NaN); + stop = next?.onButtonDepth?.(listener) ?? (() => {}); + }; + bind(); + const unsubscribe = subscribe(bind); + return () => { unsubscribe(); stop(); }; } export async function startMagneticCalibration(): Promise { @@ -6246,6 +6259,70 @@ export function toggleSleep(enabled: boolean): void { applyPulsarValue("sleep", enabled ? lastSleepSeconds : WLMOUSE_SLEEP_NEVER); } +export function applyKeychronDynamicDpi(value: NonNullable["dynamicDpi"]>): void { + if (!latestDeviceStatus?.keychronMouse?.dynamicDpi) return; + const next = structuredClone(value); + stageChange({ key: "keychron-dynamic-dpi", label: t(interfacePreferences.locale, "perf.dynSens"), + command: "Set Keychron dynamic DPI", progress: "Setting Keychron dynamic DPI...", + preview: status => { if (status.keychronMouse) status.keychronMouse.dynamicDpi = structuredClone(next); }, + apply: () => callClientMethod("setKeychronDynamicDpi", "dynamic DPI", next), + }); +} + +export function applyKeychronReceiverButton(button: string, action: string): void { + if (!latestDeviceStatus?.keychronReceiver) return; + stageChange({ key: `keychron-receiver-${button}`, label: `${button}: ${action}`, + command: `Set receiver ${button}`, progress: `Setting receiver ${button}...`, + preview: status => { if (status.keychronReceiver) status.keychronReceiver.buttonMappings[button] = action; }, + apply: () => callClientMethod("setKeychronReceiverButton", "receiver button", { button, action }), + }); +} + +export async function refreshKeychronReceiver(): Promise { + await waitForControllerIdle(); + const client = keychron8kClient(); + if (!client || refreshInProgress || settingInProgress || activationInProgress) return; + const device = activeDevice; + refreshInProgress = true; + try { + const status = await client.readStatus(); + if (activeSettingsClient() !== client || activeDevice !== device) return; + applyStatus(status); + } + catch (error) { + if (activeSettingsClient() === client && activeDevice === device) toastForError("Receiver", error); + } + finally { refreshInProgress = false; } +} + +export function applyKeychronReceiverLighting(value: MouseLighting): void { + if (!latestDeviceStatus?.keychronReceiver) return; + const next = structuredClone(value); + stageChange({ key: "keychron-receiver-lighting", label: t(interfacePreferences.locale, "light.receiverTitle"), + command: "Set receiver lighting", progress: "Setting receiver lighting...", + preview: status => { if (status.keychronReceiver) status.keychronReceiver.lighting = structuredClone(next); }, + apply: () => callClientMethod("setKeychronReceiverLighting", "receiver lighting", next), + }); +} + +export function applyKeychronPairing(value: NonNullable["pairing"]>): void { + if (!latestDeviceStatus?.keychronMouse?.pairing) return; + stageChange({ key: "keychron-pairing", label: t(interfacePreferences.locale, "magnetic.pairing"), + command: "Set Keychron pairing shortcut", progress: "Setting Keychron pairing shortcut...", + preview: status => { if (status.keychronMouse) status.keychronMouse.pairing = { ...value }; }, + apply: () => callClientMethod("setKeychronPairingShortcut", "pairing shortcut", value), + }); +} + +export function stageKeychronReset(): void { + if (!latestDeviceStatus?.keychronMouse?.factoryReset) return; + if (!window.confirm(t(interfacePreferences.locale, "magnetic.factoryHint"))) return; + stageChange({ key: "keychron-reset", label: t(interfacePreferences.locale, "magnetic.factoryReset"), + command: "Reset Keychron mouse", progress: "Resetting Keychron mouse...", + apply: async () => { await requireClientMethod("resetKeychronMouse", "factory reset").resetKeychronMouse(); }, + }); +} + export function applyKsnakeScrollDirection( direction: NonNullable, ): void { @@ -7397,6 +7474,13 @@ function magneticPreviewClient(initial: MouseStatus): SupportedClient { open: async () => undefined, close: async () => undefined, readStatus: async () => structuredClone(status), + setScrollDirection: async (direction: "Forward" | "Reverse") => { status.scrollDirection = direction; }, + setKeychronReceiverButton: async ({ button, action }: { button: string; action: string }) => { if (status.keychronReceiver) status.keychronReceiver.buttonMappings[button] = action; }, + setKeychronReceiverLighting: async (value: MouseLighting) => { if (status.keychronReceiver) status.keychronReceiver.lighting = structuredClone(value); }, + setKeychronPairingShortcut: async (value: { mask: number; holdTime: number }) => { if (status.keychronMouse) status.keychronMouse.pairing = { ...value }; }, + setKeychronDynamicDpi: async (value: NonNullable["dynamicDpi"]>) => { if (status.keychronMouse) status.keychronMouse.dynamicDpi = structuredClone(value); }, + resetKeychronMouse: async () => undefined, + setButtonMapping: async (button: string, action: string) => { if (status.buttonMappings) status.buttonMappings[button] = action; }, setMagneticTriggerPoint: async (button: 0 | 1, point: number) => { buttons()[button]!.triggerPoint = point; return point; }, setMagneticReleasePoint: async (button: 0 | 1, point: number | null) => { buttons()[button]!.releasePoint = point; return point; }, setMagneticRapidTrigger: async (button: 0 | 1, enabled: boolean, level: number) => { diff --git a/src/device/preview/preview-fixtures.ts b/src/device/preview/preview-fixtures.ts index 733a3402..00917d79 100644 --- a/src/device/preview/preview-fixtures.ts +++ b/src/device/preview/preview-fixtures.ts @@ -1161,6 +1161,31 @@ export const PREVIEW_FIXTURES: Record = { finalmouse: { label: "Finalmouse UltralightX", status: FINALMOUSE }, "finalmouse-slx": { label: "Finalmouse Starlight X", status: FINALMOUSE_SLX }, ninjutso: { label: "Ninjutso Sora V3", status: NINJUTSO }, + "keychron-g6-he": { label: "Keychron G6 HE 8K", status: { + brand: "Keychron", name: "Keychron G6 HE 8K", batteryPercent: 82, batteryState: "Discharging", + dpi: 800, dpiStages: [400, 800, 1600, 3200, 5000], activeDpiStage: 1, pollingRateHz: 8000, + supportedPollingRates: [125, 500, 1000, 2000, 4000, 8000], activeProfile: 1, profileCount: 5, + connectionType: "Wired", liftOffDistance: null, motionSync: true, angleSnapping: false, rippleControl: false, + scrollDirection: "Forward", debounceMs: 8, sleepTimeout: 600, firmware: [], + ui: { family: "keychron-8k", dpiStageEditor: { maxStages: 5, countEditable: true, minDpi: 50, maxDpi: 40000, stepDpi: 50 } }, + buttonMappings: { Left: "Left Click", Right: "Right Click", Middle: "Middle Click", Back: "Back", Forward: "Forward" }, + buttonOptions: ["Default", "Left Click", "Right Click", "Middle Click", "Back", "Forward", "Disabled"], + keychronReceiver: { + name: "Keychron TurboLink 8K", firmware: "v1.2.3", + buttonMappings: { Polling: "Polling Loop", Lighting: "Lighting mode cycle", "Switch type": "Toggle optical / magnetic", DPI: "DPI Loop" }, + buttonOptions: ["Default", "Polling Loop", "Lighting mode cycle", "Toggle optical / magnetic", "DPI Loop", "Disabled"], + lighting: { zone: "Receiver", modes: ["Off", "Static", "Breathing single", "Spectrum"], mode: "Static", color: "#20a080", color2: null, + colorModes: ["Static", "Breathing single"], dualColorModes: [], reactiveModes: ["Breathing single", "Spectrum"], + speeds: [1, 2, 3, 4, 5], speed: 3, brightness: 100, brightnessLevels: [25, 50, 75, 100] }, + }, + keychronMouse: { pairing: { mask: 9, holdTime: 4 }, factoryReset: true, + dynamicDpi: { profile: 0, enabled: false, mode: 0, points: [{ speed: 0, gain: 16 }, { speed: 40, gain: 24 }, { speed: 80, gain: 32 }, { speed: 140, gain: 44 }, { speed: 200, gain: 56 }] } }, + magneticButtons: { + buttons: [0, 1].map(() => ({ switchType: "magnetic" as const, triggerPoint: 4, rapidTrigger: 1, rapidTriggerEnabled: false })), + triggerPointRange: { min: 1, max: 12 }, rapidTriggerRange: { min: 1, max: 11 }, rapidTriggerUnit: "level", + rapidTriggerSwitch: true, canChooseSwitchType: true, calibration: null, liveDepth: true, + }, + } }, "nape-pro": { label: "Keychron Nape Pro", status: KEYCHRON }, "mx-master-3s": { label: "Logitech MX Master 3S", status: LOGITECH_MX_MASTER_3S }, g703: { label: "Logitech G703", status: LOGITECH_G703 }, diff --git a/src/device/preview/preview-modes.ts b/src/device/preview/preview-modes.ts index 9c32c886..b94597ab 100644 --- a/src/device/preview/preview-modes.ts +++ b/src/device/preview/preview-modes.ts @@ -36,6 +36,7 @@ export const PREVIEW_KEYS = [ "finalmouse-slx", "ninjutso", "nape-pro", + "keychron-g6-he", "mx-master-3s", "g703", "gwolves-pro", @@ -91,6 +92,7 @@ export function parsePreviewMode(value: string | null): PreviewMode | null { case "finalmouse": return "finalmouse"; case "finalmouse-slx": return "finalmouse-slx"; case "ninjutso": return "ninjutso"; + case "keychron-g6-he": return "keychron-g6-he"; case "keychron": case "keychron-nape": case "nape-pro": return "nape-pro"; diff --git a/src/device/types.ts b/src/device/types.ts index 481a95e1..ca5e48dd 100644 --- a/src/device/types.ts +++ b/src/device/types.ts @@ -11,7 +11,7 @@ import type { PreviewMode } from "./preview/preview-modes"; import type { DriverTraits } from "./traits"; import type { M2NexProfile } from "./m2nex-profiles"; -export type WorkspaceTab = "overview" | "performance" | "buttons" | "macro" | "lighting" | "profiles" | "advanced"; +export type WorkspaceTab = "overview" | "performance" | "buttons" | "macro" | "lighting" | "receiver" | "profiles" | "advanced"; export const WORKSPACE_TAB_ORDER: readonly WorkspaceTab[] = [ "overview", @@ -19,6 +19,7 @@ export const WORKSPACE_TAB_ORDER: readonly WorkspaceTab[] = [ "buttons", "macro", "lighting", + "receiver", "profiles", "advanced", ]; diff --git a/src/features/devices/ActuationGauge.tsx b/src/features/devices/ActuationGauge.tsx new file mode 100644 index 00000000..4c95d764 --- /dev/null +++ b/src/features/devices/ActuationGauge.tsx @@ -0,0 +1,19 @@ +import { t } from "../../i18n/index"; +import type { InterfaceLocale } from "../settings/interface-preferences"; + +export function ActuationGauge({ value, min, max, disabled, locale }: { + value: number | null; min: number; max: number; disabled: boolean; + locale: InterfaceLocale; +}) { + return
+ +
+ {t(locale, "magnetic.easy")} + {t(locale, "magnetic.recommended")} + {t(locale, "magnetic.hard")} +
+
; +} diff --git a/src/features/devices/DeviceHero.tsx b/src/features/devices/DeviceHero.tsx index 58da7530..42dd5a5e 100644 --- a/src/features/devices/DeviceHero.tsx +++ b/src/features/devices/DeviceHero.tsx @@ -1,6 +1,6 @@ import { connectionText, displayText, t, tp, type I18nKey } from "../../i18n/index"; import { ChevronRight, ImageUp } from "lucide-react"; -import { useMemo, useState, type KeyboardEvent, type ReactNode } from "react"; +import { useEffect, useMemo, useState, type KeyboardEvent, type ReactNode } from "react"; import * as control from "../../device/controller"; import { cachedBatterySamples, type BatterySample } from "./battery-history"; import type { ControlSnapshot, WorkspaceTab } from "../../device/types"; @@ -208,6 +208,7 @@ function sparkPath(samples: readonly BatterySample[], width: number, height: num } export function BatteryHistoryPanel({ snapshot }: { snapshot: ControlSnapshot }): ReactNode { + const [selection, setSelection] = useState<{ device: string; id: string } | null>(null); const status = snapshot.status; const locale = snapshot.preferences.locale; const samples = useMemo(() => { @@ -219,12 +220,19 @@ export function BatteryHistoryPanel({ snapshot }: { snapshot: ControlSnapshot }) return []; } }, [status?.name, status?.batteryPercent]); + useEffect(() => { + setSelection(previous => previous && (previous.device !== status?.name + || !samples.some(sample => sample.id === previous.id)) ? null : previous); + }, [samples, status?.name]); if (!status || status.batteryPercent === null) return null; const width = 600; const height = 120; const path = sparkPath(samples, width, height); const estimate = control.batteryEstimateParts(status, locale); const format = new Intl.DateTimeFormat(locale, { weekday: "short", hour: "numeric", minute: "2-digit" }); + const tooltipFormat = new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeStyle: "short" }); + const hovered = selection?.device === status.name ? samples.find(sample => sample.id === selection.id) ?? null : null; + const hoverX = hovered && path ? (hovered.timestamp - path.start) / Math.max(1, path.end - path.start) * width : 0; return (
@@ -239,12 +247,46 @@ export function BatteryHistoryPanel({ snapshot }: { snapshot: ControlSnapshot })
{path ? (
- +
+ { + const box = event.currentTarget.getBoundingClientRect(); + const time = path.start + Math.max(0, Math.min(1, (event.clientX - box.left) / box.width)) * (path.end - path.start); + let closest = 0; + samples.forEach((sample, index) => { + if (Math.abs(sample.timestamp - time) < Math.abs(samples[closest]!.timestamp - time)) closest = index; + }); + setSelection({ device: status.name, id: samples[closest]!.id! }); + }} + onPointerLeave={() => setSelection(null)} + onFocus={() => setSelection({ device: status.name, id: samples.at(-1)!.id! })} + onBlur={() => setSelection(null)} + onKeyDown={event => { + if (event.key === "Escape") { setSelection(null); return; } + if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return; + event.preventDefault(); + setSelection(previous => { + const index = previous?.device === status.name ? samples.findIndex(sample => sample.id === previous.id) : -1; + const next = event.key === "Home" ? 0 : event.key === "End" ? samples.length - 1 + : Math.max(0, Math.min(samples.length - 1, (index < 0 ? samples.length - 1 : index) + (event.key === "ArrowLeft" ? -1 : 1))); + return { device: status.name, id: samples[next]!.id! }; + }); + }}> + {hovered ? : null} + {hovered ?
+ {hovered.percent}% + +
: null} +
{format.format(path.start)} {format.format(path.end)} diff --git a/src/features/devices/MagneticButtons.tsx b/src/features/devices/MagneticButtons.tsx index 80072fbe..9a5b5e1f 100644 --- a/src/features/devices/MagneticButtons.tsx +++ b/src/features/devices/MagneticButtons.tsx @@ -1,6 +1,9 @@ +import { MousePointer2 } from "lucide-react"; +import { MagneticTravel } from "./MagneticTravel"; +import { ActuationGauge } from "./ActuationGauge"; import { displayText } from "../../i18n/index"; import { useUiLocale } from "../../shared/ui-locale"; -import { useEffect, useState, type ReactNode } from "react"; +import { useState, type ReactNode } from "react"; import * as control from "../../device/controller"; import { t } from "../../i18n/index"; import type { InterfaceLocale } from "../settings/interface-preferences"; @@ -43,6 +46,7 @@ function Toggle({ on, onChange, disabled = false, + enableDisabled = false, label, locale, }: { @@ -50,6 +54,7 @@ function Toggle({ on: boolean | null; onChange: (next: boolean) => void; disabled?: boolean; + enableDisabled?: boolean; label: string; locale: InterfaceLocale; }): ReactNode { @@ -57,7 +62,7 @@ function Toggle({
{([false, true] as const).map((value) => ( - ))} @@ -81,40 +86,6 @@ function Row({ label, hint, children }: { label: string; hint?: string; children ); } -/** Press depth runs 0 to 100; the bar has ten segments and marks where the click registers. */ -function DepthMeter({ magnetic }: { magnetic: MagneticButtonsStatus }): ReactNode { - const __uiLocale = useUiLocale(); - const [depth, setDepth] = useState<[number, number]>([0, 0]); - useEffect(() => { - const stop = control.subscribeButtonDepth((left, right) => setDepth([left, right])); - const suppressContextMenu = (event: MouseEvent) => event.preventDefault(); - window.addEventListener("contextmenu", suppressContextMenu); - return () => { - stop(); - window.removeEventListener("contextmenu", suppressContextMenu); - }; - }, []); - const span = magnetic.triggerPointRange.max; - return ( -
- {(["Left", "Right"] as const).map((side, index) => { - const trigger = magnetic.buttons[index]?.triggerPoint; - const mark = trigger ? Math.max(0, Math.min(9, Math.round((trigger / span) * 10) - 1)) : -1; - return ( -
- {displayText(__uiLocale, side)} -
- {Array.from({ length: 10 }, (_, step) => ( - - ))} -
-
- ); - })} -
- ); -} - function ButtonControls({ group, magnetic, @@ -133,7 +104,9 @@ function ButtonControls({ const { triggerPointRange: trigger, releasePointRange: release, rapidTriggerRange: rapid } = magnetic; const optical = state.switchType === "optical"; const separateRelease = state.releasePoint != null; - const rapidLevel = state.rapidTrigger ?? rapid?.min ?? 1; + const rapidMax = brand === "Keychron" ? Math.min(rapid?.max ?? 0, + ...targets.map(button => Math.max(0, 12 - (magnetic.buttons[button]?.triggerPoint ?? 12)))) : rapid?.max ?? 0; + const rapidLevel = Math.min(state.rapidTrigger ?? rapid?.min ?? 1, Math.max(1, rapidMax)); const unit = magnetic.rapidTriggerUnit === "ms" ? " ms" : ""; const calibrated = magnetic.calibration !== "needed"; // Release 9 is how the mouse says "follows the trigger point", so a separate release starts beside it. @@ -160,6 +133,7 @@ function ButtonControls({ ) : null} +
targets.forEach((button) => control.applyMagneticTriggerPoint(button, next))} /> + {brand === "Keychron" ? : null} +
{release ? ( @@ -196,7 +173,7 @@ function ButtonControls({ ) : null} {rapid ? ( - +
targets.forEach((button) => control.applyMagneticRapidTrigger(button, on, rapidLevel, unit))} + enableDisabled={rapidMax === 0} + onChange={(on) => targets.forEach((button) => control.applyMagneticRapidTrigger(button, on, + on ? rapidLevel : magnetic.buttons[button]?.rapidTrigger ?? rapid?.min ?? 1, unit))} /> targets.forEach((button) => control.applyMagneticRapidTrigger(button, true, next, unit))} />
@@ -305,8 +284,7 @@ export function MagneticButtons({ snapshot }: { snapshot: ControlSnapshot }): Re aria-label={displayText(locale, "Magnetic button settings")} >
-

{displayText(locale, "Magnetic Buttons")}

- {magnetic.liveDepth ? : null} +
{(["both", "independent"] as const).map((value) => ( ))}
+
+ {magnetic.liveDepth ? : null}
{([0, 1] as const).map((side) => ( @@ -331,7 +311,7 @@ export function MagneticButtons({ snapshot }: { snapshot: ControlSnapshot }): Re
- + {brand !== "Keychron" || magnetic.calibration !== null ? : null}
); diff --git a/src/features/devices/MagneticTravel.tsx b/src/features/devices/MagneticTravel.tsx new file mode 100644 index 00000000..f00d7f98 --- /dev/null +++ b/src/features/devices/MagneticTravel.tsx @@ -0,0 +1,91 @@ +import { useEffect, useId, useRef, useState } from "react"; +import type { MagneticButtonsStatus } from "@openmouse/protocol/drivers/mouse-types"; +import type { InterfaceLocale } from "../settings/interface-preferences"; +import { t } from "../../i18n/index"; +import { subscribeButtonDepth } from "../../device/controller"; + +type Sample = { time: number; depths: [number, number] }; + +/** Only received device samples enter the three-second travel window. */ +export function MagneticTravel({ magnetic, locale, brand }: { + magnetic: MagneticButtonsStatus; locale: InterfaceLocale; brand: string; +}) { + const [samples, setSamples] = useState([]); + const received = useRef([]); + const traces = useRef>([]); + const activeTraces = useRef>([]); + const areas = useRef>([]); + const thresholds = useRef>([]); + const plotId = useId().replace(/:/g, ""); + const levelScale = brand === "Keychron"; + const maximum = levelScale ? 12 : 100; + const depthValue = (percent: number) => levelScale ? Math.max(0, Math.min(12, (Math.round(percent * .65) - 5) / 5)) : percent; + useEffect(() => { + const clear = () => { received.current = []; setSamples([]); }; + const stop = subscribeButtonDepth((left, right) => { + if (!Number.isFinite(left) || !Number.isFinite(right)) { clear(); return; } + const time = performance.now(); + received.current = [...received.current.filter(s => time - s.time < 3000), { + time, depths: [Math.max(0, Math.min(100, left)), Math.max(0, Math.min(100, right))] as [number, number], + }].slice(-300); + setSamples(received.current); + }); + const stale = setInterval(() => { + const last = received.current[received.current.length - 1]; + if (last && performance.now() - last.time > 1500) clear(); + }, 500); + // Scroll the time axis every display frame, independently of HID sample arrival. + // Only received points are drawn; no synthetic travel values are interpolated. + let frame = 0; + const draw = () => { + const now = performance.now(); + const visible = received.current.filter(sample => now - sample.time <= 3000); + traces.current.forEach((trace, side) => { + const points = visible.map(sample => `${598 - (now - sample.time) / 3000 * 566},${10 + depthValue(sample.depths[side]!) / maximum * 220}`); + trace?.setAttribute("points", points.join(" ")); + activeTraces.current[side]?.setAttribute("points", points.join(" ")); + const threshold = thresholds.current[side]; + const first = visible[0], last = visible[visible.length - 1]; + const y = 10 + (threshold ?? 0) / maximum * 220; + areas.current[side]?.setAttribute("d", first && last && threshold != null + ? `M${598 - (now - first.time) / 3000 * 566},${y} L${points.join(" L")} L${598 - (now - last.time) / 3000 * 566},${y} Z` : ""); + }); + frame = requestAnimationFrame(draw); + }; + frame = requestAnimationFrame(draw); + return () => { stop(); clearInterval(stale); cancelAnimationFrame(frame); }; + }, [brand]); + const latest = samples[samples.length - 1]; + return
+ {t(locale, "magnetic.liveTravel")} + {!latest ?

{t(locale, "magnetic.waitingTravel")}

: null} +
+ {([0, 1] as const).map(side => { + const button = magnetic.buttons[side]!; + const point = button.triggerPoint; + const threshold = point == null ? null : levelScale ? point : point / magnetic.triggerPointRange.max * 100; + const label = t(locale, side === 0 ? "adv.leftButton" : "adv.rightButton"); + const activeThreshold = button.switchType === "optical" ? null : threshold; + thresholds.current[side] = activeThreshold; + const clipId = `${plotId}-${side}`; + return
+
{label}= activeThreshold}>{latest ? levelScale && depthValue(latest.depths[side]) < .5 ? "–" : `${Math.round(depthValue(latest.depths[side]))}${levelScale ? "" : "%"}` : "–"}
+ + + {(levelScale ? [0, 2, 4, 6, 8, 10, 12] : [0, 50, 100]).map(value => + + {value} + )} + {threshold !== null && button.switchType !== "optical" ? : null} + { traces.current[side] = node; }} /> + + { areas.current[side] = node; }} /> + { activeTraces.current[side] = node; }} /> + + +
; + })} +
+
; +} diff --git a/src/features/devices/OverviewPage.tsx b/src/features/devices/OverviewPage.tsx index 81b34d0e..6ee4da05 100644 --- a/src/features/devices/OverviewPage.tsx +++ b/src/features/devices/OverviewPage.tsx @@ -1,3 +1,5 @@ +import { KeychronDynamicDpiCard, KeychronPairingCard, KeychronResetCard } from "./cards/KeychronMouseCards"; +import { KeychronReceiverButtonsCard, KeychronReceiverLightingCard } from "./cards/KeychronReceiverCards"; import { slotCards } from "../../shared/CardSlot"; import { displayText } from "../../i18n/index"; import { useUiLocale } from "../../shared/ui-locale"; @@ -9,6 +11,7 @@ import { Lightbulb, MousePointerClick, Settings2, + Usb, type LucideIcon, } from "lucide-react"; import { useEffect, useRef, type ReactNode } from "react"; @@ -82,6 +85,7 @@ const TAB_ICON: Record = { macro: Keyboard, profiles: Layers, advanced: Settings2, + receiver: Usb, }; export function TabIcon({ tab }: { tab: WorkspaceTab }): ReactNode { @@ -356,6 +360,14 @@ export function Workspace({ }): ReactNode { const status = snapshot.status; const tab = snapshot.workspaceTab; + useEffect(() => { + if (tab !== "buttons") return; + const suppress = (event: MouseEvent) => { + if (event.target instanceof Element && event.target.closest("#magnetic-button-settings, #performance-settings")) event.preventDefault(); + }; + window.addEventListener("contextmenu", suppress); + return () => window.removeEventListener("contextmenu", suppress); + }, [tab]); if (!status) return null; const locale = snapshot.preferences.locale; const has = cardAvailability(snapshot); @@ -383,7 +395,6 @@ export function Workspace({ show(has.eggCpi, ["performance"]) ? : null, show(has.powerMode, ["performance"]) ? : null, - show(has.debounce, ["buttons"]) ? : null, show(has.eggSpdt, ["buttons"]) ? : null, show(has.eggHanded, ["buttons"]) ? : null, show(has.eggButtons, ["buttons"]) ? : null, @@ -393,8 +404,10 @@ export function Workspace({ show(has.atkButtons, ["buttons"]) ? : null, show(has.buttonMapping && !snapshot.traits.teevolution, ["buttons"]) ? : null, + show(has.debounce, ["buttons"]) ? : null, show(has.ksnakeScroll, ["buttons"]) ? : null, + show(status.keychronMouse?.dynamicDpi != null, ["performance"]) ? : null, ].filter((node) => node !== null); const macro = [ @@ -408,6 +421,8 @@ export function Workspace({ !powerOverview && show(has.sleep, ["advanced"]) ? : null, show(has.lightingAdvanced, ["advanced"]) ? : null, + device && show(status.keychronMouse?.factoryReset === true, ["advanced"]) ? : null, + device && show(status.keychronMouse?.pairing != null, ["advanced"]) ? : null, show(has.lowPower, ["advanced"]) ? : null, show(has.perfectPolling, ["advanced"]) ? : null, show(has.finalmouse, ["advanced"]) ? : null, @@ -443,6 +458,7 @@ export function Workspace({ && (status.hapticIntensity != null || status.wheelMode != null || status.friendlyName != null || status.hostCount != null); const showDiagnostics = device && on(tab, ["advanced"]); const showOverview = on(tab, ["overview"]); + const showReceiver = device && show(has.keychronReceiver, ["receiver"]); const showButtonMarkers = on(tab, ["buttons"]) && isNoirKsnakeStatus(status) && status.buttonMappings != null; const anyPanel = performance.length > 0 || macro.length > 0 || advanced.length > 0 || lighting.length > 0 @@ -459,7 +475,7 @@ export function Workspace({ <> {showOverview ? : null} - {!anyPanel ? ( + {!anyPanel && !showReceiver ? (

{tp(locale, "tab.unavailable", { @@ -473,6 +489,15 @@ export function Workspace({ {showProfiles ? : null} {showTeevolutionProfiles ? : null} {showNapeLayers ? : null} + {showReceiver ?

+ {status.keychronReceiver ? slotCards([ + , + , + ]) :

{t(locale, "tab.receiver")}

{t(locale, "diag.notReported")}

} + +
: null} + {showMagnetic ? : null} {performance.length > 0 || showSuperstrike || showButtonMap ? (
: null} {showButtonMap ? : null} {performance.length > 0 ? ( -
+
{slotCards(performance)}
) : null} @@ -536,7 +561,6 @@ export function Workspace({
) : null} - {showMagnetic ? : null} {advanced.length > 0 ? (
{ assert.equal(changed.length, 2); }); +test("battery samples in the same millisecond retain unique identities across writes and rollover", () => { + const storage = new MemoryStorage(); + saveBatterySample(storage, "SameTime", 90, "discharging", 1000); + saveBatterySample(storage, "SameTime", 89, "discharging", 1000); + const samples = saveBatterySample(storage, "SameTime", 90, "discharging", 1000); + assert.equal(new Set(samples.map(sample => sample.id)).size, 3); + const retained = samples[2]!.id; + let next = samples; + for (let index = 0; index < 498; index++) next = saveBatterySample(storage, "SameTime", 80, "discharging", 2000 + index * 300000); + assert.equal(next.length, 500); + assert.equal(next[1]!.id, retained); +}); + +test("legacy sample identities survive migration when a new checkpoint is stored", () => { + const storage = new MemoryStorage(); + storage.setItem("openmouse-battery-history-v1", JSON.stringify({ LegacyIds: [ + { timestamp: 1000, percent: 90, mode: "discharging" }, + { timestamp: 1000, percent: 89, mode: "discharging" }, + ] })); + const original = cachedBatterySamples(storage, "LegacyIds", 2000); + const next = saveBatterySample(storage, "LegacyIds", 88, "discharging", 2000); + assert.equal(new Set(original.map(sample => sample.id)).size, 2); + assert.equal(next[0]!.id, original[0]!.id); + assert.equal(next[1]!.id, original[1]!.id); +}); + +test("malformed stored timestamps are discarded before legacy IDs are constructed", () => { + const storage = new MemoryStorage(); + storage.setItem("openmouse-battery-history-v1", JSON.stringify({ BadTimestamp: [ + { timestamp: { toString: null }, percent: 90, mode: "discharging" }, + { timestamp: 1000, percent: 89, mode: "discharging" }, + ] })); + const samples = saveBatterySample(storage, "BadTimestamp", 88, "discharging", 2000); + assert.equal(samples.length, 2); + assert.equal(samples[0]!.id, "legacy:1000:1"); +}); + test("battery estimate requires a recent continuous trend", () => { const samples = [ { timestamp: 0, percent: 100, mode: "discharging" as const }, diff --git a/src/features/devices/battery-history.ts b/src/features/devices/battery-history.ts index 9de8a27f..4a3337d3 100644 --- a/src/features/devices/battery-history.ts +++ b/src/features/devices/battery-history.ts @@ -1,6 +1,8 @@ export type BatteryMode = "charging" | "discharging"; export interface BatterySample { + /** Browser-owned identity; legacy histories are assigned deterministic IDs when read. */ + id?: string; timestamp: number; percent: number; mode: BatteryMode; @@ -26,7 +28,10 @@ function loadHistory(storage: Storage): BatteryHistory { function pruneSamples(stored: unknown, cutoff: number): BatterySample[] { if (!Array.isArray(stored)) return []; - return stored.filter((sample): sample is BatterySample => + return stored.map((sample, index) => { + if (!sample || typeof sample !== "object" || !Number.isFinite(sample.timestamp)) return sample; + return { ...sample, id: typeof sample.id === "string" && sample.id ? sample.id : `legacy:${sample.timestamp}:${index}` }; + }).filter((sample): sample is BatterySample => typeof sample === "object" && sample !== null && Number.isFinite((sample as BatterySample).timestamp) @@ -57,7 +62,7 @@ export function saveBatterySample( || previous.percent !== percent || now - previous.timestamp >= CHECKPOINT_MS; - if (shouldSave) samples.push({ timestamp: now, percent, mode }); + if (shouldSave) samples.push({ id: crypto.randomUUID(), timestamp: now, percent, mode }); const retainedSamples = samples.slice(-MAX_SAMPLES_PER_DEVICE); history[deviceName] = retainedSamples; if (shouldSave || retainedSamples.length !== storedCount) { diff --git a/src/features/devices/cards/AdvancedCards.tsx b/src/features/devices/cards/AdvancedCards.tsx index afd85a6d..8dbca9bf 100644 --- a/src/features/devices/cards/AdvancedCards.tsx +++ b/src/features/devices/cards/AdvancedCards.tsx @@ -309,7 +309,7 @@ export function SleepCard({ snapshot }: { snapshot: ControlSnapshot }): ReactNod export function KsnakeScrollCard({ snapshot }: { snapshot: ControlSnapshot }): ReactNode { const status = snapshot.status; const locale = snapshot.preferences.locale; - if (status?.ui?.family !== "ksnake" || status.scrollDirection == null) return null; + if (status?.scrollDirection == null || !["ksnake", "keychron-8k"].includes(status.ui?.family ?? "") && !isNoirKsnakeStatus(status)) return null; const staged = snapshot.pending.keys.includes("ksnake-scroll-direction"); return (
@@ -338,7 +338,12 @@ export function KsnakeScrollCard({ snapshot }: { snapshot: ControlSnapshot }): R - {t(locale, "adv.scrollStored")} + {status.brand === "Keychron" && /Windows|Macintosh|Mac OS X/.test(navigator.userAgent) ? + + {t(locale, "magnetic.openSystem")} + : null} + {status.ui?.family === "keychron-8k" ? t(locale, "magnetic.scrollStored") : t(locale, "adv.scrollStored")}
); } @@ -2637,6 +2642,7 @@ export function WallhackMacroCard({ snapshot }: { snapshot: ControlSnapshot }): * so nothing here knows what a given mouse can do. */ export function ButtonMappingCard({ snapshot }: { snapshot: ControlSnapshot }): ReactNode { + const [leftLocked, setLeftLocked] = useState(true); const status = snapshot.status; if (!status?.buttonMappings || !status.buttonOptions?.length) return null; const locale = snapshot.preferences.locale; @@ -2656,13 +2662,14 @@ export function ButtonMappingCard({ snapshot }: { snapshot: ControlSnapshot }): return (

{t(locale, "map.remap")}

+ {status.brand === "Keychron" ? : null}
{Object.entries(status.buttonMappings).map(([button, deviceAssigned], index) => { const assigned = resettingButtons || pendingButtons.has(`button-${button}`) ? status.buttonMappings?.[button] ?? mappings[button] ?? deviceAssigned : mappings[button] ?? deviceAssigned; const selectId = `button-${button.toLowerCase()}-select`; - const isFixed = fixed.has(button) || (isNoirKsnakeStatus(status) && button === "Left"); + const isFixed = fixed.has(button) || (isNoirKsnakeStatus(status) && button === "Left") || (status.brand === "Keychron" && leftLocked && button === "Left"); return (