The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.
Studio: keyboard shortcut schemes, with Premiere Pro's, Final Cut Pro X's and three custom ones (#123)
riverisbuilding9728bae004c0
diff --git a/.changeset/keyboard-schemes.md b/.changeset/keyboard-schemes.mdnew file mode 100644index 0000000..c4e9a38--- /dev/null+++ b/.changeset/keyboard-schemes.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Studio: keyboard shortcut schemes. Settings › Keyboard shortcuts lists every editor action in tabs (Timeline, Player, Basic, Other) and lets you switch between OpenFilm's keys, Premiere Pro's and Final Cut Pro X's. Three custom schemes take any keys you record: changing a key in a built-in scheme copies it to a custom one first, and a key already in use asks before it moves. Menus and tooltips show the keys of the scheme in use.diff --git a/packages/openfilm/studio/server/prefs.mjs b/packages/openfilm/studio/server/prefs.mjsindex e252d72..121f79c 100644--- a/packages/openfilm/studio/server/prefs.mjs+++ b/packages/openfilm/studio/server/prefs.mjs@@ -8,22 +8,54 @@* projectsFolder where the projects library is, when the person chose (null: the default; src/locations.mjs,* which the `openfilm` command reads too). Kept in the prefs.json of the home that holds the library* (OPENFILM_SHARED_HOME, else this one), so every OpenFilm on the computer shares it.+ * keys the keyboard shortcuts: the scheme in use and the custom ones (null: OpenFilm's). Kept as Studio's+ * page gives them, in shape only (keysOf); the page checks every action and key (ui/src/lib/keymap.ts).*/import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';import { isAbsolute, join, resolve } from 'node:path';import { studioHome } from './projects.mjs';import { chooseFolder, chosenFolder } from '../../src/locations.mjs';-/** @typedef {{ proxies: { on: boolean, height: 540 | 720 | 1080 }, seenVersion: string | null, projectsFolder: string | null }} Prefs */+/** @typedef {{ scheme: string, custom: Record<string, { base: string, keys: Record<string, string[]> }> }} Keys */+/** @typedef {{ proxies: { on: boolean, height: 540 | 720 | 1080 }, seenVersion: string | null, projectsFolder: string | null, keys: Keys | null }} Prefs *//** Proxies on by default, at 720p. */-export const DEFAULT_PREFS = /** @type {Prefs} */ ({ proxies: { on: true, height: 720 }, seenVersion: null, projectsFolder: null });+export const DEFAULT_PREFS = /** @type {Prefs} */ ({ proxies: { on: true, height: 720 }, seenVersion: null, projectsFolder: null, keys: null });const VERSION = /^\d+\.\d+\.\d+(?:-[\w.]+)?$/;const HEIGHTS = [540, 720, 1080];+const NAME = /^[\w-]{1,40}$/;+const SLOTS = ['custom1', 'custom2', 'custom3'];++/**+ * The keyboard shortcuts in shape: a scheme's name, and up to three custom schemes, each the scheme it came from and+ * its keys (an action's name, then up to 8 combinations of at most 40 characters). Null when there is no scheme.+ * @param {unknown} raw @returns {Keys | null}+ */+export function keysOf(raw) {+ const k = /** @type {{ scheme?: unknown, custom?: unknown } | null} */ (raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : null);+ if (!k || typeof k.scheme !== 'string' || !NAME.test(k.scheme)) return null;+ /** @type {Keys['custom']} */+ const custom = {};+ const given = /** @type {Record<string, unknown>} */ (k.custom && typeof k.custom === 'object' ? k.custom : {});+ for (const slot of SLOTS) {+ const one = /** @type {{ base?: unknown, keys?: unknown } | undefined} */ (given[slot]);+ if (!one || typeof one !== 'object' || typeof one.base !== 'string' || !NAME.test(one.base)) continue;+ /** @type {Record<string, string[]>} */+ const keys = {};+ const list = Object.entries(one.keys && typeof one.keys === 'object' ? one.keys : {}).slice(0, 200);+ for (const [action, combos] of list) {+ if (!NAME.test(action) || !Array.isArray(combos)) continue;+ keys[action] = combos.filter((c) => typeof c === 'string' && c.length > 0 && c.length <= 40).slice(0, 8);+ }+ custom[slot] = { base: one.base, keys };+ }+ return { scheme: k.scheme, custom };+}+/** What is kept, each field checked; anything missing or wrong is its default. @param {unknown} raw @returns {Prefs} */export function prefsOf(raw) {- const p = /** @type {{ proxies?: { on?: unknown, height?: unknown }, seenVersion?: unknown, projectsFolder?: unknown } | null} */ (raw && typeof raw === 'object' ? raw : null);+ const p = /** @type {{ proxies?: { on?: unknown, height?: unknown }, seenVersion?: unknown, projectsFolder?: unknown, keys?: unknown } | null} */ (raw && typeof raw === 'object' ? raw : null);const folder = (/** @type {unknown} */ v) => (typeof v === 'string' && isAbsolute(v) ? resolve(v) : null);const height = Number(p?.proxies?.height);return {@@ -33,6 +65,7 @@ export function prefsOf(raw) {},seenVersion: typeof p?.seenVersion === 'string' && VERSION.test(p.seenVersion) ? p.seenVersion : null,projectsFolder: folder(p?.projectsFolder),+ keys: keysOf(p?.keys),};}@@ -52,7 +85,7 @@ export function readPrefs() {*/export function writePrefs(patch) {const now = readPrefs();- const asked = /** @type {{ proxies?: object, seenVersion?: unknown, projectsFolder?: unknown }} */ (patch && typeof patch === 'object' ? patch : {});+ const asked = /** @type {{ proxies?: object, seenVersion?: unknown, projectsFolder?: unknown, keys?: unknown }} */ (patch && typeof patch === 'object' ? patch : {});const next = prefsOf({ ...now, ...asked, proxies: { ...now.proxies, ...(asked.proxies ?? {}) } });const at = file();let kept = {};diff --git a/packages/openfilm/studio/server/prefs.test.mjs b/packages/openfilm/studio/server/prefs.test.mjsindex 032761b..c783a60 100644--- a/packages/openfilm/studio/server/prefs.test.mjs+++ b/packages/openfilm/studio/server/prefs.test.mjs@@ -29,3 +29,30 @@ test('what a newer OpenFilm keeps in prefs.json stays when this one writes it',if (was === undefined) delete process.env.OPENFILM_HOME; else process.env.OPENFILM_HOME = was;}});++test('the keyboard shortcuts are kept as given, in shape only; none is null', () => {+ assert.equal(prefsOf(null).keys, null);+ assert.equal(prefsOf({ keys: 'premiere' }).keys, null);+ assert.equal(prefsOf({ keys: { scheme: '../x' } }).keys, null);+ const keys = { scheme: 'custom1', custom: { custom1: { base: 'premiere', keys: { split: ['mod+e'], refer: [] } } } };+ assert.deepEqual(prefsOf({ keys }).keys, keys);+ const odd = prefsOf({ keys: { scheme: 'fcp', custom: { custom1: { base: 'fcp', keys: { split: ['mod+e', 7, 'x'.repeat(41)] } }, custom7: { base: 'fcp', keys: {} }, custom2: { keys: {} } } } }).keys;+ assert.deepEqual(odd, { scheme: 'fcp', custom: { custom1: { base: 'fcp', keys: { split: ['mod+e'] } } } });+});++test('the keyboard shortcuts written are read back, and the rest of prefs.json stays', () => {+ const home = mkdtempSync(join(tmpdir(), 'of-prefs-'));+ const was = process.env.OPENFILM_HOME;+ process.env.OPENFILM_HOME = home;+ try {+ writePrefs({ proxies: { on: false } });+ const keys = { scheme: 'custom2', custom: { custom2: { base: 'fcp', keys: { loop: ['shift+l'] } } } };+ assert.deepEqual(writePrefs({ keys }).keys, keys);+ const written = JSON.parse(readFileSync(join(home, 'prefs.json'), 'utf8'));+ assert.deepEqual(written.keys, keys);+ assert.equal(written.proxies.on, false);+ assert.deepEqual(writePrefs({ seenVersion: '0.2.3' }).keys, keys, 'another change leaves them');+ } finally {+ if (was === undefined) delete process.env.OPENFILM_HOME; else process.env.OPENFILM_HOME = was;+ }+});diff --git a/packages/openfilm/studio/server/server.test.mjs b/packages/openfilm/studio/server/server.test.mjsindex 7cdc0da..1d0e01c 100644--- a/packages/openfilm/studio/server/server.test.mjs+++ b/packages/openfilm/studio/server/server.test.mjs@@ -370,7 +370,7 @@ test('the preview plays heavy footage from its proxy once made; what the file ismkdirSync(join(project.path, 'assets'), { recursive: true });const big = join(project.path, 'assets', 'big.mp4');execFileSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'testsrc=size=2560x1440:rate=25:duration=1', '-pix_fmt', 'yuv420p', big]);- assert.deepEqual(await (await api('/api/prefs')).json(), { proxies: { on: true, height: 720 }, seenVersion: null, projectsFolder: null });+ assert.deepEqual(await (await api('/api/prefs')).json(), { proxies: { on: true, height: 720 }, seenVersion: null, projectsFolder: null, keys: null });let answer;for (const end = Date.now() + 30_000; answer?.states?.['assets/big.mp4']?.state !== 'ready' && Date.now() < end;) {answer = await (await api(`/api/projects/${project.id}/proxies`, { method: 'POST', body: {} })).json();@@ -383,7 +383,7 @@ test('the preview plays heavy footage from its proxy once made; what the file isassert.ok(played > 0 && played !== statSync(big).size, 'the proxy');assert.equal(await size('?film-facts=1'), statSync(big).size, 'what the file is: the file');/* off: the original, and no proxy asked for */- assert.deepEqual(await (await api('/api/prefs', { method: 'PATCH', body: { proxies: { on: false } } })).json(), { proxies: { on: false, height: 720 }, seenVersion: null, projectsFolder: null });+ assert.deepEqual(await (await api('/api/prefs', { method: 'PATCH', body: { proxies: { on: false } } })).json(), { proxies: { on: false, height: 720 }, seenVersion: null, projectsFolder: null, keys: null });assert.equal(await size(), statSync(big).size);assert.deepEqual((await (await api(`/api/projects/${project.id}/proxies`, { method: 'POST', body: {} })).json()).states, {});await api('/api/prefs', { method: 'PATCH', body: { proxies: { on: true } } });diff --git a/packages/openfilm/studio/ui/src/api.ts b/packages/openfilm/studio/ui/src/api.tsindex 87245ec..1a4e767 100644--- a/packages/openfilm/studio/ui/src/api.ts+++ b/packages/openfilm/studio/ui/src/api.ts@@ -79,7 +79,13 @@ async function call<T>(path: string, init: RequestInit & { json?: unknown } = {}const p = (id: string) => `projects/${encodeURIComponent(id)}`;/** Studio's own preferences, the same for every project (studio/server/prefs.mjs). */-export interface StudioPrefs { proxies: { on: boolean; height: 540 | 720 | 1080 }; seenVersion: string | null; projectsFolder: string | null }+export interface StudioPrefs {+ proxies: { on: boolean; height: 540 | 720 | 1080 };+ seenVersion: string | null;+ projectsFolder: string | null;+ /** the keyboard shortcuts: the scheme in use and the custom ones (lib/keymap `KeyPrefs`, checked there) */+ keys?: unknown;+}/** Where the projects library is (src/locations.mjs): the folder, its default, whether the person chose it, the free space on its disk, how many projects are in it. */export interface StudioLocation { path: string; default: string; chosen: boolean; free: number | null; count: number }export interface StudioLocations { projects: StudioLocation }@@ -121,7 +127,7 @@ export const api = {revealProject: (id: string) => call<object>(`projects/${encodeURIComponent(id)}/reveal`, { method: 'POST', json: {} }),/** one of them in the system's file manager */openLocation: (which: keyof StudioLocations) => call<{ ok: true }>(`locations/${which}`, { method: 'POST', json: {} }),- setPrefs: (patch: { proxies?: Partial<StudioPrefs['proxies']>; seenVersion?: string; projectsFolder?: string | null }) => call<StudioPrefs>('prefs', { method: 'PATCH', json: patch }).then((prefs) => {+ setPrefs: (patch: { proxies?: Partial<StudioPrefs['proxies']>; seenVersion?: string; projectsFolder?: string | null; keys?: unknown }) => call<StudioPrefs>('prefs', { method: 'PATCH', json: patch }).then((prefs) => {window.dispatchEvent(new Event(PREFS_EVENT));return prefs;}),diff --git a/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx b/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsxindex 177ea27..99dae36 100644--- a/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx+++ b/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx@@ -33,7 +33,9 @@* point winning. What is written is always film.html: a clip's `box`, a page's `overrides`, through the callbacks.*/import * as React from 'react';-import { isSelectAll as isSelectAllKey, type KeyLike } from '@/lib/select-all-key';+import { currentKeymap, keyAction } from '@/lib/keymap-store';+import { hintOf } from '@/lib/keymap';+import type { KeyPress } from '@/lib/timeline-keys';import { doubleClickAim, keepPress, type Press } from '@/lib/double-press';import {AlignCenterHorizontal, AlignCenterVertical, AlignEndHorizontal, AlignEndVertical, AlignHorizontalDistributeCenter,@@ -77,7 +79,6 @@ import { regionBox, regionClipIds, regionTexts } from '@/lib/studio-refs';import type { StageBox } from '@/lib/host';import { samePictureMarks, type PictureMarks } from '@/lib/chat-marks';import { distributeShifts } from '@/lib/selection-toolbar';-import { shortcutHint } from '@/lib/shortcut-hint';import { trackLockedAt } from '@/lib/track-lock';import {compactScale, type NodeOverride, type StageElement, type StageElementStyle, type StageGeometry, type StageNodeKind,@@ -111,8 +112,8 @@ type PressEvent = Pick<PointerEvent, 'button' | 'timeStamp' | 'pointerId' | 'tar/** Controls in the viewer's picture area: a press on one is theirs. */const CONTROLS = 'button, a, input, textarea, select, [role="button"], [role="slider"], [role="menu"], [contenteditable="true"]';const regionKeyHeld = (e: { metaKey: boolean; ctrlKey: boolean }) => (MAC ? e.metaKey : e.ctrlKey);-/** ⌘A (Ctrl+A elsewhere): every layer on the picture selected. */-const isSelectAll = (e: KeyLike) => isSelectAllKey(e, MAC);+/** ⌘A (Ctrl+A elsewhere; lib/keymap): every layer on the picture selected. */+const isSelectAll = (e: KeyPress) => keyAction(e) === 'select-all';/** Arrow keys write what they moved this long after the last one (held down they come thirty a second). */const NUDGE_WRITE_MS = 350;const NO_CROP: Crop = [0, 0, 0, 0];@@ -2483,7 +2484,7 @@ function FilmStageSelectImpl({: barKind === 'layers' ? `layers:${(multi ?? []).map((i) => i.layer.handle).join(',')}`: barKind === 'clip' ? `clip:${heldEl?.clipLoc ?? ''}` : `layer:${heldEl?.loc ?? ''}:${picked?.layer?.handle ?? ''}`;const barLead = barKind && onRefer ? {- id: 'refer', label: t('selectionBar.addToChat'), icon: <MessageSquarePlus size={14} />, shortcut: shortcutHint('L', { mod: true }),+ id: 'refer', label: t('selectionBar.addToChat'), icon: <MessageSquarePlus size={14} />, shortcut: hintOf(currentKeymap(), 'refer', MAC),onSelect: () => onRefer(pickedItems()),} : null;const barLabel = barKind === 'layers' ? t('selectionBar.layers').replace('{n}', String(multi?.length ?? 0)) : undefined;diff --git a/packages/openfilm/studio/ui/src/components/OperationHistory.tsx b/packages/openfilm/studio/ui/src/components/OperationHistory.tsxindex 268c85c..b661169 100644--- a/packages/openfilm/studio/ui/src/components/OperationHistory.tsx+++ b/packages/openfilm/studio/ui/src/components/OperationHistory.tsx@@ -12,7 +12,8 @@ import React from 'react';import { createPortal } from 'react-dom';import { User } from 'lucide-react';import { useT } from '@/i18n';-import { shortcutHint } from '@/lib/shortcut-hint';+import { hintOf } from '@/lib/keymap';+import { currentKeymap, MAC } from '@/lib/keymap-store';/** One step of the session. */export interface SessionOp {@@ -174,7 +175,7 @@ function OpRow({</span>{next ? (<span className="shrink-0 rounded-full bg-[var(--accent)]/15 px-1.5 py-px text-[10px] font-medium text-[var(--accent)]">- {shortcutHint('Z', { mod: true })}+ {hintOf(currentKeymap(), 'undo', MAC)}</span>) : null}</button>diff --git a/packages/openfilm/studio/ui/src/components/ProjectView.tsx b/packages/openfilm/studio/ui/src/components/ProjectView.tsxindex 7475f10..2063a2d 100644--- a/packages/openfilm/studio/ui/src/components/ProjectView.tsx+++ b/packages/openfilm/studio/ui/src/components/ProjectView.tsx@@ -21,7 +21,9 @@ import type { ReplaceFamily } from '@/lib/clip-replace';import { layoutTracks, type TimelineBlock, type TimelineTrack } from '@/lib/timeline-layout';import { filmClipKind, filmSrcIsPage, filmSrcKind, filmTrackBadges, parseFilmDocLoc, type FilmBox, type FilmDoc, type FilmOverride } from '@/lib/film';import { exactRate, footageFps, setTimecodeFps, snapToFrame, stepFrames } from '@/lib/timecode';-import { JUMP_FRAMES, keyCommandOf, loopBack, playStart, shuttleRate } from '@/lib/timeline-keys';+import { JUMP_FRAMES, loopBack, playStart, shuttleRate } from '@/lib/timeline-keys';+import { comboOf, parseCombo } from '@/lib/keymap';+import { currentKeymap, keyAction, useKeyHint } from '@/lib/keymap-store';import { attrsOf, pasteAttrs, type AttrGroup, type CopiedAttrs } from '@/lib/clip-attrs';import { cutPoints, namedTrack, nextCut, trackNamesOf } from '@/lib/timeline-nav';import { anyLocked, lockedEdits } from '@/lib/track-lock';@@ -56,7 +58,6 @@ import type { ContextMenuEntry } from './ContextMenu';import { studioHost, useHostPanel, type CommunityItem, type HostPanel, type StageBox, type StudioCommand, type StudioRef } from '../lib/host';import { clipRef, fileRef, layerRef, markRange, momentRef, rangeRef, regionRef, stillUrl, subtitleRef, trackRef, type ClipFrameSource, type FilmRange } from '@/lib/studio-refs';import { boxNow, chatPointOf, draftBoxesAt, draftMarksOf, sameClip, NO_DRAFT, type DraftMarks, type PictureMarks } from '@/lib/chat-marks';-import { shortcutHint } from '@/lib/shortcut-hint';import { usePageChanges } from './use-page-changes';import { SubtitleOverlay } from './SubtitleOverlay';import { SubtitleInspector, subtitleLineKey, type SubtitleLineAt, type SubtitleLineRefer } from './SubtitleInspector';@@ -198,6 +199,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {}) {const t = useT();const toast = useToast();+ const keyHint = useKeyHint();/* how many times the project's files changed since it opened (see the folder events below) */const [filesTick, setFilesTick] = React.useState(0);const [loaded, setLoaded] = React.useState<ProjectFilm | null>(null);@@ -1351,9 +1353,9 @@ export function ProjectView({ projectId, onProject, onLeave }: {of: refOfSubtitle,send: refer,pick: (line) => setSubtitlePick((cur) => (same(cur, line) ? cur : line)),- shortcut: shortcutHint('L', { mod: true }),+ shortcut: keyHint('refer') ?? '',};- }, [projectId]); // eslint-disable-line react-hooks/exhaustive-deps+ }, [projectId, keyHint]); // eslint-disable-line react-hooks/exhaustive-deps/** A thing in hand on the picture as a reference: a whole clip as its block is, a layer where it is drawn. */const refOfStagePick = (pick: StagePick): StudioRef | null => {const el = pick.element;@@ -1737,7 +1739,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {if (!refer) return [];return [{id: 'refer', label: t('host.refer'), icon: <MessageSquarePlus size={14} />,- ...(withKey ? { shortcut: shortcutHint('L', { mod: true }) } : {}),+ ...(withKey ? { shortcut: keyHint('refer') } : {}),onSelect: () => { for (const ref of refs()) refer(ref); },}];};@@ -1748,15 +1750,15 @@ export function ProjectView({ projectId, onProject, onLeave }: {const extra = whole && !block ? [] : [...referEntry(() => [whole ? refOfBlock(block!) : refOfLayer(el)]), ...(whole && block ? saveEntry([block]) : [])];return extra.length ? [...extra, ...(entries.length ? [{ id: 'refer-sep', separator: true } as const] : []), ...entries] : entries;// eslint-disable-next-line react-hooks/exhaustive-deps- }, [stageMenuFor, t, saveBlocks]);+ }, [stageMenuFor, t, keyHint, saveBlocks]);/** Two groups of menu entries, a line between them when both have some. */const menuGroups = (a: ContextMenuEntry[], b: ContextMenuEntry[]): ContextMenuEntry[] => (a.length && b.length ? [...a, { id: 'tools-sep', separator: true }, ...b] : [...a, ...b]);/* copy and paste attributes, in the clip menu */const attrsEntries = (blocks: readonly TimelineBlock[]): ContextMenuEntry[] => [- { id: 'copy-attrs', label: t('clipAttrs.copy'), icon: <ClipboardCopy size={14} />, shortcut: shortcutHint('C', { mod: true, shift: true }), disabled: blocks.length !== 1, onSelect: () => copyAttrs(blocks) },- { id: 'paste-attrs', label: t('clipAttrs.pasteMenu'), icon: <ClipboardPaste size={14} />, shortcut: shortcutHint('V', { mod: true, shift: true }), disabled: !copiedAttrs, hint: t('clipAttrs.nothing'), onSelect: () => askPasteAttrs(blocks) },+ { id: 'copy-attrs', label: t('clipAttrs.copy'), icon: <ClipboardCopy size={14} />, shortcut: keyHint('copy-attrs'), disabled: blocks.length !== 1, onSelect: () => copyAttrs(blocks) },+ { id: 'paste-attrs', label: t('clipAttrs.pasteMenu'), icon: <ClipboardPaste size={14} />, shortcut: keyHint('paste-attrs'), disabled: !copiedAttrs, hint: t('clipAttrs.nothing'), onSelect: () => askPasteAttrs(blocks) },];- const timelineMenuExtra = React.useCallback((blocks: readonly TimelineBlock[]) => (blocks.length ? menuGroups(menuGroups([...referEntry(() => blocks.map(refOfBlock)), ...saveEntry(blocks)], tools.menuExtra(blocks)), attrsEntries(blocks)) : []), [t, tools.menuExtra, copiedAttrs, copyAttrs, askPasteAttrs, saveBlocks]); // eslint-disable-line react-hooks/exhaustive-deps+ const timelineMenuExtra = React.useCallback((blocks: readonly TimelineBlock[]) => (blocks.length ? menuGroups(menuGroups([...referEntry(() => blocks.map(refOfBlock)), ...saveEntry(blocks)], tools.menuExtra(blocks)), attrsEntries(blocks)) : []), [t, keyHint, tools.menuExtra, copiedAttrs, copyAttrs, askPasteAttrs, saveBlocks]); // eslint-disable-line react-hooks/exhaustive-depsconst trackMenuExtra = React.useCallback((track: TimelineTrack) => {const docIndex = track.docIndex;const refer = docIndex == null || !studioHost?.refer ? [] : referEntry(() => { const ref = trackRef(tracksRef.current, docIndex); return ref ? [ref] : []; }, false);@@ -2260,9 +2262,9 @@ export function ProjectView({ projectId, onProject, onLeave }: {});/*- * ── keys (lib/timeline-keys, listed in Settings): Space plays, J / K / L shuttle, I / O mark a range, ← / → step a- * frame (⇧ a second), ↑ / ↓ go from cut to cut, ⌘Z / ⇧⌘Z undo; the timeline's own (⌘B, Q / W, ⌥← / →, N…) through- * its commands. Not while typing, nor in a dialog. ──+ * ── keys (lib/keymap, the scheme chosen in Settings; by default): Space plays, J / K / L shuttle, I / O mark a range,+ * ← / → step a frame (⇧ ten), ↑ / ↓ go from cut to cut, ⌘Z / ⇧⌘Z undo; the timeline's own (⌘B, Q / W, ⌥← / →, N…)+ * through its commands. Not while typing, nor in a dialog. ──*/const tabbed = React.useRef(false);React.useEffect(() => {@@ -2272,10 +2274,13 @@ export function ProjectView({ projectId, onProject, onLeave }: {window.addEventListener('pointerdown', byPointer, true);return () => { window.removeEventListener('keydown', byKey, true); window.removeEventListener('pointerdown', byPointer, true); };}, []);- /* K held down: J and L step a frame (K+J, K+L) */+ /* K (stop) held down: J and L (back, forward) step a frame (K+J, K+L) */const kHeld = React.useRef(false);React.useEffect(() => {- const up = (e: KeyboardEvent) => { if (e.key.toLowerCase() === 'k' || e.code === 'KeyK') kHeld.current = false; };+ const up = (e: KeyboardEvent) => {+ const key = parseCombo(comboOf({ key: e.key, code: e.code, metaKey: false, ctrlKey: false, altKey: false, shiftKey: false }, MAC) ?? '')?.key;+ if (key && currentKeymap()['shuttle-stop'].some((combo) => parseCombo(combo)?.key === key)) kHeld.current = false;+ };const lost = () => { kHeld.current = false; };window.addEventListener('keyup', up, true);window.addEventListener('blur', lost);@@ -2290,8 +2295,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {const refer = studioHost?.refer;const el = event.target as HTMLElement | null;if (!refer || event.defaultPrevented || isTypingTarget(el) || el?.closest?.('[role="dialog"]')) return false;- const mod = event.metaKey || event.ctrlKey;- if (mod && event.key.toLowerCase() === 'l' && !event.shiftKey && !event.altKey) {+ if (keyAction(event) === 'refer') {event.preventDefault();for (const ref of selectedRefs()) refer(ref);return true;@@ -2303,15 +2307,15 @@ export function ProjectView({ projectId, onProject, onLeave }: {keyNowRef.current = (event) => {if (referKeysRef.current(event)) return;const el = event.target as HTMLElement | null;- const mod = MAC ? event.metaKey : event.ctrlKey;- if (event.key.toLowerCase() === 'z' && mod && !event.altKey) {+ const cmd = keyAction(event);+ if (cmd === 'undo' || cmd === 'redo') {if (isTypingTarget(el) || el?.closest('[role="dialog"]')) return;/* not checked against canUndo: a nudge on the picture not written yet is written first, and is the step undone */event.preventDefault();- stepHistory(event.shiftKey ? 'redo' : 'undo');+ stepHistory(cmd);return;}- if (event.code === 'Space' && !event.shiftKey && !event.metaKey && !event.ctrlKey && !event.altKey) {+ if (cmd === 'play-pause') {if (isTypingTarget(el)) return;if (event.repeat) { event.preventDefault(); return; }if (el?.closest('[role="dialog"]')) return;@@ -2325,7 +2329,6 @@ export function ProjectView({ projectId, onProject, onLeave }: {if (event.defaultPrevented || isTypingTarget(el) || el?.closest?.('[role="dialog"]')) return;/* Esc lets the range go as it lets the selection go (those listen on their own); a menu or a panel open takes it */if (event.key === 'Escape' && markedRange && !document.querySelector('[role="menu"], [role="listbox"], [data-popover-panel]')) setMarkedRange(null);- const cmd = keyCommandOf(event, MAC);if (!cmd) return;/* a menu or a list open has the arrows; a slider (the ruler, a volume) steps itself with ← / → */if (el?.closest?.('[role="menu"], [role="listbox"]') && /^(frame|second|prev|next|start|end|nudge)/.test(cmd)) return;diff --git a/packages/openfilm/studio/ui/src/components/SourcePreview.tsx b/packages/openfilm/studio/ui/src/components/SourcePreview.tsxindex f5fdeba..16657e1 100644--- a/packages/openfilm/studio/ui/src/components/SourcePreview.tsx+++ b/packages/openfilm/studio/ui/src/components/SourcePreview.tsx@@ -14,6 +14,7 @@ import { STILL_DROP_MS } from '@/lib/asset-timeline';import type { SourceRange } from '@/lib/media-place';import { exactRate, formatTimecode, snapToFrame, useTimecodeFps } from '@/lib/timecode';import { type MediaSources, type WorkspaceResource } from '@/lib/workspace-resources';+import { keyAction } from '@/lib/keymap-store';import { isTypingTarget } from './typing-target';import { KIND_ICON, MediaPreview } from './MediaPreview';import { PANE_BTN, PANE_ICON } from './dock-pane-bar';@@ -34,7 +35,7 @@ function rangeOf(marks: Marks, duration: number): SourceRange | null {/*** The source's keys while it is up (before the editor's own: these are the source monitor's): I / O mark, X lets the- * marks go, `,` / `.` put the part marked on the film. Not while typing.+ * marks go, `,` / `.` put the part marked on the film (by default; lib/keymap). Not while typing.*/function useSourceKeys(path: string, time: number, duration: number, onPlace: SourcePreviewProps['onPlace']) {const [marks, setMarksState] = React.useState<Marks>(() => marksByPath.get(path) ?? { in: null, out: null });@@ -44,20 +45,20 @@ function useSourceKeys(path: string, time: number, duration: number, onPlace: Sonow.current = { time, duration, marks };React.useEffect(() => {const onKey = (e: KeyboardEvent) => {- if (isTypingTarget(e.target) || e.metaKey || e.ctrlKey || e.altKey || e.defaultPrevented) return;+ if (isTypingTarget(e.target) || e.defaultPrevented) return;if ((e.target as Element | null)?.closest?.('[role="dialog"]')) return;const { time: at, duration: dur, marks: m } = now.current;- const key = e.key.toLowerCase();+ const action = keyAction(e);/* on the file's own frame grid, as the film's marks are on the film's */const sec = Math.min(dur, snapToFrame(at * 1000) / 1000);let next: Marks | null = null;- if (key === 'i' && !e.shiftKey) next = { in: sec, out: m.out != null && m.out > sec ? m.out : null };- else if (key === 'o' && !e.shiftKey) next = { in: m.in != null && m.in < sec ? m.in : null, out: sec };- else if (key === 'x' && !e.shiftKey) next = { in: null, out: null };- else if ((e.key === ',' || e.key === '.') && onPlace && !e.shiftKey) {+ if (action === 'mark-in') next = { in: sec, out: m.out != null && m.out > sec ? m.out : null };+ else if (action === 'mark-out') next = { in: m.in != null && m.in < sec ? m.in : null, out: sec };+ else if (action === 'clear-range') next = { in: null, out: null };+ else if ((action === 'insert-source' || action === 'overwrite-source') && onPlace) {e.preventDefault();e.stopPropagation();- onPlace(e.key === ',' ? 'insert' : 'overwrite', rangeOf(m, dur));+ onPlace(action === 'insert-source' ? 'insert' : 'overwrite', rangeOf(m, dur));return;} else return;e.preventDefault();diff --git a/packages/openfilm/studio/ui/src/components/SubtitleRow.tsx b/packages/openfilm/studio/ui/src/components/SubtitleRow.tsxindex 7d46384..7e17890 100644--- a/packages/openfilm/studio/ui/src/components/SubtitleRow.tsx+++ b/packages/openfilm/studio/ui/src/components/SubtitleRow.tsx@@ -14,7 +14,8 @@import React from 'react';import { Captions, Combine, EyeOff, Pencil, Plus, Scissors, Trash2 } from 'lucide-react';import { useT } from '@/i18n';-import { shortcutHint } from '@/lib/shortcut-hint';+import { hintOf } from '@/lib/keymap';+import { currentKeymap, keyAction, MAC } from '@/lib/keymap-store';import {addSpan,canMerge,@@ -236,7 +237,8 @@ export const SubtitleRow = React.forwardRef<SubtitleRowHandle, {const picked = list.find((c) => cueKey(c) === selected);const mod = e.metaKey || e.ctrlKey;const take = () => { e.preventDefault(); e.stopPropagation(); };- if (mod && !e.shiftKey && !e.altKey && e.key.toLowerCase() === 'b') {+ const action = keyAction(e);+ if (action === 'split') {take();if (e.repeat) return;const at = playheadMs();@@ -244,8 +246,9 @@ export const SubtitleRow = React.forwardRef<SubtitleRowHandle, {if (cue) split(cue, at);return;}- if (!picked || mod || e.altKey) return;- if (e.key === 'Delete' || e.key === 'Backspace') { take(); remove(picked); return; }+ if (!picked) return;+ if (action === 'remove' || action === 'ripple-delete') { take(); remove(picked); return; }+ if (mod || e.altKey) return;if (e.key === 'Enter') { take(); setEditing({ key: cueKey(picked), text: picked.text }); return; }if (e.key === 'Escape') { setSelected(null); }};@@ -328,12 +331,12 @@ export const SubtitleRow = React.forwardRef<SubtitleRowHandle, {const next = list[list.indexOf(cue) + 1];setMenu({x: e.clientX, y: e.clientY, items: [- { id: 'split', label: t('subtitleRow.split'), icon: <Scissors size={14} />, shortcut: shortcutHint('B', { mod: true }),+ { id: 'split', label: t('subtitleRow.split'), icon: <Scissors size={14} />, shortcut: hintOf(currentKeymap(), 'split', MAC),disabled: !canSplitAt(cue, at), hint: t('subtitleRow.splitWhere'), onSelect: () => split(cue, at) },{ id: 'merge', label: t('subtitleRow.merge'), icon: <Combine size={14} />, disabled: !canMerge(cue, next), hint: t('subtitleRow.mergeWhy'), onSelect: () => merge(cue) },{ id: 'edit', label: t('subtitleRow.edit'), icon: <Pencil size={14} />, shortcut: '↵', onSelect: () => setEditing({ key: cueKey(cue), text: cue.text }) },{ id: 'sep', separator: true },- { id: 'delete', label: t('subtitleRow.delete'), icon: <Trash2 size={14} />, danger: true, shortcut: '⌫', onSelect: () => remove(cue) },+ { id: 'delete', label: t('subtitleRow.delete'), icon: <Trash2 size={14} />, danger: true, shortcut: hintOf(currentKeymap(), 'remove', MAC), onSelect: () => remove(cue) },],});};diff --git a/packages/openfilm/studio/ui/src/components/Timeline.tsx b/packages/openfilm/studio/ui/src/components/Timeline.tsxindex 8b753dd..ea7e429 100644--- a/packages/openfilm/studio/ui/src/components/Timeline.tsx+++ b/packages/openfilm/studio/ui/src/components/Timeline.tsx@@ -58,7 +58,7 @@ import {Blend,} from 'lucide-react';import { useT } from '@/i18n';-import { shortcutHint } from '@/lib/shortcut-hint';+import { keyAction, useKeyHint } from '@/lib/keymap-store';import { ownTrackHeight } from '@/lib/track-heights';import type { Op } from '@/api';import type { ClipEdit } from '@/lib/film-clip-edits';@@ -1010,6 +1010,7 @@ export const Timeline = React.memo(function Timeline({return clock.subscribe(sync);}, [clock]);const t = useT();+ const keyHint = useKeyHint();const scrollRef = React.useRef<HTMLDivElement | null>(null);const rootRef = React.useRef<HTMLDivElement | null>(null);const toolbarRef = React.useRef<HTMLDivElement | null>(null);@@ -2114,7 +2115,7 @@ export const Timeline = React.memo(function Timeline({[rippleRemove, removeMany],);- /* selected clips: Delete / Backspace deletes, ⌘C copies, ⌘V pastes at the playhead; not while typing */+ /* selected clips: Delete / Backspace deletes, ⌘C copies, ⌘V pastes at the playhead (lib/keymap); not while typing */React.useEffect(() => {const onKey = (e: KeyboardEvent): void => {if (isTypingTarget(e.target)) return;@@ -2127,14 +2128,15 @@ export const Timeline = React.memo(function Timeline({onPickTransition?.(null);return;}- if ((e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey && e.key.toLowerCase() === 'a' && activeRef.current) {+ const action = keyAction(e);+ if (action === 'select-all' && activeRef.current) {const all = tracks.filter((tr) => !tr.locked).flatMap((tr) => tr.blocks).filter((b) => b.loc).map((b) => b.id);if (!all.length) return;e.preventDefault();setSelected(all);return;}- if ((e.key === 'Delete' || e.key === 'Backspace') && !e.metaKey && !e.ctrlKey && !e.altKey) {+ if (action === 'remove' || action === 'ripple-delete') {/* a transition picked: taken away (its fades, and the overlap it made) */if (pickedTransition && !picked.length && onTransition) {e.preventDefault();@@ -2151,27 +2153,24 @@ export const Timeline = React.memo(function Timeline({if ((!onRemove && !onRemoveMany && !onEditOps) || !picked.length) return;e.preventDefault();/* ⌫ leaves a gap (with the magnet the main track closes up); ⇧⌫ closes it (a ripple delete) */- void (e.shiftKey ? rippleRemove(picked) : magnetRemove(picked));+ void (action === 'ripple-delete' ? rippleRemove(picked) : magnetRemove(picked));return;}- const mod = e.metaKey || e.ctrlKey;- /* ⌘= / ⌘- / ⌘0 zoom the timeline (only when it is visible). ⌘+ is ⇧= on most keyboards, so before the ⇧ check. */- if (mod && !e.altKey && (e.key === '=' || e.key === '+' || e.key === '-' || e.key === '0')) {+ /* ⌘= / ⌘- / ⌘0 zoom the timeline (only when it is visible) */+ if (action === 'zoom-in' || action === 'zoom-out' || action === 'zoom-reset') {if (!playable || !scrollRef.current?.checkVisibility?.({ visibilityProperty: true })) return;e.preventDefault();- if (e.key === '0') zoomToStable(ZOOM_DEFAULT);- else zoomByStable(e.key === '-' ? 1 / ZOOM_STEP : ZOOM_STEP);+ if (action === 'zoom-reset') zoomToStable(ZOOM_DEFAULT);+ else zoomByStable(action === 'zoom-out' ? 1 / ZOOM_STEP : ZOOM_STEP);return;}- if (!mod || e.altKey || e.shiftKey) return;- const key = e.key.toLowerCase();- if (key === 'c') {+ if (action === 'copy') {if (!onCopy || !picked.length) return;e.preventDefault();onCopy(picked);return;}- if (key === 'v') {+ if (action === 'paste') {if (!onPaste || !hasClipboard) return;const lane = picked[0] ? laneOfBlock(tracks, picked[0].id) : null;if (lane && tracks.find((tr) => tr.lane === lane)?.locked) return;@@ -2357,20 +2356,18 @@ export const Timeline = React.memo(function Timeline({}, [onSplit, splitting, tracks]);/**- * The tool keys: plain A / V / B switch the tool (the letters printed in the mode picker): B = "the pointer becomes a- * blade". ⌘B, "cut here", is the editor's (see TimelineCommands.split).+ * The tool keys: A / V select, B splits (by default; lib/keymap): B = "the pointer becomes a blade". ⌘B, "cut here",+ * is the editor's (see TimelineCommands.split).*/React.useEffect(() => {const onKey = (e: KeyboardEvent): void => {if (isTypingTarget(e.target)) return;if ((e.target as Element | null)?.closest?.('[role="dialog"]')) return;- if (!onSplit) return;- if (e.altKey || e.shiftKey || e.metaKey || e.ctrlKey || e.defaultPrevented) return;- const key = e.key.toLowerCase();- /* A or V selects, B splits */- if (key !== 'a' && key !== 'b' && key !== 'v') return;+ if (!onSplit || e.defaultPrevented) return;+ const action = keyAction(e);+ if (action !== 'select-mode' && action !== 'split-mode') return;e.preventDefault();- setMode(key === 'b' ? 'split' : 'select');+ setMode(action === 'split-mode' ? 'split' : 'select');};window.addEventListener('keydown', onKey);return () => window.removeEventListener('keydown', onKey);@@ -3480,7 +3477,7 @@ export const Timeline = React.memo(function Timeline({if (menu.transition) {const there = menu.transition;return [{- id: 'tr-remove', label: t('transitions.remove'), icon: <Trash2 size={14} />, danger: true, shortcut: '⌫',+ id: 'tr-remove', label: t('transitions.remove'), icon: <Trash2 size={14} />, danger: true, shortcut: keyHint('remove'),onSelect: () => { void onTransition?.({ kind: 'remove', key: there.key }).then((err) => { if (err) setDropError(err); }); onPickTransition?.(null); },}];}@@ -3498,7 +3495,7 @@ export const Timeline = React.memo(function Timeline({id: 'paste',label: t('timeline.menuPaste'),icon: <ClipboardPaste size={14} />,- shortcut: shortcutHint('V', { mod: true }),+ shortcut: keyHint('paste'),disabled: !onPaste || !hasClipboard || !menu.lane || laneLocked,hint: laneLocked ? t('timeline.trackLocked') : t('timeline.menuPasteEmpty'),onSelect: () => { if (menu.lane) void onPaste?.(menu.lane, menu.atMs); },@@ -3510,7 +3507,7 @@ export const Timeline = React.memo(function Timeline({id: 'close-gap',label: t('timeline.menuCloseGap'),icon: <BetweenHorizontalStart size={14} />,- shortcut: '⌫',+ shortcut: keyHint('remove'),onSelect: () => closeGapOn(found),});}@@ -3543,7 +3540,7 @@ export const Timeline = React.memo(function Timeline({id: 'split',label: t('timeline.menuSplitHere'),icon: <Scissors size={14} />,- shortcut: shortcutHint('B', { mod: true }),+ shortcut: keyHint('split'),disabled: !canSplit,/* disabled for one reason only: the playhead is not over this clip */hint: t('timeline.menuSplitOutside'),@@ -3557,7 +3554,7 @@ export const Timeline = React.memo(function Timeline({id: 'ripple-start',label: t('timeline.menuRippleStart'),icon: <ArrowLeftToLine size={14} />,- shortcut: 'Q',+ shortcut: keyHint('ripple-start'),disabled: !under,hint: pickedLocked ? t('timeline.trackLocked') : t('timeline.menuSplitOutside'),onSelect: () => { rippleTrimToPlayhead('start', [one]); },@@ -3565,7 +3562,7 @@ export const Timeline = React.memo(function Timeline({id: 'ripple-end',label: t('timeline.menuRippleEnd'),icon: <ArrowRightToLine size={14} />,- shortcut: 'W',+ shortcut: keyHint('ripple-end'),disabled: !under,hint: pickedLocked ? t('timeline.trackLocked') : t('timeline.menuSplitOutside'),onSelect: () => { rippleTrimToPlayhead('end', [one]); },@@ -3634,7 +3631,7 @@ export const Timeline = React.memo(function Timeline({id: 'copy',label: t('timeline.menuCopy'),icon: <Copy size={14} />,- shortcut: shortcutHint('C', { mod: true }),+ shortcut: keyHint('copy'),disabled: !picked.some((b) => b.loc),hint: t('timeline.menuCopyNone'),onSelect: () => onCopy(picked.filter((b) => b.loc)),@@ -3646,7 +3643,7 @@ export const Timeline = React.memo(function Timeline({id: 'paste',label: t('timeline.menuPaste'),icon: <ClipboardPaste size={14} />,- shortcut: shortcutHint('V', { mod: true }),+ shortcut: keyHint('paste'),disabled: !hasClipboard || !pasteLane || pickedLocked,hint: pickedLocked ? t('timeline.trackLocked') : t('timeline.menuPasteEmpty'),onSelect: () => { if (pasteLane) void onPaste(pasteLane, menu.atMs); },@@ -3673,7 +3670,7 @@ export const Timeline = React.memo(function Timeline({danger: true,disabled: pickedLocked || !picked.some((b) => b.loc),hint: pickedLocked ? t('timeline.trackLocked') : t('timeline.menuCopyNone'),- shortcut: '⌫',+ shortcut: keyHint('remove'),/* as ⌫: a gap is left */onSelect: () => { void magnetRemove(picked); },});@@ -3685,14 +3682,14 @@ export const Timeline = React.memo(function Timeline({danger: true,disabled: pickedLocked || !picked.some((b) => b.loc),hint: pickedLocked ? t('timeline.trackLocked') : t('timeline.menuCopyNone'),- shortcut: '⇧⌫',+ shortcut: keyHint('ripple-delete'),onSelect: () => { void rippleRemove(picked); },});}}return out;}, [- menu, t, onSplit, onDetachAudio, onRemove, onRemoveMany, onCopy, onPaste, onExportBlock, mediaTrouble, relinkCandidates,+ menu, t, keyHint, onSplit, onDetachAudio, onRemove, onRemoveMany, onCopy, onPaste, onExportBlock, mediaTrouble, relinkCandidates,onRelink, hasClipboard, runSplit, removeMany, rippleRemove, magnetRemove, onEditOps, tracks, blockMenuExtra, headEntries, withLinked,runPlan, closeGapOn, rippleTrimToPlayhead, linkBlocks, unlinkBlocks, transitions, onTransition, onPickTransition, transitionEntries,]);@@ -3719,7 +3716,7 @@ export const Timeline = React.memo(function Timeline({if (barKind === 'point') {if (onSplit && selectedBlocks.length) {out.push({- id: 'split', label: t('selectionBar.splitSelected'), icon: <Scissors size={14} />, shortcut: shortcutHint('B', { mod: true }),+ id: 'split', label: t('selectionBar.splitSelected'), icon: <Scissors size={14} />, shortcut: keyHint('split'),disabled: !underPlayhead.length || splitting, hint: t('selectionBar.splitNone'), onSelect: () => { void splitAll(); },});}@@ -3727,7 +3724,7 @@ export const Timeline = React.memo(function Timeline({}if (barKind === 'range' && range) {if (onPlayRange) out.push({ id: 'play-range', label: t('selectionBar.playRange'), icon: <Play size={14} />, onSelect: () => onPlayRange(range) });- if (onRangeChange) out.push({ id: 'clear-range', label: t('selectionBar.clearRange'), icon: <X size={14} />, shortcut: 'X', onSelect: () => onRangeChange(null) });+ if (onRangeChange) out.push({ id: 'clear-range', label: t('selectionBar.clearRange'), icon: <X size={14} />, shortcut: keyHint('clear-range'), onSelect: () => onRangeChange(null) });return out;}const picked = selectedBlocks;@@ -3735,7 +3732,7 @@ export const Timeline = React.memo(function Timeline({const lockedHint = t('timeline.trackLocked');if (onSplit) {out.push({- id: 'split', label: t('timeline.menuSplitHere'), icon: <Scissors size={14} />, shortcut: shortcutHint('B', { mod: true }),+ id: 'split', label: t('timeline.menuSplitHere'), icon: <Scissors size={14} />, shortcut: keyHint('split'),disabled: !underPlayhead.length || splitting, hint: pickedLocked ? lockedHint : t('timeline.menuSplitOutside'), onSelect: () => { void splitAll(); },});}@@ -3767,7 +3764,7 @@ export const Timeline = React.memo(function Timeline({}if (onRemove || onRemoveMany || onEditOps) {out.push({- id: 'delete', label: t('timeline.removeBlock'), icon: <Trash2 size={14} />, shortcut: '⌫', danger: true,+ id: 'delete', label: t('timeline.removeBlock'), icon: <Trash2 size={14} />, shortcut: keyHint('remove'), danger: true,disabled: pickedLocked || !picked.some((b) => b.loc), hint: lockedHint,onSelect: () => { void magnetRemove(picked); },});@@ -3783,7 +3780,7 @@ export const Timeline = React.memo(function Timeline({})();/* first, always: the clips and the range, or the moment of the point */const barLead = barKind && onReferSelection ? {- id: 'refer', label: t('selectionBar.addToChat'), icon: <MessageSquarePlus size={14} />, shortcut: shortcutHint('L', { mod: true }),+ id: 'refer', label: t('selectionBar.addToChat'), icon: <MessageSquarePlus size={14} />, shortcut: keyHint('refer'),onSelect: () => onReferSelection(barKind === 'point'? { blocks: [], range: null, atMs: timeMsRef.current }: { blocks: selectedBlocks, range: range ?? null, atMs: null }),@@ -3862,7 +3859,7 @@ export const Timeline = React.memo(function Timeline({onClick={() => history.step('undo')}disabled={!history.canUndo}label={t('history.undo')}- hint={shortcutHint('Z', { mod: true })}+ hint={keyHint('undo')}><Undo2 size={16} /></ToolButton>@@ -3870,7 +3867,7 @@ export const Timeline = React.memo(function Timeline({onClick={() => history.step('redo')}disabled={!history.canRedo}label={t('history.redo')}- hint={shortcutHint('Z', { mod: true, shift: true })}+ hint={keyHint('redo')}><Redo2 size={16} /></ToolButton>@@ -3882,7 +3879,7 @@ export const Timeline = React.memo(function Timeline({) : null}{onAddMarker ? (- <ToolButton onClick={onAddMarker} disabled={!playable} label={t('editorTools.markerAdd')} hint={shortcutHint('M')}>+ <ToolButton onClick={onAddMarker} disabled={!playable} label={t('editorTools.markerAdd')} hint={keyHint('add-marker')}><MarkerGlyph size={16} /></ToolButton>) : null}@@ -3893,7 +3890,7 @@ export const Timeline = React.memo(function Timeline({/* lit only with a selection: a disabled button already says "this acts on the selection" */disabled={!selectedBlocks.some((b) => drag.can(b).resize)}label={t('timeline.split')}- hint={shortcutHint('B', { mod: true })}+ hint={keyHint('split')}><Scissors size={16} /></ToolButton>@@ -3963,7 +3960,7 @@ export const Timeline = React.memo(function Timeline({onClick={() => zoomBy(1 / ZOOM_STEP)}disabled={!(hasLanes && spanMs > 0) || viewZoom <= zoomMinOf(spanMs)}label={t('timeline.zoomOut')}- hint={shortcutHint('-', { mod: true })}+ hint={keyHint('zoom-out')}><ZoomOut size={15} /></ToolButton>@@ -3985,7 +3982,7 @@ export const Timeline = React.memo(function Timeline({onClick={() => zoomBy(ZOOM_STEP)}disabled={!(hasLanes && spanMs > 0) || viewZoom >= zoomMaxOf(spanMs)}label={t('timeline.zoomIn')}- hint={shortcutHint('+', { mod: true })}+ hint={keyHint('zoom-in')}><ZoomIn size={15} /></ToolButton>@@ -4336,7 +4333,7 @@ export const Timeline = React.memo(function Timeline({{shownRange && hasLanes ? (() => {const fromX = shownRange.startMs * pxPerMs - scrollLeft;const width = Math.max(1, (shownRange.endMs - shownRange.startMs) * pxPerMs);- const label = rangeLabel(shownRange, rangeRef ? shortcutHint('L', { mod: true }) : undefined);+ const label = rangeLabel(shownRange, rangeRef ? keyHint('refer') : undefined);return (<><div className="pointer-events-none absolute z-[24] overflow-hidden" style={{ left: headW, right: 0, top: TOOLBAR_H, bottom: H_SCROLL_H }}>@@ -4601,11 +4598,12 @@ function ModePicker({mode, onPick,}: { mode: TimelineMode; onPick: (m: TimelineMode) => void }) {const t = useT();+ const keyHint = useKeyHint();const [open, setOpen] = React.useState(false);- const items: { id: TimelineMode; label: string; key: string; icon: React.ReactNode }[] = [- { id: 'select', label: t('timeline.modeSelect'), key: 'A', icon: <MousePointer2 size={16} /> },- { id: 'split', label: t('timeline.modeSplit'), key: 'B', icon: <SplitSquareHorizontal size={16} /> },+ const items: { id: TimelineMode; label: string; key: string | undefined; icon: React.ReactNode }[] = [+ { id: 'select', label: t('timeline.modeSelect'), key: keyHint('select-mode'), icon: <MousePointer2 size={16} /> },+ { id: 'split', label: t('timeline.modeSplit'), key: keyHint('split-mode'), icon: <SplitSquareHorizontal size={16} /> },];const current = items.find((i) => i.id === mode) ?? items[0]!;@@ -4616,7 +4614,7 @@ function ModePicker({<ToolButtononClick={() => onPick(mode === 'split' ? 'select' : 'split')}label={mode === 'split' ? t('timeline.modeSelect') : t('timeline.modeSplit')}- hint={mode === 'split' ? 'A' : 'B'}+ hint={mode === 'split' ? keyHint('select-mode') : keyHint('split-mode')}>{current.icon}</ToolButton>diff --git a/packages/openfilm/studio/ui/src/components/ViewerBar.tsx b/packages/openfilm/studio/ui/src/components/ViewerBar.tsxindex 46ea8f4..3858af7 100644--- a/packages/openfilm/studio/ui/src/components/ViewerBar.tsx+++ b/packages/openfilm/studio/ui/src/components/ViewerBar.tsx@@ -9,6 +9,7 @@ import { formatTimecode, useTimecodeFps } from '@/lib/timecode';import { PANE_BTN, PANE_ICON } from './dock-pane-bar';import { LiveText, type PlaybackClock } from './LiveTime';import { Tooltip } from './Tooltip';+import { useKeyHint } from '@/lib/keymap-store';/** The bar's buttons: the pane-bar size (22×22, icon 14) plus a keyboard focus ring (Tab must show where it is). */const VIEW_BTN = `${PANE_BTN} outline-none focus-visible:ring-1 focus-visible:ring-[var(--accent)]`;@@ -37,6 +38,7 @@ export function ViewerBar({loop?: { on: boolean; ranged: boolean; onToggle: () => void } | null;}) {const t = useT();+ const keyHint = useKeyHint();/* frames are counted at the project's rate: shown anew when it changes */useTimecodeFps();const playable = totalMs > 0;@@ -54,7 +56,7 @@ export function ViewerBar({{' / '}{formatTimecode(totalMs, { hours })}</span></span>- <Tooltip label={playing ? t('viewer.pause') : t('viewer.play')} shortcut="Space">+ <Tooltip label={playing ? t('viewer.pause') : t('viewer.play')} shortcut={keyHint('play-pause')}><buttontype="button"onClick={onPlayPause}@@ -69,7 +71,7 @@ export function ViewerBar({</Tooltip><span className="flex items-center justify-end gap-1">{loop ? (- <Tooltip label={t(loop.ranged ? 'viewer.loopRange' : 'viewer.loopFilm')} shortcut="⇧L">+ <Tooltip label={t(loop.ranged ? 'viewer.loopRange' : 'viewer.loopFilm')} shortcut={keyHint('loop')}><buttontype="button"onClick={loop.onToggle}diff --git a/packages/openfilm/studio/ui/src/components/settings/SettingsModal.tsx b/packages/openfilm/studio/ui/src/components/settings/SettingsModal.tsxindex b05e19f..fb44d65 100644--- a/packages/openfilm/studio/ui/src/components/settings/SettingsModal.tsx+++ b/packages/openfilm/studio/ui/src/components/settings/SettingsModal.tsx@@ -9,8 +9,6 @@ import React from 'react';import { createPortal } from 'react-dom';import { X, Settings2, Keyboard, Sun, Moon, Monitor, Plug, Boxes, Bot, Search, SquareTerminal, Loader2, SlidersHorizontal } from 'lucide-react';import { LANGUAGES, phrasesUnder, useLanguage, useLanguageChoice, useT, type LanguageChoice } from '@/i18n';-import { shortcutHint } from '@/lib/shortcut-hint';-import { SHORTCUTS, type ShortcutKey } from '@/lib/timeline-keys';import { studioHost, type HostDeveloper, type HostUpdateState } from '@/lib/host';import { showWhatsNew } from '@/lib/whats-new';import { usePreviewPrefs, writePreviewPref } from '@/lib/preview-prefs';@@ -22,6 +20,7 @@ import { DiagnosticsGroup } from './DiagnosticsGroup';import { ModelsSection } from './ModelsSection';import { ProvidersSection } from './ProvidersSection';import { SettingsSelect } from './SettingsSelect';+import { ShortcutsSection } from './ShortcutsSection';import { SettingsButton, SettingsGroup, SettingsItem, SettingsPage, SettingsSegmented, SettingsSwitch } from './ui';import { useThemeMode, type ThemeMode } from './theme';import { StorageGroup } from './StorageGroup';@@ -510,62 +509,3 @@ function DeveloperSection() {</SettingsPage>);}--/**- * The keys, as lib/timeline-keys lists them beside the code that reads them (playback, marks, editing, the view),- * then the picture's own (FilmStageSelect).- */-function ShortcutsSection() {- const t = useT();- const mac = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform);- const alt = mac ? '⌥' : 'Alt';- const k = (key: string, opts?: { mod?: boolean; shift?: boolean }) => shortcutHint(key, opts);- /* a key as this platform writes it: ⌘⇧B on a Mac, Ctrl+Shift+B elsewhere; ⌫ is Backspace off a Mac */- const keyText = (key: ShortcutKey): string => {- const name = !mac && key.key === '⌫' ? 'Backspace' : key.key;- const mods = [key.ctrl ? (mac ? '⌃' : 'Ctrl') : '', key.mod ? (mac ? '⌘' : 'Ctrl') : '', key.alt ? alt : '', key.shift ? (mac ? '⇧' : 'Shift') : ''].filter(Boolean);- return mac ? `${mods.join('')}${name}` : [...mods, name].filter(Boolean).join('+');- };-- const groups: Array<{ title: string; items: Array<{ label: string; keys: string[] }> }> = [- ...(studioHost?.settings ? [{ title: t('settings.sections.general'), items: [{ label: t('settings.title'), keys: [k(',', { mod: true })] }] }] : []),- ...SHORTCUTS.map((group) => ({- title: t(`settings.shortcuts.${group.group}`),- items: group.rows.map((row) => ({ label: t(`settings.shortcuts.${row.label}`), keys: row.keys.map(keyText) })),- })),- {- title: t('settings.shortcuts.groupCanvas'),- items: [- { label: t('settings.shortcuts.nudge'), keys: ['↑', '↓', '←', '→'] },- { label: t('settings.shortcuts.nudgeFast'), keys: [k('↑', { shift: true }), k('↓', { shift: true }), k('←', { shift: true }), k('→', { shift: true })] },- { label: t('settings.shortcuts.editText'), keys: ['Enter'] },- { label: t('settings.shortcuts.commitText'), keys: [k('Enter', { mod: true })] },- { label: t('settings.shortcuts.cancelText'), keys: ['Esc'] },- ],- },- ];-- return (- <SettingsPage note={t('settings.shortcuts.hint')}>- {groups.map((group) => (- <SettingsGroup key={group.title} title={group.title}>- {group.items.map((item) => (- <div key={item.label} className="flex min-h-[52px] items-center justify-between gap-6 py-2.5">- <span className="text-[15px] text-[var(--text)]">{item.label}</span>- <span className="flex max-w-[55%] shrink-0 flex-wrap items-center justify-end gap-1">- {item.keys.map((key, j) => (- <React.Fragment key={key}>- {j > 0 ? <span className="px-0.5 text-[13px] text-[var(--text-faint)]">/</span> : null}- <kbd className="inline-flex h-7 min-w-7 items-center justify-center rounded-[6px] border border-[var(--border)] px-1.5 font-sans text-[13px] text-[var(--text-dim)]">- {key}- </kbd>- </React.Fragment>- ))}- </span>- </div>- ))}- </SettingsGroup>- ))}- </SettingsPage>- );-}diff --git a/packages/openfilm/studio/ui/src/components/settings/ShortcutsSection.tsx b/packages/openfilm/studio/ui/src/components/settings/ShortcutsSection.tsxnew file mode 100644index 0000000..8dbd5f0--- /dev/null+++ b/packages/openfilm/studio/ui/src/components/settings/ShortcutsSection.tsx@@ -0,0 +1,291 @@+/**+ * Settings › Keyboard shortcuts: the editor's actions (lib/keymap) in tabs (Timeline, Player, Basic, Other), two+ * columns of an action and its keys, and the scheme they come from: OpenFilm, Premiere Pro, Final Cut Pro X, or one of+ * three custom ones.+ *+ * A built-in scheme is read-only: clicking a key there copies the scheme into a free custom slot first, and says so.+ * In a custom scheme a click records the next keys pressed (Esc cancels); keys another action has are offered to it+ * only after "Replace". Restore defaults sets the custom scheme back to the scheme it was copied from. Nothing is kept+ * until Save; Cancel lets the changes go.+ */+import React from 'react';+import { X } from 'lucide-react';+import { useT } from '@/i18n';+import { studioHost } from '@/lib/host';+import {+ ACTIONS, BUILT_IN_SCHEMES, comboCaps, comboOf, conflictOf, copyOf, CUSTOM_SLOTS, editable, FIXED_KEYS, isBuiltIn, KEY_TABS,+ keymapFor, restoreDefaults, withKey, withoutKeys, type ActionId, type CustomSlot, type KeyPrefs, type KeyTab, type SchemeId,+} from '@/lib/keymap';+import { MAC, saveKeyPrefs, useKeyPrefs } from '@/lib/keymap-store';+import { SettingsSelect } from './SettingsSelect';+import { SettingsButton, SettingsPage, SettingsSegmented, settingsError } from './ui';++/** The built-in schemes are named for the app whose keys they give. */+const SCHEME_NAMES: Record<(typeof BUILT_IN_SCHEMES)[number], string> = { openfilm: 'OpenFilm', premiere: 'Premiere Pro', fcp: 'Final Cut Pro X' };++/** A row: its words and keys; `held`: combinations pressed while another is held (K, then J). */+type Row = { id: string; label: string; keys: readonly string[]; action?: ActionId; held?: readonly (readonly string[])[] };++/** A combination as key caps: its modifiers, then its key. */+function Caps({ combo }: { combo: string }) {+ return (+ <span className="inline-flex items-center gap-1">+ {comboCaps(combo, MAC).map((cap, i) => (+ <kbd key={i} className="inline-flex h-6 min-w-6 items-center justify-center rounded-[5px] border border-[var(--border)] bg-[var(--dock-pane)] px-1.5 font-sans text-[12.5px] leading-none text-[var(--text-dim)]">+ {cap}+ </kbd>+ ))}+ </span>+ );+}++/** An action's keys, one combination after another. */+function KeyList({ keys, none }: { keys: readonly string[]; none: string }) {+ if (!keys.length) return <span className="text-[13px] text-[var(--text-faint)]">{none}</span>;+ return (+ <span className="flex flex-wrap items-center justify-end gap-x-1.5 gap-y-1">+ {keys.map((combo, i) => (+ <React.Fragment key={combo}>+ {i > 0 ? <span className="text-[12px] text-[var(--text-faint)]">/</span> : null}+ <Caps combo={combo} />+ </React.Fragment>+ ))}+ </span>+ );+}++export function ShortcutsSection() {+ const t = useT();+ const saved = useKeyPrefs();+ const [draft, setDraft] = React.useState<KeyPrefs>(saved);+ const [tab, setTab] = React.useState<KeyTab>('timeline');+ const [recording, setRecording] = React.useState<ActionId | null>(null);+ const [pending, setPending] = React.useState<{ id: ActionId; combo: string; other: ActionId } | null>(null);+ const [notice, setNotice] = React.useState<string | null>(null);+ const [error, setError] = React.useState<string | null>(null);+ const [saving, setSaving] = React.useState(false);+ const dirty = JSON.stringify(draft) !== JSON.stringify(saved);+ /* the schemes kept changed elsewhere while nothing here is changed: show them */+ const dirtyRef = React.useRef(dirty);+ dirtyRef.current = dirty;+ React.useEffect(() => { if (!dirtyRef.current) setDraft(saved); }, [saved]);++ const schemeName = React.useCallback((id: SchemeId) => (isBuiltIn(id) ? SCHEME_NAMES[id] : t('settings.shortcuts.customName').replace('{n}', id.slice(-1))), [t]);+ const actionName = React.useCallback((id: ActionId) => t(`settings.shortcuts.actions.${id}`), [t]);+ const keymap = React.useMemo(() => keymapFor(draft, draft.scheme, MAC), [draft]);+ const custom = isBuiltIn(draft.scheme) ? null : draft.scheme as CustomSlot;++ /* a key pressed while recording is the action's new key; Esc stops recording, a click anywhere else too */+ const recordRef = React.useRef<(combo: string) => void>(() => {});+ recordRef.current = (combo) => {+ if (!recording || !custom) return;+ setRecording(null);+ const other = conflictOf(keymap, recording, combo, MAC);+ if (other) setPending({ id: recording, combo, other });+ else setDraft((d) => withKey(d, custom, recording, combo, MAC));+ };+ React.useEffect(() => {+ if (!recording) return;+ const onKey = (e: KeyboardEvent) => {+ if (e.key === 'Tab') return;+ e.preventDefault();+ e.stopImmediatePropagation();+ if (e.key === 'Escape' && !e.metaKey && !e.ctrlKey && !e.altKey && !e.shiftKey) { setRecording(null); return; }+ const combo = comboOf(e, MAC);+ if (combo) recordRef.current(combo);+ };+ const onDown = (e: PointerEvent) => {+ if (!(e.target as Element | null)?.closest?.(`[data-recording]`)) setRecording(null);+ };+ window.addEventListener('keydown', onKey, true);+ window.addEventListener('pointerdown', onDown, true);+ return () => { window.removeEventListener('keydown', onKey, true); window.removeEventListener('pointerdown', onDown, true); };+ }, [recording]);++ const chooseScheme = (id: SchemeId) => {+ setRecording(null);+ setPending(null);+ setError(null);+ if (!isBuiltIn(id) && !draft.custom[id]) {+ /* an empty custom slot starts as a copy of the scheme shown */+ setDraft({ scheme: id, custom: { ...draft.custom, [id]: copyOf(draft, draft.scheme, MAC) } });+ setNotice(t('settings.shortcuts.started').replace('{to}', schemeName(id)).replace('{from}', schemeName(draft.scheme)));+ return;+ }+ setDraft({ ...draft, scheme: id });+ setNotice(null);+ };++ const startRecording = (id: ActionId) => {+ setPending(null);+ setError(null);+ if (custom) { setNotice(null); setRecording(id); return; }+ const ready = editable(draft, MAC);+ if (!ready) { setNotice(t('settings.shortcuts.full')); return; }+ setDraft(ready.prefs);+ setNotice(t('settings.shortcuts.copied').replace('{from}', schemeName(draft.scheme)).replace('{to}', schemeName(ready.slot)));+ setRecording(id);+ };++ const replace = () => {+ if (!pending || !custom) return;+ setDraft((d) => withKey(d, custom, pending.id, pending.combo, MAC));+ setPending(null);+ };++ const restore = () => {+ if (!custom) return;+ setRecording(null);+ setPending(null);+ setNotice(null);+ setDraft((d) => restoreDefaults(d, custom, MAC));+ };++ const cancel = () => {+ setDraft(saved);+ setRecording(null);+ setPending(null);+ setNotice(null);+ setError(null);+ };++ const save = async () => {+ setRecording(null);+ setPending(null);+ setSaving(true);+ try {+ await saveKeyPrefs(draft);+ setNotice(null);+ setError(null);+ } catch (e) {+ setError(t('settings.shortcuts.saveFailed').replace('{error}', e instanceof Error ? e.message : String(e)));+ } finally {+ setSaving(false);+ }+ };++ const actionRows: Row[] = ACTIONS+ .filter((a) => a.tab === tab && (a.id !== 'refer' || studioHost?.refer))+ .map((a) => ({ id: a.id, label: actionName(a.id), keys: keymap[a.id], action: a.id }));+ /* Other: the keys that are always the same, after the actions */+ const fixedRows: Row[] = tab !== 'other' ? [] : [+ ...(studioHost?.settings ? [{ id: 'settings', label: t('settings.title'), keys: ['mod+,'] }] : []),+ ...(() => {+ /* stop held, then back or forward: a frame that way */+ const stop = keymap['shuttle-stop'][0];+ const held = [keymap['shuttle-back'][0], keymap['shuttle-forward'][0]].flatMap((step) => (stop && step ? [[stop, step]] : []));+ return [{ id: 'shuttle-hold', label: t('settings.shortcuts.shuttleHold'), keys: [], held }];+ })(),+ ...FIXED_KEYS.map((row) => ({ id: row.label, label: t(`settings.shortcuts.${row.label}`), keys: row.keys })),+ ];++ const renderRow = (row: Row) => {+ const id = row.action;+ const on = id && recording === id;+ const caps = row.held+ ? (+ <span className="flex flex-wrap items-center justify-end gap-x-1.5 gap-y-1">+ {row.held.map((combos, i) => (+ <React.Fragment key={combos.join(' ')}>+ {i > 0 ? <span className="text-[12px] text-[var(--text-faint)]">/</span> : null}+ <span className="inline-flex items-center gap-1">+ {combos.flatMap((combo, j) => [+ ...(j > 0 ? [<span key={`p${j}`} className="text-[12px] text-[var(--text-faint)]">+</span>] : []),+ <Caps key={j} combo={combo} />,+ ])}+ </span>+ </React.Fragment>+ ))}+ </span>+ )+ : <KeyList keys={row.keys} none={t('settings.shortcuts.none')} />;+ const conflict = pending && pending.id === id ? pending : null;+ return (+ <div key={row.id} className="py-1">+ <div className="group flex min-h-[36px] items-center justify-between gap-4">+ <span className="min-w-0 text-[14px] leading-snug text-[var(--text)]">{row.label}</span>+ {id ? (+ <span className="flex shrink-0 items-center gap-1">+ {custom && row.keys.length && !on ? (+ <button type="button" aria-label={`${t('settings.shortcuts.clear')}: ${row.label}`} title={t('settings.shortcuts.clear')}+ onClick={() => { setPending(null); setDraft((d) => withoutKeys(d, custom, id, MAC)); }}+ className="flex h-6 w-6 items-center justify-center rounded-[5px] text-[var(--text-faint)] opacity-0 transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)] focus-visible:opacity-100 group-hover:opacity-100">+ <X size={13} />+ </button>+ ) : null}+ <button type="button" data-recording={on ? '' : undefined}+ aria-label={`${row.label}: ${custom ? t('settings.shortcuts.change') : t('settings.shortcuts.editCopy')}`}+ title={custom ? t('settings.shortcuts.change') : t('settings.shortcuts.editCopy')}+ onClick={() => (on ? setRecording(null) : startRecording(id))}+ className={`flex min-h-8 max-w-[220px] items-center justify-end rounded-[7px] px-2 py-1 transition ${+ on ? 'bg-[var(--bg-active)] ring-1 ring-[var(--accent)]' : pending?.id === id ? 'ring-1 ring-[var(--err)]' : 'hover:bg-[var(--bg-hover)]'+ }`}>+ {on ? <span className="text-[13px] text-[var(--text-muted)]">{t('settings.shortcuts.recording')}</span> : conflict ? <Caps combo={conflict.combo} /> : caps}+ </button>+ </span>+ ) : <span className="flex max-w-[220px] shrink-0 justify-end px-2">{caps}</span>}+ </div>+ {/* the keys pressed are another action's: replace, or keep things as they are */}+ {conflict ? (+ <div role="alert" className="mb-1 mt-1.5 flex flex-col gap-2 rounded-[8px] border border-[var(--border)] bg-[var(--dock-pane)] px-3 py-2.5">+ <span className="text-[13.5px] leading-snug text-[var(--text)]">+ {t('settings.shortcuts.conflict').replace('{keys}', comboCaps(conflict.combo, MAC).join(MAC ? '' : '+')).replace('{action}', actionName(conflict.other))}+ </span>+ <span className="flex justify-end gap-2">+ <SettingsButton className="h-8" onClick={() => setPending(null)}>{t('settings.shortcuts.cancel')}</SettingsButton>+ <SettingsButton className="h-8" variant="primary" onClick={replace}>{t('settings.shortcuts.replace')}</SettingsButton>+ </span>+ </div>+ ) : null}+ </div>+ );+ };++ /* two columns, filled top to bottom, the left one first */+ const columns = (rows: Row[]) => {+ const half = Math.ceil(rows.length / 2);+ return [rows.slice(0, half), rows.slice(half)];+ };++ const schemeOptions = [...BUILT_IN_SCHEMES, ...CUSTOM_SLOTS].map((id) => ({ value: id as SchemeId, label: schemeName(id) }));++ return (+ <SettingsPage note={t('settings.shortcuts.hint')}>+ <div className="mb-4 flex flex-wrap items-center justify-between gap-3">+ <SettingsSegmented<KeyTab>+ label={t('settings.sections.shortcuts')}+ value={tab}+ onChange={(next) => { setTab(next); setRecording(null); }}+ options={KEY_TABS.map((id) => ({ value: id, label: t(`settings.shortcuts.tabs.${id}`) }))}+ />+ <SettingsSelect<SchemeId> label={t('settings.shortcuts.scheme')} value={draft.scheme} options={schemeOptions} onChange={chooseScheme} width={200} />+ </div>+ {notice ? <p role="status" className="mb-3 text-[13.5px] leading-relaxed text-[var(--text-muted)]">{notice}</p> : null}+ <div className="@container rounded-[12px] bg-[var(--fill-tsp)] px-5 py-3">+ <div className="grid grid-cols-1 gap-x-8 @xl:grid-cols-2">+ {columns(actionRows).map((rows, i) => (+ <div key={i} className={`flex flex-col ${i === 1 ? '@xl:border-l @xl:border-[var(--border)] @xl:pl-8' : ''}`}>{rows.map(renderRow)}</div>+ ))}+ </div>+ {fixedRows.length ? (+ <>+ <p className="mt-3 border-t border-[var(--border)] pt-3 text-[13px] text-[var(--text-faint)]">{t('settings.shortcuts.fixed')}</p>+ <div className="grid grid-cols-1 gap-x-8 @xl:grid-cols-2">+ {columns(fixedRows).map((rows, i) => (+ <div key={i} className={`flex flex-col ${i === 1 ? '@xl:border-l @xl:border-[var(--border)] @xl:pl-8' : ''}`}>{rows.map(renderRow)}</div>+ ))}+ </div>+ </>+ ) : null}+ </div>+ {error ? <p className={`mt-3 ${settingsError}`}>{error}</p> : null}+ <div className="mt-5 flex items-center justify-between gap-3">+ <SettingsButton onClick={restore} disabled={!custom}>{t('settings.shortcuts.restore')}</SettingsButton>+ <span className="flex gap-2">+ <SettingsButton onClick={cancel} disabled={!dirty || saving}>{t('settings.shortcuts.cancel')}</SettingsButton>+ <SettingsButton variant="primary" onClick={() => { void save(); }} disabled={!dirty || saving}>{t('settings.shortcuts.save')}</SettingsButton>+ </span>+ </div>+ </SettingsPage>+ );+}diff --git a/packages/openfilm/studio/ui/src/components/stage-menu.tsx b/packages/openfilm/studio/ui/src/components/stage-menu.tsxindex 00083d3..6a66d37 100644--- a/packages/openfilm/studio/ui/src/components/stage-menu.tsx+++ b/packages/openfilm/studio/ui/src/components/stage-menu.tsx@@ -15,6 +15,8 @@ import type { ContextMenuEntry } from '@/components/ContextMenu';import type { FilmDoc } from '@/lib/film';import type { OverrideGeometry } from '@/lib/film-overrides';import { shortcutHint } from '@/lib/shortcut-hint';+import { hintOf } from '@/lib/keymap';+import { currentKeymap, MAC } from '@/lib/keymap-store';import type { AlignEdge } from '@/lib/stage-gesture';import { recoverableLayers, type RecoverableLayer } from '@/lib/stage-layers';import type { StageElement } from '@/lib/stage-types';@@ -158,7 +160,7 @@ export function stageMenu(el: StageElement, ctx: StageMenuContext, actions: Stagm.push({ id: 'export', label: t('timeline.menuExportClip'), icon: <Download size={14} />, onSelect: () => exportClip(id) });}m.sep();- m.push({ id: 'delete', label: t('timeline.removeBlock'), icon: <Trash2 size={14} />, danger: true, shortcut: '⌫', disabled: trackLocked, hint: lockedHint, onSelect: () => clip.remove(clipLoc) });+ m.push({ id: 'delete', label: t('timeline.removeBlock'), icon: <Trash2 size={14} />, danger: true, shortcut: hintOf(currentKeymap(), 'remove', MAC), disabled: trackLocked, hint: lockedHint, onSelect: () => clip.remove(clipLoc) });return m.done();}diff --git a/packages/openfilm/studio/ui/src/components/use-editor-tools.tsx b/packages/openfilm/studio/ui/src/components/use-editor-tools.tsxindex 5f52ad2..a768b4d 100644--- a/packages/openfilm/studio/ui/src/components/use-editor-tools.tsx+++ b/packages/openfilm/studio/ui/src/components/use-editor-tools.tsx@@ -19,7 +19,8 @@ import type { ClipEdit } from '@/lib/film-clip-edits';import { heardClips, toggleSolo } from '@/lib/solo';import type { EditModel } from '@/lib/timeline-edit';import { readTimelinePrefs, switchesOf } from '@/lib/timeline-prefs';-import type { KeyCommand } from '@/lib/timeline-keys';+import type { ActionId } from '@/lib/keymap';+import { useKeyHint } from '@/lib/keymap-store';import type { TimelineBlock, TimelineTrack } from '@/lib/timeline-layout';import type { MediaListing } from '@/lib/workspace-resources';import { ownTrackHeight, sizeOf, trackHeightsOf, withTrackHeight, TRACK_SIZES, type TrackSize } from '@/lib/track-heights';@@ -68,6 +69,7 @@ export function useEditorTools({pickFile?: (family: ReplaceFamily) => Promise<string | null>;}) {const t = useT();+ const keyHint = useKeyHint();/* what can take a clip's place: the media and the pages */const media = React.useMemo<readonly (ReplaceFile & { name: string })[]>(() => [...(listing?.files ?? []).filter((f) => f.kind !== 'other'), ...(listing?.pages ?? [])],@@ -139,8 +141,8 @@ export function useEditorTools({onNamed,}), [seek, saveMarkers, naming, onNamed]);- /** The editor's keys for markers (lib/timeline-keys): true when it was one. */- const onKey = React.useCallback((cmd: KeyCommand): boolean => {+ /** The editor's keys for markers (lib/keymap): true when it was one. */+ const onKey = React.useCallback((cmd: ActionId): boolean => {if (cmd === 'add-marker') { addMarkerHere(); return true; }if (cmd === 'next-marker' || cmd === 'prev-marker') { goMarker(cmd === 'next-marker' ? 1 : -1); return true; }return false;@@ -360,10 +362,10 @@ export function useEditorTools({submenu: choices,});const on = atMs >= one.startMs && atMs < one.endMs;- out.push({ id: 'clip-marker', label: t('editorTools.markerAddClip'), icon: <MarkerGlyph size={14} />, shortcut: 'M', disabled: !on, hint: t('editorTools.freezeOutside'), onSelect: () => addMarkerHere(one) });+ out.push({ id: 'clip-marker', label: t('editorTools.markerAddClip'), icon: <MarkerGlyph size={14} />, shortcut: keyHint('add-marker'), disabled: !on, hint: t('editorTools.freezeOutside'), onSelect: () => addMarkerHere(one) });}return out;- }, [measuring, media, normalize, freeze, replaceEntries, addMarkerHere, timeRef, t]);+ }, [measuring, media, normalize, freeze, replaceEntries, addMarkerHere, timeRef, t, keyHint]);/* ── what the timeline draws ── */const clipMarkersByTrack = React.useMemo(() => {@@ -382,8 +384,8 @@ export function useEditorTools({const onAddMarker = React.useCallback(() => addMarkerHere(), [addMarkerHere]);/* the ruler's own menu: a marker there (on the film), as M puts one at the playhead */const rulerMenu = React.useCallback((atMs: number): ContextMenuEntry[] => [- { id: 'add-marker', label: t('editorTools.markerAdd'), icon: <MarkerGlyph size={14} />, shortcut: 'M', onSelect: () => addMarkerHere(null, atMs) },- ], [addMarkerHere, t]);+ { id: 'add-marker', label: t('editorTools.markerAdd'), icon: <MarkerGlyph size={14} />, shortcut: keyHint('add-marker'), onSelect: () => addMarkerHere(null, atMs) },+ ], [addMarkerHere, t, keyHint]);const trackOverlay = React.useCallback((track: TimelineTrack, pxPerMs: number) => {const here = clipMarkersByTrack.get(track.lane);return here ? <ClipMarkers placed={here} pxPerMs={pxPerMs} height={track.height ?? ownTrackHeight(track)} actions={markerActions} /> : null;diff --git a/packages/openfilm/studio/ui/src/i18n/en.ts b/packages/openfilm/studio/ui/src/i18n/en.tsindex 4a7b5be..735bb91 100644--- a/packages/openfilm/studio/ui/src/i18n/en.ts+++ b/packages/openfilm/studio/ui/src/i18n/en.ts@@ -1687,69 +1687,96 @@ export const en = {preview: 'Preview',},shortcuts: {- groupMarks: "In and out",- groupView: "Timeline view",- shuttle: "Play backward / stop / play forward (again: faster)",- shuttleFrame: "Step one frame back / forward (hold K)",- cutStep: "Go to the previous / next cut",- markIn: "Mark in at the playhead",- markOut: "Mark out at the playhead",- clearMarks: "Clear in and out",- rangeClip: "Set in and out to the selected clips",- goInOut: "Go to in / out",- playRange: "Play from in to out",- loop: "Loop playback (the range, else the film)",- insertSource: "Source viewer: insert at the playhead",- overwriteSource: "Source viewer: overwrite at the playhead",+ hint: "Keys follow your operating system, and pause while you type. Pick a scheme to use another editor's keys, or change any key in a custom scheme.",addMedia: "Add the media picked to the timeline",- addMarker: "Add a marker at the playhead (on the selected clip when it is there)",- markerStep: "Go to the next / previous marker",- splitAll: "Split every unlocked track at the playhead",- rippleStart: "Ripple trim the start to the playhead",- rippleEnd: "Ripple trim the end to the playhead",- cut: "Cut selected clips",- duplicate: "Duplicate selected clips",- copyAttrs: "Copy a clip's attributes",- pasteAttrs: "Paste attributes onto the selected clips",- speedPanel: "Speed of the selected clip",- detachAudio: "Detach a video's sound",- nudgeClip: "Move selected clips one frame",- toggleMagnet: "Main track magnet on / off",- toggleSnap: "Snapping on / off",- toggleLinkage: "Linkage on / off",- togglePreviewAxis: "Preview axis on / off",- zoomFit: "Zoom to fit the film",- frameStep: "Move playhead one frame",- jumpStep: "Move playhead 10 frames",- rippleDelete: "Ripple delete and close the gap",- selectAll: "Select unlocked clips (click timeline first)",- selectSide: "Select every clip before / after the playhead",deselect: "Deselect",- zoomIn: "Zoom in on timeline",- zoomOut: "Zoom out on timeline",- zoomReset: "Reset timeline zoom",- groupCanvas: "Canvas elements",nudge: "Move selected element 1 px",nudgeFast: "Move selected element 10 px",editText: "Edit selected text",commitText: "Apply text edit",cancelText: "Cancel text edit / deselect",- hint: "Keys follow your operating system. Playback and editing shortcuts pause while typing. The arrow keys move the playhead; after you click the picture (a ring shows round it), they move what is selected there.",- groupPlayback: 'Playback',- groupEdit: "Timeline & editing",- playPause: 'Play / pause',- seekEnds: 'Jump to start / end',- undo: 'Undo',- redo: 'Redo',- split: "Split selected clips at the playhead (none selected: the targeted track's)",- copy: 'Copy selected clips',- paste: 'Paste at playhead',- remove: 'Delete selected clips',- selectMode: 'Select tool',- splitMode: 'Split tool',splitModeAll: 'With the split tool, click with it held: every track is cut there',editModeSwap: 'Hold while dropping a clip: it goes in between and what follows moves along',copyDrag: 'Drag a clip with it held: a copy goes where you let go, the clip stays',+ customName: "Custom {n}",+ scheme: "Shortcut scheme",+ restore: "Restore defaults",+ save: "Save",+ cancel: "Cancel",+ recording: "Press keys…",+ change: "Click to change",+ editCopy: "Click to change it in a copy",+ none: "None",+ clear: "Remove keys",+ replace: "Replace",+ copied: "{from} is built in, so it was copied to {to}. Your changes go there.",+ started: "{to} starts as a copy of {from}.",+ full: "All three custom schemes are in use. Choose one to change its keys.",+ conflict: "{keys} is already used for \"{action}\". Replace it?",+ fixed: "These keys can't be changed.",+ saveFailed: "Couldn't save the shortcuts: {error}",+ shuttleHold: "Step one frame back / forward (hold stop)",+ tabs: { timeline: "Timeline", player: "Player", basic: "Basic", other: "Other" },+ /* the editor's actions (lib/keymap ACTIONS) */+ actions: {+ "split": "Split at playhead",+ "split-all": "Split all tracks",+ "select-mode": "Select tool",+ "split-mode": "Split tool",+ "ripple-start": "Ripple trim start",+ "ripple-end": "Ripple trim end",+ "select-left": "Select all to the left",+ "select-right": "Select all to the right",+ "nudge-back": "Move clips 1 frame left",+ "nudge-forward": "Move clips 1 frame right",+ "toggle-magnet": "Main track magnet on / off",+ "toggle-snap": "Snapping on / off",+ "toggle-linkage": "Linkage on / off",+ "toggle-preview-axis": "Preview axis on / off",+ "zoom-in": "Zoom in",+ "zoom-out": "Zoom out",+ "zoom-reset": "Reset zoom",+ "zoom-fit": "Zoom to fit",+ "add-marker": "Add marker",+ "next-marker": "Next marker",+ "prev-marker": "Previous marker",+ "speed": "Clip speed",+ "detach-audio": "Detach audio",+ "play-pause": "Play / pause",+ "play-range": "Play in to out",+ "loop": "Loop playback",+ "shuttle-back": "Play backward",+ "shuttle-stop": "Stop",+ "shuttle-forward": "Play forward",+ "frame-back": "Back 1 frame",+ "frame-forward": "Forward 1 frame",+ "jump-back": "Back 10 frames",+ "jump-forward": "Forward 10 frames",+ "prev-cut": "Previous cut",+ "next-cut": "Next cut",+ "start": "Go to start",+ "end": "Go to end",+ "mark-in": "Mark in",+ "mark-out": "Mark out",+ "clear-range": "Clear in and out",+ "range-clip": "Mark selected clips",+ "go-in": "Go to in",+ "go-out": "Go to out",+ "insert-source": "Insert from source viewer",+ "overwrite-source": "Overwrite from source viewer",+ "undo": "Undo",+ "redo": "Redo",+ "cut": "Cut",+ "copy": "Copy",+ "paste": "Paste at playhead",+ "duplicate": "Duplicate",+ "remove": "Delete",+ "ripple-delete": "Ripple delete",+ "select-all": "Select all",+ "copy-attrs": "Copy attributes",+ "paste-attrs": "Paste attributes",+ "refer": "Add to chat",+ },},providers: {desc: 'Where voices, music, sound effects, transcripts, images and video come from. OpenFilm makes and edits films without any of them: connect one when your agent needs media. Which one makes each kind of media is chosen under Services.',diff --git a/packages/openfilm/studio/ui/src/i18n/es.ts b/packages/openfilm/studio/ui/src/i18n/es.tsindex 9abc224..cd70228 100644--- a/packages/openfilm/studio/ui/src/i18n/es.ts+++ b/packages/openfilm/studio/ui/src/i18n/es.ts@@ -1686,69 +1686,96 @@ export const es: Words = {preview: 'Vista previa',},shortcuts: {- groupMarks: "Entrada y salida",- groupView: "Vista de la línea de tiempo",- shuttle: "Reproducir hacia atrás / detener / reproducir (otra vez: más rápido)",- shuttleFrame: "Retroceder / avanzar un fotograma (mantén K)",- cutStep: "Ir al corte anterior / siguiente",- markIn: "Marcar entrada en el cabezal",- markOut: "Marcar salida en el cabezal",- clearMarks: "Borrar entrada y salida",- rangeClip: "Entrada y salida en los clips seleccionados",- goInOut: "Ir a la entrada / salida",- playRange: "Reproducir de la entrada a la salida",- loop: "Reproducción en bucle (el rango, si no la película)",- insertSource: "Visor de origen: insertar en el cabezal",- overwriteSource: "Visor de origen: sobrescribir en el cabezal",+ hint: "Las teclas siguen tu sistema operativo y se pausan mientras escribes. Elige un esquema para usar las teclas de otro editor, o cambia cualquier tecla en un esquema personalizado.",addMedia: "Añadir el medio elegido a la línea de tiempo",- addMarker: "Añadir un marcador en el cabezal (en el clip seleccionado si está ahí)",- markerStep: "Ir al marcador siguiente / anterior",- splitAll: "Dividir todas las pistas desbloqueadas en el cabezal",- rippleStart: "Recorte de rizo del inicio hasta el cabezal",- rippleEnd: "Recorte de rizo del final desde el cabezal",- cut: "Cortar los clips seleccionados",- duplicate: "Duplicar los clips seleccionados",- copyAttrs: "Copiar los atributos de un clip",- pasteAttrs: "Pegar atributos en los clips seleccionados",- speedPanel: "Velocidad del clip seleccionado",- detachAudio: "Separar el sonido de un vídeo",- nudgeClip: "Mover los clips seleccionados un fotograma",- toggleMagnet: "Activar / desactivar el imán de la pista principal",- toggleSnap: "Activar / desactivar el ajuste",- toggleLinkage: "Activar / desactivar la vinculación",- togglePreviewAxis: "Activar / desactivar el eje de vista previa",- zoomFit: "Ajustar el zoom a toda la película",- frameStep: 'Mover el cabezal de reproducción un fotograma',- jumpStep: "Mover el cabezal 10 fotogramas",- rippleDelete: 'Eliminar con desplazamiento y cerrar el hueco',- selectAll: 'Seleccionar los clips desbloqueados (haz clic antes en la línea de tiempo)',- selectSide: "Seleccionar todos los clips antes / después del cabezal",deselect: 'Deseleccionar',- zoomIn: 'Acercar la línea de tiempo',- zoomOut: 'Alejar la línea de tiempo',- zoomReset: 'Restablecer el zoom de la línea de tiempo',- groupCanvas: 'Elementos del lienzo',nudge: 'Mover el elemento seleccionado 1 px',nudgeFast: 'Mover el elemento seleccionado 10 px',editText: 'Editar el texto seleccionado',commitText: 'Aplicar la edición de texto',cancelText: 'Cancelar la edición de texto / deseleccionar',- hint: "Las teclas siguen tu sistema operativo. Los atajos de reproducción y edición se pausan mientras escribes. Las flechas mueven el cabezal de reproducción; tras hacer clic en la imagen (aparece un marco alrededor), mueven lo seleccionado en ella.",- groupPlayback: 'Reproducción',- groupEdit: 'Línea de tiempo y edición',- playPause: 'Reproducir / pausar',- seekEnds: 'Ir al inicio / final',- undo: 'Deshacer',- redo: 'Rehacer',- split: "Dividir los clips seleccionados en el cabezal (sin selección: el de la pista de destino)",- copy: 'Copiar los clips seleccionados',- paste: 'Pegar en el cabezal de reproducción',- remove: 'Eliminar los clips seleccionados',- selectMode: 'Herramienta de selección',- splitMode: 'Herramienta de división',splitModeAll: 'Con la herramienta de corte, haz clic con ella pulsada: se cortan todas las pistas ahí',editModeSwap: 'Mantén al soltar un clip: se intercala y lo que sigue se desplaza',copyDrag: 'Arrastra un clip con ella pulsada: una copia va donde lo sueltas y el clip se queda',+ customName: "Personalizado {n}",+ scheme: "Esquema de atajos",+ restore: "Restablecer valores",+ save: "Guardar",+ cancel: "Cancelar",+ recording: "Pulsa las teclas…",+ change: "Haz clic para cambiar",+ editCopy: "Haz clic para cambiarlo en una copia",+ none: "Ninguno",+ clear: "Quitar teclas",+ replace: "Reemplazar",+ copied: "{from} viene incluido, así que se copió en {to}. Tus cambios se guardan ahí.",+ started: "{to} empieza como una copia de {from}.",+ full: "Los tres esquemas personalizados están en uso. Elige uno para cambiar sus teclas.",+ conflict: "{keys} ya se usa para \"{action}\". ¿Reemplazarlo?",+ fixed: "Estas teclas no se pueden cambiar.",+ saveFailed: "No se pudieron guardar los atajos: {error}",+ shuttleHold: "Retroceder / avanzar un fotograma (mantén la tecla de detener)",+ tabs: { timeline: "Línea de tiempo", player: "Reproductor", basic: "Básico", other: "Otros" },+ /* the editor's actions (lib/keymap ACTIONS) */+ actions: {+ "split": "Dividir en el cabezal",+ "split-all": "Dividir todas las pistas",+ "select-mode": "Herramienta de selección",+ "split-mode": "Herramienta de división",+ "ripple-start": "Recorte de rizo del inicio",+ "ripple-end": "Recorte de rizo del final",+ "select-left": "Seleccionar todo a la izquierda",+ "select-right": "Seleccionar todo a la derecha",+ "nudge-back": "Mover clips 1 fotograma a la izquierda",+ "nudge-forward": "Mover clips 1 fotograma a la derecha",+ "toggle-magnet": "Activar / desactivar el imán de la pista principal",+ "toggle-snap": "Activar / desactivar el ajuste",+ "toggle-linkage": "Activar / desactivar la vinculación",+ "toggle-preview-axis": "Activar / desactivar el eje de vista previa",+ "zoom-in": "Acercar",+ "zoom-out": "Alejar",+ "zoom-reset": "Restablecer zoom",+ "zoom-fit": "Ajustar el zoom a toda la película",+ "add-marker": "Añadir marcador",+ "next-marker": "Marcador siguiente",+ "prev-marker": "Marcador anterior",+ "speed": "Velocidad del clip",+ "detach-audio": "Separar audio",+ "play-pause": "Reproducir / pausar",+ "play-range": "Reproducir de entrada a salida",+ "loop": "Reproducción en bucle",+ "shuttle-back": "Reproducir hacia atrás",+ "shuttle-stop": "Detener",+ "shuttle-forward": "Reproducir hacia delante",+ "frame-back": "Retroceder 1 fotograma",+ "frame-forward": "Avanzar 1 fotograma",+ "jump-back": "Retroceder 10 fotogramas",+ "jump-forward": "Avanzar 10 fotogramas",+ "prev-cut": "Corte anterior",+ "next-cut": "Corte siguiente",+ "start": "Ir al inicio",+ "end": "Ir al final",+ "mark-in": "Marcar entrada",+ "mark-out": "Marcar salida",+ "clear-range": "Borrar entrada y salida",+ "range-clip": "Marcar los clips seleccionados",+ "go-in": "Ir a la entrada",+ "go-out": "Ir a la salida",+ "insert-source": "Insertar desde el visor de origen",+ "overwrite-source": "Sobrescribir desde el visor de origen",+ "undo": "Deshacer",+ "redo": "Rehacer",+ "cut": "Cortar",+ "copy": "Copiar",+ "paste": "Pegar en el cabezal",+ "duplicate": "Duplicar",+ "remove": "Eliminar",+ "ripple-delete": "Eliminar con desplazamiento",+ "select-all": "Seleccionar todo",+ "copy-attrs": "Copiar atributos",+ "paste-attrs": "Pegar atributos",+ "refer": "Añadir al chat",+ },},providers: {desc: 'De dónde vienen las voces, la música, los efectos de sonido, las transcripciones, las imágenes y el video. OpenFilm crea y edita películas sin ninguno de ellos: conecta uno cuando tu agente necesite medios. Cuál crea cada tipo de medio se elige en Servicios.',diff --git a/packages/openfilm/studio/ui/src/i18n/ja.ts b/packages/openfilm/studio/ui/src/i18n/ja.tsindex dd6cbc3..1c1b11c 100644--- a/packages/openfilm/studio/ui/src/i18n/ja.ts+++ b/packages/openfilm/studio/ui/src/i18n/ja.ts@@ -1686,69 +1686,96 @@ export const ja: Words = {preview: 'プレビュー',},shortcuts: {- groupMarks: "イン点とアウト点",- groupView: "タイムラインの表示",- shuttle: "逆再生 / 停止 / 再生(もう一度押すと速く)",- shuttleFrame: "1 フレーム戻る / 進む(K を押したまま)",- cutStep: "前 / 次の編集点へ移動",- markIn: "再生ヘッドにイン点を設定",- markOut: "再生ヘッドにアウト点を設定",- clearMarks: "イン点とアウト点を消去",- rangeClip: "選んだクリップにイン点とアウト点を合わせる",- goInOut: "イン点 / アウト点へ移動",- playRange: "イン点からアウト点まで再生",- loop: "ループ再生(範囲があれば範囲、なければ全体)",- insertSource: "ソースビューア:再生ヘッドに挿入",- overwriteSource: "ソースビューア:再生ヘッドに上書き",+ hint: "キーはお使いの OS に従い、入力中は無効になります。スキームを選ぶとほかの編集ソフトのキーを使えます。カスタムスキームではどのキーも変更できます。",addMedia: "選択したメディアをタイムラインに追加",- addMarker: "再生ヘッドの位置にマーカーを追加(選択したクリップがそこにあればクリップに)",- markerStep: "次 / 前のマーカーへ移動",- splitAll: "ロックされていない全トラックを再生ヘッドで分割",- rippleStart: "先頭を再生ヘッドまでリップルトリム",- rippleEnd: "末尾を再生ヘッドからリップルトリム",- cut: "選択したクリップをカット",- duplicate: "選択したクリップを複製",- copyAttrs: "クリップの属性をコピー",- pasteAttrs: "選んだクリップに属性をペースト",- speedPanel: "選んだクリップの速度",- detachAudio: "動画の音声を分離",- nudgeClip: "選択したクリップを 1 フレーム移動",- toggleMagnet: "メイントラックのマグネットのオン / オフ",- toggleSnap: "スナップのオン / オフ",- toggleLinkage: "連動のオン / オフ",- togglePreviewAxis: "プレビュー軸のオン / オフ",- zoomFit: "全体が収まるようにズーム",- frameStep: '再生ヘッドを 1 フレーム移動',- jumpStep: "再生ヘッドを 10 フレーム移動",- rippleDelete: 'リップル削除して隙間を詰める',- selectAll: 'ロックされていないクリップを選択(先にタイムラインをクリック)',- selectSide: "再生ヘッドより前 / 後のクリップをすべて選択",deselect: '選択解除',- zoomIn: 'タイムラインをズームイン',- zoomOut: 'タイムラインをズームアウト',- zoomReset: 'タイムラインのズームをリセット',- groupCanvas: 'キャンバス要素',nudge: '選択した要素を 1 px 移動',nudgeFast: '選択した要素を 10 px 移動',editText: '選択したテキストを編集',commitText: 'テキストの編集を確定',cancelText: 'テキストの編集をキャンセル / 選択解除',- hint: "キーはお使いの OS に従います。入力中は再生と編集のショートカットが無効になります。矢印キーは再生ヘッドを動かします。画面をクリックすると(周りに枠が出ます)、画面で選択しているものを動かします。",- groupPlayback: '再生',- groupEdit: 'タイムラインと編集',- playPause: '再生 / 一時停止',- seekEnds: '先頭 / 末尾へ移動',- undo: '取り消す',- redo: 'やり直す',- split: "選択したクリップを再生ヘッドで分割(未選択時:ターゲットトラックのクリップ)",- copy: '選択したクリップをコピー',- paste: '再生ヘッドの位置にペースト',- remove: '選択したクリップを削除',- selectMode: '選択ツール',- splitMode: '分割ツール',splitModeAll: '分割ツールで押しながらクリック:すべてのトラックをその位置で分割',editModeSwap: 'クリップを置くときに押す:間に挿入し、後ろのクリップを送る',copyDrag: '押しながらクリップをドラッグ:離した位置にコピー、元のクリップはそのまま',+ customName: "カスタム {n}",+ scheme: "ショートカットのスキーム",+ restore: "デフォルトに戻す",+ save: "保存",+ cancel: "キャンセル",+ recording: "キーを押してください…",+ change: "クリックして変更",+ editCopy: "クリックしてコピーで変更",+ none: "なし",+ clear: "キーを削除",+ replace: "置き換える",+ copied: "{from} は組み込みのため、{to} にコピーしました。変更はそちらに保存されます。",+ started: "{to} は {from} のコピーから始まります。",+ full: "3 つのカスタムスキームはすべて使用中です。キーを変更するにはそのいずれかを選んでください。",+ conflict: "{keys} はすでに「{action}」に使われています。置き換えますか?",+ fixed: "これらのキーは変更できません。",+ saveFailed: "ショートカットを保存できませんでした:{error}",+ shuttleHold: "1 フレーム戻る / 進む(停止キーを押したまま)",+ tabs: { timeline: "タイムライン", player: "プレーヤー", basic: "基本", other: "その他" },+ /* the editor's actions (lib/keymap ACTIONS) */+ actions: {+ "split": "再生ヘッドで分割",+ "split-all": "すべてのトラックを分割",+ "select-mode": "選択ツール",+ "split-mode": "分割ツール",+ "ripple-start": "先頭をリップルトリム",+ "ripple-end": "末尾をリップルトリム",+ "select-left": "左側をすべて選択",+ "select-right": "右側をすべて選択",+ "nudge-back": "クリップを 1 フレーム左へ",+ "nudge-forward": "クリップを 1 フレーム右へ",+ "toggle-magnet": "メイントラックのマグネットのオン / オフ",+ "toggle-snap": "スナップのオン / オフ",+ "toggle-linkage": "連動のオン / オフ",+ "toggle-preview-axis": "プレビュー軸のオン / オフ",+ "zoom-in": "ズームイン",+ "zoom-out": "ズームアウト",+ "zoom-reset": "ズームをリセット",+ "zoom-fit": "全体が収まるようにズーム",+ "add-marker": "マーカーを追加",+ "next-marker": "次のマーカー",+ "prev-marker": "前のマーカー",+ "speed": "クリップの速度",+ "detach-audio": "オーディオを分離",+ "play-pause": "再生 / 一時停止",+ "play-range": "イン点からアウト点まで再生",+ "loop": "ループ再生",+ "shuttle-back": "逆再生",+ "shuttle-stop": "停止",+ "shuttle-forward": "再生",+ "frame-back": "1 フレーム戻る",+ "frame-forward": "1 フレーム進む",+ "jump-back": "10 フレーム戻る",+ "jump-forward": "10 フレーム進む",+ "prev-cut": "前のカット",+ "next-cut": "次のカット",+ "start": "先頭へ移動",+ "end": "末尾へ移動",+ "mark-in": "イン点を設定",+ "mark-out": "アウト点を設定",+ "clear-range": "イン点とアウト点を消去",+ "range-clip": "選んだクリップにイン点とアウト点を設定",+ "go-in": "イン点へ移動",+ "go-out": "アウト点へ移動",+ "insert-source": "ソースビューアから挿入",+ "overwrite-source": "ソースビューアから上書き",+ "undo": "取り消す",+ "redo": "やり直す",+ "cut": "カット",+ "copy": "コピー",+ "paste": "再生ヘッドにペースト",+ "duplicate": "複製",+ "remove": "削除",+ "ripple-delete": "リップル削除",+ "select-all": "すべて選択",+ "copy-attrs": "属性をコピー",+ "paste-attrs": "属性をペースト",+ "refer": "チャットに追加",+ },},providers: {desc: '音声、音楽、効果音、書き起こし、画像、ビデオの提供元です。OpenFilm はこれらがなくても映像の作成・編集ができます。エージェントがメディアを必要とするときに接続してください。各種メディアにどれを使うかは「サービス」で選びます。',diff --git a/packages/openfilm/studio/ui/src/i18n/ko.ts b/packages/openfilm/studio/ui/src/i18n/ko.tsindex 013906c..ad5dd3c 100644--- a/packages/openfilm/studio/ui/src/i18n/ko.ts+++ b/packages/openfilm/studio/ui/src/i18n/ko.ts@@ -1685,69 +1685,96 @@ export const ko: Words = {preview: '미리 보기',},shortcuts: {- groupMarks: "시작점과 끝점",- groupView: "타임라인 보기",- shuttle: "역재생 / 정지 / 재생 (다시 누르면 더 빠르게)",- shuttleFrame: "1프레임 뒤로 / 앞으로 (K를 누른 채)",- cutStep: "이전 / 다음 컷으로 이동",- markIn: "재생 헤드에 시작점 지정",- markOut: "재생 헤드에 끝점 지정",- clearMarks: "시작점과 끝점 지우기",- rangeClip: "선택한 클립으로 시작점과 끝점 설정",- goInOut: "시작점 / 끝점으로 이동",- playRange: "시작점부터 끝점까지 재생",- loop: "반복 재생 (범위가 있으면 범위, 없으면 전체)",- insertSource: "소스 뷰어: 재생 헤드에 삽입",- overwriteSource: "소스 뷰어: 재생 헤드에 덮어쓰기",+ hint: "키는 운영 체제에 따르며, 입력하는 동안에는 작동하지 않습니다. 스킴을 고르면 다른 편집 프로그램의 키를 쓸 수 있고, 사용자 지정 스킴에서는 어떤 키든 바꿀 수 있습니다.",addMedia: "선택한 미디어를 타임라인에 추가",- addMarker: "재생 헤드 위치에 마커 추가 (선택한 클립이 그 위에 있으면 클립에)",- markerStep: "다음 / 이전 마커로 이동",- splitAll: "잠기지 않은 모든 트랙을 재생 헤드에서 분할",- rippleStart: "시작을 재생 헤드까지 리플 트림",- rippleEnd: "끝을 재생 헤드부터 리플 트림",- cut: "선택한 클립 잘라내기",- duplicate: "선택한 클립 복제",- copyAttrs: "클립 속성 복사",- pasteAttrs: "선택한 클립에 속성 붙여넣기",- speedPanel: "선택한 클립의 속도",- detachAudio: "동영상의 소리 분리",- nudgeClip: "선택한 클립을 1프레임 이동",- toggleMagnet: "메인 트랙 자석 켜기 / 끄기",- toggleSnap: "스냅 켜기 / 끄기",- toggleLinkage: "연동 켜기 / 끄기",- togglePreviewAxis: "미리보기 축 켜기 / 끄기",- zoomFit: "전체가 보이게 확대/축소",- frameStep: '재생 헤드를 1프레임 이동',- jumpStep: "재생 헤드 10프레임 이동",- rippleDelete: '리플 삭제 후 간격 메우기',- selectAll: '잠기지 않은 클립 선택(먼저 타임라인 클릭)',- selectSide: "재생 헤드 앞 / 뒤의 모든 클립 선택",deselect: '선택 해제',- zoomIn: '타임라인 확대',- zoomOut: '타임라인 축소',- zoomReset: '타임라인 확대/축소 초기화',- groupCanvas: '캔버스 요소',nudge: '선택한 요소를 1px 이동',nudgeFast: '선택한 요소를 10px 이동',editText: '선택한 텍스트 편집',commitText: '텍스트 편집 적용',cancelText: '텍스트 편집 취소 / 선택 해제',- hint: "키는 운영 체제에 따라 다릅니다. 입력하는 동안에는 재생 및 편집 단축키가 일시 중지됩니다. 화살표 키는 재생 헤드를 움직이고, 화면을 클릭하면(테두리가 표시됨) 화면에서 선택한 것을 움직입니다.",- groupPlayback: '재생',- groupEdit: '타임라인 및 편집',- playPause: '재생 / 일시 정지',- seekEnds: '처음 / 끝으로 이동',- undo: '실행 취소',- redo: '다시 실행',- split: "선택한 클립을 재생 헤드에서 분할 (선택이 없으면 대상 트랙의 클립)",- copy: '선택한 클립 복사',- paste: '재생 헤드에 붙여넣기',- remove: '선택한 클립 삭제',- selectMode: '선택 도구',- splitMode: '분할 도구',splitModeAll: '분할 도구에서 누른 채 클릭: 모든 트랙을 그 자리에서 분할',editModeSwap: '클립을 놓을 때 누르기: 사이에 끼워 넣고 뒤 클립을 밀어냄',copyDrag: '누른 채 클립 드래그: 놓은 자리에 복사본, 원래 클립은 그대로',+ customName: "사용자 지정 {n}",+ scheme: "단축키 스킴",+ restore: "기본값 복원",+ save: "저장",+ cancel: "취소",+ recording: "키를 누르세요…",+ change: "클릭하여 변경",+ editCopy: "클릭하여 사본에서 변경",+ none: "없음",+ clear: "키 제거",+ replace: "바꾸기",+ copied: "{from}은(는) 기본 제공 스킴이라 {to}에 복사했습니다. 변경 사항은 그곳에 저장됩니다.",+ started: "{to}은(는) {from}의 사본으로 시작합니다.",+ full: "사용자 지정 스킴 세 개가 모두 사용 중입니다. 키를 바꾸려면 그중 하나를 선택하세요.",+ conflict: "{keys}은(는) 이미 \"{action}\"에 사용 중입니다. 바꿀까요?",+ fixed: "이 키들은 바꿀 수 없습니다.",+ saveFailed: "단축키를 저장하지 못했습니다: {error}",+ shuttleHold: "1프레임 뒤로 / 앞으로 (정지 키를 누른 채)",+ tabs: { timeline: "타임라인", player: "플레이어", basic: "기본", other: "기타" },+ /* the editor's actions (lib/keymap ACTIONS) */+ actions: {+ "split": "재생 헤드에서 분할",+ "split-all": "모든 트랙 분할",+ "select-mode": "선택 도구",+ "split-mode": "분할 도구",+ "ripple-start": "시작 리플 트림",+ "ripple-end": "끝 리플 트림",+ "select-left": "왼쪽 모두 선택",+ "select-right": "오른쪽 모두 선택",+ "nudge-back": "클립을 1프레임 왼쪽으로",+ "nudge-forward": "클립을 1프레임 오른쪽으로",+ "toggle-magnet": "메인 트랙 자석 켜기 / 끄기",+ "toggle-snap": "스냅 켜기 / 끄기",+ "toggle-linkage": "연동 켜기 / 끄기",+ "toggle-preview-axis": "미리보기 축 켜기 / 끄기",+ "zoom-in": "확대",+ "zoom-out": "축소",+ "zoom-reset": "확대/축소 초기화",+ "zoom-fit": "전체가 보이게 확대/축소",+ "add-marker": "마커 추가",+ "next-marker": "다음 마커",+ "prev-marker": "이전 마커",+ "speed": "클립 속도",+ "detach-audio": "오디오 분리",+ "play-pause": "재생 / 일시 정지",+ "play-range": "시작점에서 끝점까지 재생",+ "loop": "반복 재생",+ "shuttle-back": "역재생",+ "shuttle-stop": "정지",+ "shuttle-forward": "재생",+ "frame-back": "1프레임 뒤로",+ "frame-forward": "1프레임 앞으로",+ "jump-back": "10프레임 뒤로",+ "jump-forward": "10프레임 앞으로",+ "prev-cut": "이전 컷",+ "next-cut": "다음 컷",+ "start": "처음으로 이동",+ "end": "끝으로 이동",+ "mark-in": "시작점 지정",+ "mark-out": "끝점 지정",+ "clear-range": "시작점과 끝점 지우기",+ "range-clip": "선택한 클립으로 시작점과 끝점 설정",+ "go-in": "시작점으로 이동",+ "go-out": "끝점으로 이동",+ "insert-source": "소스 뷰어에서 삽입",+ "overwrite-source": "소스 뷰어에서 덮어쓰기",+ "undo": "실행 취소",+ "redo": "다시 실행",+ "cut": "잘라내기",+ "copy": "복사",+ "paste": "재생 헤드에 붙여넣기",+ "duplicate": "복제",+ "remove": "삭제",+ "ripple-delete": "리플 삭제",+ "select-all": "모두 선택",+ "copy-attrs": "속성 복사",+ "paste-attrs": "속성 붙여넣기",+ "refer": "채팅에 추가",+ },},providers: {desc: '음성, 음악, 효과음, 대본, 이미지, 비디오를 가져오는 곳입니다. OpenFilm은 이 서비스 없이도 영상을 만들고 편집합니다. 에이전트에게 미디어가 필요할 때 연결하세요. 각 미디어에 무엇을 쓸지는 「서비스」에서 고릅니다.',diff --git a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts b/packages/openfilm/studio/ui/src/i18n/zh-CN.tsindex 99b6c2c..eed716b 100644--- a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts+++ b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts@@ -1687,69 +1687,96 @@ export const zhCN: Words = {preview: '预览',},shortcuts: {- groupMarks: "入点和出点",- groupView: "时间线视图",- shuttle: "倒放 / 停止 / 播放(再按:加速)",- shuttleFrame: "后退 / 前进一帧(按住 K)",- cutStep: "跳到上一个 / 下一个剪切点",- markIn: "在播放头处设入点",- markOut: "在播放头处设出点",- clearMarks: "清除入点和出点",- rangeClip: "以选中片段设定入点和出点",- goInOut: "跳到入点 / 出点",- playRange: "从入点播放到出点",- loop: "循环播放(有范围时循环范围,否则整片)",- insertSource: "素材预览:在播放头处插入",- overwriteSource: "素材预览:在播放头处覆盖",+ hint: "按键随操作系统而定,输入文字时暂停。选一个方案即可用其他剪辑软件的按键;在自定义方案里可以改任何一个键。",addMedia: "把选中的素材加到时间线",- addMarker: "在播放头处添加标记(选中的片段在播放头下时加在片段上)",- markerStep: "跳到下一个 / 上一个标记",- splitAll: "在播放头处切分所有未锁定的轨道",- rippleStart: "波纹裁剪开头到播放头",- rippleEnd: "波纹裁剪结尾到播放头",- cut: "剪切所选片段",- duplicate: "复制一份所选片段",- copyAttrs: "复制片段属性",- pasteAttrs: "把属性粘贴到选中的片段",- speedPanel: "选中片段的变速",- detachAudio: "分离视频的音频",- nudgeClip: "把所选片段移动一帧",- toggleMagnet: "开关主轨磁吸",- toggleSnap: "开关吸附",- toggleLinkage: "开关联动",- togglePreviewAxis: "开关预览轴",- zoomFit: "缩放到整片",- frameStep: '播放头移动一帧',- jumpStep: "播放头移动 10 帧",- rippleDelete: '波纹删除并合拢间隙',- selectAll: '选择未锁定的片段(需先点击时间轴)',- selectSide: "向左全选 / 向右全选(播放头之前 / 之后的所有片段)",deselect: '取消选择',- zoomIn: '放大时间轴',- zoomOut: '缩小时间轴',- zoomReset: '重置时间轴缩放',- groupCanvas: '画布元素',nudge: '将所选元素移动 1 px',nudgeFast: '将所选元素移动 10 px',editText: '编辑所选文字',commitText: '应用文字编辑',cancelText: '取消文字编辑 / 取消选择',- hint: "按键随操作系统而定。输入文字时,播放和编辑快捷键会暂停。方向键移动播放头;点击画面后(画面周围出现边框),方向键移动画面里选中的元素。",- groupPlayback: '播放',- groupEdit: '时间轴与编辑',- playPause: '播放 / 暂停',- seekEnds: '跳到开头 / 结尾',- undo: '撤销',- redo: '重做',- split: "在播放头处切分所选片段(未选中时:目标轨道上的片段)",- copy: '复制所选片段',- paste: '在播放头处粘贴',- remove: '删除所选片段',- selectMode: '选择工具',- splitMode: '分割工具',splitModeAll: '分割工具下按住它点击:所有轨道都在这里切开',editModeSwap: '放下片段时按住:插到中间,后面的片段跟着后移',copyDrag: '按住它拖动片段:在松手处复制一份,原片段不动',+ customName: "自定义 {n}",+ scheme: "快捷键方案",+ restore: "恢复默认值",+ save: "保存",+ cancel: "取消",+ recording: "请按键…",+ change: "点击修改",+ editCopy: "点击后在副本里修改",+ none: "无",+ clear: "移除按键",+ replace: "替换",+ copied: "{from} 是内置方案,已复制到 {to},修改都保存在那里。",+ started: "{to} 从 {from} 的副本开始。",+ full: "三个自定义方案都已使用。请选择其中一个来修改按键。",+ conflict: "{keys} 已用于“{action}”。要替换吗?",+ fixed: "这些按键不能修改。",+ saveFailed: "无法保存快捷键:{error}",+ shuttleHold: "后退 / 前进一帧(按住停止键)",+ tabs: { timeline: "时间线", player: "播放器", basic: "基础", other: "其他" },+ /* the editor's actions (lib/keymap ACTIONS) */+ actions: {+ "split": "在播放头处分割",+ "split-all": "分割所有轨道",+ "select-mode": "选择工具",+ "split-mode": "分割工具",+ "ripple-start": "波纹裁剪开头",+ "ripple-end": "波纹裁剪结尾",+ "select-left": "向左全选",+ "select-right": "向右全选",+ "nudge-back": "片段左移一帧",+ "nudge-forward": "片段右移一帧",+ "toggle-magnet": "主轨磁吸开关",+ "toggle-snap": "吸附开关",+ "toggle-linkage": "联动开关",+ "toggle-preview-axis": "预览轴开关",+ "zoom-in": "时间轴放大",+ "zoom-out": "时间轴缩小",+ "zoom-reset": "重置缩放",+ "zoom-fit": "缩放到整片",+ "add-marker": "添加标记",+ "next-marker": "下一个标记",+ "prev-marker": "上一个标记",+ "speed": "片段变速",+ "detach-audio": "分离音频",+ "play-pause": "播放 / 暂停",+ "play-range": "从入点播放到出点",+ "loop": "循环播放",+ "shuttle-back": "倒放",+ "shuttle-stop": "停止",+ "shuttle-forward": "正放",+ "frame-back": "后退一帧",+ "frame-forward": "前进一帧",+ "jump-back": "后退 10 帧",+ "jump-forward": "前进 10 帧",+ "prev-cut": "上一个剪切点",+ "next-cut": "下一个剪切点",+ "start": "跳到开头",+ "end": "跳到结尾",+ "mark-in": "设入点",+ "mark-out": "设出点",+ "clear-range": "清除入点和出点",+ "range-clip": "以选中片段设入点和出点",+ "go-in": "跳到入点",+ "go-out": "跳到出点",+ "insert-source": "从素材预览插入",+ "overwrite-source": "从素材预览覆盖",+ "undo": "撤销",+ "redo": "重做",+ "cut": "剪切",+ "copy": "复制",+ "paste": "在播放头处粘贴",+ "duplicate": "创建副本",+ "remove": "删除",+ "ripple-delete": "波纹删除",+ "select-all": "全选",+ "copy-attrs": "复制属性",+ "paste-attrs": "粘贴属性",+ "refer": "添加到对话",+ },},providers: {desc: '配音、音乐、音效、文字稿、图片和视频从哪里来。即使不连接任何服务,OpenFilm 也能制作和编辑影片:等智能体需要素材时再连接即可。每种媒体具体用哪一个,在「服务」里选择。',diff --git a/packages/openfilm/studio/ui/src/lib/keymap-store.ts b/packages/openfilm/studio/ui/src/lib/keymap-store.tsnew file mode 100644index 0000000..cd5c81f--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/keymap-store.ts@@ -0,0 +1,74 @@+/**+ * The keys in use on this page: the scheme and custom schemes from Studio's prefs (`keys`, lib/keymap), read once and+ * again whenever the page comes back into view (Settings may have changed them in another window), and the keymap+ * they make. The key handlers read it as each key is pressed (`keyAction`); hints and Settings re-render on a change.+ */+import { useMemo, useSyncExternalStore } from 'react';+import { api } from '@/api';+import { actionOf, DEFAULT_KEY_PREFS, hintOf, keyPrefsOf, keymapOf, type ActionId, type KeyPrefs, type Keymap } from './keymap.ts';+import type { KeyPress } from './timeline-keys.ts';++/** ⌘ is the modifier on a Mac, Ctrl elsewhere (as lib/shortcut-hint). */+export const MAC = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform);++let prefs: KeyPrefs = DEFAULT_KEY_PREFS;+let keymap: Keymap = keymapOf(prefs, MAC);+const listeners = new Set<() => void>();+let loaded = false;++function set(next: KeyPrefs): void {+ if (JSON.stringify(next) === JSON.stringify(prefs)) return;+ prefs = next;+ keymap = keymapOf(next, MAC);+ for (const fn of listeners) fn();+}++function load(): void {+ void api.prefs().then((p) => set(keyPrefsOf(p.keys)), () => { /* Studio not reachable: the keys as they are */ });+}++function ensure(): void {+ if (loaded || typeof window === 'undefined') return;+ loaded = true;+ load();+ window.addEventListener('focus', load);+}++/** The keys in use. */+export function currentKeymap(): Keymap {+ ensure();+ return keymap;+}++/** The action a key press is, with the keys in use; null when it is none. */+export const keyAction = (e: KeyPress): ActionId | null => actionOf(e, currentKeymap(), MAC);++/** The schemes as kept. */+export function currentKeyPrefs(): KeyPrefs {+ ensure();+ return prefs;+}++/** Keep the schemes (Settings' Save): in use at once here, and in Studio's prefs for every window and next time. */+export async function saveKeyPrefs(next: KeyPrefs): Promise<void> {+ set(next);+ await api.setPrefs({ keys: next });+}++function subscribe(fn: () => void): () => void {+ ensure();+ listeners.add(fn);+ return () => { listeners.delete(fn); };+}++/** The schemes as kept, kept up to date. */+export const useKeyPrefs = (): KeyPrefs => useSyncExternalStore(subscribe, currentKeyPrefs, () => DEFAULT_KEY_PREFS);++/** The keys in use, kept up to date. */+export const useKeymap = (): Keymap => useSyncExternalStore(subscribe, currentKeymap, currentKeymap);++/** A hint for an action (its first key, ⌘B on a Mac and Ctrl+B elsewhere), with the keys in use; undefined: it has none. */+export function useKeyHint(): (id: ActionId) => string | undefined {+ const map = useKeymap();+ return useMemo(() => (id: ActionId) => hintOf(map, id, MAC), [map]);+}diff --git a/packages/openfilm/studio/ui/src/lib/keymap.test.ts b/packages/openfilm/studio/ui/src/lib/keymap.test.tsnew file mode 100644index 0000000..6a111b7--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/keymap.test.ts@@ -0,0 +1,269 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import {+ ACTIONS, ACTION_IDS, actionOf, assignKey, BUILT_IN_SCHEMES, comboCaps, comboOf, conflictOf, copyOf, CUSTOM_SLOTS, customKeymap,+ DEFAULT_KEY_PREFS, editable, hintOf, isCombo, KEY_TABS, keymapOf, keyPrefsOf, platformCombo, restoreDefaults, schemeKeymap,+ withKey, withoutKeys, type ActionId, type KeyPrefs, type Keymap,+} from './keymap.ts';+import type { KeyPress } from './timeline-keys.ts';+import { en } from '../i18n/en.ts';+import { es } from '../i18n/es.ts';+import { ja } from '../i18n/ja.ts';+import { ko } from '../i18n/ko.ts';+import { zhCN } from '../i18n/zh-CN.ts';++const press = (key: string, mods: Partial<KeyPress> = {}): KeyPress => ({ key, metaKey: false, ctrlKey: false, shiftKey: false, altKey: false, ...mods });+const OPENFILM_MAC = schemeKeymap('openfilm', true);+const OPENFILM_WIN = schemeKeymap('openfilm', false);+const mac = (key: string, mods: Partial<KeyPress> = {}) => actionOf(press(key, mods), OPENFILM_MAC, true);+const win = (key: string, mods: Partial<KeyPress> = {}) => actionOf(press(key, mods), OPENFILM_WIN, false);++/** Every combination a keymap uses, and whether any is used twice (on that platform). */+function twice(keymap: Keymap, isMac: boolean): string[] {+ const seen = new Map<string, ActionId>();+ const doubled: string[] = [];+ for (const id of ACTION_IDS) for (const combo of keymap[id]) {+ const at = platformCombo(combo, isMac);+ if (seen.has(at)) doubled.push(`${at}: ${seen.get(at)} and ${id}`);+ seen.set(at, id);+ }+ return doubled;+}++test('the action table: each action once, in a tab, with keys that are combinations', () => {+ assert.equal(new Set(ACTION_IDS).size, ACTIONS.length, 'no action twice');+ for (const tab of KEY_TABS) assert.ok(ACTIONS.some((a) => a.tab === tab), `${tab} has actions`);+ for (const a of ACTIONS) for (const combo of a.keys) assert.ok(isCombo(combo), `${a.id}: ${combo}`);+ assert.deepEqual(twice(OPENFILM_MAC, true), []);+ assert.deepEqual(twice(OPENFILM_WIN, false), []);+});++test('every action is named in the five languages', () => {+ for (const [lang, words] of Object.entries({ en, es, ja, ko, zhCN })) {+ const names = (words as { settings?: { shortcuts?: { actions?: Record<string, string> } } }).settings?.shortcuts?.actions ?? {};+ for (const id of ACTION_IDS) assert.ok(names[id]?.trim(), `${lang}: ${id}`);+ }+});++test('OpenFilm\'s keys are the keys Studio had', () => {+ assert.equal(mac(' '), 'play-pause');+ assert.equal(mac(' ', { shiftKey: true }), 'play-range');+ assert.equal(mac('j'), 'shuttle-back');+ assert.equal(mac('k'), 'shuttle-stop');+ assert.equal(mac('L'), 'shuttle-forward');+ assert.equal(mac('i'), 'mark-in');+ assert.equal(mac('o'), 'mark-out');+ assert.equal(mac('x'), 'clear-range');+ assert.equal(mac('I', { shiftKey: true }), 'go-in');+ assert.equal(mac('O', { shiftKey: true }), 'go-out');+ assert.equal(mac('L', { shiftKey: true }), 'loop');+ assert.equal(mac('b', { metaKey: true }), 'split');+ assert.equal(mac('b', { metaKey: true, shiftKey: true }), 'split-all');+ assert.equal(mac('k', { metaKey: true }), 'split-all');+ assert.equal(mac('x', { metaKey: true }), 'cut');+ assert.equal(mac('d', { metaKey: true }), 'duplicate');+ assert.equal(mac('c', { metaKey: true }), 'copy');+ assert.equal(mac('v', { metaKey: true }), 'paste');+ assert.equal(mac('z', { metaKey: true }), 'undo');+ assert.equal(mac('z', { metaKey: true, shiftKey: true }), 'redo');+ assert.equal(mac('a', { metaKey: true }), 'select-all');+ assert.equal(mac('l', { metaKey: true }), 'refer');+ assert.equal(mac('ArrowUp'), 'prev-cut');+ assert.equal(mac('ArrowDown'), 'next-cut');+ assert.equal(mac('ArrowLeft'), 'frame-back');+ assert.equal(mac('ArrowRight', { shiftKey: true }), 'jump-forward');+ assert.equal(mac('ArrowLeft', { altKey: true }), 'nudge-back');+ assert.equal(mac('ArrowRight', { altKey: true }), 'nudge-forward');+ assert.equal(mac('Z', { shiftKey: true }), 'zoom-fit');+ assert.equal(mac('n'), 'toggle-snap');+ assert.equal(mac('N', { shiftKey: true }), 'toggle-magnet');+ assert.equal(mac('p'), 'toggle-magnet');+ assert.equal(mac('`'), 'toggle-linkage');+ assert.equal(mac('~', { shiftKey: true }), 'toggle-linkage');+ assert.equal(actionOf({ ...press('`'), code: 'Backquote' }, OPENFILM_MAC, true), 'toggle-linkage');+ assert.equal(mac('s'), 'toggle-preview-axis');+ assert.equal(mac('S', { shiftKey: true, ctrlKey: true }), 'detach-audio');+ assert.equal(win('S', { shiftKey: true, ctrlKey: true }), 'detach-audio');+ assert.equal(mac('q'), 'ripple-start');+ assert.equal(mac('w'), 'ripple-end');+ assert.equal(mac(','), 'insert-source');+ assert.equal(mac('.'), 'overwrite-source');+ assert.equal(mac('Home'), 'start');+ assert.equal(mac('End'), 'end');+ assert.equal(mac('a'), 'select-mode');+ assert.equal(mac('v'), 'select-mode');+ assert.equal(mac('b'), 'split-mode');+ assert.equal(mac('Backspace'), 'remove');+ assert.equal(mac('Delete'), 'remove');+ assert.equal(mac('Backspace', { shiftKey: true }), 'ripple-delete');+ assert.equal(mac('X', { shiftKey: true }), 'range-clip');+ assert.equal(actionOf({ ...press('≈', { altKey: true }), code: 'KeyX' }, OPENFILM_MAC, true), 'clear-range', '⌥X types ≈ on a Mac');+ assert.equal(mac('r', { metaKey: true }), 'speed');+ assert.equal(mac('C', { metaKey: true, shiftKey: true }), 'copy-attrs');+ assert.equal(mac('V', { metaKey: true, shiftKey: true }), 'paste-attrs');+ assert.equal(actionOf({ ...press('['), code: 'BracketLeft' }, OPENFILM_MAC, true), 'select-left');+ assert.equal(actionOf({ ...press(']'), code: 'BracketRight' }, OPENFILM_MAC, true), 'select-right');+ /* zoom: ⌘= and ⌘+ (⇧= on a US keyboard, or the keypad's), ⌘-, ⌘0 */+ assert.equal(mac('=', { metaKey: true }), 'zoom-in');+ assert.equal(actionOf({ ...press('+', { metaKey: true, shiftKey: true }), code: 'Equal' }, OPENFILM_MAC, true), 'zoom-in');+ assert.equal(actionOf({ ...press('+', { ctrlKey: true }), code: 'NumpadAdd' }, OPENFILM_WIN, false), 'zoom-in');+ assert.equal(mac('-', { metaKey: true }), 'zoom-out');+ assert.equal(mac('0', { metaKey: true }), 'zoom-reset');+});++test('M adds a marker, ⇧M and ⌥M go to the next and the one before (⌥M types µ on a Mac)', () => {+ assert.equal(mac('m'), 'add-marker');+ assert.equal(mac('M', { shiftKey: true }), 'next-marker');+ assert.equal(actionOf({ ...press('µ', { altKey: true }), code: 'KeyM' }, OPENFILM_MAC, true), 'prev-marker');+ assert.equal(win('m', { altKey: true }), 'prev-marker');+ assert.equal(mac('m', { metaKey: true }), null);+ assert.equal(mac('m', { altKey: true, shiftKey: true }), 'prev-marker', '⌥⇧M too');+});++test('keys that are not the editor\'s stay the browser\'s, and Ctrl is the modifier off a Mac', () => {+ assert.equal(mac('b', { ctrlKey: true }), null, 'Ctrl+B on a Mac is not ⌘B');+ assert.equal(win('b', { ctrlKey: true }), 'split');+ assert.equal(win('b', { metaKey: true }), null, 'the Windows key is no shortcut');+ assert.equal(mac('j', { altKey: true }), null);+ assert.equal(mac('ArrowUp', { shiftKey: true }), null);+ assert.equal(mac('a', { ctrlKey: true }), null, 'Ctrl+A on a Mac moves the caret');+ assert.equal(mac('a', { metaKey: true, shiftKey: true }), null);+ assert.equal(mac('a', { metaKey: true, altKey: true }), null);+ assert.equal(mac('Shift', { shiftKey: true }), null, 'a modifier alone');+});++test('a letter is read by what it types, or where it sits when it types no Latin letter', () => {+ /* a French keyboard's A is where Q is on a US one: the letter it types counts */+ assert.equal(actionOf({ ...press('a'), code: 'KeyQ' }, OPENFILM_MAC, true), 'select-mode');+ /* Korean: ㅓ is on J */+ assert.equal(actionOf({ ...press('ㅓ'), code: 'KeyJ' }, OPENFILM_MAC, true), 'shuttle-back');+});++test('a key press as a combination, for recording a new key', () => {+ assert.equal(comboOf(press('B', { metaKey: true, shiftKey: true }), true), 'mod+shift+b');+ assert.equal(comboOf(press('b', { ctrlKey: true, shiftKey: true }), false), 'mod+shift+b', 'Ctrl is the modifier off a Mac');+ assert.equal(comboOf(press('s', { ctrlKey: true, shiftKey: true }), true), 'ctrl+shift+s', 'Control itself on a Mac');+ assert.equal(comboOf(press('k', { altKey: true, metaKey: true }), true), 'mod+alt+k');+ assert.equal(comboOf(press(' '), true), 'Space');+ assert.equal(comboOf(press('F5'), true), 'F5');+ assert.equal(comboOf({ ...press('!', { shiftKey: true }), code: 'Digit1' }, true), 'shift+1');+ assert.equal(comboOf(press('Meta', { metaKey: true }), true), null);+ assert.equal(comboOf(press('k', { metaKey: true }), false), null, 'the Windows key');+ for (const combo of ['mod+shift+b', 'ctrl+shift+s', 'mod+alt+k', 'Space', 'F5', 'shift+1']) assert.ok(isCombo(combo), combo);+ for (const combo of ['shift+mod+b', 'Mod+B', 'mod+', 'nope', '']) assert.ok(!isCombo(combo), combo);+});++test('hints and key caps follow the platform', () => {+ assert.equal(hintOf(OPENFILM_MAC, 'split', true), '⌘B');+ assert.equal(hintOf(OPENFILM_WIN, 'split', false), 'Ctrl+B');+ assert.equal(hintOf(OPENFILM_MAC, 'redo', true), '⌘⇧Z');+ assert.equal(hintOf(OPENFILM_WIN, 'redo', false), 'Ctrl+Shift+Z');+ assert.equal(hintOf(OPENFILM_MAC, 'zoom-in', true), '⌘+');+ assert.deepEqual(comboCaps('ctrl+shift+s', true), ['⌃', '⇧', 'S']);+ assert.deepEqual(comboCaps('ctrl+shift+s', false), ['Ctrl', 'Shift', 'S']);+ assert.deepEqual(comboCaps('Backspace', true), ['⌫']);+ assert.deepEqual(comboCaps('Backspace', false), ['Backspace']);+ assert.deepEqual(comboCaps('alt+', true), ['⌥'], 'a modifier held alone');+ assert.equal(hintOf({ ...OPENFILM_MAC, split: [] }, 'split', true), undefined, 'no key, no hint');+});++test('the built-in schemes: each app\'s keys where Studio has the action, OpenFilm\'s for the rest, no key twice', () => {+ for (const id of BUILT_IN_SCHEMES) for (const isMac of [true, false]) {+ const keymap = schemeKeymap(id, isMac);+ assert.deepEqual(twice(keymap, isMac), [], `${id} on ${isMac ? 'a Mac' : 'Windows'}`);+ for (const a of ACTION_IDS) for (const combo of keymap[a]) assert.ok(isCombo(combo), `${id}: ${a}: ${combo}`);+ }+ const premiere = schemeKeymap('premiere', true);+ assert.deepEqual(premiere.split, ['mod+k'], 'Add Edit');+ assert.deepEqual(premiere['split-all'], ['mod+shift+k']);+ assert.deepEqual(premiere['split-mode'], ['c'], 'the Razor tool');+ assert.deepEqual(premiere['toggle-snap'], ['s']);+ assert.deepEqual(premiere['toggle-preview-axis'], [], 'S snaps there: the preview axis has no key');+ assert.deepEqual(premiere['toggle-magnet'], ['p', 'shift+n'], 'what the app has no key for keeps OpenFilm\'s');+ assert.deepEqual(premiere.refer, ['mod+l']);+ assert.deepEqual(premiere['nudge-back'], ['mod+ArrowLeft'], 'macOS');+ assert.deepEqual(schemeKeymap('premiere', false)['nudge-back'], ['alt+ArrowLeft'], 'Windows');+ assert.deepEqual(schemeKeymap('premiere', false)['clear-range'], ['mod+shift+x']);+ assert.equal(actionOf(press('k', { metaKey: true }), premiere, true), 'split');+ assert.equal(actionOf(press('\\'), premiere, true), 'zoom-fit');++ const fcp = schemeKeymap('fcp', true);+ assert.deepEqual(fcp.loop, ['mod+l']);+ assert.deepEqual(fcp.refer, [], '⌘L loops there');+ assert.deepEqual(fcp['ripple-delete'], ['Backspace', 'Delete'], 'Delete closes the gap');+ assert.deepEqual(fcp.remove, ['shift+Backspace', 'shift+Delete'], 'Replace with Gap');+ assert.deepEqual(fcp['insert-source'], ['w']);+ assert.deepEqual(fcp['ripple-end'], ['alt+]']);+ assert.equal(actionOf({ ...press('‘', { altKey: true }), code: 'BracketRight' }, fcp, true), 'ripple-end', '⌥] types ‘ on a Mac');+ assert.equal(actionOf(press("'", { ctrlKey: true }), fcp, true), 'next-marker');+ assert.equal(actionOf(press("'", { ctrlKey: true }), schemeKeymap('fcp', false), false), 'next-marker', 'Control is Ctrl on Windows');+});++test('a key that another action has is a conflict, and replacing takes it from that action', () => {+ assert.equal(conflictOf(OPENFILM_MAC, 'split', 'mod+k', true), 'split-all');+ assert.equal(conflictOf(OPENFILM_MAC, 'split', 'mod+b', true), null, 'its own key');+ assert.equal(conflictOf(OPENFILM_MAC, 'split', 'mod+shift+y', true), null);+ /* off a Mac, Control and the modifier are one key */+ assert.equal(conflictOf(OPENFILM_WIN, 'split', 'ctrl+shift+s', false), 'detach-audio');+ assert.equal(conflictOf(OPENFILM_MAC, 'split', 'mod+shift+s', true), null, 'on a Mac ⌘ is not ⌃');+ const next = assignKey(OPENFILM_MAC, 'split', 'mod+k', true);+ assert.deepEqual(next.split, ['mod+k']);+ assert.deepEqual(next['split-all'], ['mod+shift+b']);+ assert.deepEqual(OPENFILM_MAC['split-all'], ['mod+shift+b', 'mod+k'], 'the keymap given is left as it was');+});++test('changing a built-in scheme copies it into a free custom slot first; a full set of slots says so', () => {+ const start: KeyPrefs = { scheme: 'premiere', custom: {} };+ const first = editable(start, true);+ assert.ok(first);+ assert.equal(first.copiedTo, 'custom1');+ assert.equal(first.prefs.scheme, 'custom1');+ assert.equal(first.prefs.custom.custom1?.base, 'premiere');+ assert.deepEqual(customKeymap(first.prefs.custom.custom1!, true), schemeKeymap('premiere', true), 'the copy has the scheme\'s keys');+ const changed = withKey(first.prefs, 'custom1', 'split', 'mod+e', true);+ assert.deepEqual(keymapOf(changed, true).split, ['mod+e']);+ assert.deepEqual(schemeKeymap('premiere', true).split, ['mod+k'], 'the built-in scheme stays as it is');++ /* the next copy goes into the next slot; a custom scheme is changed itself */+ const again = editable({ ...changed, scheme: 'fcp' }, true);+ assert.equal(again?.copiedTo, 'custom2');+ assert.equal(editable(changed, true)?.copiedTo, null);+ const full: KeyPrefs = { scheme: 'openfilm', custom: Object.fromEntries(CUSTOM_SLOTS.map((slot) => [slot, copyOf(start, 'openfilm', true)])) };+ assert.equal(editable(full, true), null);++ /* keys taken away, then the scheme it came from restored */+ const bare = withoutKeys(changed, 'custom1', 'undo', true);+ assert.deepEqual(keymapOf(bare, true).undo, []);+ assert.equal(actionOf(press('z', { metaKey: true }), keymapOf(bare, true), true), null);+ const restored = restoreDefaults(bare, 'custom1', true);+ assert.deepEqual(keymapOf(restored, true), schemeKeymap('premiere', true));+});++test('an action added after a custom scheme was made takes its base\'s keys, unless they are used', () => {+ const keys = Object.fromEntries(ACTION_IDS.filter((id) => id !== 'refer' && id !== 'loop').map((id) => [id, [...OPENFILM_MAC[id]]]));+ keys.split = ['shift+l'];+ const keymap = customKeymap({ base: 'openfilm', keys }, true);+ assert.deepEqual(keymap.refer, ['mod+l']);+ assert.deepEqual(keymap.loop, [], '⇧L is split\'s now');+});++test('what is kept: the scheme and the custom ones, checked when read', () => {+ const prefs = withKey(editable({ scheme: 'fcp', custom: {} }, true)!.prefs, 'custom1', 'refer', 'mod+shift+l', true);+ const back = keyPrefsOf(JSON.parse(JSON.stringify(prefs)));+ assert.deepEqual(back, prefs, 'a round trip through JSON');+ assert.deepEqual(keymapOf(back, true).refer, ['mod+shift+l']);++ assert.deepEqual(keyPrefsOf(null), DEFAULT_KEY_PREFS);+ assert.deepEqual(keyPrefsOf({ scheme: 'nope' }), DEFAULT_KEY_PREFS);+ assert.equal(keyPrefsOf({ scheme: 'custom2', custom: {} }).scheme, 'openfilm', 'an empty slot is no scheme');+ const odd = keyPrefsOf({+ scheme: 'custom1',+ custom: { custom1: { base: 'someday', keys: { split: ['mod+e', 'Mod+E', 7], 'beam-me-up': ['x'] } }, custom9: { base: 'openfilm', keys: {} } },+ });+ assert.equal(odd.scheme, 'custom1');+ assert.equal(odd.custom.custom1?.base, 'openfilm', 'an unknown base is OpenFilm');+ assert.deepEqual(odd.custom.custom1?.keys, { split: ['mod+e'] }, 'unknown actions and keys that are none are left out');+ assert.deepEqual(Object.keys(odd.custom), ['custom1']);+ assert.deepEqual(keymapOf(odd, true).split, ['mod+e']);+ assert.deepEqual(keymapOf(odd, true)['split-all'], ['mod+shift+b', 'mod+k'], 'the rest from its base');+});diff --git a/packages/openfilm/studio/ui/src/lib/keymap.ts b/packages/openfilm/studio/ui/src/lib/keymap.tsnew file mode 100644index 0000000..d1be19f--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/keymap.ts@@ -0,0 +1,529 @@+/**+ * The editor's keys, in one table: every action has an id, a tab in Settings › Keyboard shortcuts, and its default+ * keys. The key handlers (`actionOf`), Settings' list and the hints in menus and tooltips (`hintOf`) all read it.+ *+ * A scheme gives the actions their keys: OpenFilm's own (the defaults), Premiere Pro's and Final Cut Pro X's (from each+ * app's default keyboard shortcuts, mapped onto the actions Studio has), or one of three custom ones. A built-in scheme+ * is read-only; a custom one starts as a copy of a scheme and can change any key.+ *+ * A key combination is a string: its modifiers in a fixed order, then the key, joined by "+" (`mod+shift+b`). `mod` is+ * ⌘ on a Mac and Ctrl elsewhere; `ctrl` is the Control key itself, which off a Mac is the same key as `mod`. Letters+ * are read by the letter they type (so they follow the keyboard's layout), or by where they sit on a US keyboard on a+ * layout without Latin letters; digits and punctuation by where they sit.+ */+import { letterOf, type KeyPress } from './timeline-keys.ts';++export type KeyTab = 'timeline' | 'player' | 'basic' | 'other';+export const KEY_TABS: readonly KeyTab[] = ['timeline', 'player', 'basic', 'other'];++/** The actions, in the order Settings lists them. */+export const ACTIONS = [+ /* the timeline */+ { id: 'split', tab: 'timeline', keys: ['mod+b'] },+ { id: 'split-all', tab: 'timeline', keys: ['mod+shift+b', 'mod+k'] },+ { id: 'select-mode', tab: 'timeline', keys: ['a', 'v'] },+ { id: 'split-mode', tab: 'timeline', keys: ['b'] },+ { id: 'ripple-start', tab: 'timeline', keys: ['q'] },+ { id: 'ripple-end', tab: 'timeline', keys: ['w'] },+ { id: 'select-left', tab: 'timeline', keys: ['['] },+ { id: 'select-right', tab: 'timeline', keys: [']'] },+ { id: 'nudge-back', tab: 'timeline', keys: ['alt+ArrowLeft'] },+ { id: 'nudge-forward', tab: 'timeline', keys: ['alt+ArrowRight'] },+ { id: 'toggle-magnet', tab: 'timeline', keys: ['p', 'shift+n'] },+ { id: 'toggle-snap', tab: 'timeline', keys: ['n'] },+ { id: 'toggle-linkage', tab: 'timeline', keys: ['`', 'shift+`'] },+ { id: 'toggle-preview-axis', tab: 'timeline', keys: ['s'] },+ { id: 'zoom-in', tab: 'timeline', keys: ['mod++', 'mod+='] },+ { id: 'zoom-out', tab: 'timeline', keys: ['mod+-'] },+ { id: 'zoom-reset', tab: 'timeline', keys: ['mod+0'] },+ { id: 'zoom-fit', tab: 'timeline', keys: ['shift+z'] },+ { id: 'add-marker', tab: 'timeline', keys: ['m'] },+ { id: 'next-marker', tab: 'timeline', keys: ['shift+m'] },+ { id: 'prev-marker', tab: 'timeline', keys: ['alt+m', 'alt+shift+m'] },+ { id: 'speed', tab: 'timeline', keys: ['mod+r'] },+ { id: 'detach-audio', tab: 'timeline', keys: ['ctrl+shift+s'] },+ /* the player */+ { id: 'play-pause', tab: 'player', keys: ['Space'] },+ { id: 'play-range', tab: 'player', keys: ['shift+Space'] },+ { id: 'loop', tab: 'player', keys: ['shift+l'] },+ { id: 'shuttle-back', tab: 'player', keys: ['j'] },+ { id: 'shuttle-stop', tab: 'player', keys: ['k'] },+ { id: 'shuttle-forward', tab: 'player', keys: ['l'] },+ { id: 'frame-back', tab: 'player', keys: ['ArrowLeft'] },+ { id: 'frame-forward', tab: 'player', keys: ['ArrowRight'] },+ { id: 'jump-back', tab: 'player', keys: ['shift+ArrowLeft'] },+ { id: 'jump-forward', tab: 'player', keys: ['shift+ArrowRight'] },+ { id: 'prev-cut', tab: 'player', keys: ['ArrowUp'] },+ { id: 'next-cut', tab: 'player', keys: ['ArrowDown'] },+ { id: 'start', tab: 'player', keys: ['Home'] },+ { id: 'end', tab: 'player', keys: ['End'] },+ { id: 'mark-in', tab: 'player', keys: ['i'] },+ { id: 'mark-out', tab: 'player', keys: ['o'] },+ { id: 'clear-range', tab: 'player', keys: ['x', 'alt+x'] },+ { id: 'range-clip', tab: 'player', keys: ['shift+x'] },+ { id: 'go-in', tab: 'player', keys: ['shift+i'] },+ { id: 'go-out', tab: 'player', keys: ['shift+o'] },+ { id: 'insert-source', tab: 'player', keys: [','] },+ { id: 'overwrite-source', tab: 'player', keys: ['.'] },+ /* the basics */+ { id: 'undo', tab: 'basic', keys: ['mod+z'] },+ { id: 'redo', tab: 'basic', keys: ['mod+shift+z'] },+ { id: 'cut', tab: 'basic', keys: ['mod+x'] },+ { id: 'copy', tab: 'basic', keys: ['mod+c'] },+ { id: 'paste', tab: 'basic', keys: ['mod+v'] },+ { id: 'duplicate', tab: 'basic', keys: ['mod+d'] },+ { id: 'remove', tab: 'basic', keys: ['Backspace', 'Delete'] },+ { id: 'ripple-delete', tab: 'basic', keys: ['shift+Backspace', 'shift+Delete'] },+ { id: 'select-all', tab: 'basic', keys: ['mod+a'] },+ { id: 'copy-attrs', tab: 'basic', keys: ['mod+shift+c'] },+ { id: 'paste-attrs', tab: 'basic', keys: ['mod+shift+v'] },+ /* the rest */+ { id: 'refer', tab: 'other', keys: ['mod+l'] },+] as const satisfies readonly { id: string; tab: KeyTab; keys: readonly string[] }[];++export type ActionId = (typeof ACTIONS)[number]['id'];+export type Action = { id: ActionId; tab: KeyTab; keys: readonly string[] };+export const ACTION_IDS: readonly ActionId[] = ACTIONS.map((a) => a.id);+const KNOWN = new Set<string>(ACTION_IDS);++/**+ * Keys that do one thing wherever they are and are not set by a scheme: listed under Other, as Settings has always+ * listed them. `keys` as combinations; a modifier held during a drag is the modifier alone (`alt+`).+ */+export const FIXED_KEYS: readonly { label: string; keys: readonly string[] }[] = [+ { label: 'deselect', keys: ['Escape'] },+ { label: 'addMedia', keys: ['Enter'] },+ { label: 'splitModeAll', keys: ['shift+'] },+ { label: 'editModeSwap', keys: ['alt+'] },+ { label: 'copyDrag', keys: ['alt+'] },+ { label: 'nudge', keys: ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'] },+ { label: 'nudgeFast', keys: ['shift+ArrowUp', 'shift+ArrowDown', 'shift+ArrowLeft', 'shift+ArrowRight'] },+ { label: 'editText', keys: ['Enter'] },+ { label: 'commitText', keys: ['mod+Enter'] },+ { label: 'cancelText', keys: ['Escape'] },+];++/* ── schemes ── */++export type BuiltInScheme = 'openfilm' | 'premiere' | 'fcp';+export type CustomSlot = 'custom1' | 'custom2' | 'custom3';+export type SchemeId = BuiltInScheme | CustomSlot;+export const BUILT_IN_SCHEMES: readonly BuiltInScheme[] = ['openfilm', 'premiere', 'fcp'];+export const CUSTOM_SLOTS: readonly CustomSlot[] = ['custom1', 'custom2', 'custom3'];+export const isBuiltIn = (id: SchemeId): id is BuiltInScheme => (BUILT_IN_SCHEMES as readonly string[]).includes(id);++/** An action's keys in a scheme: the same everywhere, or one list for a Mac and another for Windows and Linux. */+type Binding = readonly string[] | { mac: readonly string[]; other: readonly string[] };++/**+ * Premiere Pro's default keyboard shortcuts (Adobe's "Default keyboard shortcuts" list), where Studio has the action.+ * Where Windows and macOS differ, both are given.+ */+const PREMIERE: Partial<Record<ActionId, Binding>> = {+ 'play-pause': ['Space'],+ /* Play In to Out */+ 'play-range': { mac: ['alt+k'], other: ['mod+shift+Space'] },+ 'shuttle-back': ['j'],+ 'shuttle-stop': ['k'],+ 'shuttle-forward': ['l'],+ 'frame-back': ['ArrowLeft'],+ 'frame-forward': ['ArrowRight'],+ 'jump-back': ['shift+ArrowLeft'],+ 'jump-forward': ['shift+ArrowRight'],+ /* Go to Previous / Next Edit Point */+ 'prev-cut': ['ArrowUp'],+ 'next-cut': ['ArrowDown'],+ start: ['Home'],+ end: ['End'],+ 'mark-in': ['i'],+ 'mark-out': ['o'],+ 'clear-range': { mac: ['alt+x'], other: ['mod+shift+x'] },+ /* Mark Selection */+ 'range-clip': ['/'],+ 'go-in': ['shift+i'],+ 'go-out': ['shift+o'],+ 'insert-source': [','],+ 'overwrite-source': ['.'],+ /* Add Edit, Add Edit to All Tracks */+ split: ['mod+k'],+ 'split-all': ['mod+shift+k'],+ /* the Selection and Razor tools */+ 'select-mode': ['v'],+ 'split-mode': ['c'],+ /* Ripple Trim Previous / Next Edit to Playhead */+ 'ripple-start': ['q'],+ 'ripple-end': ['w'],+ /* Nudge Clip Selection Left / Right One Frame */+ 'nudge-back': { mac: ['mod+ArrowLeft'], other: ['alt+ArrowLeft'] },+ 'nudge-forward': { mac: ['mod+ArrowRight'], other: ['alt+ArrowRight'] },+ /* Snap in Timeline */+ 'toggle-snap': ['s'],+ 'zoom-in': ['='],+ 'zoom-out': ['-'],+ /* Zoom to Sequence */+ 'zoom-fit': ['\\'],+ 'add-marker': ['m'],+ 'next-marker': ['shift+m'],+ 'prev-marker': ['mod+shift+m'],+ /* Speed/Duration */+ speed: ['mod+r'],+ undo: ['mod+z'],+ redo: ['mod+shift+z'],+ cut: ['mod+x'],+ copy: ['mod+c'],+ paste: ['mod+v'],+ duplicate: ['mod+shift+/'],+ /* Clear */+ remove: ['Backspace', 'Delete'],+ 'ripple-delete': ['shift+Delete', 'alt+Backspace'],+ 'select-all': ['mod+a'],+ 'paste-attrs': ['mod+alt+v'],+};++/** Final Cut Pro's default keyboard shortcuts (Apple's "Keyboard shortcuts in Final Cut Pro"), where Studio has the action. */+const FINAL_CUT: Partial<Record<ActionId, Binding>> = {+ 'play-pause': ['Space'],+ /* Play Selection */+ 'play-range': ['/'],+ /* Loop Playback */+ loop: ['mod+l'],+ 'shuttle-back': ['j'],+ 'shuttle-stop': ['k'],+ 'shuttle-forward': ['l'],+ 'frame-back': ['ArrowLeft'],+ 'frame-forward': ['ArrowRight'],+ 'jump-back': ['shift+ArrowLeft'],+ 'jump-forward': ['shift+ArrowRight'],+ /* Go to Previous / Next Edit */+ 'prev-cut': ['ArrowUp', ';'],+ 'next-cut': ['ArrowDown', "'"],+ start: ['Home'],+ end: ['End'],+ /* Set Range Start / End, Clear Selected Ranges, Select Clip Range, Go to Range Start / End */+ 'mark-in': ['i'],+ 'mark-out': ['o'],+ 'clear-range': ['alt+x'],+ 'range-clip': ['x'],+ 'go-in': ['shift+i'],+ 'go-out': ['shift+o'],+ 'insert-source': ['w'],+ 'overwrite-source': ['d'],+ /* Blade, Blade All */+ split: ['mod+b'],+ 'split-all': ['mod+shift+b'],+ /* the Select and Blade tools */+ 'select-mode': ['a'],+ 'split-mode': ['b'],+ /* Trim Start, Trim End */+ 'ripple-start': ['alt+['],+ 'ripple-end': ['alt+]'],+ /* Nudge Left / Right */+ 'nudge-back': [','],+ 'nudge-forward': ['.'],+ /* Snapping, Skimming */+ 'toggle-snap': ['n'],+ 'toggle-preview-axis': ['s'],+ 'zoom-in': ['mod++', 'mod+='],+ 'zoom-out': ['mod+-'],+ 'zoom-fit': ['shift+z'],+ 'add-marker': ['m'],+ 'next-marker': ["ctrl+'"],+ 'prev-marker': ['ctrl+;'],+ /* Show/Hide Retime Editor */+ speed: ['mod+r'],+ 'detach-audio': ['ctrl+shift+s'],+ undo: ['mod+z'],+ redo: ['mod+shift+z'],+ cut: ['mod+x'],+ copy: ['mod+c'],+ paste: ['mod+v'],+ duplicate: ['mod+d'],+ /* Delete closes the gap; Replace with Gap leaves one */+ 'ripple-delete': ['Backspace', 'Delete'],+ remove: ['shift+Backspace', 'shift+Delete'],+ 'select-all': ['mod+a'],+ 'paste-attrs': ['mod+shift+v'],+};++const SCHEMES: Record<BuiltInScheme, Partial<Record<ActionId, Binding>>> = { openfilm: {}, premiere: PREMIERE, fcp: FINAL_CUT };++/** Every action's keys. */+export type Keymap = Record<ActionId, readonly string[]>;++/* ── key combinations ── */++const MODIFIERS = ['ctrl', 'mod', 'alt', 'shift'] as const;+type Modifier = (typeof MODIFIERS)[number];++/** A combination's modifiers and key (`shift+` is ⇧ alone, held during a drag); null when it is not one. */+export function parseCombo(combo: string): { mods: Set<Modifier>; key: string } | null {+ const m = /^((?:(?:ctrl|mod|alt|shift)\+)*)(.*)$/.exec(combo);+ if (!m) return null;+ const mods = new Set(m[1]!.split('+').filter(Boolean) as Modifier[]);+ return { mods, key: m[2]! };+}++const comboOfParts = (mods: Set<Modifier>, key: string): string => [...MODIFIERS.filter((x) => mods.has(x)), key].join('+');++/** A combination as this platform presses it: off a Mac, Control is the modifier, so `ctrl` is `mod`. */+export function platformCombo(combo: string, mac: boolean): string {+ const parsed = parseCombo(combo);+ if (!parsed) return combo;+ if (!mac && parsed.mods.delete('ctrl')) parsed.mods.add('mod');+ return comboOfParts(parsed.mods, parsed.key);+}++const NAMED = /^(?:Arrow(?:Left|Right|Up|Down)|Home|End|PageUp|PageDown|Backspace|Delete|Enter|Escape|Tab|Space|Insert|F(?:[1-9]|1[0-9]))$/;++/** A combination a key can be set to: modifiers in order, then a single character or a named key. */+export function isCombo(combo: unknown): combo is string {+ if (typeof combo !== 'string' || combo.length > 40) return false;+ const parsed = parseCombo(combo);+ if (!parsed || comboOfParts(parsed.mods, parsed.key) !== combo) return false;+ return (parsed.key.length === 1 && parsed.key !== ' ' && parsed.key === parsed.key.toLowerCase()) || NAMED.test(parsed.key);+}++/* punctuation read by where it sits (US keyboard), and what its key types with ⇧ */+const CODE_KEYS: Record<string, string> = {+ Backquote: '`', Minus: '-', Equal: '=', BracketLeft: '[', BracketRight: ']', Backslash: '\\', Semicolon: ';', Quote: "'",+ Comma: ',', Period: '.', Slash: '/',+ Digit0: '0', Digit1: '1', Digit2: '2', Digit3: '3', Digit4: '4', Digit5: '5', Digit6: '6', Digit7: '7', Digit8: '8', Digit9: '9',+};+const PUNCTUATION = new Set(Object.values(CODE_KEYS).filter((k) => !/\d/.test(k)));+const SHIFTED: Record<string, string> = {+ '~': '`', _: '-', '{': '[', '}': ']', '|': '\\', ':': ';', '"': "'", '<': ',', '>': '.', '?': '/',+ '!': '1', '@': '2', '#': '3', $: '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0',+};+const MODIFIER_KEYS = new Set(['Shift', 'Control', 'Alt', 'Meta', 'CapsLock', 'OS', 'Fn', 'Hyper', 'Super', 'AltGraph']);++/** The key of a press, as combinations name it. */+function keyName(e: Pick<KeyPress, 'key' | 'code' | 'shiftKey' | 'altKey'>): string {+ if (e.key === ' ' || e.code === 'Space') return 'Space';+ const letter = letterOf(e);+ if (/^[a-z]$/.test(letter)) return letter;+ if (e.key === '+') return '+';+ /* punctuation the layout types where it is, unshifted: read as typed */+ if (e.key.length === 1 && !e.shiftKey && !e.altKey && PUNCTUATION.has(e.key)) return e.key;+ const byCode = CODE_KEYS[e.code ?? ''];+ if (byCode) return byCode;+ if (e.key.length === 1) return SHIFTED[e.key] ?? e.key.toLowerCase();+ return e.key === 'Esc' ? 'Escape' : e.key;+}++/**+ * The combination a key press is, or null (a modifier alone, or the other platform's modifier: the Windows key is no+ * shortcut off a Mac). `+` is the same with or without ⇧ (⌘+ is ⌘⇧= on a US keyboard).+ */+export function comboOf(e: KeyPress, mac: boolean): string | null {+ if (MODIFIER_KEYS.has(e.key) || e.key === 'Dead' || e.key === 'Unidentified' || !e.key) return null;+ if (!mac && e.metaKey) return null;+ const key = keyName(e);+ const mods = new Set<Modifier>();+ if (mac && e.ctrlKey) mods.add('ctrl');+ if (mac ? e.metaKey : e.ctrlKey) mods.add('mod');+ if (e.altKey) mods.add('alt');+ if (e.shiftKey && key !== '+') mods.add('shift');+ return comboOfParts(mods, key);+}++/* ── keymaps ── */++const bindingFor = (b: Binding, mac: boolean): readonly string[] => ('mac' in b ? (mac ? b.mac : b.other) : b);++/**+ * Every action's keys under `base`, then `own` (an action's keys; missing: base's). An action without its own keys+ * keeps base's, less any key the actions given their own already use: no key does two things.+ */+function layered(base: (id: ActionId) => readonly string[], own: Partial<Record<ActionId, readonly string[]>>, mac: boolean): Keymap {+ const map = {} as Record<ActionId, readonly string[]>;+ const taken = new Set<string>();+ for (const id of ACTION_IDS) {+ const keys = own[id];+ if (!keys) continue;+ map[id] = keys;+ for (const combo of keys) taken.add(platformCombo(combo, mac));+ }+ for (const id of ACTION_IDS) {+ if (map[id]) continue;+ const keys = base(id).filter((combo) => !taken.has(platformCombo(combo, mac)));+ map[id] = keys;+ for (const combo of keys) taken.add(platformCombo(combo, mac));+ }+ return map;+}++const DEFAULTS = Object.fromEntries(ACTIONS.map((a) => [a.id, a.keys])) as unknown as Keymap;++/**+ * A built-in scheme's keys on this platform. Actions the scheme's app has take its keys; the rest keep OpenFilm's,+ * unless the app uses that key for another of Studio's actions.+ */+export function schemeKeymap(id: BuiltInScheme, mac: boolean): Keymap {+ const own = SCHEMES[id];+ const keys = Object.fromEntries(Object.entries(own).map(([action, b]) => [action, bindingFor(b, mac)])) as Partial<Record<ActionId, readonly string[]>>;+ return layered((action) => DEFAULTS[action], keys, mac);+}++/** A custom scheme: the scheme it was copied from (whose keys fill in actions it has no word on), and its keys. */+export interface CustomScheme { base: BuiltInScheme; keys: Partial<Record<ActionId, readonly string[]>> }++/** A custom scheme's keys. An action added after it was made takes its base's keys, unless one of them is used. */+export function customKeymap(custom: CustomScheme, mac: boolean): Keymap {+ const base = schemeKeymap(custom.base, mac);+ return layered((id) => base[id], custom.keys, mac);+}++/* ── finding, showing and changing keys ── */++const indexes = new WeakMap<Keymap, Map<string, ActionId>>();+const indexOf = (keymap: Keymap, mac: boolean): Map<string, ActionId> => {+ let index = indexes.get(keymap);+ if (!index) {+ index = new Map();+ for (const id of ACTION_IDS) for (const combo of keymap[id]) {+ const at = platformCombo(combo, mac);+ if (!index.has(at)) index.set(at, id);+ }+ indexes.set(keymap, index);+ }+ return index;+};++/** The action a key press is in `keymap`, or null. */+export function actionOf(e: KeyPress, keymap: Keymap, mac: boolean): ActionId | null {+ const combo = comboOf(e, mac);+ return combo ? indexOf(keymap, mac).get(combo) ?? null : null;+}++/** Whether a press is one of an action's keys. */+export const pressIs = (e: KeyPress, id: ActionId, keymap: Keymap, mac: boolean): boolean => actionOf(e, keymap, mac) === id;++/** The other action `combo` already does in `keymap` (not `id` itself), or null. */+export function conflictOf(keymap: Keymap, id: ActionId, combo: string, mac: boolean): ActionId | null {+ const at = platformCombo(combo, mac);+ for (const other of ACTION_IDS) {+ if (other !== id && keymap[other].some((c) => platformCombo(c, mac) === at)) return other;+ }+ return null;+}++/** `id` set to `combo` alone; any other action that had it loses it. */+export function assignKey(keymap: Keymap, id: ActionId, combo: string, mac: boolean): Keymap {+ const at = platformCombo(combo, mac);+ const next = { ...keymap } as Record<ActionId, readonly string[]>;+ for (const other of ACTION_IDS) {+ if (other !== id && next[other].some((c) => platformCombo(c, mac) === at)) next[other] = next[other].filter((c) => platformCombo(c, mac) !== at);+ }+ next[id] = [combo];+ return next;+}++const KEY_LABELS: Record<string, [mac: string, other: string]> = {+ ArrowLeft: ['←', '←'], ArrowRight: ['→', '→'], ArrowUp: ['↑', '↑'], ArrowDown: ['↓', '↓'],+ Backspace: ['⌫', 'Backspace'], Delete: ['⌦', 'Delete'], Escape: ['Esc', 'Esc'], Enter: ['Enter', 'Enter'],+ Space: ['Space', 'Space'], PageUp: ['Page Up', 'Page Up'], PageDown: ['Page Down', 'Page Down'], Tab: ['Tab', 'Tab'],+ '-': ['−', '−'], '`': ['~', '~'],+};+const MOD_LABELS: Record<Modifier, [mac: string, other: string]> = { ctrl: ['⌃', 'Ctrl'], mod: ['⌘', 'Ctrl'], alt: ['⌥', 'Alt'], shift: ['⇧', 'Shift'] };++/** A combination as key caps on this platform: its modifiers, then its key (none for a modifier held alone). */+export function comboCaps(combo: string, mac: boolean): string[] {+ const parsed = parseCombo(platformCombo(combo, mac));+ if (!parsed) return [combo];+ const pick = (labels: [string, string]) => labels[mac ? 0 : 1];+ const mods = MODIFIERS.filter((m) => parsed.mods.has(m)).map((m) => pick(MOD_LABELS[m]));+ if (!parsed.key) return mods;+ const known = KEY_LABELS[parsed.key];+ return [...mods, known ? pick(known) : parsed.key.length === 1 ? parsed.key.toUpperCase() : parsed.key];+}++/** A combination as one hint: ⌘⇧B on a Mac, Ctrl+Shift+B elsewhere (as lib/shortcut-hint writes them). */+export const comboText = (combo: string, mac: boolean): string => comboCaps(combo, mac).join(mac ? '' : '+');++/** An action's first key as a hint, or undefined when it has none. */+export function hintOf(keymap: Keymap, id: ActionId, mac: boolean): string | undefined {+ const combo = keymap[id][0];+ return combo ? comboText(combo, mac) : undefined;+}++/* ── what is kept ── */++/** The scheme in use and the custom ones, as Studio's prefs keep them (`keys`). */+export interface KeyPrefs { scheme: SchemeId; custom: Partial<Record<CustomSlot, CustomScheme>> }+export const DEFAULT_KEY_PREFS: KeyPrefs = { scheme: 'openfilm', custom: {} };++/** What is kept, each part checked: an unknown scheme is OpenFilm's; unknown actions and keys that are none are left out. */+export function keyPrefsOf(raw: unknown): KeyPrefs {+ const p = raw && typeof raw === 'object' ? raw as { scheme?: unknown; custom?: unknown } : {};+ const custom: KeyPrefs['custom'] = {};+ const given = p.custom && typeof p.custom === 'object' ? p.custom as Record<string, unknown> : {};+ for (const slot of CUSTOM_SLOTS) {+ const one = given[slot] as { base?: unknown; keys?: unknown } | undefined;+ if (!one || typeof one !== 'object') continue;+ const base = (BUILT_IN_SCHEMES as readonly unknown[]).includes(one.base) ? one.base as BuiltInScheme : 'openfilm';+ const keys: CustomScheme['keys'] = {};+ if (one.keys && typeof one.keys === 'object') {+ for (const [id, list] of Object.entries(one.keys as Record<string, unknown>)) {+ if (KNOWN.has(id) && Array.isArray(list)) keys[id as ActionId] = list.filter(isCombo).slice(0, 8);+ }+ }+ custom[slot] = { base, keys };+ }+ const scheme = ([...BUILT_IN_SCHEMES, ...CUSTOM_SLOTS] as readonly unknown[]).includes(p.scheme) ? p.scheme as SchemeId : 'openfilm';+ return { scheme: isBuiltIn(scheme) || custom[scheme] ? scheme : 'openfilm', custom };+}++/** The keys of a scheme (an empty custom slot: OpenFilm's). */+export function keymapFor(prefs: KeyPrefs, id: SchemeId, mac: boolean): Keymap {+ if (isBuiltIn(id)) return schemeKeymap(id, mac);+ const custom = prefs.custom[id];+ return custom ? customKeymap(custom, mac) : schemeKeymap('openfilm', mac);+}++/** The keys in use. */+export const keymapOf = (prefs: KeyPrefs, mac: boolean): Keymap => keymapFor(prefs, prefs.scheme, mac);++/** A copy of scheme `from`, as a custom scheme: all its keys, and the built-in scheme it comes from. */+export function copyOf(prefs: KeyPrefs, from: SchemeId, mac: boolean): CustomScheme {+ const keymap = keymapFor(prefs, from, mac);+ const base = isBuiltIn(from) ? from : prefs.custom[from]?.base ?? 'openfilm';+ return { base, keys: Object.fromEntries(ACTION_IDS.map((id) => [id, [...keymap[id]]])) };+}++/** The first custom slot nothing is kept in, or null. */+export const freeSlot = (prefs: KeyPrefs): CustomSlot | null => CUSTOM_SLOTS.find((slot) => !prefs.custom[slot]) ?? null;++/**+ * Ready to change a key: a custom scheme is changed itself; a built-in one is first copied into a free custom slot,+ * which becomes the scheme (`copiedTo` says which). Null: every custom slot is taken, so there is none to copy into.+ */+export function editable(prefs: KeyPrefs, mac: boolean): { prefs: KeyPrefs; slot: CustomSlot; copiedTo: CustomSlot | null } | null {+ if (!isBuiltIn(prefs.scheme)) {+ const slot = prefs.scheme;+ if (prefs.custom[slot]) return { prefs, slot, copiedTo: null };+ return { prefs: { ...prefs, custom: { ...prefs.custom, [slot]: copyOf(prefs, 'openfilm', mac) } }, slot, copiedTo: null };+ }+ const slot = freeSlot(prefs);+ if (!slot) return null;+ return { prefs: { scheme: slot, custom: { ...prefs.custom, [slot]: copyOf(prefs, prefs.scheme, mac) } }, slot, copiedTo: slot };+}++/** A custom scheme set back to the keys of the scheme it was copied from. */+export function restoreDefaults(prefs: KeyPrefs, slot: CustomSlot, mac: boolean): KeyPrefs {+ const base = prefs.custom[slot]?.base ?? 'openfilm';+ return { ...prefs, custom: { ...prefs.custom, [slot]: copyOf(prefs, base, mac) } };+}++/** A custom scheme with one action's keys changed (`combo` alone; whatever had it loses it). */+export function withKey(prefs: KeyPrefs, slot: CustomSlot, id: ActionId, combo: string, mac: boolean): KeyPrefs {+ const custom = prefs.custom[slot] ?? copyOf(prefs, 'openfilm', mac);+ const keys = assignKey(customKeymap(custom, mac), id, combo, mac);+ return { ...prefs, custom: { ...prefs.custom, [slot]: { base: custom.base, keys: Object.fromEntries(ACTION_IDS.map((a) => [a, [...keys[a]]])) } } };+}++/** A custom scheme with one action's keys taken away. */+export function withoutKeys(prefs: KeyPrefs, slot: CustomSlot, id: ActionId, mac: boolean): KeyPrefs {+ const custom = prefs.custom[slot] ?? copyOf(prefs, 'openfilm', mac);+ const keys = { ...customKeymap(custom, mac), [id]: [] };+ return { ...prefs, custom: { ...prefs.custom, [slot]: { base: custom.base, keys: Object.fromEntries(ACTION_IDS.map((a) => [a, [...keys[a]]])) } } };+}diff --git a/packages/openfilm/studio/ui/src/lib/select-all-key.test.ts b/packages/openfilm/studio/ui/src/lib/select-all-key.test.tsdeleted file mode 100644index 9e3ab96..0000000--- a/packages/openfilm/studio/ui/src/lib/select-all-key.test.ts+++ /dev/null@@ -1,17 +0,0 @@-import { test } from 'node:test';-import assert from 'node:assert/strict';-import { isSelectAll } from './select-all-key.ts';--const key = (k: string, mods: Partial<{ metaKey: boolean; ctrlKey: boolean; shiftKey: boolean; altKey: boolean }> = {}) => (- { key: k, metaKey: false, ctrlKey: false, shiftKey: false, altKey: false, ...mods }-);--test('select all is ⌘A on a Mac and Ctrl+A elsewhere; with Shift or Alt it is another shortcut', () => {- assert.equal(isSelectAll(key('a', { metaKey: true }), true), true);- assert.equal(isSelectAll(key('A', { metaKey: true }), true), true);- assert.equal(isSelectAll(key('a', { ctrlKey: true }), true), false, 'Ctrl+A on a Mac moves the caret');- assert.equal(isSelectAll(key('a', { ctrlKey: true }), false), true);- assert.equal(isSelectAll(key('a', { metaKey: true, shiftKey: true }), true), false);- assert.equal(isSelectAll(key('a', { metaKey: true, altKey: true }), true), false);- assert.equal(isSelectAll(key('a'), true), false);-});diff --git a/packages/openfilm/studio/ui/src/lib/select-all-key.ts b/packages/openfilm/studio/ui/src/lib/select-all-key.tsdeleted file mode 100644index b98c690..0000000--- a/packages/openfilm/studio/ui/src/lib/select-all-key.ts+++ /dev/null@@ -1,7 +0,0 @@-/** A key that can be select-all: what a keydown, or a key passed on from the film, says of itself. */-export interface KeyLike { key: string; metaKey: boolean; ctrlKey: boolean; shiftKey: boolean; altKey: boolean }--/** ⌘A on a Mac, Ctrl+A elsewhere, without Shift or Alt: select all. */-export function isSelectAll(e: KeyLike, mac: boolean): boolean {- return (mac ? e.metaKey : e.ctrlKey) && !e.shiftKey && !e.altKey && e.key.toLowerCase() === 'a';-}diff --git a/packages/openfilm/studio/ui/src/lib/timeline-keys.test.ts b/packages/openfilm/studio/ui/src/lib/timeline-keys.test.tsindex a32e87b..b754196 100644--- a/packages/openfilm/studio/ui/src/lib/timeline-keys.test.ts+++ b/packages/openfilm/studio/ui/src/lib/timeline-keys.test.ts@@ -1,84 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { keyCommandOf, letterOf, loopBack, playStart, SHORTCUTS, shuttleRate, type KeyPress } from './timeline-keys.ts';--const press = (key: string, mods: Partial<KeyPress> = {}): KeyPress => ({ key, metaKey: false, ctrlKey: false, shiftKey: false, altKey: false, ...mods });-const mac = (key: string, mods: Partial<KeyPress> = {}) => keyCommandOf(press(key, mods), true);-const win = (key: string, mods: Partial<KeyPress> = {}) => keyCommandOf(press(key, mods), false);--test('the keys', () => {- assert.equal(mac('j'), 'shuttle-back');- assert.equal(mac('k'), 'shuttle-stop');- assert.equal(mac('L'), 'shuttle-forward');- assert.equal(mac('i'), 'mark-in');- assert.equal(mac('o'), 'mark-out');- assert.equal(mac('x'), 'clear-range');- assert.equal(mac('I', { shiftKey: true }), 'go-in');- assert.equal(mac('O', { shiftKey: true }), 'go-out');- assert.equal(mac('L', { shiftKey: true }), 'loop');- assert.equal(mac(' ', { shiftKey: true }), 'play-range');- assert.equal(mac(' '), null, 'Space alone is play / pause, the editor\'s own');- assert.equal(mac('b', { metaKey: true }), 'split');- assert.equal(mac('b', { metaKey: true, shiftKey: true }), 'split-all');- assert.equal(mac('k', { metaKey: true }), 'split-all');- assert.equal(mac('x', { metaKey: true }), 'cut');- assert.equal(mac('d', { metaKey: true }), 'duplicate');- assert.equal(mac('ArrowUp'), 'prev-cut');- assert.equal(mac('ArrowDown'), 'next-cut');- assert.equal(mac('ArrowLeft'), 'frame-back');- assert.equal(mac('ArrowRight', { shiftKey: true }), 'jump-forward');- assert.equal(mac('ArrowLeft', { altKey: true }), 'nudge-back');- assert.equal(mac('ArrowRight', { altKey: true }), 'nudge-forward');- assert.equal(mac('Z', { shiftKey: true }), 'zoom-fit');- assert.equal(mac('n'), 'toggle-snap');- /* the switches: P (and ⇧N) the main-track magnet, ~ linkage, S the preview axis */- assert.equal(mac('N', { shiftKey: true }), 'toggle-magnet');- assert.equal(mac('p'), 'toggle-magnet');- assert.equal(mac('`'), 'toggle-linkage');- assert.equal(mac('~', { shiftKey: true }), 'toggle-linkage');- assert.equal(mac('s'), 'toggle-preview-axis');- assert.equal(mac('S', { shiftKey: true, ctrlKey: true }), 'detach-audio');- assert.equal(mac('q'), 'ripple-start');- assert.equal(mac('w'), 'ripple-end');- assert.equal(mac(','), 'insert-source');- assert.equal(mac('.'), 'overwrite-source');- assert.equal(mac('Home'), 'start');- assert.equal(mac('End'), 'end');-});--test('M adds a marker, ⇧M and ⌥M go to the next and the one before (⌥M types µ on a Mac)', () => {- assert.equal(mac('m'), 'add-marker');- assert.equal(mac('M', { shiftKey: true }), 'next-marker');- assert.equal(keyCommandOf({ ...press('µ', { altKey: true }), code: 'KeyM' }, true), 'prev-marker');- assert.equal(win('m', { altKey: true }), 'prev-marker');- assert.equal(mac('m', { metaKey: true }), null);- assert.equal(mac('m', { altKey: true, shiftKey: true }), 'prev-marker', '⌥⇧M too');-});--test('the switch, range, speed, sound and attribute keys: P, ~, S, ⇧X, ⌥X, ⌘R, ⇧⌃S, ⌘⇧C, ⌘⇧V', () => {- assert.equal(mac('p'), 'toggle-magnet');- assert.equal(keyCommandOf({ ...press('`'), code: 'Backquote' }, true), 'toggle-linkage');- assert.equal(mac('s'), 'toggle-preview-axis');- assert.equal(mac('X', { shiftKey: true }), 'range-clip');- assert.equal(keyCommandOf({ ...press('≈', { altKey: true }), code: 'KeyX' }, true), 'clear-range');- assert.equal(mac('r', { metaKey: true }), 'speed');- assert.equal(mac('S', { ctrlKey: true, shiftKey: true }), 'detach-audio');- assert.equal(win('S', { ctrlKey: true, shiftKey: true }), 'detach-audio');- assert.equal(mac('C', { metaKey: true, shiftKey: true }), 'copy-attrs');- assert.equal(mac('V', { metaKey: true, shiftKey: true }), 'paste-attrs');- assert.equal(keyCommandOf({ ...press('['), code: 'BracketLeft' }, true), 'select-left');- assert.equal(keyCommandOf({ ...press(']'), code: 'BracketRight' }, true), 'select-right');-});--test('keys that are not the editor\'s stay the browser\'s, and Ctrl is the modifier off a Mac', () => {- assert.equal(mac('b', { ctrlKey: true }), null, 'Ctrl+B on a Mac is not ⌘B');- assert.equal(win('b', { ctrlKey: true }), 'split');- assert.equal(win('b', { metaKey: true }), null);- assert.equal(mac('c', { metaKey: true }), null, 'copy is the timeline\'s own');- assert.equal(mac('z', { metaKey: true }), null, 'undo is the editor\'s own');- assert.equal(mac('j', { altKey: true }), null);- assert.equal(mac('ArrowUp', { shiftKey: true }), null);-});+import { letterOf, loopBack, playStart, shuttleRate } from './timeline-keys.ts';test('a letter is read by what it types, or where it sits when it types no Latin letter', () => {assert.equal(letterOf({ key: 'J', code: 'KeyJ' }), 'j');@@ -86,13 +8,6 @@ test('a letter is read by what it types, or where it sits when it types no Latinassert.equal(letterOf({ key: 'a', code: 'KeyQ' }), 'a');/* Korean: ㅓ is on J */assert.equal(letterOf({ key: 'ㅓ', code: 'KeyJ' }), 'j');- assert.equal(keyCommandOf({ ...press('ㅓ'), code: 'KeyJ' }, true), 'shuttle-back');-});--test('every key in Settings\' list is one the editor takes', () => {- const rows = SHORTCUTS.flatMap((g) => g.rows);- assert.ok(rows.length > 30);- assert.equal(new Set(rows.map((r) => r.label)).size, rows.length, 'no row twice');});test('J / K / L: L faster each time up to 4×, J the same backwards, K stops; the other way starts at 1×', () => {diff --git a/packages/openfilm/studio/ui/src/lib/timeline-keys.ts b/packages/openfilm/studio/ui/src/lib/timeline-keys.tsindex b86eabf..bfc3fa0 100644--- a/packages/openfilm/studio/ui/src/lib/timeline-keys.ts+++ b/packages/openfilm/studio/ui/src/lib/timeline-keys.ts@@ -1,26 +1,11 @@/**- * The editor's keys: which key does what (`keyCommandOf`), the list Settings shows (`SHORTCUTS`), J / K / L shuttle- * (`shuttleRate`) and looping a range (`loopBack`, `playStart`).+ * Reading keys (`letterOf`), J / K / L shuttle (`shuttleRate`) and looping a range (`loopBack`, `playStart`). Which key+ * does what is lib/keymap's.** Plain letters are read by the letter they type, so they follow the keyboard's layout; on a layout without Latin* letters (Korean, Russian…) by where the key is on a US keyboard.*/-export type KeyCommand =- | 'shuttle-back' | 'shuttle-stop' | 'shuttle-forward'- | 'mark-in' | 'mark-out' | 'clear-range' | 'go-in' | 'go-out'- | 'loop' | 'play-range'- | 'split' | 'split-all' | 'cut' | 'duplicate'- | 'prev-cut' | 'next-cut'- | 'frame-back' | 'frame-forward' | 'jump-back' | 'jump-forward'- | 'nudge-back' | 'nudge-forward'- | 'start' | 'end'- | 'zoom-fit' | 'toggle-snap' | 'toggle-magnet' | 'toggle-linkage' | 'toggle-preview-axis'- | 'range-clip' | 'speed' | 'detach-audio' | 'copy-attrs' | 'paste-attrs' | 'select-left' | 'select-right'- | 'ripple-start' | 'ripple-end'- | 'insert-source' | 'overwrite-source'- | 'add-marker' | 'next-marker' | 'prev-marker';-export interface KeyPress {key: string;code?: string;@@ -41,164 +26,6 @@ export function letterOf(e: Pick<KeyPress, 'key' | 'code'>): string {/** How many frames ⇧← / ⇧→ move the playhead (a big step). */export const JUMP_FRAMES = 10;-/**- * The command a key press is, or null. `mac`: ⌘ is the modifier there (Ctrl elsewhere). Arrows: ← / → a frame (⇧ ten- * frames), ⌥ ← / → move the selected clips a frame, ↑ / ↓ the previous / next cut.- */-export function keyCommandOf(e: KeyPress, mac: boolean): KeyCommand | null {- const mod = mac ? e.metaKey : e.ctrlKey;- const k = letterOf(e);- /* ⇧⌃S detaches a video's sound (on a Mac Ctrl itself, elsewhere Ctrl the modifier) */- if (k === 's' && e.shiftKey && e.ctrlKey && !e.metaKey && !e.altKey) return 'detach-audio';- /* the other platform's modifier (Ctrl on a Mac) is no shortcut here */- const other = mac ? e.ctrlKey : e.metaKey;- if (other) return null;- if (mod) {- if (e.altKey) return null;- if (k === 'b') return e.shiftKey ? 'split-all' : 'split';- /* ⌘⇧C / ⌘⇧V copy a clip's look, place and sound onto others (copy / paste attributes) */- if (k === 'c' && e.shiftKey) return 'copy-attrs';- if (k === 'v' && e.shiftKey) return 'paste-attrs';- if (k === 'r' && !e.shiftKey) return 'speed';- if (k === 'k' && !e.shiftKey) return 'split-all';- if (k === 'x' && !e.shiftKey) return 'cut';- if (k === 'd' && !e.shiftKey) return 'duplicate';- return null;- }- switch (e.key) {- case 'ArrowLeft': return e.altKey ? (e.shiftKey ? null : 'nudge-back') : e.shiftKey ? 'jump-back' : 'frame-back';- case 'ArrowRight': return e.altKey ? (e.shiftKey ? null : 'nudge-forward') : e.shiftKey ? 'jump-forward' : 'frame-forward';- case 'ArrowUp': return e.altKey || e.shiftKey ? null : 'prev-cut';- case 'ArrowDown': return e.altKey || e.shiftKey ? null : 'next-cut';- case 'Home': return e.altKey ? null : 'start';- case 'End': return e.altKey ? null : 'end';- case ' ': return e.shiftKey && !e.altKey ? 'play-range' : null;- case ',': return e.altKey || e.shiftKey ? null : 'insert-source';- case '.': return e.altKey || e.shiftKey ? null : 'overwrite-source';- default: break;- }- /* [ / ]: every clip before / after the playhead selected, read by where the key is */- if (!e.shiftKey && !e.altKey && (e.code === 'BracketLeft' || e.key === '[')) return 'select-left';- if (!e.shiftKey && !e.altKey && (e.code === 'BracketRight' || e.key === ']')) return 'select-right';- /* ~ (the key left of 1, with ⇧ or without): linkage on / off */- if (e.code === 'Backquote' || e.key === '`' || e.key === '~') return e.altKey ? null : 'toggle-linkage';- /* ⌥M / ⌥⇧M: the marker before; ⌥X: the range cleared (on a Mac ⌥ types another letter: read by where the key is) */- if (e.altKey) return k === 'm' ? 'prev-marker' : k === 'x' && !e.shiftKey ? 'clear-range' : null;- if (e.shiftKey) {- switch (k) {- case 'i': return 'go-in';- case 'o': return 'go-out';- case 'l': return 'loop';- case 'z': return 'zoom-fit';- case 'n': return 'toggle-magnet';- case 'm': return 'next-marker';- /* ⇧X: the range is the selected clips' */- case 'x': return 'range-clip';- default: return null;- }- }- switch (k) {- case 'j': return 'shuttle-back';- case 'k': return 'shuttle-stop';- case 'l': return 'shuttle-forward';- case 'i': return 'mark-in';- case 'o': return 'mark-out';- case 'x': return 'clear-range';- case 'n': return 'toggle-snap';- case 'p': return 'toggle-magnet';- case 's': return 'toggle-preview-axis';- case 'q': return 'ripple-start';- case 'w': return 'ripple-end';- case 'm': return 'add-marker';- default: return null;- }-}--/**- * Settings' list of keys, in groups: each row's words (a key of settings.shortcuts) and its keys, as `mod` (⌘ / Ctrl),- * `ctrl` (⌃, Ctrl itself), `shift` (⇧), `alt` (⌥) and the key. Kept here beside keyCommandOf, so the list says what the- * keys do.- */-export type ShortcutKey = { key: string; mod?: boolean; ctrl?: boolean; shift?: boolean; alt?: boolean };-export type ShortcutRow = { label: string; keys: ShortcutKey[] };--const k = (key: string, mods: Omit<ShortcutKey, 'key'> = {}): ShortcutKey => ({ key, ...mods });--export const SHORTCUTS: { group: 'groupPlayback' | 'groupMarks' | 'groupEdit' | 'groupView'; rows: ShortcutRow[] }[] = [- {- group: 'groupPlayback',- rows: [- { label: 'playPause', keys: [k('Space')] },- { label: 'shuttle', keys: [k('J'), k('K'), k('L')] },- { label: 'shuttleFrame', keys: [k('K+J'), k('K+L')] },- { label: 'frameStep', keys: [k('←'), k('→')] },- { label: 'jumpStep', keys: [k('←', { shift: true }), k('→', { shift: true })] },- { label: 'cutStep', keys: [k('↑'), k('↓')] },- { label: 'seekEnds', keys: [k('Home'), k('End')] },- ],- },- {- group: 'groupMarks',- rows: [- { label: 'markIn', keys: [k('I')] },- { label: 'markOut', keys: [k('O')] },- { label: 'clearMarks', keys: [k('X'), k('X', { alt: true })] },- { label: 'rangeClip', keys: [k('X', { shift: true })] },- { label: 'goInOut', keys: [k('I', { shift: true }), k('O', { shift: true })] },- { label: 'playRange', keys: [k('Space', { shift: true })] },- { label: 'loop', keys: [k('L', { shift: true })] },- { label: 'insertSource', keys: [k(',')] },- { label: 'overwriteSource', keys: [k('.')] },- { label: 'addMedia', keys: [k('Enter')] },- { label: 'addMarker', keys: [k('M')] },- { label: 'markerStep', keys: [k('M', { shift: true }), k('M', { alt: true, shift: true })] },- ],- },- {- group: 'groupEdit',- rows: [- { label: 'undo', keys: [k('Z', { mod: true })] },- { label: 'redo', keys: [k('Z', { mod: true, shift: true })] },- { label: 'split', keys: [k('B', { mod: true })] },- { label: 'splitAll', keys: [k('B', { mod: true, shift: true }), k('K', { mod: true })] },- { label: 'rippleStart', keys: [k('Q')] },- { label: 'rippleEnd', keys: [k('W')] },- { label: 'copy', keys: [k('C', { mod: true })] },- { label: 'cut', keys: [k('X', { mod: true })] },- { label: 'paste', keys: [k('V', { mod: true })] },- { label: 'duplicate', keys: [k('D', { mod: true })] },- { label: 'copyAttrs', keys: [k('C', { mod: true, shift: true })] },- { label: 'pasteAttrs', keys: [k('V', { mod: true, shift: true })] },- { label: 'speedPanel', keys: [k('R', { mod: true })] },- { label: 'detachAudio', keys: [k('S', { ctrl: true, shift: true })] },- { label: 'remove', keys: [k('⌫'), k('Delete')] },- { label: 'rippleDelete', keys: [k('⌫', { shift: true }), k('Delete', { shift: true })] },- { label: 'nudgeClip', keys: [k('←', { alt: true }), k('→', { alt: true })] },- { label: 'selectAll', keys: [k('A', { mod: true })] },- { label: 'selectSide', keys: [k('['), k(']')] },- { label: 'deselect', keys: [k('Esc')] },- { label: 'selectMode', keys: [k('A'), k('V')] },- { label: 'splitMode', keys: [k('B')] },- { label: 'splitModeAll', keys: [k('', { shift: true })] },- { label: 'toggleMagnet', keys: [k('P'), k('N', { shift: true })] },- { label: 'toggleSnap', keys: [k('N')] },- { label: 'toggleLinkage', keys: [k('~')] },- { label: 'togglePreviewAxis', keys: [k('S')] },- { label: 'editModeSwap', keys: [k('', { alt: true })] },- { label: 'copyDrag', keys: [k('', { alt: true })] },- ],- },- {- group: 'groupView',- rows: [- { label: 'zoomIn', keys: [k('=', { mod: true }), k('+', { mod: true })] },- { label: 'zoomOut', keys: [k('−', { mod: true })] },- { label: 'zoomReset', keys: [k('0', { mod: true })] },- { label: 'zoomFit', keys: [k('Z', { shift: true })] },- ],- },-];-/* ── J / K / L ── *//** The fastest a shuttle goes, either way. */