From 32cfb034e2fa3a50c8be7f5c2faf4f644f4d25b6 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Thu, 15 Oct 2026 16:30:34 +0200 Subject: [PATCH] Implemented better shortcut menu --- CLAUDE.md | 2 +- frontend/src/components/SettingsMenu.tsx | 21 +- frontend/src/components/ShortcutsDialog.tsx | 628 ++++++++++++++++---- frontend/src/lib/icons.tsx | 6 + frontend/src/lib/shortcuts.ts | 252 ++++++++ 5 files changed, 793 insertions(+), 116 deletions(-) create mode 100644 frontend/src/lib/shortcuts.ts diff --git a/CLAUDE.md b/CLAUDE.md index 9af126d..73d8bfb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -893,7 +893,7 @@ Two independent apps that talk over HTTP: / Try again (`backend_restart`). The shell has no timeout of its own. Before ready it answers quit requests itself — nothing can be unsaved — and stops at ready so it never races `QuitGuard`), `SaveBar` (+ "Discard changes…" when - dirty, and the settings gear beside it, whose menu opens `ShortcutsDialog` — the shortcut list is written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too — and `AppSettings` ("Konduktor Settings…": app-level prefs, each with its default in `APP_SETTING_DEFAULTS` and read through `useAppSetting`; today `expandPlaylistFolders` and `exportRootFolder`, both default off — the latter read by the backend at `run_export` and passed down as `ExportPayload.root_folder`. The Sidebar holds folder open state as per-id overrides of that setting, reset on a new library or a change of the setting, and carried to the new ids when a rename/move changes a folder's path id)), `Toolbar` (search/filters; columns are chosen by right-clicking the table header), + dirty, and the settings gear beside it, whose menu (or `?` anywhere) opens `ShortcutsDialog` — a KEYBOARD MAP (decided 2026-10-15): keys lit in the colour of what they do, a caption explaining the key pointed at or pressed (pressing explains, it never acts: a capture-phase listener keeps the deck's and table's keys from firing), holding or picking ⇧ / Cmd-Ctrl / Alt relights it with that layer, mouse gestures listed beneath. It shrinks to fit the dialog and drops the words on the keys when too small. Its content is `lib/shortcuts.ts`, written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too — and `AppSettings` ("Konduktor Settings…": app-level prefs, each with its default in `APP_SETTING_DEFAULTS` and read through `useAppSetting`; today `expandPlaylistFolders` and `exportRootFolder`, both default off — the latter read by the backend at `run_export` and passed down as `ExportPayload.root_folder`. The Sidebar holds folder open state as per-id overrides of that setting, reset on a new library or a change of the setting, and carried to the new ids when a rename/move changes a folder's path id)), `Toolbar` (search/filters; columns are chosen by right-clicking the table header), `TrackTable` (**the one track list** — All Tracks, playlists, exports and devices. TanStack Table + **virtualized** grid; per-row play button, configurable columns, header sorting, inline double-click editing, and diff --git a/frontend/src/components/SettingsMenu.tsx b/frontend/src/components/SettingsMenu.tsx index e9d8929..c0143eb 100644 --- a/frontend/src/components/SettingsMenu.tsx +++ b/frontend/src/components/SettingsMenu.tsx @@ -38,6 +38,25 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) { return () => document.removeEventListener('mousedown', onDoc) }, [open]) + // The `?` key opens the shortcut map from anywhere — unless typing, or + // something already holds the keyboard. Pressed as it is, no Shift: by its + // position (the US/UK "/ ?" key), and by the character on layouts that put + // `?` elsewhere (typed with Shift there). + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.metaKey || e.ctrlKey || e.altKey) return + if (!(e.code === 'Slash' && !e.shiftKey) && e.key !== '?') return + const t = e.target as HTMLElement | null + if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable)) return + if (document.querySelector('[aria-modal="true"], [role="menu"]')) return + e.preventDefault() + setOpen(false) + setShowShortcuts(true) + } + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, []) + const item = 'flex w-full flex-col items-start rounded-[10px] px-2.5 py-1.5 text-left hover:bg-ink-800' @@ -122,7 +141,7 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) { className={item} > View Shortcuts - Every keyboard shortcut in one list + Every keyboard shortcut, on a keyboard (?) )} diff --git a/frontend/src/components/ShortcutsDialog.tsx b/frontend/src/components/ShortcutsDialog.tsx index 84bd1e5..082bac5 100644 --- a/frontend/src/components/ShortcutsDialog.tsx +++ b/frontend/src/components/ShortcutsDialog.tsx @@ -1,112 +1,167 @@ import { createPortal } from 'react-dom' -import { useEffect } from 'react' +import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react' import { useCaps } from '../lib/capabilities' +import { Icon } from '../lib/icons' +import { + ARROW_GAP, + ARROW_KEYS, + AREA_COLORS, + AREAS, + KEY_ROWS, + KEYBOARD_UNITS, + KEYS_BY_CODE, + LAYER_NAMES, + LAYERS, + MODIFIER_KEY, + MOUSE, + bindings, + modifierLayer, + padRange, + unusedNote, + type Area, + type Binding, + type KeyDef, + type Layer, + type MouseGesture, +} from '../lib/shortcuts' interface Props { onClose: () => void } -// Cmd on macOS, Ctrl elsewhere — the handlers accept either, but a list that -// says "Cmd/Ctrl" everywhere is harder to scan than one that names your key. -const IS_MAC = /Mac|iPhone|iPad/.test(navigator.userAgent) -const MOD = IS_MAC ? '⌘' : 'Ctrl' -const ALT_KEY = IS_MAC ? '⌥' : 'Alt' +/** Key unit bounds, px. The map shrinks to fit the dialog; below LABEL_MIN the + * words on the keys go (the caption still explains each key), below SHORT_MIN + * the long modifier legends become symbols. */ +const UNIT_MAX = 52 +const UNIT_MIN = 20 +const LABEL_MIN = 44 +const SHORT_MIN = 38 -type Row = { keys: string[][]; action: string } -type Section = { title: string; rows: Row[] } +const ALL_AREAS = Object.keys(AREAS) as Area[] +const matchText = (b: Binding) => `${b.text} ${b.label}`.toLowerCase() +const mouseText = (r: MouseGesture) => `${r.gesture} ${r.on ?? ''} ${r.text}`.toLowerCase() -/** Hotcue keys are digits in pad order, 0 being the tenth, so the list follows - * the loaded library's bank size rather than hard-coding eight. */ -function hotcueKeys(slots: number): string { - const n = Math.min(slots, 10) - if (n <= 0) return '1' - if (n <= 9) return `1–${n}` - return '1–9, 0' -} - -function sections(slots: number): Section[] { - const pads = hotcueKeys(slots) - return [ - { - title: 'Deck', - rows: [ - { keys: [['Space']], action: 'Play / pause' }, - { keys: [['C']], action: 'CUE — jump back, set, or hold to preview' }, - { keys: [['←'], ['→']], action: 'Beat jump back / forward — or move the loop, while one plays' }, - { keys: [[MOD, '↓'], [MOD, '↑']], action: 'Halve / double the loop and jump size' }, - { keys: [['Shift', '←'], ['Shift', '→']], action: 'Previous / next grid marker' }, - { keys: [[pads]], action: 'Hotcue — set if empty, else jump (hold to preview)' }, - { keys: [['Shift', pads]], action: 'Delete hotcue' }, - { keys: [['Q'], ['W'], ['E'], ['R']], action: 'Stem track: mute / unmute stem 1–4' }, - { keys: [['Shift', 'Q–R']], action: 'Stem track: solo — mute every other stem (again to unmute all)' }, - { keys: [[ALT_KEY, 'Click', 'stem']], action: 'Solo a stem from its lane button' }, - { keys: [['Drag waveform']], action: 'Scratch' }, - { keys: [[MOD, 'Scroll']], action: 'Zoom the waveform' }, - { keys: [['Right-click', 'pad']], action: 'Hotcue type, rename, delete' }, - ], - }, - { - title: 'Track list', - rows: [ - { keys: [['Enter']], action: 'Load and play the highlighted track' }, - { keys: [['↑'], ['↓']], action: 'Move the selection' }, - { keys: [['Shift', '↑'], ['Shift', '↓']], action: 'Extend the selection' }, - { keys: [[MOD, 'A']], action: 'Select all' }, - { keys: [['Esc']], action: 'Clear the selection' }, - { keys: [['Delete']], action: 'Remove from this playlist' }, - { keys: [['Shift', 'Click']], action: 'Select a range' }, - { keys: [[MOD, 'Click']], action: 'Add to / remove from the selection' }, - { keys: [['Double-click']], action: 'Edit a cell' }, - { keys: [['Right-click']], action: 'Track menu (header: choose columns)' }, - { keys: [['Drag rows']], action: 'Onto a playlist or export to add, onto the deck to load, within a playlist to reorder' }, - { keys: [[ALT_KEY, 'Drag']], action: 'Move tracks to another playlist (out of this one)' }, - { keys: [['Esc']], action: 'While dragging: cancel the drag' }, - ], - }, - { - title: 'Sidebar', - rows: [ - { keys: [['Right-click']], action: 'New playlist or folder, rename, delete' }, - { keys: [['Drag']], action: 'Rearrange playlists and folders; onto an export to add one' }, - ], - }, - { - title: 'Fields & dialogs', - rows: [ - { keys: [['Enter']], action: 'Save the edit / confirm' }, - { keys: [['Esc']], action: 'Cancel / close' }, - ], - }, - ] -} - -function Keys({ combo }: { combo: string[] }) { - return ( - - {combo.map((k, i) => ( - - {k} - - ))} - - ) -} - -/** Every keyboard shortcut (and the mouse gestures that go with them), from the - * settings menu. Keep in step with the handlers in `PrepStrip` and `TrackTable` - * — this list is written out by hand, not derived from them. */ +/** Every shortcut, drawn on a keyboard: a key lights in the colour of what it + * does, pointing at (or pressing) it explains it, and holding a modifier — or + * picking one above — relights the map with that layer. Mouse gestures are + * listed beneath. The content lives in `lib/shortcuts.ts`. */ export function ShortcutsDialog({ onClose }: Props) { const slots = useCaps().cues.hotcue_slots + const binds = useMemo(() => bindings(slots), [slots]) + const [sticky, setSticky] = useState('base') + const [held, setHeld] = useState>(new Set()) + const [hover, setHover] = useState(null) + const [pressed, setPressed] = useState(null) + const [query, setQuery] = useState('') + const [areas, setAreas] = useState>(new Set(ALL_AREAS)) + const layer: Layer = held.has('mod') ? 'mod' : held.has('alt') ? 'alt' : held.has('shift') ? 'shift' : sticky + const q = query.trim().toLowerCase() + + // ---- fit: one key unit from the width the map has ---- + const fitRef = useRef(null) + const [unit, setUnit] = useState(UNIT_MAX) + useLayoutEffect(() => { + const el = fitRef.current + if (!el) return + const fit = () => { + const u = Math.floor(el.clientWidth / KEYBOARD_UNITS) + setUnit(Math.max(UNIT_MIN, Math.min(UNIT_MAX, u))) + } + fit() + const ro = new ResizeObserver(fit) + ro.observe(el) + return () => ro.disconnect() + }, []) + + // ---- keyboard: pressing a key explains it rather than doing it ---- + // Capture phase on window, so the deck's and the table's own listeners (which + // are on window too, bubbling) never see a key pressed in here. + const queryRef = useRef(query) + queryRef.current = query useEffect(() => { - const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose() - window.addEventListener('keydown', onKey) - return () => window.removeEventListener('keydown', onKey) + let release: number | undefined + const onDown = (e: KeyboardEvent) => { + const inField = (e.target as HTMLElement | null)?.tagName === 'INPUT' + if (e.key === 'Escape') { + e.preventDefault() + e.stopPropagation() + if (inField && queryRef.current) setQuery('') + else onClose() + return + } + if (inField) return + const mod = modifierLayer(e.code) + if (mod) { + setHeld((h) => new Set(h).add(mod)) + return + } + if (e.code === 'Tab' || !KEYS_BY_CODE[e.code]) return + e.stopPropagation() + // Space / Enter still press a focused control (a layer tab, a modifier key). + const t = e.target as HTMLElement | null + if ((e.code === 'Space' || e.code === 'Enter') && t?.tagName === 'BUTTON' && !t.dataset.mapKey) return + e.preventDefault() + setHover(e.code) + setPressed(e.code) + window.clearTimeout(release) + release = window.setTimeout(() => setPressed(null), 160) + } + const onUp = (e: KeyboardEvent) => { + const mod = modifierLayer(e.code) + if (mod) { + setHeld((h) => { + const next = new Set(h) + next.delete(mod) + return next + }) + } else if (KEYS_BY_CODE[e.code] && (e.target as HTMLElement | null)?.tagName !== 'INPUT') { + e.stopPropagation() // the deck's keyup ends a held cue/hotcue preview + } + } + const onBlur = () => setHeld(new Set()) + window.addEventListener('keydown', onDown, true) + window.addEventListener('keyup', onUp, true) + window.addEventListener('blur', onBlur) + return () => { + window.clearTimeout(release) + window.removeEventListener('keydown', onDown, true) + window.removeEventListener('keyup', onUp, true) + window.removeEventListener('blur', onBlur) + } }, [onClose]) + const visible = (l: Layer, code: string) => (binds[l][code] ?? []).filter((b) => areas.has(b.area)) + const layerCount = (l: Layer) => + Object.values(binds[l]).flat().filter((b) => areas.has(b.area) && (!q || matchText(b).includes(q))).length + + MOUSE.flatMap((c) => c.rows).filter((r) => (r.mod ?? 'base') === l && (!q || mouseText(r).includes(q))).length + + const pickLayer = (l: Layer) => setSticky((s) => (s === l && l !== 'base' ? 'base' : l)) + const toggleArea = (a: Area) => + setAreas((cur) => { + const next = new Set(cur) + if (next.has(a) && next.size > 1) next.delete(a) + else next.add(a) + return next + }) + + const gap = Math.max(2, Math.round(unit / 10)) + const keyProps = { + unit, + gap, + labels: unit >= LABEL_MIN, + short: unit < SHORT_MIN, + layer, + hover, + pressed, + q, + visible, + noted: (code: string) => !!unusedNote(code, slots), + bound: (code: string) => LAYERS.some((l) => binds[l][code]), + onHover: setHover, + onPick: pickLayer, + } + return createPortal(
e.stopPropagation()} > -
+
Keyboard Shortcuts
+ setQuery(e.target.value)} + placeholder="Search shortcuts" + aria-label="Search shortcuts" + className="well ml-auto w-64 min-w-0 rounded-[9px] border border-line px-2.5 py-1.5 text-[13px] text-text outline-none" + />
-
- {sections(slots).map((s) => ( -
-
- {s.title} -
-
- {s.rows.map((r, i) => ( -
- {r.action} - - {r.keys.map((combo, j) => ( - - ))} - + +
+
+
+ {LAYERS.map((l) => ( + + ))} +
+
+ {ALL_AREAS.map((a) => ( + + ))} +
+
+ +
+
setHover(null)} + > +
+ {KEY_ROWS.map((row, i) => ( +
+ {row.map((k) => ( + + ))}
))}
-
- ))} +
+ {ARROW_KEYS.map((k, i) => + k ? : , + )} +
+
+
+ +
+ +
+ +
+
Mouse
+
+ {MOUSE.map((col) => ( +
+
{col.title}
+ {col.rows.map((r, i) => { + const m = r.mod ?? 'base' + const hit = !q || mouseText(r).includes(q) + const lit = layer !== 'base' && m === layer && hit + const dim = (layer !== 'base' && m !== layer) || !hit + return ( +
+ + {r.mod && {MODIFIER_KEY[r.mod]}} + + + {r.gesture} + {r.on ? ` ${r.on}` : ''} + + + {r.text} +
+ ) + })} +
+ ))} +
+
+ +
+ Press the ? key anywhere to open this list. +
, document.body, ) } + +function Kbd({ children }: { children: ReactNode }) { + return ( + + {children} + + ) +} + +function Combo({ layer, code }: { layer: Layer; code: string }) { + const legend = KEYS_BY_CODE[code]?.legend ?? code + return ( + + {layer !== 'base' && {MODIFIER_KEY[layer]}} + {legend} + + ) +} + +function Line({ layer, code, b, other }: { layer: Layer; code: string; b: Binding; other?: boolean }) { + return ( +
+ + {b.text} + + {AREAS[b.area]} + +
+ ) +} + +const Sub = ({ children }: { children: ReactNode }) => ( +
{children}
+) + +function Caption({ + hover, + layer, + q, + query, + slots, + binds, + areas, +}: { + hover: string | null + layer: Layer + q: string + query: string + slots: number + binds: ReturnType + areas: ReadonlySet +}) { + if (hover) { + const role = KEYS_BY_CODE[hover]?.role + if (role) { + const keys = Object.keys(binds[role]).length + const mouse = MOUSE.flatMap((c) => c.rows).filter((r) => r.mod === role).length + return ( +
+ {MODIFIER_KEY[role]} + + Hold, or click, to light up what {LAYER_NAMES[role]} changes: {keys} key{keys === 1 ? '' : 's'} and{' '} + {mouse} mouse gesture{mouse === 1 ? '' : 's'}. + +
+ ) + } + const here = binds[layer][hover] ?? [] + const others = LAYERS.filter((l) => l !== layer && binds[l][hover]) + return ( + <> + {here.length ? ( + here.map((b, i) => ) + ) : ( +
+ + {unusedNote(hover, slots) ?? 'Does nothing in Konduktor.'} +
+ )} + {others.length > 0 && Also on this key} + {others.flatMap((l) => binds[l][hover].map((b, i) => ))} + + ) + } + + if (q) { + const hits = LAYERS.flatMap((l) => + Object.entries(binds[l]).flatMap(([code, bs]) => + bs + .filter((b) => areas.has(b.area) && matchText(b).includes(q)) + .map((b, i) => ), + ), + ) + const mouse = MOUSE.flatMap((c) => c.rows).filter((r) => mouseText(r).includes(q)).length + if (!hits.length && !mouse) return No shortcut matches “{query.trim()}”. + return ( + <> + {hits} + {mouse > 0 && {mouse} mouse gesture{mouse === 1 ? '' : 's'} below} + + ) + } + + if (layer !== 'base') { + return ( + <> + + Showing what {LAYER_NAMES[layer]} changes. The highlighted mouse gestures below use it too. + + Let go of the key, or pick “No modifier”, to go back. + + ) + } + return ( + <> + Point at a key, or press it, to see what it does. + + Hold {MODIFIER_KEY.shift} {MODIFIER_KEY.mod} or {MODIFIER_KEY.alt}, or pick + one above, to see what each modifier changes. + + + {padRange(slots)} are this library's {slots} hotcue pads; Q W E R are the stems of a stem track. + + + ) +} + +interface KeyProps { + def: KeyDef + fnRow: boolean + unit: number + gap: number + labels: boolean + short: boolean + layer: Layer + hover: string | null + pressed: string | null + q: string + visible: (layer: Layer, code: string) => Binding[] + noted: (code: string) => boolean + bound: (code: string) => boolean + onHover: (code: string | null) => void + onPick: (layer: Layer) => void +} + +function Key({ def, fnRow, unit, gap, labels, short, layer, hover, pressed, q, visible, noted, bound, onHover, onPick }: KeyProps) { + const { code, role } = def + const legend = short && def.short ? def.short : def.legend + const ents = role ? [] : visible(layer, code) + const first = ents[0] + const kc = first ? (first.color ?? AREA_COLORS[first.area]) : 'var(--color-faint)' + const on = role === layer + const miss = !!first && !!q && !ents.some((b) => matchText(b).includes(q)) + const pad = first?.label === 'Pad' || first?.label === 'Delete' + const interactive = !!role || bound(code) || noted(code) + const inset = Math.max(2, Math.round(unit * 0.1)) + + const style: CSSProperties = { + width: (def.w ?? 1) * unit - gap, + height: fnRow ? Math.round(unit * 0.72) : unit - gap, + padding: `${Math.max(2, inset - 1)}px ${inset}px`, + borderRadius: pad ? Math.round(unit * 0.18) : Math.round(unit * 0.14), + borderColor: 'rgb(255 255 255 / 0.05)', + } + if (on) { + Object.assign(style, { + background: 'var(--color-accent)', + borderColor: 'transparent', + color: 'var(--color-ink-950)', + boxShadow: '0 0 22px -4px var(--color-accent)', + }) + } else if (role) { + style.borderColor = 'rgb(255 255 255 / 0.12)' + } else if (first) { + Object.assign(style, { + background: pressed === code + ? `color-mix(in oklab, ${kc} 45%, transparent)` + : `color-mix(in oklab, ${kc} ${pad ? 24 : 15}%, rgb(255 255 255 / 0.05))`, + borderColor: hover === code + ? `color-mix(in oklab, ${kc} 85%, white)` + : `color-mix(in oklab, ${kc} 50%, transparent)`, + boxShadow: `0 0 18px -6px color-mix(in oklab, ${kc} 70%, transparent), inset 0 1px 0 rgb(255 255 255 / 0.1)`, + }) + } else if (hover === code) { + style.borderColor = 'rgb(255 255 255 / 0.3)' + } + + const legendSize = Math.max(8.5, Math.min(11, unit * 0.22)) - (role && !short ? 1 : 0) + const body = ( + <> + + {legend} + + {labels && first && ( + + {first.label} + + )} + {ents.length > 1 && ( + + {ents.map((b, i) => ( + + ))} + + )} + + ) + const className = `relative flex shrink-0 flex-col items-start justify-between border text-left transition-[background,border-color,opacity,transform,box-shadow] duration-150 ${ + first || on ? '' : 'bg-ink-850' + } ${role && !on ? 'text-muted' : 'text-faint'} ${miss ? 'opacity-25' : ''} ${pressed === code ? 'scale-[0.96]' : ''}` + + if (!interactive) { + return ( + onHover(def.legend ? code : null)}> + {body} + + ) + } + return ( + + ) +} diff --git a/frontend/src/lib/icons.tsx b/frontend/src/lib/icons.tsx index b8dcf95..71d0988 100644 --- a/frontend/src/lib/icons.tsx +++ b/frontend/src/lib/icons.tsx @@ -99,6 +99,12 @@ const PATHS = { fadeOut: , eject: , grid: , + mouse: ( + <> + + + + ), } as const export type IconName = keyof typeof PATHS diff --git a/frontend/src/lib/shortcuts.ts b/frontend/src/lib/shortcuts.ts new file mode 100644 index 0000000..9f1c757 --- /dev/null +++ b/frontend/src/lib/shortcuts.ts @@ -0,0 +1,252 @@ +// What every shortcut does, for the keyboard map in `ShortcutsDialog`. +// Written out BY HAND, not derived from the handlers: keep it in step with +// `PrepStrip` (deck), `TrackTable` (track list) and `SettingsMenu` (`?`). +import { cueTypeColor, GRID_MARKER_ACTIVE_COLOR } from './cues' + +export const IS_MAC = /Mac|iPhone|iPad/.test(navigator.userAgent) + +/** A modifier layer of the keyboard. `mod` is Cmd on macOS, Ctrl elsewhere — + * the handlers accept either, but the map names your key. */ +export type Layer = 'base' | 'shift' | 'mod' | 'alt' +export const LAYERS: Layer[] = ['base', 'shift', 'mod', 'alt'] + +export const MODIFIER_KEY: Record, string> = IS_MAC + ? { shift: '⇧', mod: '⌘', alt: '⌥' } + : { shift: 'Shift', mod: 'Ctrl', alt: 'Alt' } + +export const LAYER_NAMES: Record = IS_MAC + ? { base: 'No modifier', shift: '⇧ Shift', mod: '⌘ Command', alt: '⌥ Option' } + : { base: 'No modifier', shift: 'Shift', mod: 'Ctrl', alt: 'Alt' } + +/** Where a shortcut acts. The colour lights its key on the map. */ +export type Area = 'deck' | 'list' | 'any' +export const AREAS: Record = { deck: 'Deck', list: 'Track list', any: 'Anywhere' } +export const AREA_COLORS: Record = { + deck: 'var(--color-accent)', + list: '#6fd6e8', + any: 'var(--color-text)', +} + +export interface Binding { + area: Area + /** Printed on the key — a word or two; the key's own legend names it. */ + label: string + /** The caption's full sentence. */ + text: string + /** Overrides the area colour where the key has a colour of its own (pads, stems). */ + color?: string +} +export type Bindings = Record> + +/** A stem file's default layout (NI's), since the map cannot know the loaded track's. */ +const STEMS: [string, string][] = [ + ['drums', '#009E73'], + ['bass', '#D55E00'], + ['synths', '#CC79A7'], + ['vox', '#56B4E9'], +] +const STEM_CODES = ['KeyQ', 'KeyW', 'KeyE', 'KeyR'] + +/** The digit keys of a bank of `slots` pads: 1–9, then 0 for the tenth, as + * `PrepStrip`'s `slotForDigit` reads them. */ +export function padCodes(slots: number): string[] { + return Array.from({ length: Math.min(slots, 10) }, (_, i) => (i === 9 ? 'Digit0' : `Digit${i + 1}`)) +} + +/** "1–8", or "1–9, 0" for a ten-pad bank. */ +export function padRange(slots: number): string { + const n = Math.min(slots, 10) + if (n <= 1) return '1' + if (n <= 9) return `1–${n}` + return '1–9, 0' +} + +export function bindings(slots: number): Bindings { + const b: Bindings = { base: {}, shift: {}, mod: {}, alt: {} } + const pad = cueTypeColor('cue') + padCodes(slots).forEach((code, i) => { + const n = i + 1 + b.base[code] = [ + { area: 'deck', label: 'Pad', color: pad, text: `Hotcue ${n}: set it if the pad is empty, otherwise jump to it. Hold to preview.` }, + ] + b.shift[code] = [{ area: 'deck', label: 'Delete', color: 'var(--color-pink)', text: `Delete hotcue ${n}` }] + }) + STEM_CODES.forEach((code, i) => { + const [name, color] = STEMS[i] + b.base[code] = [{ area: 'deck', label: 'Mute', color, text: `Stem tracks: mute or unmute stem ${i + 1} (usually ${name})` }] + b.shift[code] = [ + { area: 'deck', label: 'Solo', color, text: `Solo stem ${i + 1}: mute every other stem. Press again to unmute them all.` }, + ] + }) + Object.assign(b.base, { + Space: [{ area: 'deck', label: 'Play / pause', text: 'Play / pause' }], + KeyC: [ + { area: 'deck', label: 'CUE', color: 'var(--color-gold)', text: 'CUE: jump back to the cue point, set it while paused, or hold to preview' }, + ], + ArrowLeft: [ + { area: 'deck', label: 'Jump −', text: 'Beat jump back by the loop size. While a loop plays, move the loop back by its length.' }, + ], + ArrowRight: [ + { area: 'deck', label: 'Jump +', text: 'Beat jump forward by the loop size. While a loop plays, move the loop forward by its length.' }, + ], + ArrowUp: [{ area: 'list', label: 'Up', text: 'Move the selection up one track' }], + ArrowDown: [{ area: 'list', label: 'Down', text: 'Move the selection down one track' }], + Enter: [ + { area: 'list', label: 'Load · OK', text: 'Load and play the highlighted track' }, + { area: 'any', label: 'OK', text: 'Save an edit, or confirm a dialog' }, + ], + Backspace: [ + { + area: 'list', + label: 'Remove', + text: `Remove the selected tracks from this playlist${IS_MAC ? '' : ' (Delete works too)'}`, + }, + ], + Slash: [{ area: 'any', label: 'Help', text: 'Open this list of shortcuts' }], + Escape: [ + { area: 'list', label: 'Cancel', text: 'Clear the selection' }, + { area: 'any', label: 'Cancel', text: 'Cancel a drag or an edit, or close a dialog' }, + ], + } satisfies Record) + Object.assign(b.shift, { + ArrowLeft: [{ area: 'deck', label: '◂ Grid', color: GRID_MARKER_ACTIVE_COLOR, text: 'Go to the previous grid marker' }], + ArrowRight: [{ area: 'deck', label: 'Grid ▸', color: GRID_MARKER_ACTIVE_COLOR, text: 'Go to the next grid marker' }], + ArrowUp: [{ area: 'list', label: 'Extend', text: 'Extend the selection up' }], + ArrowDown: [{ area: 'list', label: 'Extend', text: 'Extend the selection down' }], + } satisfies Record) + Object.assign(b.mod, { + ArrowDown: [{ area: 'deck', label: 'Size ÷2', text: 'Halve the loop and beat-jump size (down to 1/32 beat)' }], + ArrowUp: [{ area: 'deck', label: 'Size ×2', text: 'Double the loop and beat-jump size (up to 32 beats)' }], + KeyA: [{ area: 'list', label: 'All', text: 'Select every track in the list' }], + } satisfies Record) + return b +} + +/** Why a digit past the bank does nothing — the bank follows the library. */ +export function unusedNote(code: string, slots: number): string | null { + if (!/^Digit\d$/.test(code) || padCodes(slots).includes(code)) return null + return `Not used: this library has ${slots} hotcue pad${slots === 1 ? '' : 's'}.` +} + +export interface MouseGesture { + mod?: Exclude + gesture: string + /** What is clicked or dragged, when it is not the column's whole area. */ + on?: string + text: string +} +export const MOUSE: { title: string; rows: MouseGesture[] }[] = [ + { + title: 'Deck', + rows: [ + { gesture: 'Drag', on: 'waveform', text: 'Scratch' }, + { mod: 'mod', gesture: 'Scroll', on: 'waveform', text: 'Zoom in and out' }, + { gesture: 'Click', on: 'stem button', text: 'Mute or unmute that stem' }, + { mod: 'alt', gesture: 'Click', on: 'stem button', text: 'Solo that stem' }, + { gesture: 'Right-click', on: 'pad', text: 'Hotcue type, colour, rename, delete' }, + ], + }, + { + title: 'Track list', + rows: [ + { gesture: 'Click', text: 'Select a track' }, + { mod: 'shift', gesture: 'Click', text: 'Select a range' }, + { mod: 'mod', gesture: 'Click', text: 'Add to or remove from the selection' }, + { gesture: 'Double-click', on: 'cell', text: 'Edit it in place' }, + { gesture: 'Right-click', text: 'Track menu. On the header: choose columns' }, + { gesture: 'Drag', on: 'rows', text: 'Onto a playlist or export to add, onto the deck to load, within a playlist to reorder' }, + { mod: 'alt', gesture: 'Drag', on: 'rows', text: 'Move them out of this playlist into another' }, + ], + }, + { + title: 'Sidebar', + rows: [ + { gesture: 'Right-click', text: 'New playlist or folder, rename, delete' }, + { gesture: 'Drag', on: 'playlist', text: 'Rearrange playlists and folders, or drop onto an export to add it' }, + ], + }, +] + +// ---- the keyboard drawn ----------------------------------------------------- + +export interface KeyDef { + code: string + legend: string + /** The legend when keys are too small for `legend`. */ + short?: string + /** Width in key units. */ + w?: number + /** A modifier key: holding or clicking it shows its layer. */ + role?: Exclude +} + +const key = (code: string, legend: string, w = 1, role?: KeyDef['role'], short?: string): KeyDef => ({ + code, + legend, + w, + role, + short, +}) +const chars = (s: string, prefix: string) => [...s].map((c) => key(prefix + c, c)) + +/** The main block, a row per list. Every row is 14.5 units wide. */ +export const KEY_ROWS: KeyDef[][] = (() => { + const fn = [key('Escape', 'esc', 1.5)] + for (let i = 1; i <= 12; i++) fn.push(key(`F${i}`, `F${i}`)) + fn.push(key('Power', '')) + const shift = IS_MAC ? 'shift ⇧' : 'Shift' + const shiftShort = IS_MAC ? '⇧' : 'Shift' + const bottom = IS_MAC + ? [ + key('Fn', 'fn'), + key('ControlLeft', 'control', 1.25, undefined, 'ctrl'), + key('AltLeft', 'option ⌥', 1.25, 'alt', '⌥'), + key('MetaLeft', 'command ⌘', 1.5, 'mod', '⌘'), + key('Space', 'space', 6.75), + key('MetaRight', 'command ⌘', 1.5, 'mod', '⌘'), + key('AltRight', 'option ⌥', 1.25, 'alt', '⌥'), + ] + : [ + key('ControlLeft', 'Ctrl', 1.25, 'mod'), + key('MetaLeft', 'Win', 1.25), + key('AltLeft', 'Alt', 1.25, 'alt'), + key('Space', 'space', 6.75), + key('AltRight', 'Alt', 1.25, 'alt'), + key('MetaRight', 'Win', 1.25), + key('ControlRight', 'Ctrl', 1.5, 'mod'), + ] + return [ + fn, + [key('Backquote', '`'), ...chars('1234567890', 'Digit'), key('Minus', '-'), key('Equal', '='), + key('Backspace', IS_MAC ? 'delete' : 'Backspace', 1.5, undefined, IS_MAC ? 'del' : 'Bksp')], + [key('Tab', 'tab', 1.5), ...chars('QWERTYUIOP', 'Key'), key('BracketLeft', '['), key('BracketRight', ']'), key('Backslash', '\\')], + [key('CapsLock', 'caps', 1.75), ...chars('ASDFGHJKL', 'Key'), key('Semicolon', ';'), key('Quote', "'"), + key('Enter', IS_MAC ? 'return' : 'Enter', 1.75)], + [key('ShiftLeft', shift, 2.25, 'shift', shiftShort), ...chars('ZXCVBNM', 'Key'), key('Comma', ','), key('Period', '.'), + key('Slash', '/ ?'), key('ShiftRight', shift, 2.25, 'shift', shiftShort)], + bottom, + ] +})() + +/** The inverted-T arrow cluster, 3 × 2, `null` for the gaps beside ↑. */ +export const ARROW_KEYS: (KeyDef | null)[] = [ + null, key('ArrowUp', '↑'), null, + key('ArrowLeft', '←'), key('ArrowDown', '↓'), key('ArrowRight', '→'), +] + +/** The space between the main block and the arrows, in key units. */ +export const ARROW_GAP = 0.36 +/** The whole map's width in key units. */ +export const KEYBOARD_UNITS = 14.5 + ARROW_GAP + 3 + +export const KEYS_BY_CODE: Record = Object.fromEntries( + [...KEY_ROWS.flat(), ...ARROW_KEYS.filter((k): k is KeyDef => !!k)].map((k) => [k.code, k]), +) + +/** The modifier layer a physical key holds, if it is one. */ +export function modifierLayer(code: string): Exclude | null { + if (code === 'ShiftLeft' || code === 'ShiftRight') return 'shift' + if (code === 'AltLeft' || code === 'AltRight') return 'alt' + const mod = IS_MAC ? ['MetaLeft', 'MetaRight'] : ['ControlLeft', 'ControlRight'] + return mod.includes(code) ? 'mod' : null +}