Implemented better shortcut menu

This commit is contained in:
patben8 committed 2026-10-15 16:30:34 +02:00
1 parent b70798a0fe
commit 32cfb034e2
5 files changed
+793 -116

No files matched your search

+1 -1
View File
@@ -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
+20 -1
View File
@@ -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}
>
<span className="text-sm text-text">View Shortcuts</span>
<span className="text-[11px] text-faint">Every keyboard shortcut in one list</span>
<span className="text-[11px] text-faint">Every keyboard shortcut, on a keyboard (?)</span>
</button>
</div>
)}
+514 -114
View File
@@ -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 (
<span className="inline-flex items-center gap-0.5">
{combo.map((k, i) => (
<kbd
key={i}
className="min-w-[1.5rem] rounded border border-line bg-ink-800 px-1.5 py-0.5 text-center font-sans text-[11px] text-text"
>
{k}
</kbd>
))}
</span>
)
}
/** 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<Layer>('base')
const [held, setHeld] = useState<ReadonlySet<Layer>>(new Set())
const [hover, setHover] = useState<string | null>(null)
const [pressed, setPressed] = useState<string | null>(null)
const [query, setQuery] = useState('')
const [areas, setAreas] = useState<ReadonlySet<Area>>(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<HTMLDivElement>(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(
<div
aria-modal="true"
@@ -114,42 +169,387 @@ export function ShortcutsDialog({ onClose }: Props) {
onClick={onClose}
>
<div
className="flex max-h-full w-full max-w-lg flex-col overflow-hidden glass-overlay"
className="flex max-h-full w-full max-w-[960px] flex-col overflow-hidden glass-overlay"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between border-b border-line px-5 py-4">
<div className="flex flex-wrap items-center gap-3 border-b border-line py-3.5 pl-5 pr-4">
<div className="text-[15px] font-semibold tracking-tight">Keyboard Shortcuts</div>
<input
type="search"
value={query}
onChange={(e) => 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"
/>
<button
onClick={onClose}
aria-label="Close"
className="rounded px-1.5 text-muted hover:bg-ink-800 hover:text-text"
className="h-7 w-7 rounded-md text-lg leading-none text-muted hover:bg-ink-800 hover:text-text"
>
×
</button>
</div>
<div className="space-y-5 overflow-y-auto px-5 py-4">
{sections(slots).map((s) => (
<section key={s.title}>
<div className="mb-1.5 text-[10px] font-semibold uppercase tracking-wider text-faint">
{s.title}
</div>
<div className="divide-y divide-line/60">
{s.rows.map((r, i) => (
<div key={i} className="flex items-center justify-between gap-4 py-1.5">
<span className="text-sm text-muted">{r.action}</span>
<span className="flex shrink-0 items-center gap-1.5">
{r.keys.map((combo, j) => (
<Keys key={j} combo={combo} />
))}
</span>
<div className="overflow-y-auto">
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2.5 px-5 pb-1 pt-3.5">
<div className="well inline-flex flex-wrap gap-0.5 rounded-[10px] p-[3px]">
{LAYERS.map((l) => (
<button
key={l}
onClick={() => setSticky(l)}
aria-pressed={l === layer}
className={`inline-flex items-baseline gap-1.5 rounded-[7px] px-2.5 py-1 text-xs font-medium ${
l === layer ? 'bg-ink-600 text-text' : 'text-muted hover:text-text'
}`}
>
{LAYER_NAMES[l]}
<span className="font-mono text-[10px] text-faint">{layerCount(l)}</span>
</button>
))}
</div>
<div className="flex flex-wrap gap-1.5">
{ALL_AREAS.map((a) => (
<button
key={a}
onClick={() => toggleArea(a)}
aria-pressed={areas.has(a)}
className={`inline-flex items-center gap-1.5 rounded-full border border-line py-0.5 pl-2 pr-2.5 text-[11.5px] font-medium text-muted ${
areas.has(a) ? '' : 'opacity-40'
}`}
>
<i
className="h-[7px] w-[7px] rounded-full"
style={{ background: AREA_COLORS[a], boxShadow: areas.has(a) ? `0 0 8px ${AREA_COLORS[a]}` : undefined }}
/>
{AREAS[a]}
</button>
))}
</div>
</div>
<div ref={fitRef} className="mx-5 mb-2.5 mt-4">
<div
className="mx-auto flex w-max items-end"
style={{ gap: unit * ARROW_GAP }}
onPointerLeave={() => setHover(null)}
>
<div className="flex flex-col" style={{ gap }}>
{KEY_ROWS.map((row, i) => (
<div key={i} className="flex" style={{ gap, marginBottom: i === 0 ? gap * 0.4 : 0 }}>
{row.map((k) => (
<Key key={k.code} def={k} fnRow={i === 0} {...keyProps} />
))}
</div>
))}
</div>
</section>
))}
<div className="grid" style={{ gap, gridTemplateColumns: `repeat(3, ${unit - gap}px)` }}>
{ARROW_KEYS.map((k, i) =>
k ? <Key key={k.code} def={k} fnRow={false} {...keyProps} /> : <span key={i} />,
)}
</div>
</div>
</div>
<div
aria-live="polite"
// A FIXED height, so the dialog does not resize under the pointer as
// it moves between keys: tall enough for the fullest key (three
// lines + "Also on this key"); search results scroll inside it.
className="well mx-5 flex h-32 shrink-0 flex-col gap-[7px] overflow-y-auto rounded-xl px-3.5 py-3 text-[13px] text-muted"
>
<Caption
hover={hover}
layer={layer}
q={q}
query={query}
slots={slots}
binds={binds}
areas={areas}
/>
</div>
<div className="px-5 pb-2 pt-5">
<div className="mb-2.5 text-[10px] font-semibold uppercase tracking-wider text-faint">Mouse</div>
<div className="grid grid-cols-[repeat(auto-fit,minmax(250px,1fr))] gap-x-7 gap-y-2">
{MOUSE.map((col) => (
<div key={col.title} className="min-w-0">
<div className="pb-1.5 text-xs font-semibold text-muted">{col.title}</div>
{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 (
<div
key={i}
className={`-mx-1.5 grid grid-cols-[minmax(8.5rem,auto)_1fr] items-baseline gap-2.5 rounded-md border-t px-1.5 py-1 text-[12.5px] transition-opacity ${
lit ? 'border-transparent bg-accent-soft text-text' : 'border-line text-muted'
} ${dim ? 'opacity-30' : ''}`}
>
<span className="inline-flex flex-wrap items-baseline gap-1">
{r.mod && <Kbd>{MODIFIER_KEY[r.mod]}</Kbd>}
<span className="inline-flex items-center gap-1 whitespace-nowrap rounded-full border border-dashed border-ink-600 py-px pl-1.5 pr-2 text-[11px] font-medium text-text">
<Icon name="mouse" size={11} strokeWidth={2} />
{r.gesture}
{r.on ? ` ${r.on}` : ''}
</span>
</span>
<span>{r.text}</span>
</div>
)
})}
</div>
))}
</div>
</div>
<div className="mt-2.5 border-t border-line px-5 py-3 text-xs text-faint">
Press the <Kbd>?</Kbd> key anywhere to open this list.
</div>
</div>
</div>
</div>,
document.body,
)
}
function Kbd({ children }: { children: ReactNode }) {
return (
<kbd className="min-w-[1.5em] rounded-[5px] border border-b-2 border-line bg-ink-800 px-1.5 py-px text-center font-mono text-[11px] text-text">
{children}
</kbd>
)
}
function Combo({ layer, code }: { layer: Layer; code: string }) {
const legend = KEYS_BY_CODE[code]?.legend ?? code
return (
<span className="inline-flex shrink-0 gap-[3px]">
{layer !== 'base' && <Kbd>{MODIFIER_KEY[layer]}</Kbd>}
<Kbd>{legend}</Kbd>
</span>
)
}
function Line({ layer, code, b, other }: { layer: Layer; code: string; b: Binding; other?: boolean }) {
return (
<div className={`flex flex-wrap items-baseline gap-2.5 ${other ? 'text-xs' : ''}`}>
<Combo layer={layer} code={code} />
<span className={`min-w-0 ${other ? 'text-muted' : 'text-text'}`}>{b.text}</span>
<span className="text-[9.5px] font-semibold uppercase tracking-wider" style={{ color: AREA_COLORS[b.area] }}>
{AREAS[b.area]}
</span>
</div>
)
}
const Sub = ({ children }: { children: ReactNode }) => (
<div className="mt-0.5 text-[10px] font-semibold uppercase tracking-wider text-faint">{children}</div>
)
function Caption({
hover,
layer,
q,
query,
slots,
binds,
areas,
}: {
hover: string | null
layer: Layer
q: string
query: string
slots: number
binds: ReturnType<typeof bindings>
areas: ReadonlySet<Area>
}) {
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 (
<div className="flex flex-wrap items-baseline gap-2.5">
<Kbd>{MODIFIER_KEY[role]}</Kbd>
<span className="text-text">
Hold, or click, to light up what {LAYER_NAMES[role]} changes: {keys} key{keys === 1 ? '' : 's'} and{' '}
{mouse} mouse gesture{mouse === 1 ? '' : 's'}.
</span>
</div>
)
}
const here = binds[layer][hover] ?? []
const others = LAYERS.filter((l) => l !== layer && binds[l][hover])
return (
<>
{here.length ? (
here.map((b, i) => <Line key={i} layer={layer} code={hover} b={b} />)
) : (
<div className="flex flex-wrap items-baseline gap-2.5">
<Combo layer={layer} code={hover} />
<span>{unusedNote(hover, slots) ?? 'Does nothing in Konduktor.'}</span>
</div>
)}
{others.length > 0 && <Sub>Also on this key</Sub>}
{others.flatMap((l) => binds[l][hover].map((b, i) => <Line key={`${l}${i}`} layer={l} code={hover} b={b} other />))}
</>
)
}
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) => <Line key={`${l}${code}${i}`} layer={l} code={code} b={b} />),
),
)
const mouse = MOUSE.flatMap((c) => c.rows).filter((r) => mouseText(r).includes(q)).length
if (!hits.length && !mouse) return <span>No shortcut matches “{query.trim()}”.</span>
return (
<>
{hits}
{mouse > 0 && <Sub>{mouse} mouse gesture{mouse === 1 ? '' : 's'} below</Sub>}
</>
)
}
if (layer !== 'base') {
return (
<>
<span className="text-text">
Showing what {LAYER_NAMES[layer]} changes. The highlighted mouse gestures below use it too.
</span>
<span className="text-xs">Let go of the key, or pick “No modifier”, to go back.</span>
</>
)
}
return (
<>
<span className="text-text">Point at a key, or press it, to see what it does.</span>
<span className="text-xs">
Hold <Kbd>{MODIFIER_KEY.shift}</Kbd> <Kbd>{MODIFIER_KEY.mod}</Kbd> or <Kbd>{MODIFIER_KEY.alt}</Kbd>, or pick
one above, to see what each modifier changes.
</span>
<span className="text-xs">
{padRange(slots)} are this library's {slots} hotcue pads; Q W E R are the stems of a stem track.
</span>
</>
)
}
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 = (
<>
<span
className={`whitespace-nowrap font-medium leading-none ${first || on ? (on ? '' : 'text-text') : ''}`}
style={{ fontSize: legendSize }}
>
{legend}
</span>
{labels && first && (
<span
className="max-w-full overflow-hidden text-ellipsis whitespace-nowrap text-[9px] font-semibold leading-tight"
style={{ color: kc }}
>
{first.label}
</span>
)}
{ents.length > 1 && (
<span className="absolute right-1 top-1 flex gap-0.5">
{ents.map((b, i) => (
<i key={i} className="h-[5px] w-[5px] rounded-full" style={{ background: AREA_COLORS[b.area] }} />
))}
</span>
)}
</>
)
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 (
<span className={className} style={style} onPointerEnter={() => onHover(def.legend ? code : null)}>
{body}
</span>
)
}
return (
<button
type="button"
className={`${className} ${role ? 'cursor-pointer' : 'cursor-help'}`}
style={style}
aria-label={first ? `${def.legend}: ${first.text}` : def.legend}
aria-pressed={role ? on : undefined}
data-map-key={role ? undefined : code}
onPointerEnter={() => onHover(code)}
onFocus={() => onHover(code)}
onClick={() => role && onPick(role)}
>
{body}
</button>
)
}
+6
View File
@@ -99,6 +99,12 @@ const PATHS = {
fadeOut: <path d="M3 5l18 14H3z" strokeLinejoin="round" />,
eject: <path d="M12 4l8 9H4zM4 18h16" strokeLinejoin="round" />,
grid: <path d="M5 3v18M10 3v18M15 3v18M20 3v18" />,
mouse: (
<>
<rect x="6" y="3" width="12" height="18" rx="6" />
<path d="M12 7v3" />
</>
),
} as const
export type IconName = keyof typeof PATHS
+252
View File
@@ -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<Exclude<Layer, 'base'>, string> = IS_MAC
? { shift: '⇧', mod: '⌘', alt: '⌥' }
: { shift: 'Shift', mod: 'Ctrl', alt: 'Alt' }
export const LAYER_NAMES: Record<Layer, string> = 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<Area, string> = { deck: 'Deck', list: 'Track list', any: 'Anywhere' }
export const AREA_COLORS: Record<Area, string> = {
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<Layer, Record<string, Binding[]>>
/** 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<string, Binding[]>)
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<string, Binding[]>)
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<string, Binding[]>)
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<Layer, 'base'>
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<Layer, 'base'>
}
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<string, KeyDef> = 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<Layer, 'base'> | 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
}