Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
One undoable step, and it **names the measures it healed** so a bar you meant
to be wildly uneven (a held grand pause reads the same as a corrupt gap) is
one Ctrl+Z away; if the grid is healthy it says so and touches nothing.
- **Command palette (Ctrl+K).** Press **Ctrl+K** (or View ▸ Command palette)
- **Command palette (Ctrl+K).** Press **Ctrl+K** (or Help ▸ Command palette)
and just type what you want to do — every editor command and menu action is
searchable in one place, each shown with its live keyboard shortcut for your
active profile. Arrow keys select, Enter runs, Esc closes. If you've ever
known the editor *probably* has something but couldn't find which menu it
lives in, this is the answer: type "snap", "tempo", "export", "guide" and
the matching commands surface instantly, fuzzy matching included.
- **Scan for tempo zones (preview).** A new **Tempo/Grid ▸ Scan for tempo zones**
action reads the recording and reports the handful of *tempo intents* it finds
— e.g. "3 tempo zones detected: 120 bpm · 140 bpm · rit 140→90". It's the first
Expand Down
10 changes: 10 additions & 0 deletions screen.html
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,16 @@
<button id="editor-segment-apply" class="px-2 py-0.5 rounded bg-teal-700 text-white hover:bg-teal-600" title="Build the grid: seed each zone, then snap its barlines to the recording inside it">Confirm &amp; refine</button>
<button id="editor-segment-dismiss" class="px-1.5 py-0.5 rounded bg-dark-700/90 text-gray-300 hover:text-white hover:bg-dark-600" title="Dismiss (Esc)">&#10005;</button>
</div>
<!-- Command palette (Ctrl+K) — a searchable front door over every
registry command (with its live keybinding) and menu action.
Type-to-filter; ↑/↓ select, Enter runs, Esc / backdrop closes. -->
<div id="editor-command-palette" class="hidden absolute inset-0 z-40 bg-black/40 backdrop-blur-[2px]">
<div class="mx-auto mt-16 w-[36rem] max-w-[calc(100%-2rem)] rounded-lg border border-gray-600 bg-dark-800/95 shadow-2xl text-sm" role="dialog" aria-label="Command palette">
<input id="editor-palette-input" type="text" placeholder="Type a command… (Esc to close)" autocomplete="off" spellcheck="false"
class="w-full bg-transparent px-3 py-2.5 text-gray-100 placeholder-gray-500 border-b border-gray-700 outline-none" />
<ul id="editor-palette-list" class="max-h-80 overflow-y-auto p-1.5 text-xs"></ul>
</div>
</div>
<!-- Playability-lint popover (P9) — anchored bottom-right of the timeline. -->
<div id="editor-lint-pop" role="dialog" aria-label="Playability notes" class="hidden absolute right-3 bottom-2 z-30 editor-lint-pop"></div>
<!-- Entry tour card (workspace-shell C3) — a non-modal, task-based
Expand Down
215 changes: 215 additions & 0 deletions src/command-palette.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
/* Slopsmith Arrangement Editor — the command palette (Ctrl+K).
*
* One searchable front door over EVERYTHING the editor can do: every command
* in the shortcut registry (with its live keybinding for the active profile)
* plus every menu action that has no registry id (the dialog-openers like
* Song Fit, Scan for tempo zones, Replace audio). Motivated by two real
* tester reports in one night of features that already existed but couldn't
* be found ("I miss a way to snap the selected notes to the grid") — a
* palette makes a feature findable by typing what you want.
*
* The registry id was reserved from day one (`openCommandPalette`, Ctrl+K in
* both profiles) but dispatched to the shortcut panel as a stub; this module
* is the real thing behind it.
*
* Cycle note: registry commands execute through input.js's dispatcher, and
* input.js opens the palette — so the dispatcher arrives as an init HOOK
* (the tempo-zones pattern) instead of an import. The menu model arrives the
* same way (menu-bar.js imports input.js — importing it back from here would
* close the input → palette → menu-bar → input loop). Menu-only actions
* execute through window[fn], exactly as the menu bar itself dispatches them.
*/

import { setStatus } from './ui.js';
import { _editorShortcutRowsPure, editorShortcutProfile } from './shortcuts.js';

/* @pure:command-palette:start */
// Build the searchable entries: registry rows (id + live key) first, then
// menu actions that dispatch a window fn (a `cmd:` menu row IS a registry row
// — skipping it here is the dedupe). `hay` is the lowercase search haystack;
// menu entries carry their menu path so "tempo scan" finds Tempo/Grid items.
export function _paletteEntriesPure(rows, menus) {
const out = [];
for (const r of (rows || [])) {
if (!r || r.status !== 'ready') continue;
// The palette never lists itself — it IS a ready registry row (and a
// View menu row), so without this "Open command palette" shows up as a
// hit that closes the palette and immediately reopens it.
if (r.id === 'openCommandPalette') continue;
out.push({ kind: 'cmd', id: r.id, label: r.label, group: r.group, key: r.key || '',
hay: (r.label + ' ' + (r.group || '')).toLowerCase() });
}
for (const menu of (menus || [])) {
for (const item of (menu.items || [])) {
if (!item || item.sep || item.hdr || !item.fn || !item.label) continue;
out.push({ kind: 'fn', fn: item.fn, label: item.label, group: menu.title, key: item.key || '',
hay: (item.label + ' ' + menu.title).toLowerCase() });
}
}
return out;
}

// Rank entries against a query. Word-start substring beats any substring
// beats a spread-out subsequence; ties break by label so the order is
// stable. An empty query returns the first `limit` entries as-is (a browse
// list). No match → dropped.
export function _paletteFilterPure(entries, query, limit = 12) {
const q = String(query || '').trim().toLowerCase();
const list = entries || [];
if (!q) return list.slice(0, limit);
const scored = [];
for (const e of list) {
const i = e.hay.indexOf(q);
let score = null;
if (i === 0 || (i > 0 && e.hay[i - 1] === ' ')) score = 100 - i;
else if (i >= 0) score = 80 - i;
else {
// subsequence: every query char in order; penalise the spread.
let hi = 0, ok = true, first = -1, last = -1;
for (const ch of q) {
const j = e.hay.indexOf(ch, hi);
if (j < 0) { ok = false; break; }
if (first < 0) first = j;
last = j; hi = j + 1;
}
if (ok) score = 50 - Math.min(40, (last - first) - q.length + 1) - first * 0.1;
}
if (score !== null) scored.push({ e, score });
}
scored.sort((a, b) => b.score - a.score || (a.e.label < b.e.label ? -1 : 1));
return scored.slice(0, limit).map(s => s.e);
}
/* @pure:command-palette:end */

// ── state + chrome ───────────────────────────────────────────────────
let _open = false;
let _results = [];
let _sel = 0;
let _prevFocus = null;
let _hooks = { run: null, menus: null };

const $pal = () => document.getElementById('editor-command-palette');
const $input = () => document.getElementById('editor-palette-input');
const $list = () => document.getElementById('editor-palette-list');

function _entries() {
// `editorShortcutProfile` is the live export-let binding — the LOADER
// returns nothing, so passing its result would silently pin the palette
// to FeedBack keys whatever profile is active.
return _paletteEntriesPure(
_editorShortcutRowsPure(editorShortcutProfile), _hooks.menus || []);
}

function _render() {
const list = $list();
if (!list) return;
if (_sel >= _results.length) _sel = Math.max(0, _results.length - 1);
list.innerHTML = '';
if (!_results.length) {
const li = document.createElement('li');
li.className = 'px-3 py-2 text-gray-500';
li.textContent = 'No matching command';
list.appendChild(li);
return;
}
_results.forEach((e, i) => {
const li = document.createElement('li');
li.className = 'flex items-center justify-between gap-3 px-3 py-1.5 rounded cursor-pointer '
+ (i === _sel ? 'bg-sky-700/60 text-white' : 'text-gray-200 hover:bg-dark-700/80');
li.dataset.idx = String(i);
const left = document.createElement('span');
left.textContent = e.label;
const right = document.createElement('span');
right.className = 'shrink-0 font-mono text-[10px] ' + (i === _sel ? 'text-sky-200' : 'text-gray-500');
right.textContent = e.key || e.group;
li.appendChild(left);
li.appendChild(right);
list.appendChild(li);
});
const cur = list.children[_sel];
if (cur && cur.scrollIntoView) cur.scrollIntoView({ block: 'nearest' });
}

function _refresh() {
const input = $input();
_results = _paletteFilterPure(_entries(), input ? input.value : '');
_render();
}

function _close() {
if (!_open) return;
_open = false;
const pal = $pal();
if (pal) pal.classList.add('hidden');
// Hand the keyboard back to whoever had it before the palette stole focus.
// Blurring to <body> is a safe floor (the editor's shortcuts listen on
// `document`), but restoring the real element keeps a menu-opened palette
// from dropping the user out of the menu bar.
const prev = _prevFocus;
_prevFocus = null;
if (prev && prev.isConnected && prev.focus) prev.focus();
else if (document.activeElement && document.activeElement.blur) document.activeElement.blur();
}

// Escape must close the palette from ANYWHERE, not just from its own input:
// the backdrop only covers #editor-canvas-wrap, so a click on the menu bar or a
// toolbar moves focus out while the overlay stays up — and the input's keydown
// handler (the only Escape path) can no longer see the key. main.js's global
// dialog listener calls this, exactly as it does for the other overlays.
export function editorCloseCommandPalette() { _close(); }

function _runSelected() {
const e = _results[_sel];
if (!e) return;
_close();
if (e.kind === 'cmd') {
if (_hooks.run) _hooks.run(e.id);
return;
}
const fn = window[e.fn];
if (typeof fn === 'function') fn();
else setStatus(`${e.label} is not available right now.`);
}

export function editorOpenCommandPalette() {
const pal = $pal();
const input = $input();
if (!pal || !input) return true;
_open = true;
_sel = 0;
_prevFocus = document.activeElement;
input.value = '';
pal.classList.remove('hidden');
_refresh();
input.focus();
return true;
}

export function initCommandPalette(hooks) {
_hooks = { ..._hooks, ...(hooks || {}) };
const pal = $pal();
const input = $input();
const list = $list();
if (!pal || !input || !list) return;
// All keyboard handling scoped to the palette's own input — the global
// shortcut chain already ignores typing targets, so nothing leaks.
input.addEventListener('keydown', (e) => {
if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); _close(); }
else if (e.key === 'ArrowDown') { e.preventDefault(); _sel = Math.min(_results.length - 1, _sel + 1); _render(); }
else if (e.key === 'ArrowUp') { e.preventDefault(); _sel = Math.max(0, _sel - 1); _render(); }
else if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); _runSelected(); }
// Focus trap. The input is the palette's ONLY focusable node (the rows
// are click-handled <li>s), so trapping Tab degenerates to swallowing
// it — otherwise Tab walks focus into the page BEHIND the open overlay.
else if (e.key === 'Tab') { e.preventDefault(); }
});
Comment thread
byrongamatos marked this conversation as resolved.
input.addEventListener('input', () => { _sel = 0; _refresh(); });
list.addEventListener('click', (e) => {
const li = e.target instanceof Element ? e.target.closest('li[data-idx]') : null;
if (!li) return;
_sel = parseInt(li.dataset.idx, 10) || 0;
_runSelected();
});
// Click on the backdrop (the palette wrapper itself) dismisses.
pal.addEventListener('mousedown', (e) => { if (e.target === pal) _close(); });
}
3 changes: 2 additions & 1 deletion src/input.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { _editorCommandById, _editorEffectiveRightClickBehaviorPure, _editorEofC
import { SNAP_VALUES, _editorEffectiveSnapValuePure, _editorSnapSubdivisionsPure } from './snap.js';
import { S } from './state.js';
import { _editorShowTabPreview, _tabPreviewKeyPolicyPure } from './tab-preview.js';
import { editorOpenCommandPalette } from './command-palette.js';
import { editorExportGp5 } from './gp5-export.js';
import { TempoGridCmd, _editorModulateTempoAtSelection, _editorTapTempoAtSelection, _editorToggleSyncLock, _editorToggleTempoMapMode, _tapTempoHandleKey, _tempoDeleteSelection, _tempoInsertSyncPoint, _tempoMapOnContextMenu, _tempoMeasureBeatCount, _tempoMeasureDenominator, _tempoPromptMeasureBpm, _tempoSetBeatsPerMeasure, _tempoSetDenominatorOnBeatsPure, _tempoPromptPickup, _tempoSelRangePure } from './tempo.js';
import { _tourNoteAction } from './tour.js';
Expand Down Expand Up @@ -923,7 +924,7 @@ export function _editorRunEofCommand(cmd) {
case 'movePartEarlier': return host.editorMovePart(-1);
case 'movePartLater': return host.editorMovePart(+1);
case 'showShortcutHelp': return _editorShowShortcutDiscovery('Shortcut help');
case 'openCommandPalette': return _editorShowShortcutDiscovery('Command palette');
case 'openCommandPalette': return editorOpenCommandPalette();
case 'importMidi': _editorOpenImportMidi(); return true;
case 'importXml': _editorOpenImportXml(); return true;
case 'importGp': _editorOpenImportGp(); return true;
Expand Down
19 changes: 18 additions & 1 deletion src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@
_editorSnapStepSeconds, editorRunShortcutCommand, editorToggleEntryPreview,
editorToggleShortcutPanel, onContextMenu, onKeyDown
} from './input.js';
import { editorCloseCommandPalette, initCommandPalette } from './command-palette.js';
import {
editorAddString, editorHideStringsModal, editorRemoveString,
editorSetStringTuning, editorShowStringsModal
Expand All @@ -118,7 +119,7 @@
import { _lintChipRefresh, editorToggleLintPopover, initPlayabilityLint } from './playability-lint.js';
import { _drumPadStripRefresh, editorToggleDrumPadStrip, initDrumPadStrip, teardownDrumPadStrip } from './drum-pad-strip.js';
import { _fretboardStripRefresh, editorToggleFretboardStrip, initFretboardStrip } from './fretboard-strip.js';
import { initMenuBar } from './menu-bar.js';
import { EDITOR_MENUS, initMenuBar } from './menu-bar.js';
import { initToolbars } from './toolbars.js';
import { editorStartTour, editorTourEscape, editorTourSkip, _tourAdvance, _tourNoteAction } from './tour.js';
import { editorDismissSignpost } from './signposts.js';
Expand Down Expand Up @@ -752,6 +753,11 @@
hideAddNote();
hideContextMenu();
window.editorHideLoadModal();
// The palette's own Escape (on its input) stops propagation, so this
// only fires when focus has LEFT the palette — a click on the menu bar
// or a toolbar, both of which sit outside the canvas-wrap its backdrop
// covers. Without it that click strands the overlay open.
editorCloseCommandPalette();
// The User Guide is NOT closed here: this listener registers at import
// time, so it runs before input.js onKeyDown — closing the guide here
// would blind onKeyDown's read-only-lens gate (it would read the modal
Expand Down Expand Up @@ -1714,7 +1720,7 @@
// the same save path as the Save button (in-place sloppak write, not the
// heavy create-mode build).
if (S.sessionId) {
try { await saveCDLC(); } catch (e) { /* surfaced via setStatus */ }

Check warning on line 1723 in src/main.js

View workflow job for this annotation

GitHub Actions / lint

'e' is defined but never used. Allowed unused caught errors must match /^_/u
}
// Capture where we are so the return trip lands on the same spot.
const returnCtx = {
Expand Down Expand Up @@ -1979,6 +1985,17 @@
// handed over as hooks so tempo-zones.js never imports tempo.js (cycle).
initTempoZones({ confirm: editorConfirmTempoZones, single: editorZonesSingleTempo,
octave: editorZonesOctaveFix });
// Registry commands run through `editorRunShortcutCommand` — the SAME
// by-id dispatcher the shortcut panel's buttons use, which is what the
// palette is (a click on a command, not a keypress). Going straight to
// `_editorRunEofCommand` (the raw keyboard switch) would leave the three
// digit-RANGE rows — "Set selected fret 0-9", the two bookmark 1-9 rows —
// silently inert: that switch only knows the per-digit forms
// (`setFretDigit:<n>`), so the bare id falls to `default: return false`.
// This path already carries their explain-hint. The menu model rides along
// too; both are hooks so command-palette.js imports neither input.js nor
// menu-bar.js (each would close an import cycle).
initCommandPalette({ run: editorRunShortcutCommand, menus: EDITOR_MENUS });
initPlayabilityLint();
initDrumPadStrip();
initFretboardStrip();
Expand Down
Loading
Loading