From 82307221055817df256235f035e9107025cc57cb Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Thu, 15 Oct 2026 10:26:41 +0200 Subject: [PATCH 1/9] Implemented raw waveform mode --- CLAUDE.md | 38 ++- frontend/src/components/MainWaveform.tsx | 54 +++- frontend/src/components/PrepStrip.tsx | 30 +- frontend/src/lib/decodeAlign.test.ts | 56 ++++ frontend/src/lib/decodeAlign.ts | 128 ++++++++ frontend/src/lib/decodeProbe.ts | 48 +++ frontend/src/lib/icons.tsx | 1 + frontend/src/lib/rawWave.test.ts | 143 +++++++++ frontend/src/lib/rawWave.ts | 362 +++++++++++++++++++++++ frontend/src/lib/waveform.ts | 18 +- 10 files changed, 862 insertions(+), 16 deletions(-) create mode 100644 frontend/src/lib/decodeAlign.test.ts create mode 100644 frontend/src/lib/decodeAlign.ts create mode 100644 frontend/src/lib/decodeProbe.ts create mode 100644 frontend/src/lib/rawWave.test.ts create mode 100644 frontend/src/lib/rawWave.ts diff --git a/CLAUDE.md b/CLAUDE.md index 95d46e8..a64fe0f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1037,8 +1037,10 @@ Two independent apps that talk over HTTP: badge, the readout well (ELAPSED / REMAIN to tenths, KEY, and `BpmReadout` — click to type an exact BPM; with no grid, a typed or tapped BPM CREATES one at the playhead, and Set grid on a track with no BPM opens the readout to ask rather than failing), SNAP, Analyze, Auto hotcues. **Waveforms**: - `MainWaveform` (scrolling; zoom +/− in its corner and Cmd/Ctrl+scroll, owned - by `PrepStrip` so it survives track switches and persists) over + `MainWaveform` (scrolling; zoom +/− in its corner and Cmd/Ctrl+scroll, + 0.25–64 s across, owned by `PrepStrip` so it survives track switches and + persists; a toggle under the zoom buttons draws the RAW signal instead + of bars — `lib/rawWave.ts`, below; persisted as `mainWaveRaw`) over `OverviewWaveform`, which frames the main view's visible range around the playhead (it takes `secPerView` for exactly that). **Controls**: play, CUE, `LoopControls`, then EITHER `HotcueBar` OR — in **Grid mode** — `GridEditStrip`, then `TempoControls` @@ -2166,6 +2168,38 @@ The prep strip plays every track through the **Web Audio API** (a plain full scale for whole sections, so a linear map draws a solid orange wall instead of the kick pulse. The main view draws 2 px bars with a 1 px gap, **binned in track space** so bars scroll rather than flicker. +- `rawWave.ts` — **the raw waveform** (decided 2026-10-15, + [the discussion](.claude/discussions/discuss-raw-waveform-2026-10-15.md)): + the bars' ~7 ms columns of unsigned band energy hide where a kick starts, so + the main view can draw the signal itself as a thin line, after Traktor at + full zoom. Its own toggle (under the zoom buttons), NOT tied to Grid mode — + tried first, changed after use. + **Shape exact, colour approximate**: the tint is the bar palette weighted by + the ~7 ms band columns, lerped, mixed in OKLab with the CHROMA restored + (`bandColour`) — a plain RGB mean of orange/violet/cyan lands near grey and + read as mud; chosen from five variants rendered on real tracks; the scale is fixed by the track's loudest + sample (no per-view gain, so nothing pumps while scrolling). Each pixel is a + min→max stroke stretched to touch its neighbour's, so it reads as an + envelope zoomed out and a line zoomed in with no switch-over. Data: min/max + per 32 samples summarised at load (~4 MB / 6 min) for wide views; below 128 + samples a pixel, the visible window read straight from the `AudioBuffer` + (`copyFromChannel` — no full-length mono copy). Bins sit on a track-space + grid like the bars'. A stem track's lanes each draw their own raw line, in + the stem's colour, each at its own peak floored at 5% of the loudest. + Measured in WKWebView: 0.3 ms a frame at 0.25 s, ~5 ms at 64 s. +- `decodeAlign.ts` — **the deck's decode vs the grid's time base.** Positions + are in the backend's PyAV decode; the deck decodes with `decodeAudioData`. + Measured 2026-10-15 with click files: identical on every format and engine + EXCEPT a **header-less MP3 under WebKit** (the macOS app), decoded 529 + samples (12 ms) EARLY — CoreAudio trims the decoder delay with no header to + say so; FFmpeg (and Chromium/WebView2) do not. Invisible under bars, a + 12 ms miss on the raw line. The engine's offset is MEASURED once per session + by decoding a built-in 2.7 KB header-less MP3 (`decodeProbe.ts`, click at a + known FFmpeg sample), and a header-less MP3's buffer (`mp3HeaderFrame`, a + port of `core/mp3_gapless.parse` behind an is-it-an-MP3 gate) is padded by + it in `decodeUrl` — so playback, scratch and both waveforms move together. + Not measured: a header without a trusted encoder-delay field; Edge on a real + Windows machine (Chromium on macOS matched). - `cues.ts` — canvas drawers for cue markers (type-colored), the active loop band, the beatgrid (per-segment white beats/brighter downbeats, plus marker lines — gold for the one governing the playhead, accent otherwise, with the diff --git a/frontend/src/components/MainWaveform.tsx b/frontend/src/components/MainWaveform.tsx index 62fefdb..c889449 100644 --- a/frontend/src/components/MainWaveform.tsx +++ b/frontend/src/components/MainWaveform.tsx @@ -1,11 +1,19 @@ import { useEffect, useRef } from 'react' import type { CuePoint } from '../api' import type { BeatGrid } from '../lib/beatgrid' +import { Icon } from '../lib/icons' import { drawBeatgrid, drawCuePoint, drawCues, drawLoop, drawLoopIn, drawPlayhead } from '../lib/cues' +import { laneScales, makeSpans, paintRaw, rawSpans, tintAt, type RawWave } from '../lib/rawWave' import { paintLane, paintWave, type WaveColumn } from '../lib/waveform' interface Props { cols: WaveColumn[] + /** The samples, for the raw view. */ + raw?: RawWave | null + /** Draw the raw signal as a thin line instead of bars (the toggle under + the zoom buttons; owned by the parent, which persists it). */ + rawMode?: boolean + onRawModeChange?: (raw: boolean) => void currentTime: number duration: number cues: CuePoint[] @@ -36,6 +44,8 @@ interface Props { export interface StemLane { data: Float32Array + /** The stem's samples, for the raw view. */ + raw?: RawWave | null name: string color: string /** Not muted. */ @@ -50,7 +60,7 @@ const ALT = typeof navigator !== 'undefined' && /Mac/.test(navigator.platform) ? const DRAG_THRESHOLD = 3 // px before a press becomes a scratch (vs a click-seek) -export const MIN_SEC = 2 // most zoomed-in (seconds across the view) +export const MIN_SEC = 0.25 // most zoomed-in (seconds across the view): a kick's attack spans dozens of px export const MAX_SEC = 64 // most zoomed-out export const DEFAULT_SEC = 16 @@ -62,6 +72,9 @@ export const DEFAULT_SEC = 16 */ export function MainWaveform({ cols, + raw = null, + rawMode = false, + onRawModeChange, currentTime, duration, cues, @@ -89,6 +102,7 @@ export function MainWaveform({ const dragRef = useRef<{ startX: number; startTime: number; lastT: number; moved: boolean } | null>( null, ) + const spansRef = useRef(makeSpans()) // Draw closes over the latest props/state; a ref lets the ResizeObserver call // the current version without re-subscribing. @@ -111,7 +125,25 @@ export function MainWaveform({ // 2 px bars with a 1 px gap: the texture that makes the scrolling view // read as discrete energy rather than a smear. const bars = { bar: Math.max(1, Math.round(2 * dpr)), gap: Math.max(1, Math.round(dpr)) } - if (lanes && lanes.length) { + // The raw line's minimum stroke, so silence and flat stretches still read. + const thick = Math.max(1, 1.25 * dpr) + const spans = spansRef.current + if (rawMode && lanes && lanes.length && lanes.every((l) => l.raw)) { + const laneH = h / lanes.length + const scales = laneScales(lanes.map((l) => l.raw!.peak), laneH / 2 - thick) + lanes.forEach((lane, k) => { + rawSpans(lane.raw!, startSec, endSec, w, spans) + ctx.globalAlpha = lane.audible ? 0.92 : 0.18 + paintRaw(ctx, spans, k * laneH, laneH, scales[k], thick, lane.color) + }) + ctx.globalAlpha = 1 + ctx.fillStyle = 'rgba(255,255,255,0.06)' + for (let k = 1; k < lanes.length; k++) ctx.fillRect(0, Math.round(k * laneH), w, Math.max(1, Math.round(dpr))) + } else if (rawMode && !lanes?.length && raw) { + rawSpans(raw, startSec, endSec, w, spans) + const scale = (h / 2 - thick) / Math.max(raw.peak, 1e-6) + paintRaw(ctx, spans, 0, h, scale, thick, (t) => tintAt(cols, duration, t)) + } else if (lanes && lanes.length) { // Stem lanes, Traktor-style: each stem its own strip in its own colour. const laneH = h / lanes.length lanes.forEach((lane, k) => { @@ -263,9 +295,10 @@ export function MainWaveform({ )} - {/* Zoom controls (Traktor-style +/-). stopPropagation on down so tapping a - button doesn't begin a scratch drag. */} -
+ {/* Zoom in · raw/bars · zoom out, centred on the waveform's height. + stopPropagation on down so tapping a button doesn't begin a scratch + drag. */} +
+
+ {canSort && ( +
+
Order
+ {option( + 'sorted', + `As sorted: ${describeSort(sorting)}`, + 'In the order shown here. The playlist keeps this order when you clear the sort.', + )} + {option( + 'playlist', + 'Playlist order', + 'In the order they have in the playlist now, whatever the sort shows.', + )} +
+ )}
, document.body, From b70798a0fe16291748fc9f039a78fa8ccd23f114 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Thu, 15 Oct 2026 15:46:39 +0200 Subject: [PATCH 4/9] Implemented track info dialog popup --- frontend/src/App.tsx | 4 + frontend/src/components/PrepStrip.tsx | 41 ++++- frontend/src/components/TrackInfoDialog.tsx | 183 ++++++++++++++++++++ frontend/src/index.css | 12 ++ 4 files changed, 234 insertions(+), 6 deletions(-) create mode 100644 frontend/src/components/TrackInfoDialog.tsx diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index a7d1605..bce7c8b 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1450,6 +1450,10 @@ export default function App() { origin={prepOrigin} cuesRefresh={cuesRefresh} onPlayingChange={setDeckPlaying} + // As the context menu's: a library that would refuse the save is + // not offered the dialog, and a deck track outside the collection + // (a device's, a loose file's) is not the collection's to edit. + onEditTags={canEdit && prepOrigin === 'collection' ? setEditing : undefined} /> diff --git a/frontend/src/components/PrepStrip.tsx b/frontend/src/components/PrepStrip.tsx index b8de1be..6b703c0 100644 --- a/frontend/src/components/PrepStrip.tsx +++ b/frontend/src/components/PrepStrip.tsx @@ -28,6 +28,7 @@ import { ScratchEngine } from '../lib/scratchEngine' import { PlaybackEngine } from '../lib/playbackEngine' import { invalidateTrackLists } from '../lib/trackQueries' import { AutoCueDialog, eventLabel } from './AutoCueDialog' +import { TrackInfoDialog } from './TrackInfoDialog' import { ContextMenu, type MenuItem } from './ContextMenu' import { BpmReadout, GridEditStrip, TempoControls, TempoFold } from './GridControls' import { HotcueBar } from './HotcueBar' @@ -60,6 +61,9 @@ interface Props { cuesRefresh?: number /** Reports whether the deck is playing, so the library can light its row. */ onPlayingChange?: (playing: boolean) => void + /** Opens Edit Tags for the loaded track — passed only where the library + * will accept the edit, so the cover popup offers it only then. */ + onEditTags?: (track: Track) => void } /** m:ss.t — the deck's readouts show tenths, as a CDJ does. */ @@ -103,6 +107,7 @@ export function PrepStrip({ origin = 'collection', cuesRefresh = 0, onPlayingChange, + onEditTags, }: Props) { const qc = useQueryClient() const [playing, setPlaying] = useState(false) @@ -133,6 +138,7 @@ export function PrepStrip({ const [snap, setSnap] = useState(true) const [selectedSlot, setSelectedSlot] = useState(null) const [cuePoint, setCuePoint] = useState(0) // floating "CUE" point (frontend-only) + const [infoOpen, setInfoOpen] = useState(false) // the cover's track-info popup const [secPerView, setSecPerView] = useState(DEFAULT_SEC) // main-waveform zoom (persisted) const [rawWave, setRawWave] = useState(false) // main waveform: raw line instead of bars (persisted) // ONE size, in beats, for beat loops and beat jump alike (persisted). @@ -1297,7 +1303,10 @@ export function PrepStrip({
{/* ---- Header: the track, its readouts, the analysis actions ---- */}
- + setInfoOpen(true) : undefined} + />
{track ? ( <> @@ -1585,6 +1594,21 @@ export function PrepStrip({ onClose={() => setPadMenu(null)} /> )} + {infoOpen && track && ( + setInfoOpen(false)} + onEditTags={ + onEditTags + ? () => { + setInfoOpen(false) + onEditTags(track) + } + : undefined + } + /> + )} {autoOpen && track && ( void }) { const [failed, setFailed] = useState(null) const showArt = trackId != null && failed !== trackId return ( -
{showArt && ( @@ -1622,6 +1651,6 @@ function CoverThumb({ trackId }: { trackId: string | null }) { onError={() => setFailed(trackId)} /> )} -
+ ) } diff --git a/frontend/src/components/TrackInfoDialog.tsx b/frontend/src/components/TrackInfoDialog.tsx new file mode 100644 index 0000000..26f8b0f --- /dev/null +++ b/frontend/src/components/TrackInfoDialog.tsx @@ -0,0 +1,183 @@ +import { createPortal } from 'react-dom' +import { useEffect, useState, type ReactNode } from 'react' +import type { Track } from '../api' +import { formatBpm, formatDuration, keyColor } from '../lib/format' +import { useCaps } from '../lib/capabilities' +import { Icon } from '../lib/icons' +import { RatingStars } from './RatingStars' + +interface Props { + track: Track + /** The cover's URL, or null where this track's library serves none (a + * device or a loose file) — the ambient swatch stands in, as in the deck. */ + artUrl: string | null + onClose: () => void + /** Offered only where the library will accept the edit; closes this first. */ + onEditTags?: () => void +} + +/** + * The deck cover's popup: the art large, beside everything the library knows + * about the track. View-only apart from the one way out to Edit Tags. Rows with + * no value are left out rather than shown as dashes, so a sparse track reads + * as short rather than broken. + */ +export function TrackInfoDialog({ track, artUrl, onClose, onEditTags }: Props) { + const caps = useCaps() + const [artFailed, setArtFailed] = useState(false) + const showArt = artUrl != null && !artFailed + + useEffect(() => { + const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose() + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, [onClose]) + + const grid = + track.grid_marker_count === 0 + ? null + : `${track.grid_marker_count > 1 ? `Flexible · ${track.grid_marker_count} markers` : 'Constant tempo'}${ + track.grid_locked ? ' · locked' : '' + }` + const details: [string, ReactNode][] = ( + [ + ['Album', track.album], + ['Label', track.label], + ['Genre', track.genre], + ['Remixer', track.remixer], + ['Producer', track.producer], + ['Mix', track.mix], + ['Released', track.release_date], + ['Added', track.import_date], + ['Last played', track.last_played], + ['Plays', track.playcount ? String(track.playcount) : null], + // The generic bitrate is bits per second. + ['Bitrate', track.bitrate ? `${Math.round(track.bitrate / 1000)} kbps` : null], + ['Grid', grid], + ['Hotcues', track.hotcue_count ? String(track.hotcue_count) : null], + ['Comment', track.comment], + ['Comment 2', track.comment2], + ] as [string, ReactNode][] + ).filter(([, v]) => v != null && v !== '') + + return createPortal( +
+
e.stopPropagation()} + > + {/* The sleeve, bled into the card behind everything: a soft wash of the + art's own colours. `filter` on this leaf is safe — nothing can open + inside it. */} + {showArt && ( + + )} + +
+
+ {showArt ? ( + {`Cover setArtFailed(true)} + /> + ) : ( +
+ +
+ )} +
+ {track.rating > 0 && } +
+ +
+
+
+
+

+ {track.title ?? 'Untitled'} +

+
{track.artist ?? 'Unknown artist'}
+
+ +
+ +
+ + + + {track.media_kind !== 'audio' && } +
+ + {details.length > 0 && ( +
+ {details.map(([label, value]) => ( +
+
{label}
+
{value}
+
+ ))} +
+ )} + + {track.filepath && ( +
+ {track.filepath} +
+ )} +
+ + {onEditTags && ( +
+ +
+ )} +
+
+
, + document.body, + ) +} + +function Stat({ label, value, color }: { label: string; value: string; color?: string }) { + return ( +
+ {label} + + {value} + +
+ ) +} diff --git a/frontend/src/index.css b/frontend/src/index.css index 77d4004..e5cb750 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -291,6 +291,18 @@ option { } } +/* ---- Track info popup (see TrackInfoDialog.tsx) ---------------------- */ +.track-info-pop { + animation: track-info-pop 220ms cubic-bezier(0.2, 0.9, 0.3, 1.15); +} +@keyframes track-info-pop { + from { opacity: 0; transform: translateY(8px) scale(0.96); } + to { opacity: 1; transform: none; } +} +@media (prefers-reduced-motion: reduce) { + .track-info-pop { animation: none; } +} + /* ---- Ambient backdrop (see AmbientBackdrop.tsx) ------------------------ */ .ambient-wash { position: absolute; From 32cfb034e2fa3a50c8be7f5c2faf4f644f4d25b6 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Thu, 15 Oct 2026 16:30:34 +0200 Subject: [PATCH 5/9] 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 +} From 16c3552be6aabc6ba6e680a7ad644df85e856030 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Thu, 15 Oct 2026 16:36:10 +0200 Subject: [PATCH 6/9] Changed option keyboard shortcuts to use command instead --- CLAUDE.md | 8 ++--- frontend/src/components/MainWaveform.tsx | 9 +++--- frontend/src/components/ShortcutsDialog.tsx | 6 ++-- frontend/src/components/Sidebar.tsx | 16 +++++----- frontend/src/components/TrackTable.tsx | 9 ++++-- frontend/src/lib/addTracks.ts | 2 +- frontend/src/lib/drag.tsx | 33 +++++++++++---------- frontend/src/lib/modKey.ts | 15 ++++++++++ frontend/src/lib/shortcuts.ts | 30 +++++++++---------- 9 files changed, 72 insertions(+), 56 deletions(-) create mode 100644 frontend/src/lib/modKey.ts diff --git a/CLAUDE.md b/CLAUDE.md index 73d8bfb..5ba50d4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -870,7 +870,7 @@ Two independent apps that talk over HTTP: too, so nested playlists are reachable). Tracks dropped on a playlist go through `lib/addTracks.ts` — shared with the context menu's "Add to" — which ASKS about duplicates where the platform can hold them (decided: - ask each time), and Option/Alt moves them out of the editable playlist + ask each time), and Cmd (Ctrl on Windows; `lib/modKey.ts`) moves them out of the editable playlist they came from. A device's or Files folder's tracks open `ImportDialog` (`trackIds` + `target`) / `AddFilesDialog` with the target filled in (`onAddForeign`), so copy-vs-reference is still asked. Export rows take the @@ -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 (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), + 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 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 @@ -915,7 +915,7 @@ Two independent apps that talk over HTTP: pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns. Every table's rows are a DRAG SOURCE through `lib/drag.tsx` (a selected row carries the selection, the payload's `lead` is the row grabbed, `dragFrom` - says whose ids they are and which editable playlist an Option-drag leaves); + says whose ids they are and which editable playlist a Cmd/Ctrl-drag leaves — a Cmd/Ctrl press arms a drag, and stays a toggle-click if it never moves); the in-table reorder is just the table's own drop target.) **`lib/drag.tsx` — drag and drop across the window** (decided 2026-10-06, [the discussion](.claude/discussions/discuss-drag-and-drop-2026-10-06.md)): @@ -1029,7 +1029,7 @@ Two independent apps that talk over HTTP: one amplitude lane per stem, each normalised to its own 99.5th percentile but never below 5% of the loudest (a silent stem stays silent). `MainWaveform` draws the lanes in the file's own colours with a mute - button at each lane's left edge (click = mute, Alt/Option-click = solo); + button at each lane's left edge (click = mute, Cmd/Ctrl-click = solo); Q W E R mute stems 1-4, Shift+ solos. **Solo is not a mode**: it SETS the mutes (every other stem muted), so each stem stays freely mutable after it; soloing the one stem still playing unmutes all. Mutes reset per track. Memory is diff --git a/frontend/src/components/MainWaveform.tsx b/frontend/src/components/MainWaveform.tsx index c889449..43db165 100644 --- a/frontend/src/components/MainWaveform.tsx +++ b/frontend/src/components/MainWaveform.tsx @@ -2,6 +2,7 @@ import { useEffect, useRef } from 'react' import type { CuePoint } from '../api' import type { BeatGrid } from '../lib/beatgrid' import { Icon } from '../lib/icons' +import { hasMod, MOD_NAME } from '../lib/modKey' import { drawBeatgrid, drawCuePoint, drawCues, drawLoop, drawLoopIn, drawPlayhead } from '../lib/cues' import { laneScales, makeSpans, paintRaw, rawSpans, tintAt, type RawWave } from '../lib/rawWave' import { paintLane, paintWave, type WaveColumn } from '../lib/waveform' @@ -38,7 +39,7 @@ interface Props { onScratchEnd: (t: number) => void /** A stem track: one lane per stem instead of the three-band mix view. */ lanes?: StemLane[] | null - /** Click = mute toggle; Alt/Option-click = solo (mute all the others). */ + /** Click = mute toggle; Cmd/Ctrl-click = solo (mute all the others). */ onStemToggle?: (index: number, solo: boolean) => void } @@ -56,8 +57,6 @@ export interface StemLane { shortcut: string } -const ALT = typeof navigator !== 'undefined' && /Mac/.test(navigator.platform) ? 'Option' : 'Alt' - const DRAG_THRESHOLD = 3 // px before a press becomes a scratch (vs a click-seek) export const MIN_SEC = 0.25 // most zoomed-in (seconds across the view): a kick's attack spans dozens of px @@ -277,8 +276,8 @@ export function MainWaveform({
diff --git a/frontend/src/components/PrepStrip.tsx b/frontend/src/components/PrepStrip.tsx index 6b703c0..94d5ddc 100644 --- a/frontend/src/components/PrepStrip.tsx +++ b/frontend/src/components/PrepStrip.tsx @@ -35,6 +35,7 @@ import { HotcueBar } from './HotcueBar' import { LoopControls, LOOP_SIZES, type LoopMode } from './LoopControls' import { MainWaveform, MIN_SEC, MAX_SEC, DEFAULT_SEC, type StemLane } from './MainWaveform' import { OverviewWaveform } from './OverviewWaveform' +import { useAppSetting } from './AppSettings' import { usePrefsWriter } from '../lib/prefs' /** Keys that mute stems 1-4 (Shift = solo), by `KeyboardEvent.code`. */ @@ -66,13 +67,19 @@ interface Props { onEditTags?: (track: Track) => void } -/** m:ss.t — the deck's readouts show tenths, as a CDJ does. */ -function fmtTenths(secs: number): string { +/** mm:ss.f — tenths by default, as a CDJ does; `places` is the + * `timeReadoutDecimals` setting (0 drops the fraction). Truncates, never + * rounds, so the readout never shows a second before it has been reached. */ +function fmtTime(secs: number, places: number): string { if (!isFinite(secs) || secs < 0) secs = 0 - const tenths = Math.floor(secs * 10) - const m = Math.floor(tenths / 600) - const s = Math.floor((tenths % 600) / 10) - return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}.${tenths % 10}` + const scale = 10 ** places + // The epsilon keeps e.g. 0.3 s from reading 0.299 at 3 places. + const units = Math.floor(secs * scale + 1e-6) + const whole = Math.floor(units / scale) + const m = Math.floor(whole / 60) + const s = whole % 60 + const frac = places > 0 ? `.${(units % scale).toString().padStart(places, '0')}` : '' + return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}${frac}` } /** @@ -117,6 +124,7 @@ export function PrepStrip({ // which the pointer's :active alone cannot, since the key never touches it. const [cueHeld, setCueHeld] = useState(false) const [current, setCurrent] = useState(0) + const timeDecimals = useAppSetting('timeReadoutDecimals') const [duration, setDuration] = useState(0) const [ready, setReady] = useState(false) const [cols, setCols] = useState(null) @@ -1338,12 +1346,12 @@ export function PrepStrip({
ELAPSED - {fmtTenths(current)} + {fmtTime(current, timeDecimals)}
REMAIN - −{fmtTenths(Math.max(0, duration - current))} + −{fmtTime(Math.max(0, duration - current), timeDecimals)}
From fc4e7804b37119ba4b3dd7550a1f768cae3dfbfc Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Thu, 15 Oct 2026 17:48:17 +0200 Subject: [PATCH 8/9] Changed how patchnotes are compiled --- .github/workflows/build.yml | 41 ++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 646251c..0c9cece 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -169,6 +169,7 @@ jobs: runs-on: ubuntu-latest permissions: contents: write # required to create the tag + release + pull-requests: read # to read the merged PR's patch notes steps: - name: Checkout uses: actions/checkout@v4 @@ -188,12 +189,50 @@ jobs: pattern: konduktor-* path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/… + # Release notes from the "Patch notes" section of the PR that merged this + # commit into main (dev → main merges carry many features in one PR, so + # its title alone says little). Written under "What's Changed", the + # heading the app's update dialog reads. No PR (a manual run, a direct + # push) or no such section → GitHub's generated notes, as before. + - name: Patch notes from the merged PR + id: notes + env: + GH_TOKEN: ${{ github.token }} + run: | + gh api "repos/${{ github.repository }}/commits/${{ github.sha }}/pulls" \ + --jq '[.[] | select(.base.ref == "main" and .merged_at != null)][0].body // ""' \ + > pr-body.md || : > pr-body.md + python3 - <<'EOF' + import os, re + body = open("pr-body.md", encoding="utf-8").read().replace("\r\n", "\n") + body = re.sub(r"", "", body, flags=re.S) + section, level = [], None + for line in body.split("\n"): + m = re.match(r"^(#{1,6})\s+(.*?)\s*#*\s*$", line) + if level is None: + if m and re.fullmatch(r"patch[\s-]?notes:?", m.group(2), re.I): + level = len(m.group(1)) + elif m and len(m.group(1)) <= level: + break + else: + section.append(line) + notes = "\n".join(section).strip() + found = bool(notes) + if found: + with open("release-notes.md", "w", encoding="utf-8") as f: + f.write("## What's Changed\n\n" + notes + "\n") + with open(os.environ["GITHUB_OUTPUT"], "a") as out: + out.write(f"found={'true' if found else 'false'}\n") + print("Using the PR's patch notes." if found else "No patch notes section; using generated notes.") + EOF + - name: Publish release uses: softprops/action-gh-release@v2 with: tag_name: v${{ steps.version.outputs.version }}-b${{ github.run_number }} name: Konduktor v${{ steps.version.outputs.version }}-b${{ github.run_number }} target_commitish: ${{ github.sha }} - generate_release_notes: true # auto changelog from commits/PRs since last release + body_path: ${{ steps.notes.outputs.found == 'true' && 'release-notes.md' || '' }} + generate_release_notes: ${{ steps.notes.outputs.found != 'true' }} fail_on_unmatched_files: true files: artifacts/**/* From 0ced274f73688aa3d735945b32f8f35712f46dd9 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Thu, 15 Oct 2026 17:48:40 +0200 Subject: [PATCH 9/9] Bumped version number --- frontend/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/package.json b/frontend/package.json index 4e9fe5a..243e982 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "frontend", "private": true, - "version": "0.2.7", + "version": "0.2.8", "type": "module", "scripts": { "dev": "vite",