M1.8: command palette, global keymap, UI commands
- Engine: ui.registerCommands (validated, replaces the previous set),
UI commands in listCommands with ui: true and labelKey, running one
through the engine emits uiCommand {id, params}.
- Frontend: ui/src/commands/ (keymap by key code, fuzzy ranking, Pinia
commands store with handlers, recents and error toasts), the command
palette (Mod+Shift+P), UI commands palette.open, settings.open (Mod+,,
disabled until M1.9b) and view.toggleProjectTree (Mod+1). The editor's
shortcuts.ts moved into the global keymap.
- Tests: engine and control-channel tests for registration and
uiCommand, Vitest for keymap, ranking, store, palette and App wiring.
- Docs: architecture, ui-parity, target-app-parity, gaps, roadmap,
ROADMAP, README.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2f8fef876b
commit
184b8a3468
33 changed files with 2282 additions and 233 deletions
|
|
@ -2,12 +2,15 @@
|
|||
/**
|
||||
* Root component: mounts the main window layout with the editor area; the
|
||||
* slogan shows while no tab is open, and the restore dialog for unsaved
|
||||
* texts from the recovery journal, and the toast stack. Loads product
|
||||
* information from the engine on mount, starts showing notifications and
|
||||
* following the theme (see `theme.ts`); a failed theme report raises an
|
||||
* error toast.
|
||||
* texts from the recovery journal, the toast stack and the command
|
||||
* palette. Loads product information from the engine on mount, starts
|
||||
* showing notifications, following the theme (see `theme.ts`; a failed
|
||||
* theme report raises an error toast) and the global keymap with the UI
|
||||
* commands (see `commands/store.ts`).
|
||||
*/
|
||||
import { onMounted, onUnmounted } from "vue";
|
||||
import { useCommandsStore } from "./commands/store";
|
||||
import CommandPalette from "./components/palette/CommandPalette.vue";
|
||||
import EditorArea from "./components/editor/EditorArea.vue";
|
||||
import MainLayout from "./components/layout/MainLayout.vue";
|
||||
import NotificationStack from "./components/notifications/NotificationStack.vue";
|
||||
|
|
@ -18,6 +21,7 @@ import { startTheme } from "./theme";
|
|||
|
||||
const app = useAppStore();
|
||||
const notifications = useNotificationsStore();
|
||||
const commands = useCommandsStore();
|
||||
|
||||
/** Stops following the theme; set while mounted. */
|
||||
let stopTheme: (() => void) | null = null;
|
||||
|
|
@ -25,12 +29,14 @@ let stopTheme: (() => void) | null = null;
|
|||
onMounted(() => {
|
||||
notifications.start();
|
||||
stopTheme = startTheme((error) => notifications.notifyError("theme.systemPreference", error));
|
||||
void commands.start();
|
||||
void app.loadAbout();
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
stopTheme?.();
|
||||
stopTheme = null;
|
||||
commands.stop();
|
||||
notifications.stop();
|
||||
});
|
||||
</script>
|
||||
|
|
@ -44,6 +50,7 @@ onUnmounted(() => {
|
|||
</EditorArea>
|
||||
</MainLayout>
|
||||
<RecoveryDialog />
|
||||
<CommandPalette />
|
||||
<NotificationStack />
|
||||
</template>
|
||||
|
||||
|
|
|
|||
205
ui/src/commands/keymap.ts
Normal file
205
ui/src/commands/keymap.ts
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
/**
|
||||
* The global keymap: default shortcuts of every command, engine and UI,
|
||||
* matched against key presses by key code.
|
||||
*
|
||||
* Shortcuts are written in Lutra notation (`Mod+Alt+S`, `Mod` = Cmd on
|
||||
* macOS, Ctrl elsewhere) and come from the command list (`listCommands`
|
||||
* plus the UI commands); nothing here hard-codes a key.
|
||||
*/
|
||||
import { t } from "../i18n";
|
||||
|
||||
/** A parsed shortcut. */
|
||||
export interface Shortcut {
|
||||
/** Ctrl must be held. */
|
||||
ctrl: boolean;
|
||||
/** Meta (Cmd) must be held. */
|
||||
meta: boolean;
|
||||
/** Alt (Option) must be held. */
|
||||
alt: boolean;
|
||||
/** Shift must be held. */
|
||||
shift: boolean;
|
||||
/** The key, lower case (`s`, `f4`, `enter`, `,`). */
|
||||
key: string;
|
||||
}
|
||||
|
||||
/** One binding of the keymap. */
|
||||
export interface Binding {
|
||||
/** The command id. */
|
||||
command: string;
|
||||
/** The shortcut that runs it. */
|
||||
shortcut: Shortcut;
|
||||
}
|
||||
|
||||
/** Whether the frontend runs on macOS, where `Mod` means Cmd. */
|
||||
export function isMac(): boolean {
|
||||
return typeof navigator !== "undefined" && /Mac OS X|Macintosh|iPhone|iPad/.test(navigator.userAgent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a shortcut in Lutra notation.
|
||||
*
|
||||
* @param text - for example `Mod+Alt+S`; a trailing `+` is the plus key
|
||||
* (`Mod++`).
|
||||
* @param mac - whether `Mod` means Cmd.
|
||||
* @returns the shortcut, or null when the text has no key or an unknown modifier.
|
||||
*/
|
||||
export function parseShortcut(text: string, mac: boolean): Shortcut | null {
|
||||
const plusKey = text.endsWith("++");
|
||||
const parts = (plusKey ? text.slice(0, -2) : text).split("+").map((part) => part.trim().toLowerCase());
|
||||
const key = plusKey ? "+" : parts.pop();
|
||||
if (key === undefined || key === "") {
|
||||
return null;
|
||||
}
|
||||
const shortcut: Shortcut = { ctrl: false, meta: false, alt: false, shift: false, key };
|
||||
for (const part of parts) {
|
||||
switch (part) {
|
||||
case "":
|
||||
if (!plusKey) {
|
||||
return null;
|
||||
}
|
||||
break;
|
||||
case "mod":
|
||||
if (mac) {
|
||||
shortcut.meta = true;
|
||||
} else {
|
||||
shortcut.ctrl = true;
|
||||
}
|
||||
break;
|
||||
case "ctrl":
|
||||
shortcut.ctrl = true;
|
||||
break;
|
||||
case "cmd":
|
||||
case "meta":
|
||||
shortcut.meta = true;
|
||||
break;
|
||||
case "alt":
|
||||
shortcut.alt = true;
|
||||
break;
|
||||
case "shift":
|
||||
shortcut.shift = true;
|
||||
break;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return shortcut;
|
||||
}
|
||||
|
||||
/** Punctuation keys by `KeyboardEvent.code`, as the US layout labels them. */
|
||||
const PUNCTUATION: Readonly<Record<string, string>> = {
|
||||
Comma: ",",
|
||||
Period: ".",
|
||||
Slash: "/",
|
||||
Semicolon: ";",
|
||||
Quote: "'",
|
||||
BracketLeft: "[",
|
||||
BracketRight: "]",
|
||||
Backslash: "\\",
|
||||
Minus: "-",
|
||||
Equal: "=",
|
||||
Backquote: "`",
|
||||
};
|
||||
|
||||
/**
|
||||
* The key of an event, independent of the keyboard layout effects of Alt
|
||||
* and Shift for letters, digits and punctuation (`Alt+S` on macOS types
|
||||
* `ß`, `Shift+1` types `!`).
|
||||
*
|
||||
* @param event - the key event.
|
||||
*/
|
||||
export function eventKey(event: KeyboardEvent): string {
|
||||
const code = event.code;
|
||||
if (/^Key[A-Z]$/.test(code)) {
|
||||
return code.slice(3).toLowerCase();
|
||||
}
|
||||
if (/^(Digit|Numpad)[0-9]$/.test(code)) {
|
||||
return code.slice(-1);
|
||||
}
|
||||
const punctuation = PUNCTUATION[code];
|
||||
if (punctuation !== undefined) {
|
||||
return punctuation;
|
||||
}
|
||||
return event.key.toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a key event matches a shortcut exactly.
|
||||
*
|
||||
* @param event - the key event.
|
||||
* @param shortcut - the shortcut.
|
||||
*/
|
||||
export function matches(event: KeyboardEvent, shortcut: Shortcut): boolean {
|
||||
return (
|
||||
event.ctrlKey === shortcut.ctrl &&
|
||||
event.metaKey === shortcut.meta &&
|
||||
event.altKey === shortcut.alt &&
|
||||
event.shiftKey === shortcut.shift &&
|
||||
eventKey(event) === shortcut.key
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the keymap from command descriptions. Commands without a shortcut
|
||||
* or with one that does not parse are left out; when two commands share a
|
||||
* shortcut, the first one listed wins.
|
||||
*
|
||||
* @param commands - id and default shortcut of each command.
|
||||
* @param mac - whether `Mod` means Cmd.
|
||||
*/
|
||||
export function buildKeymap(
|
||||
commands: readonly { id: string; defaultShortcut?: string | null | undefined }[],
|
||||
mac: boolean,
|
||||
): Binding[] {
|
||||
const keymap: Binding[] = [];
|
||||
for (const command of commands) {
|
||||
const raw: unknown = command.defaultShortcut;
|
||||
const shortcut = typeof raw === "string" ? parseShortcut(raw, mac) : null;
|
||||
if (shortcut) {
|
||||
keymap.push({ command: command.id, shortcut });
|
||||
}
|
||||
}
|
||||
return keymap;
|
||||
}
|
||||
|
||||
/**
|
||||
* The command a key event triggers.
|
||||
*
|
||||
* @param keymap - the keymap.
|
||||
* @param event - the key event.
|
||||
* @returns the command id, or null.
|
||||
*/
|
||||
export function commandFor(keymap: readonly Binding[], event: KeyboardEvent): string | null {
|
||||
return keymap.find((binding) => matches(event, binding.shortcut))?.command ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a shortcut for display: modifier names from the catalog, in the
|
||||
* order Ctrl, Alt, Shift, Cmd, and the key in upper case
|
||||
* (`Ctrl+Shift+P`, `Cmd+,`).
|
||||
*
|
||||
* @param text - the shortcut in Lutra notation.
|
||||
* @param mac - whether `Mod` means Cmd.
|
||||
* @returns the display text, or null when the shortcut does not parse.
|
||||
*/
|
||||
export function formatShortcut(text: string, mac: boolean): string | null {
|
||||
const shortcut = parseShortcut(text, mac);
|
||||
if (shortcut === null) {
|
||||
return null;
|
||||
}
|
||||
const parts: string[] = [];
|
||||
if (shortcut.ctrl) {
|
||||
parts.push(t("command.key.ctrl"));
|
||||
}
|
||||
if (shortcut.alt) {
|
||||
parts.push(mac ? t("command.key.option") : t("command.key.alt"));
|
||||
}
|
||||
if (shortcut.shift) {
|
||||
parts.push(t("command.key.shift"));
|
||||
}
|
||||
if (shortcut.meta) {
|
||||
parts.push(t("command.key.cmd"));
|
||||
}
|
||||
const key = shortcut.key;
|
||||
parts.push(key.length === 1 ? key.toUpperCase() : key.charAt(0).toUpperCase() + key.slice(1));
|
||||
return parts.join("+");
|
||||
}
|
||||
189
ui/src/commands/rank.ts
Normal file
189
ui/src/commands/rank.ts
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
/**
|
||||
* Fuzzy ranking of commands for the palette.
|
||||
*
|
||||
* A query matches a command's label (the catalog text) or its id. Matches
|
||||
* fall into tiers, best first: the text starts with the query; a word of
|
||||
* the text starts with it; the query is spread over the starts of
|
||||
* consecutive words (`togpro` → "Toggle Project"); the text contains it;
|
||||
* its characters appear in order. Within a tier, recently run commands come
|
||||
* first, then shorter texts, then the label alphabetically. Without a query
|
||||
* every command is listed, recent ones first.
|
||||
*/
|
||||
|
||||
/** Tier of a match; higher is better. */
|
||||
export const Tier = {
|
||||
/** Characters of the query appear in order. */
|
||||
Fuzzy: 1,
|
||||
/** The text contains the query. */
|
||||
Substring: 2,
|
||||
/** The query is spread over the starts of consecutive words. */
|
||||
WordStarts: 3,
|
||||
/** A word of the text starts with the query. */
|
||||
WordPrefix: 4,
|
||||
/** The text starts with the query. */
|
||||
Prefix: 5,
|
||||
} as const;
|
||||
|
||||
/** Longest query considered; longer ones are cut. */
|
||||
export const MAX_QUERY = 100;
|
||||
|
||||
/** A match: its tier and how well it fits within the tier (higher is better). */
|
||||
export interface Match {
|
||||
/** The tier. */
|
||||
tier: number;
|
||||
/** Fit within the tier; shorter texts and tighter matches fit better. */
|
||||
fit: number;
|
||||
}
|
||||
|
||||
/** What the ranking needs of a command. */
|
||||
export interface Rankable {
|
||||
/** Command id. */
|
||||
id: string;
|
||||
/** Label as shown. */
|
||||
label: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a text into lower-case words at spaces, punctuation and camelCase
|
||||
* boundaries (`view.toggleProjectTree` → view, toggle, project, tree).
|
||||
*
|
||||
* @param text - the text.
|
||||
*/
|
||||
export function words(text: string): string[] {
|
||||
return text
|
||||
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
||||
.toLowerCase()
|
||||
.split(/[^\p{L}\p{N}]+/u)
|
||||
.filter((word) => word !== "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the query can be split into pieces that start consecutive words,
|
||||
* in order, each piece starting a later word than the one before.
|
||||
*
|
||||
* @param query - the query, lower case, without spaces.
|
||||
* @param list - the words of the text.
|
||||
*/
|
||||
function spreadOverWordStarts(query: string, list: readonly string[]): boolean {
|
||||
const memo = new Map<string, boolean>();
|
||||
const from = (q: number, w: number): boolean => {
|
||||
if (q === query.length) {
|
||||
return true;
|
||||
}
|
||||
const memoKey = `${String(q)}:${String(w)}`;
|
||||
const known = memo.get(memoKey);
|
||||
if (known !== undefined) {
|
||||
return known;
|
||||
}
|
||||
let found = false;
|
||||
for (let i = w; i < list.length && !found; i += 1) {
|
||||
const word = list[i] ?? "";
|
||||
let k = 0;
|
||||
while (k < word.length && q + k < query.length && word[k] === query[q + k]) {
|
||||
k += 1;
|
||||
}
|
||||
for (let take = k; take >= 1 && !found; take -= 1) {
|
||||
found = from(q + take, i + 1);
|
||||
}
|
||||
}
|
||||
memo.set(memoKey, found);
|
||||
return found;
|
||||
};
|
||||
return from(0, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Matches a query against one text.
|
||||
*
|
||||
* @param query - the query; case and surrounding spaces are ignored.
|
||||
* @param text - the label or id.
|
||||
* @returns the match, or null if the query does not match.
|
||||
*/
|
||||
export function matchText(query: string, text: string): Match | null {
|
||||
const q = query.trim().toLowerCase().slice(0, MAX_QUERY);
|
||||
const lower = text.toLowerCase();
|
||||
const length = -text.length;
|
||||
if (q === "") {
|
||||
return { tier: Tier.Prefix, fit: length };
|
||||
}
|
||||
if (lower.startsWith(q)) {
|
||||
return { tier: Tier.Prefix, fit: length };
|
||||
}
|
||||
const list = words(text);
|
||||
if (list.some((_, i) => list.slice(i).join(" ").startsWith(q))) {
|
||||
return { tier: Tier.WordPrefix, fit: length };
|
||||
}
|
||||
const compact = q.replace(/\s+/g, "");
|
||||
if (compact !== "" && spreadOverWordStarts(compact, list)) {
|
||||
return { tier: Tier.WordStarts, fit: length };
|
||||
}
|
||||
const at = lower.indexOf(q);
|
||||
if (at >= 0) {
|
||||
return { tier: Tier.Substring, fit: length - at };
|
||||
}
|
||||
let gaps = 0;
|
||||
let pos = -1;
|
||||
for (const ch of compact) {
|
||||
const next = lower.indexOf(ch, pos + 1);
|
||||
if (next < 0) {
|
||||
return null;
|
||||
}
|
||||
if (pos >= 0) {
|
||||
gaps += next - pos - 1;
|
||||
}
|
||||
pos = next;
|
||||
}
|
||||
return compact === "" ? null : { tier: Tier.Fuzzy, fit: -gaps * 100 + length };
|
||||
}
|
||||
|
||||
/**
|
||||
* The better of two matches.
|
||||
*
|
||||
* @param a - a match or null.
|
||||
* @param b - a match or null.
|
||||
*/
|
||||
function better(a: Match | null, b: Match | null): Match | null {
|
||||
if (a === null) {
|
||||
return b;
|
||||
}
|
||||
if (b === null) {
|
||||
return a;
|
||||
}
|
||||
if (a.tier !== b.tier) {
|
||||
return a.tier > b.tier ? a : b;
|
||||
}
|
||||
return a.fit >= b.fit ? a : b;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ranks commands for a query.
|
||||
*
|
||||
* @param items - the commands.
|
||||
* @param query - what the user typed.
|
||||
* @param recent - ids of recently run commands, most recent first.
|
||||
* @returns the matching commands, best first.
|
||||
*/
|
||||
export function rank<T extends Rankable>(items: readonly T[], query: string, recent: readonly string[]): T[] {
|
||||
const recency = new Map(recent.map((id, i) => [id, i]));
|
||||
const scored: { item: T; match: Match; recent: number }[] = [];
|
||||
for (const item of items) {
|
||||
const match = better(matchText(query, item.label), matchText(query, item.id));
|
||||
if (match !== null) {
|
||||
scored.push({ item, match, recent: recency.get(item.id) ?? Number.MAX_SAFE_INTEGER });
|
||||
}
|
||||
}
|
||||
const empty = query.trim() === "";
|
||||
scored.sort((a, b) => {
|
||||
if (!empty && a.match.tier !== b.match.tier) {
|
||||
return b.match.tier - a.match.tier;
|
||||
}
|
||||
if (a.recent !== b.recent) {
|
||||
return a.recent - b.recent;
|
||||
}
|
||||
if (!empty && a.match.fit !== b.match.fit) {
|
||||
return b.match.fit - a.match.fit;
|
||||
}
|
||||
return a.item.label.localeCompare(b.item.label);
|
||||
});
|
||||
return scored.map((entry) => entry.item);
|
||||
}
|
||||
301
ui/src/commands/store.ts
Normal file
301
ui/src/commands/store.ts
Normal file
|
|
@ -0,0 +1,301 @@
|
|||
/**
|
||||
* The command store: every command the user can reach, engine and UI, the
|
||||
* global keymap built from their default shortcuts, and running commands
|
||||
* from the keyboard, the palette and `uiCommand` events.
|
||||
*
|
||||
* - **List:** `listCommands` from the engine, refreshed when a project opens
|
||||
* or closes and whenever the palette opens, plus the UI commands of
|
||||
* {@link UI_COMMANDS} (also before the engine lists them).
|
||||
* - **Keymap:** one listener on the window in the capture phase, so
|
||||
* shortcuts also work while CodeMirror or an input has the focus. A
|
||||
* disabled command's shortcut is swallowed and does nothing.
|
||||
* - **Handlers:** components supply the behaviour of UI commands and the
|
||||
* context of engine commands (the editor runs `file.save` with the active
|
||||
* buffer) with {@link useCommandsStore}'s `provide`. Other engine
|
||||
* commands run with empty params.
|
||||
* - **Errors:** a failed command raises an error toast (M1.12).
|
||||
*/
|
||||
import { defineStore } from "pinia";
|
||||
import { computed, ref, shallowReactive } from "vue";
|
||||
import { hasMessage, t } from "../i18n";
|
||||
import { listCommands, onEngineEvent, run, type CommandInfo, type EngineEventPayload, type JsonValue } from "../ipc";
|
||||
import { useNotificationsStore } from "../stores/notifications";
|
||||
import { buildKeymap, commandFor, formatShortcut, isMac } from "./keymap";
|
||||
import { UI_COMMANDS } from "./uiCommands";
|
||||
|
||||
/** Behaviour a component supplies for a command. */
|
||||
export interface CommandHandler {
|
||||
/**
|
||||
* Runs the command.
|
||||
*
|
||||
* @param params - the params it was run with (`{}` from the keyboard and
|
||||
* the palette, as given in a `uiCommand` event).
|
||||
*/
|
||||
run: (params: JsonValue) => void | Promise<void>;
|
||||
/** Whether it can run now; always when absent. Reactive reads update the palette. */
|
||||
enabled?: () => boolean;
|
||||
}
|
||||
|
||||
/** A command as the palette shows it. */
|
||||
export interface PaletteEntry {
|
||||
/** Command id. */
|
||||
id: string;
|
||||
/** Label: the catalog text for UI commands, the engine's label otherwise. */
|
||||
label: string;
|
||||
/** Default shortcut formatted for display, or null. */
|
||||
shortcut: string | null;
|
||||
/** Whether it can run now. */
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
/** Most recently run commands remembered. */
|
||||
export const MAX_RECENT = 20;
|
||||
|
||||
/**
|
||||
* Reads the command list from the engine, keeping well-formed entries.
|
||||
*
|
||||
* @param raw - the `listCommands` result.
|
||||
*/
|
||||
function toCommandInfos(raw: unknown): CommandInfo[] | null {
|
||||
if (!Array.isArray(raw)) {
|
||||
return null;
|
||||
}
|
||||
return (raw as unknown[]).filter(
|
||||
(c): c is CommandInfo =>
|
||||
typeof c === "object" &&
|
||||
c !== null &&
|
||||
"id" in c &&
|
||||
typeof c.id === "string" &&
|
||||
"label" in c &&
|
||||
typeof c.label === "string",
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The label of a command: the catalog text of its `labelKey` when the
|
||||
* catalog has it, else the engine's label.
|
||||
*
|
||||
* @param info - the command.
|
||||
*/
|
||||
function labelOf(info: CommandInfo): string {
|
||||
return typeof info.labelKey === "string" && hasMessage(info.labelKey) ? t(info.labelKey) : info.label;
|
||||
}
|
||||
|
||||
/** Store of the commands, the keymap and the recently run commands. */
|
||||
export const useCommandsStore = defineStore("commands", () => {
|
||||
const notifications = useNotificationsStore();
|
||||
/** Commands as the engine lists them; empty until loaded. */
|
||||
const infos = ref<CommandInfo[]>([]);
|
||||
/** Handlers supplied by components, by command id. */
|
||||
const handlers = shallowReactive(new Map<string, CommandHandler>());
|
||||
/** Ids of recently run commands, most recent first. */
|
||||
const recent = ref<string[]>([]);
|
||||
/** Whether `Mod` means Cmd. */
|
||||
const mac = isMac();
|
||||
/** Ends the engine event subscription; set while started. */
|
||||
let unsubscribe: (() => void) | null = null;
|
||||
|
||||
/** Every command: the engine's list plus UI commands it does not list yet. */
|
||||
const all = computed<CommandInfo[]>(() => {
|
||||
const listed = new Set(infos.value.map((info) => info.id));
|
||||
const local = UI_COMMANDS.filter((spec) => !listed.has(spec.id)).map(
|
||||
(spec): CommandInfo => ({
|
||||
id: spec.id,
|
||||
label: spec.labelKey,
|
||||
labelKey: spec.labelKey,
|
||||
menuPath: spec.menuPath ?? null,
|
||||
defaultShortcut: spec.defaultShortcut ?? null,
|
||||
params: "",
|
||||
enabled: true,
|
||||
ui: true,
|
||||
}),
|
||||
);
|
||||
return [...infos.value, ...local];
|
||||
});
|
||||
|
||||
/** The keymap of every command with a default shortcut. */
|
||||
const keymap = computed(() => buildKeymap(all.value, mac));
|
||||
|
||||
/**
|
||||
* Whether a command can run now: its handler decides if it has one; a UI
|
||||
* command without a handler cannot run; otherwise the engine's state.
|
||||
*
|
||||
* @param id - the command id.
|
||||
*/
|
||||
function isEnabled(id: string): boolean {
|
||||
const handler = handlers.get(id);
|
||||
if (handler) {
|
||||
return handler.enabled?.() ?? true;
|
||||
}
|
||||
const info = all.value.find((c) => c.id === id);
|
||||
return info !== undefined && info.ui !== true && info.enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* The commands the palette offers: UI commands and engine commands that
|
||||
* are user actions (they have a menu path or a default shortcut), not
|
||||
* the protocol commands clients call with data (`buffer.edit`).
|
||||
*/
|
||||
const entries = computed<PaletteEntry[]>(() =>
|
||||
all.value
|
||||
.filter((info) => info.ui === true || info.menuPath !== null || info.defaultShortcut !== null)
|
||||
.map((info) => ({
|
||||
id: info.id,
|
||||
label: labelOf(info),
|
||||
shortcut: typeof info.defaultShortcut === "string" ? formatShortcut(info.defaultShortcut, mac) : null,
|
||||
enabled: isEnabled(info.id),
|
||||
})),
|
||||
);
|
||||
|
||||
/**
|
||||
* Supplies the behaviour of a command.
|
||||
*
|
||||
* @param id - the command id.
|
||||
* @param handler - what running it does.
|
||||
* @returns a function that withdraws the handler (only if it is still this one).
|
||||
*/
|
||||
function provide(id: string, handler: CommandHandler): () => void {
|
||||
handlers.set(id, handler);
|
||||
return () => {
|
||||
if (handlers.get(id) === handler) {
|
||||
handlers.delete(id);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Remembers a command as run most recently. Opening the palette itself
|
||||
* is not remembered: it would always head the list it opens.
|
||||
*
|
||||
* @param id - the command id.
|
||||
*/
|
||||
function remember(id: string): void {
|
||||
if (id === "palette.open") {
|
||||
return;
|
||||
}
|
||||
recent.value = [id, ...recent.value.filter((other) => other !== id)].slice(0, MAX_RECENT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a command the user chose (keyboard or palette): through its
|
||||
* handler if a component supplied one, else through the engine. A
|
||||
* disabled command does nothing. A failure raises an error toast.
|
||||
*
|
||||
* @param id - the command id.
|
||||
* @param params - the params.
|
||||
*/
|
||||
async function execute(id: string, params: JsonValue = {}): Promise<void> {
|
||||
if (!isEnabled(id)) {
|
||||
return;
|
||||
}
|
||||
remember(id);
|
||||
const handler = handlers.get(id);
|
||||
if (handler) {
|
||||
try {
|
||||
await handler.run(params);
|
||||
} catch (reason: unknown) {
|
||||
notifications.notifyError(id, {
|
||||
code: "internal",
|
||||
message: reason instanceof Error ? reason.message : String(reason),
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
const result = await run(id, params);
|
||||
if (!result.ok) {
|
||||
notifications.notifyError(id, result.error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a UI command the engine dispatched (`uiCommand`). One without a
|
||||
* handler, or disabled now, raises a warning toast instead, so an agent
|
||||
* learns that nothing happened.
|
||||
*
|
||||
* @param id - the command id; unchecked, it comes from the engine.
|
||||
* @param params - its params.
|
||||
*/
|
||||
async function dispatch(id: unknown, params: unknown): Promise<void> {
|
||||
const name = typeof id === "string" ? id : String(id);
|
||||
const handler = handlers.get(name);
|
||||
if (!handler || !(handler.enabled?.() ?? true)) {
|
||||
notifications.notify({ level: "warning", message: t("command.unavailable", { command: name }) });
|
||||
return;
|
||||
}
|
||||
await execute(name, (params ?? {}) as JsonValue);
|
||||
}
|
||||
|
||||
/** Loads the command list from the engine; a failure raises an error toast. */
|
||||
async function refresh(): Promise<void> {
|
||||
const result = await listCommands();
|
||||
const list = result.ok ? toCommandInfos(result.value) : null;
|
||||
if (list) {
|
||||
infos.value = list;
|
||||
} else {
|
||||
notifications.notifyError(
|
||||
"listCommands",
|
||||
result.ok
|
||||
? { code: "ipc", message: t("common.error.unexpectedResult", { command: "listCommands" }) }
|
||||
: result.error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles an engine event: runs `uiCommand`s and refreshes the enabled
|
||||
* states when a project opens or closes.
|
||||
*
|
||||
* @param event - the engine event.
|
||||
*/
|
||||
function onEvent(event: EngineEventPayload): void {
|
||||
if (event.kind === "uiCommand") {
|
||||
void dispatch(event.id, event.params);
|
||||
} else if (event.kind === "projectOpened" || event.kind === "projectClosed") {
|
||||
void refresh();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the command bound to a key press.
|
||||
*
|
||||
* @param event - a key press anywhere in the window.
|
||||
*/
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
const id = commandFor(keymap.value, event);
|
||||
if (id === null) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void execute(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the keymap and the `uiCommand` subscription, registers the UI
|
||||
* commands with the engine and loads the command list. Starting twice is
|
||||
* a no-op.
|
||||
*/
|
||||
async function start(): Promise<void> {
|
||||
if (unsubscribe) {
|
||||
return;
|
||||
}
|
||||
unsubscribe = onEngineEvent(onEvent);
|
||||
window.addEventListener("keydown", onKeydown, true);
|
||||
const registered = await run("ui.registerCommands", {
|
||||
commands: UI_COMMANDS.map((spec) => ({ ...spec })),
|
||||
});
|
||||
if (!registered.ok) {
|
||||
notifications.notifyError("ui.registerCommands", registered.error);
|
||||
}
|
||||
await refresh();
|
||||
}
|
||||
|
||||
/** Stops the keymap and the subscription. */
|
||||
function stop(): void {
|
||||
window.removeEventListener("keydown", onKeydown, true);
|
||||
unsubscribe?.();
|
||||
unsubscribe = null;
|
||||
}
|
||||
|
||||
return { infos, recent, keymap, entries, isEnabled, provide, execute, dispatch, refresh, start, stop };
|
||||
});
|
||||
27
ui/src/commands/uiCommands.ts
Normal file
27
ui/src/commands/uiCommands.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
/**
|
||||
* UI commands: commands the frontend runs itself. They are registered with
|
||||
* the engine (`ui.registerCommands`) so `listCommands`, the palette, the
|
||||
* keymap and agents see them; running one through the engine comes back as
|
||||
* a `uiCommand` event. Components supply the behaviour with
|
||||
* `useCommandsStore().provide(id, handler)`; a UI command nobody provides
|
||||
* is disabled.
|
||||
*/
|
||||
|
||||
/** A UI command as registered with the engine. */
|
||||
export interface UiCommandSpec {
|
||||
/** Command id, `area.action` in camelCase. */
|
||||
id: string;
|
||||
/** Catalog key of the label. */
|
||||
labelKey: string;
|
||||
/** Menu path with `/` separators. */
|
||||
menuPath?: string;
|
||||
/** Default shortcut in Lutra notation. */
|
||||
defaultShortcut?: string;
|
||||
}
|
||||
|
||||
/** The frontend's UI commands. */
|
||||
export const UI_COMMANDS: readonly UiCommandSpec[] = [
|
||||
{ id: "palette.open", labelKey: "command.palette.open", defaultShortcut: "Mod+Shift+P" },
|
||||
{ id: "settings.open", labelKey: "command.settings.open", defaultShortcut: "Mod+," },
|
||||
{ id: "view.toggleProjectTree", labelKey: "command.view.toggleProjectTree", defaultShortcut: "Mod+1" },
|
||||
];
|
||||
|
|
@ -3,65 +3,39 @@
|
|||
* The editor area: tab bar, a notice line for the active tab, the editor
|
||||
* and the close question. Without open tabs it shows the default slot.
|
||||
*
|
||||
* Shortcuts come from the engine's command specs (see `shortcuts.ts`); the
|
||||
* area listens on the window in the capture phase so they also work while
|
||||
* CodeMirror has the focus. A keymap that cannot be loaded raises an
|
||||
* error toast.
|
||||
* Save, save all and close run through the global keymap and the
|
||||
* palette (`commands/store.ts`): the area supplies their behaviour with the
|
||||
* active buffer as context and says when they can run.
|
||||
*/
|
||||
import { onBeforeUnmount, onMounted } from "vue";
|
||||
import { useCommandsStore } from "../../commands/store";
|
||||
import { t } from "../../i18n";
|
||||
import { useEditorStore } from "../../stores/editor";
|
||||
import { useNotificationsStore } from "../../stores/notifications";
|
||||
import ClosePrompt from "./ClosePrompt.vue";
|
||||
import CodeEditor from "./CodeEditor.vue";
|
||||
import EditorTabs from "./EditorTabs.vue";
|
||||
import { commandFor, loadEditorKeymap, type EditorKeymap } from "./shortcuts";
|
||||
|
||||
const editor = useEditorStore();
|
||||
const notifications = useNotificationsStore();
|
||||
const commands = useCommandsStore();
|
||||
|
||||
/** Keymap loaded from the engine, empty until loaded. */
|
||||
let keymap: EditorKeymap = [];
|
||||
|
||||
/**
|
||||
* Runs the editor command bound to a key press.
|
||||
*
|
||||
* @param event - a key press anywhere in the window.
|
||||
*/
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
const command = commandFor(keymap, event);
|
||||
if (command === null) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
switch (command) {
|
||||
case "file.save":
|
||||
void editor.save();
|
||||
break;
|
||||
case "file.saveAll":
|
||||
void editor.saveAll();
|
||||
break;
|
||||
case "buffer.close":
|
||||
void editor.requestClose();
|
||||
break;
|
||||
}
|
||||
}
|
||||
/** Withdraws the command handlers; filled while mounted. */
|
||||
let withdraw: (() => void)[] = [];
|
||||
|
||||
onMounted(() => {
|
||||
editor.start();
|
||||
window.addEventListener("keydown", onKeydown, true);
|
||||
void loadEditorKeymap().then((result) => {
|
||||
if (result.ok) {
|
||||
keymap = result.value;
|
||||
} else {
|
||||
notifications.notifyError("listCommands", result.error);
|
||||
}
|
||||
});
|
||||
const hasActive = (): boolean => editor.activeTab !== null;
|
||||
withdraw = [
|
||||
commands.provide("file.save", { run: async () => { await editor.save(); }, enabled: hasActive }),
|
||||
commands.provide("file.saveAll", { run: () => editor.saveAll(), enabled: () => editor.tabs.length > 0 }),
|
||||
commands.provide("buffer.close", { run: () => editor.requestClose(), enabled: hasActive }),
|
||||
];
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener("keydown", onKeydown, true);
|
||||
for (const fn of withdraw) {
|
||||
fn();
|
||||
}
|
||||
withdraw = [];
|
||||
editor.stop();
|
||||
});
|
||||
</script>
|
||||
|
|
|
|||
|
|
@ -1,156 +0,0 @@
|
|||
/**
|
||||
* Editor shortcuts, taken from the engine's command specs.
|
||||
*
|
||||
* The engine defines default shortcuts in Lutra notation (`Mod+Alt+S`,
|
||||
* `Mod` = Cmd on macOS, Ctrl elsewhere). The editor area loads them with
|
||||
* `listCommands` and maps key presses to the editor commands it handles
|
||||
* with context (the active buffer): saving, saving all and closing a tab.
|
||||
* Nothing here hard-codes a key.
|
||||
*/
|
||||
import { t } from "../../i18n";
|
||||
import { listCommands, type CommandInfo, type RunResult } from "../../ipc";
|
||||
|
||||
/** Engine commands the editor area runs with the active buffer as context. */
|
||||
export const EDITOR_SHORTCUT_COMMANDS = ["file.save", "file.saveAll", "buffer.close"] as const;
|
||||
|
||||
/** One of {@link EDITOR_SHORTCUT_COMMANDS}. */
|
||||
export type EditorShortcutCommand = (typeof EDITOR_SHORTCUT_COMMANDS)[number];
|
||||
|
||||
/** A parsed shortcut. */
|
||||
export interface Shortcut {
|
||||
/** Ctrl must be held. */
|
||||
ctrl: boolean;
|
||||
/** Meta (Cmd) must be held. */
|
||||
meta: boolean;
|
||||
/** Alt (Option) must be held. */
|
||||
alt: boolean;
|
||||
/** Shift must be held. */
|
||||
shift: boolean;
|
||||
/** The key, lower case (`s`, `f4`, `enter`). */
|
||||
key: string;
|
||||
}
|
||||
|
||||
/** Whether the frontend runs on macOS, where `Mod` means Cmd. */
|
||||
export function isMac(): boolean {
|
||||
return typeof navigator !== "undefined" && /Mac OS X|Macintosh|iPhone|iPad/.test(navigator.userAgent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a shortcut in Lutra notation.
|
||||
*
|
||||
* @param text - for example `Mod+Alt+S`.
|
||||
* @param mac - whether `Mod` means Cmd.
|
||||
* @returns the shortcut, or null when the text has no key or an unknown modifier.
|
||||
*/
|
||||
export function parseShortcut(text: string, mac: boolean): Shortcut | null {
|
||||
const parts = text.split("+").map((part) => part.trim().toLowerCase());
|
||||
const key = parts.pop();
|
||||
if (key === undefined || key === "") {
|
||||
return null;
|
||||
}
|
||||
const shortcut: Shortcut = { ctrl: false, meta: false, alt: false, shift: false, key };
|
||||
for (const part of parts) {
|
||||
switch (part) {
|
||||
case "mod":
|
||||
if (mac) {
|
||||
shortcut.meta = true;
|
||||
} else {
|
||||
shortcut.ctrl = true;
|
||||
}
|
||||
break;
|
||||
case "ctrl":
|
||||
shortcut.ctrl = true;
|
||||
break;
|
||||
case "cmd":
|
||||
case "meta":
|
||||
shortcut.meta = true;
|
||||
break;
|
||||
case "alt":
|
||||
shortcut.alt = true;
|
||||
break;
|
||||
case "shift":
|
||||
shortcut.shift = true;
|
||||
break;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return shortcut;
|
||||
}
|
||||
|
||||
/**
|
||||
* The key of an event, independent of keyboard layout effects of Alt and
|
||||
* Shift for letters and digits (`Alt+S` on macOS types `ß`).
|
||||
*
|
||||
* @param event - the key event.
|
||||
*/
|
||||
function eventKey(event: KeyboardEvent): string {
|
||||
const code = event.code;
|
||||
if (/^Key[A-Z]$/.test(code)) {
|
||||
return code.slice(3).toLowerCase();
|
||||
}
|
||||
if (/^Digit[0-9]$/.test(code)) {
|
||||
return code.slice(5);
|
||||
}
|
||||
return event.key.toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a key event matches a shortcut exactly.
|
||||
*
|
||||
* @param event - the key event.
|
||||
* @param shortcut - the shortcut.
|
||||
*/
|
||||
export function matches(event: KeyboardEvent, shortcut: Shortcut): boolean {
|
||||
return (
|
||||
event.ctrlKey === shortcut.ctrl &&
|
||||
event.metaKey === shortcut.meta &&
|
||||
event.altKey === shortcut.alt &&
|
||||
event.shiftKey === shortcut.shift &&
|
||||
eventKey(event) === shortcut.key
|
||||
);
|
||||
}
|
||||
|
||||
/** Shortcuts of the editor commands, by command. */
|
||||
export type EditorKeymap = { command: EditorShortcutCommand; shortcut: Shortcut }[];
|
||||
|
||||
/**
|
||||
* Loads the default shortcuts of the editor commands from the engine.
|
||||
*
|
||||
* @param mac - whether `Mod` means Cmd.
|
||||
* @returns the keymap, or the error of `listCommands`.
|
||||
*/
|
||||
export async function loadEditorKeymap(mac = isMac()): Promise<RunResult<EditorKeymap>> {
|
||||
const result = await listCommands();
|
||||
if (!result.ok) {
|
||||
return result;
|
||||
}
|
||||
const list: unknown = result.value;
|
||||
if (!Array.isArray(list)) {
|
||||
return { ok: false, error: { code: "ipc", message: t("common.error.unexpectedResult", { command: "listCommands" }) } };
|
||||
}
|
||||
const commands = (list as unknown[]).filter(
|
||||
(c): c is CommandInfo => typeof c === "object" && c !== null && "id" in c,
|
||||
);
|
||||
const keymap: EditorKeymap = [];
|
||||
for (const command of EDITOR_SHORTCUT_COMMANDS) {
|
||||
const info = commands.find((c) => c.id === command);
|
||||
const raw: unknown = info?.defaultShortcut;
|
||||
const shortcut = typeof raw === "string" ? parseShortcut(raw, mac) : null;
|
||||
if (shortcut) {
|
||||
keymap.push({ command, shortcut });
|
||||
}
|
||||
}
|
||||
return { ok: true, value: keymap };
|
||||
}
|
||||
|
||||
/**
|
||||
* The editor command a key event triggers.
|
||||
*
|
||||
* @param keymap - the loaded keymap.
|
||||
* @param event - the key event.
|
||||
* @returns the command, or null.
|
||||
*/
|
||||
export function commandFor(keymap: EditorKeymap, event: KeyboardEvent): EditorShortcutCommand | null {
|
||||
return keymap.find((entry) => matches(event, entry.shortcut))?.command ?? null;
|
||||
}
|
||||
|
|
@ -4,9 +4,12 @@
|
|||
* editor area in the middle and the status bar along the bottom.
|
||||
*
|
||||
* The editor area is a slot so the editor (M1.6) can replace the
|
||||
* placeholder without touching the layout.
|
||||
* placeholder without touching the layout. The layout supplies the UI
|
||||
* command `view.toggleProjectTree` (`Mod+1`), which shows or hides the
|
||||
* Project tool window.
|
||||
*/
|
||||
import { ref } from "vue";
|
||||
import { onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import { useCommandsStore } from "../../commands/store";
|
||||
import { t } from "../../i18n";
|
||||
import ProjectToolWindow from "../project/ProjectToolWindow.vue";
|
||||
import StatusBar from "../StatusBar.vue";
|
||||
|
|
@ -16,6 +19,24 @@ import ToolWindow from "./ToolWindow.vue";
|
|||
const leftWidth = ref(260);
|
||||
/** Whether the left tool window is shown. */
|
||||
const leftOpen = ref(true);
|
||||
|
||||
const commands = useCommandsStore();
|
||||
|
||||
/** Withdraws the command handler; set while mounted. */
|
||||
let withdraw: (() => void) | null = null;
|
||||
|
||||
onMounted(() => {
|
||||
withdraw = commands.provide("view.toggleProjectTree", {
|
||||
run: () => {
|
||||
leftOpen.value = !leftOpen.value;
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
withdraw?.();
|
||||
withdraw = null;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
|
|
|||
298
ui/src/components/palette/CommandPalette.vue
Normal file
298
ui/src/components/palette/CommandPalette.vue
Normal file
|
|
@ -0,0 +1,298 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* The command palette (`palette.open`, `Mod+Shift+P`): an overlay with a
|
||||
* search field over every command the user can run, engine and UI.
|
||||
*
|
||||
* Typing ranks the commands fuzzily by label and id (see `rank.ts`);
|
||||
* recently run commands come first. Each row shows the command's
|
||||
* shortcut; commands that cannot run now are dimmed and cannot be chosen.
|
||||
* Arrow keys move the selection, Enter runs it, Escape or a click outside
|
||||
* closes. The command runs after the palette closed and gave the focus
|
||||
* back, so a command that asks something (closing a dirty tab) gets it.
|
||||
*/
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
import { rank } from "../../commands/rank";
|
||||
import { useCommandsStore, type PaletteEntry } from "../../commands/store";
|
||||
import { t } from "../../i18n";
|
||||
|
||||
const commands = useCommandsStore();
|
||||
|
||||
/** Whether the palette is shown. */
|
||||
const open = ref(false);
|
||||
/** What the user typed. */
|
||||
const query = ref("");
|
||||
/** Index of the selected row. */
|
||||
const selected = ref(0);
|
||||
/** The search field. */
|
||||
const input = ref<HTMLInputElement | null>(null);
|
||||
/** The list. */
|
||||
const list = ref<HTMLElement | null>(null);
|
||||
/** The element that had the focus before the palette opened. */
|
||||
let returnFocus: HTMLElement | null = null;
|
||||
/** Withdraws the `palette.open` handler; set while mounted. */
|
||||
let withdraw: (() => void) | null = null;
|
||||
|
||||
/** The matching commands, best first. */
|
||||
const results = computed<PaletteEntry[]>(() => rank(commands.entries, query.value, commands.recent));
|
||||
|
||||
/** DOM id of the selected row, for `aria-activedescendant`. */
|
||||
const activeId = computed(() => (results.value.length > 0 ? `lt-palette-${String(selected.value)}` : undefined));
|
||||
|
||||
watch(query, () => {
|
||||
selected.value = 0;
|
||||
});
|
||||
|
||||
/** Opens the palette with an empty query and refreshes the enabled states. */
|
||||
async function show(): Promise<void> {
|
||||
if (!open.value) {
|
||||
const active = document.activeElement;
|
||||
returnFocus = active instanceof HTMLElement ? active : null;
|
||||
}
|
||||
query.value = "";
|
||||
selected.value = 0;
|
||||
open.value = true;
|
||||
await nextTick();
|
||||
input.value?.focus();
|
||||
await commands.refresh();
|
||||
}
|
||||
|
||||
/** Closes the palette and gives the focus back. */
|
||||
function close(): void {
|
||||
if (!open.value) {
|
||||
return;
|
||||
}
|
||||
open.value = false;
|
||||
returnFocus?.focus();
|
||||
returnFocus = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a row's command if it is enabled; the palette closes first.
|
||||
*
|
||||
* @param entry - the row.
|
||||
*/
|
||||
function choose(entry: PaletteEntry | undefined): void {
|
||||
if (!entry?.enabled) {
|
||||
return;
|
||||
}
|
||||
close();
|
||||
void commands.execute(entry.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the selection, wrapping around, and keeps the row in view.
|
||||
*
|
||||
* @param step - rows to move, negative for up.
|
||||
*/
|
||||
function move(step: number): void {
|
||||
const count = results.value.length;
|
||||
if (count === 0) {
|
||||
return;
|
||||
}
|
||||
selected.value = (selected.value + step + count) % count;
|
||||
void nextTick(() => {
|
||||
const row = list.value?.querySelector<HTMLElement>(`#lt-palette-${String(selected.value)}`);
|
||||
row?.scrollIntoView({ block: "nearest" });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Keyboard handling of the search field.
|
||||
*
|
||||
* @param event - the key press.
|
||||
*/
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
switch (event.key) {
|
||||
case "ArrowDown":
|
||||
move(1);
|
||||
break;
|
||||
case "ArrowUp":
|
||||
move(-1);
|
||||
break;
|
||||
case "Enter":
|
||||
choose(results.value[selected.value]);
|
||||
break;
|
||||
case "Escape":
|
||||
close();
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
withdraw = commands.provide("palette.open", { run: show });
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
withdraw?.();
|
||||
withdraw = null;
|
||||
});
|
||||
|
||||
defineExpose({ show, close });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="open"
|
||||
class="palette"
|
||||
data-test="palette"
|
||||
@mousedown.self.prevent="close()"
|
||||
>
|
||||
<div
|
||||
class="palette__dialog"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-label="t('palette.label')"
|
||||
>
|
||||
<input
|
||||
ref="input"
|
||||
v-model="query"
|
||||
class="palette__input"
|
||||
type="text"
|
||||
role="combobox"
|
||||
aria-autocomplete="list"
|
||||
aria-expanded="true"
|
||||
aria-controls="lt-palette-list"
|
||||
:aria-activedescendant="activeId"
|
||||
:aria-label="t('palette.label')"
|
||||
:placeholder="t('palette.placeholder')"
|
||||
spellcheck="false"
|
||||
autocomplete="off"
|
||||
data-test="palette-input"
|
||||
@keydown="onKeydown"
|
||||
>
|
||||
<ul
|
||||
id="lt-palette-list"
|
||||
ref="list"
|
||||
class="palette__list"
|
||||
role="listbox"
|
||||
:aria-label="t('palette.label')"
|
||||
>
|
||||
<li
|
||||
v-for="(entry, index) in results"
|
||||
:id="`lt-palette-${String(index)}`"
|
||||
:key="entry.id"
|
||||
class="palette__row"
|
||||
:class="{
|
||||
'palette__row--selected': index === selected,
|
||||
'palette__row--disabled': !entry.enabled,
|
||||
}"
|
||||
role="option"
|
||||
:aria-selected="index === selected"
|
||||
:aria-disabled="!entry.enabled"
|
||||
:data-command="entry.id"
|
||||
data-test="palette-row"
|
||||
@mousemove="selected = index"
|
||||
@mousedown.prevent
|
||||
@click="choose(entry)"
|
||||
>
|
||||
<span class="palette__label">{{ entry.label }}</span>
|
||||
<span class="palette__id">{{ entry.id }}</span>
|
||||
<kbd
|
||||
v-if="entry.shortcut"
|
||||
class="palette__shortcut"
|
||||
data-test="palette-shortcut"
|
||||
>{{ entry.shortcut }}</kbd>
|
||||
</li>
|
||||
</ul>
|
||||
<p
|
||||
v-if="results.length === 0"
|
||||
class="palette__empty"
|
||||
role="status"
|
||||
data-test="palette-empty"
|
||||
>
|
||||
{{ t("palette.noMatches") }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.palette {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
padding-top: 12vh;
|
||||
background: color-mix(in srgb, var(--lt-bg) 40%, transparent);
|
||||
z-index: 30;
|
||||
}
|
||||
|
||||
.palette__dialog {
|
||||
width: min(600px, 90vw);
|
||||
max-height: 60vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--lt-bg);
|
||||
color: var(--lt-fg);
|
||||
border: 1px solid var(--lt-border);
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.palette__input {
|
||||
padding: 8px 12px;
|
||||
font: inherit;
|
||||
color: var(--lt-fg);
|
||||
background: var(--lt-editor-bg);
|
||||
border: none;
|
||||
border-bottom: 1px solid var(--lt-border);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.palette__list {
|
||||
margin: 0;
|
||||
padding: 4px 0;
|
||||
list-style: none;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.palette__row {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 12px;
|
||||
padding: 4px 12px;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.palette__row--selected {
|
||||
background: var(--lt-editor-selection-bg);
|
||||
}
|
||||
|
||||
.palette__row--disabled {
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.palette__label {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.palette__id {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.palette__shortcut {
|
||||
font: inherit;
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.palette__row--selected .palette__id,
|
||||
.palette__row--selected .palette__shortcut {
|
||||
color: var(--lt-fg);
|
||||
}
|
||||
|
||||
.palette__empty {
|
||||
margin: 0;
|
||||
padding: 8px 12px;
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
</style>
|
||||
|
|
@ -1,5 +1,14 @@
|
|||
{
|
||||
"app.statusBar.version": "{name} {version}",
|
||||
"command.key.alt": "Alt",
|
||||
"command.key.cmd": "Cmd",
|
||||
"command.key.ctrl": "Ctrl",
|
||||
"command.key.option": "Option",
|
||||
"command.key.shift": "Shift",
|
||||
"command.palette.open": "Command Palette",
|
||||
"command.settings.open": "Settings…",
|
||||
"command.unavailable": "{command} cannot run right now",
|
||||
"command.view.toggleProjectTree": "Show or Hide Project",
|
||||
"common.cancel": "Cancel",
|
||||
"common.close": "Close",
|
||||
"common.dismiss": "Dismiss",
|
||||
|
|
@ -31,6 +40,9 @@
|
|||
"notification.stack.more": "+{count} more",
|
||||
"notification.vfs.pumpFailed": "Applying changes on disk failed: {reason}",
|
||||
"notification.watch.failed": "Lutra stopped watching the project for changes on disk: {reason}",
|
||||
"palette.label": "Command palette",
|
||||
"palette.noMatches": "No matching commands",
|
||||
"palette.placeholder": "Type a command name",
|
||||
"project.empty.noFolder": "No folder is open.",
|
||||
"project.openFolder": "Open Folder…",
|
||||
"project.toolWindow.title": "Project",
|
||||
|
|
|
|||
|
|
@ -44,6 +44,13 @@ export type EngineEventPayload =
|
|||
message?: unknown;
|
||||
/** Placeholder values; unchecked. */
|
||||
params?: unknown;
|
||||
}
|
||||
| {
|
||||
kind: "uiCommand";
|
||||
/** Id of the UI command to run; unchecked, it comes from the engine. */
|
||||
id: unknown;
|
||||
/** The params it was run with, as given; unchecked. */
|
||||
params?: unknown;
|
||||
};
|
||||
|
||||
/** Callback receiving engine events. */
|
||||
|
|
@ -140,8 +147,10 @@ export type RunResult<T> = { ok: true; value: T } | { ok: false; error: EngineEr
|
|||
export interface CommandInfo {
|
||||
/** Command id, e.g. `app.about`. */
|
||||
id: string;
|
||||
/** Label shown in menus and the command palette. */
|
||||
/** Label shown in menus and the command palette; for UI commands the catalog key. */
|
||||
label: string;
|
||||
/** Catalog key of the label; set for UI commands. */
|
||||
labelKey?: string;
|
||||
/** Menu path such as `Help/About Lutra`, or null if not in a menu. */
|
||||
menuPath: string | null;
|
||||
/** Default shortcut in Lutra notation (`Mod+Q`), or null. */
|
||||
|
|
@ -150,6 +159,8 @@ export interface CommandInfo {
|
|||
params: string;
|
||||
/** Whether the command can run in the current state. */
|
||||
enabled: boolean;
|
||||
/** Whether the frontend registered the command (`ui.registerCommands`) and runs it. */
|
||||
ui?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue