Add the command palette, Write formatting keys, and platform labels

Phase 5-2.

- Ctrl+Shift+P opens the command palette: every workbench command with
  its shortcut, then the plugin commands (UI-048).
- In Write, Ctrl+B, Ctrl+I, Ctrl+Shift+X, and Ctrl+Shift+H format the
  selection, and Ctrl+K inserts a Markdown link. The Format menu shows
  these shortcuts.
- Ctrl+\ toggles the side pane. It matches the physical key on every
  keyboard layout. Ctrl+B now belongs to Write.
- Help lists every shortcut in groups, open by default. The list comes
  from the command table.
- src/lib/ui/shortcuts.ts writes shortcut labels for the platform:
  Ctrl+Shift+P on Windows and Linux, and the macOS symbols on a Mac.
  The catalog uses placeholders, so no translation contains "Ctrl".
- 19 new catalog rows, and 10 rows converted to placeholders, in
  French, Japanese, and Simplified Chinese.
- Docs: UI-048, the user guide keyboard tables, and a label rule in
  ui-design.md.

New tests: layout/commands, tests/unit/ui/shortcuts.spec.ts, and new
cases in workbenchKeys.spec.ts. Tests that read the old labels or
pressed Ctrl+B for the side pane now use the new names and Ctrl+\.

The smoke harness raises the resource timing buffer to 5000 entries.
The new modules pushed the CodeMirror language module past the
default 250 entries, so editor/markdownPaste could not find its URL.
This commit is contained in:
Knotty Wyvern
2026-10-28 19:10:25 -07:00
parent b2348d0fe8
commit ebacdb8164
48 changed files with 506 additions and 125 deletions
+15
View File
@@ -903,3 +903,18 @@ Native shell, background image, and desktop acceptance remain open.
- Evidence: `tests/smoke/appearance/themeEditor.smoke.mjs` and `tests/unit/theme/themeEditor.spec.ts`. Screenshots are in `output/phase-5a/5a-5/` in the main checkout. - Evidence: `tests/smoke/appearance/themeEditor.smoke.mjs` and `tests/unit/theme/themeEditor.spec.ts`. Screenshots are in `output/phase-5a/5a-5/` in the main checkout.
- Replaces / replaced by: The theme choice in the action menu rule of "Choice lists and pickers". Other short choices stay in the action menu. - Replaces / replaced by: The theme choice in the action menu rule of "Choice lists and pickers". Other short choices stay in the action menu.
- Limits: The editor changes colors, not fonts. Browser checks use desktop service mocks. Native desktop acceptance remains open. - Limits: The editor changes colors, not fonts. Browser checks use desktop service mocks. Native desktop acceptance remains open.
### UI-048 — Command palette, formatting shortcuts, and platform labels
- Type: Rule change
- Date: 2026-10-28
- Status: Implemented for user review
- Decision source: Owner decisions 2, 7 (shortcut labels), and 10 of 2026-10-27 (interface review issues 2, 15, and 22), stage 5-2.
- Previous rule: Ctrl+B toggled the sidebar, so Writer had no Ctrl+B, Ctrl+I, or Ctrl+K. Formatting needed the context menu. Interface text wrote "Ctrl" in three styles ("Ctrl T", "Ctrl+T", "Ctrl N"). Help listed 6 shortcuts in a closed section, and no command list existed.
- New rule: In Writer, Ctrl+B, Ctrl+I, Ctrl+Shift+X, and Ctrl+Shift+H format the selection, and Ctrl+K inserts a Markdown link. The Format menu shows these shortcuts. Ctrl+\ (the physical key on every layout) toggles the sidebar. Ctrl+Shift+P opens the command palette: every workbench command with its shortcut, then the plugin commands. Help lists every shortcut in groups, open by default. `src/lib/ui/shortcuts.ts` writes each shortcut label for the platform, and the catalog uses placeholders.
- Reason: A writing app needs the common formatting keys. A shortcut that a user cannot find does not help.
- Scope: The workbench, Writer, Help, the menus, the tooltips, and the catalog.
- Shared implementation: `workbenchKeys.ts` (labels, `commandShortcut`, and the Help list), `shortcuts.ts`, `CommandPalette.svelte`, `formatKeys.ts`, and `SettingsDialog.svelte`.
- Evidence: `tests/smoke/layout/commands.smoke.mjs`, `tests/unit/ui/shortcuts.spec.ts`, and `tests/unit/layout/workbenchKeys.spec.ts`.
- Replaces / replaced by: The Ctrl+B sidebar shortcut in the user guide.
- Limits: The macOS labels are tested as unit cases, not on a Mac. Browser checks use desktop service mocks.
+1
View File
@@ -105,6 +105,7 @@ Use one menu design for context menus, action menus, and their submenus in the h
- A menu with only text choices omits the icon column. A mixed menu reserves the icon column on every row. - A menu with only text choices omits the icon column. A mixed menu reserves the icon column on every row.
- Shortcut text and submenu arrows use separate trailing columns. - Shortcut text and submenu arrows use separate trailing columns.
- A common text action has the same label, icon, and shortcut in every menu. Build Undo, Redo, the clipboard rows, and the search row with `menuItems.ts`. - A common text action has the same label, icon, and shortcut in every menu. Build Undo, Redo, the clipboard rows, and the search row with `menuItems.ts`.
- Write shortcut labels with `src/lib/ui/shortcuts.ts`: `keys("Mod+Shift+P")` gives Ctrl+Shift+P on Windows and Linux and ⇧⌘P on macOS. A workbench command takes its label from `commandShortcut()` in `workbenchKeys.ts`. Do not write "Ctrl" in interface text or in the catalog. Use a placeholder.
- Use inset separators between related groups. - Use inset separators between related groups.
- Enabled rows share one hover fill and one keyboard focus fill. - Enabled rows share one hover fill and one keyboard focus fill.
- Disabled rows stay readable. Keyboard navigation skips them, and they do not run. - Disabled rows stay readable. Keyboard navigation skips them, and they do not run.
+16 -4
View File
@@ -42,7 +42,8 @@ To show workspace settings and plugin data in the navigator, turn on **Settings
| Find a file by path | Press Ctrl+P. | | Find a file by path | Press Ctrl+P. |
| Search all files | Press Ctrl+Shift+F. | | Search all files | Press Ctrl+Shift+F. |
| Find in the document | Press Ctrl+F. | | Find in the document | Press Ctrl+F. |
| Show or hide the sidebar | Press Ctrl+B. | | Show or hide the sidebar | Press Ctrl+\. |
| Find a command | Press Ctrl+Shift+P, type part of the command name, and press Enter. The list also shows each shortcut and the plugin commands. |
| Rename | Select an item in the navigator and press F2. RuneStone selects the name without the extension. | | Rename | Select an item in the navigator and press F2. RuneStone selects the name without the extension. |
| Move | Drag files between folders. | | Move | Drag files between folders. |
| Bookmark | Right-click a file and choose **Bookmark**. The Bookmarks pane lists it. | | Bookmark | Right-click a file and choose **Bookmark**. The Bookmarks pane lists it. |
@@ -103,6 +104,14 @@ Right-click Markdown text, or press Shift+F10, to open the context menu. Use the
| Menu | Actions | | Menu | Actions |
| --- | --- | | --- | --- |
| Format | Bold, italic, strikethrough, highlight, code, math, comment, and clear formatting | | Format | Bold, italic, strikethrough, highlight, code, math, comment, and clear formatting |
In Writer, these shortcuts format the selected text:
| Format | Shortcut |
| --- | --- |
| Bold / Italic | Ctrl+B / Ctrl+I |
| Strikethrough / Highlight | Ctrl+Shift+X / Ctrl+Shift+H |
| Link (`[text]()`, with the cursor in the address) | Ctrl+K |
| Paragraph | Bulleted and numbered lists, tasks, headings 1–6, body text, and quotes | | Paragraph | Bulleted and numbered lists, tasks, headings 1–6, body text, and quotes |
| Insert | Footnotes, tables, callouts, horizontal rules, code blocks, and math blocks | | Insert | Footnotes, tables, callouts, horizontal rules, code blocks, and math blocks |
@@ -200,10 +209,11 @@ To open web links from your documents in your system browser instead, turn off *
## Keyboard reference ## Keyboard reference
This table lists the Windows and Linux keys. This table lists the Windows and Linux keys. On macOS, Cmd replaces Ctrl, and RuneStone shows the macOS symbols, such as ⇧⌘P. Help lists every shortcut.
| Action | Shortcut | | Action | Shortcut |
| --- | --- | | --- | --- |
| Find a command | Ctrl+Shift+P |
| Open a workspace | Ctrl+O | | Open a workspace | Ctrl+O |
| Find a file / New file | Ctrl+P / Ctrl+N | | Find a file / New file | Ctrl+P / Ctrl+N |
| New tab / Close tab | Ctrl+T / Ctrl+W | | New tab / Close tab | Ctrl+T / Ctrl+W |
@@ -213,7 +223,9 @@ This table lists the Windows and Linux keys.
| Find in document / Search workspace | Ctrl+F / Ctrl+Shift+F | | Find in document / Search workspace | Ctrl+F / Ctrl+Shift+F |
| Switch Writer and IDE | Ctrl+E | | Switch Writer and IDE | Ctrl+E |
| Nest a list item / Move it up | Tab / Shift+Tab | | Nest a list item / Move it up | Tab / Shift+Tab |
| Show or hide the sidebar | Ctrl+B | | Bold / Italic / Link (Writer) | Ctrl+B / Ctrl+I / Ctrl+K |
| Strikethrough / Highlight (Writer) | Ctrl+Shift+X / Ctrl+Shift+H |
| Show or hide the sidebar | Ctrl+\ |
| Rename | F2 | | Rename | F2 |
| Delete to the trash / Delete permanently | Delete / Shift+Delete | | Delete to the trash / Delete permanently | Delete / Shift+Delete |
| Context menu | Shift+F10 | | Context menu | Shift+F10 |
@@ -230,6 +242,6 @@ The [Terminal guide](guides/terminal.md) lists the terminal shortcuts.
## Get help ## Get help
Press F1, or select the question mark at the bottom of the sidebar, for **Help and about**. It shows the app version, basic steps, and shortcuts. Press F1, or select the question mark at the bottom of the sidebar, for **Help and about**. It shows the app version, basic steps, and every shortcut.
When you report a problem, include the app version, operating system, steps, expected result, and error text. When you report a problem, include the app version, operating system, steps, expected result, and error text.
+9 -8
View File
@@ -1,5 +1,6 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n"; import { t } from "$lib/i18n";
import { keys } from '$lib/ui/shortcuts';
import { onMount, untrack, tick } from 'svelte'; import { onMount, untrack, tick } from 'svelte';
import IconButton from '$lib/ui/IconButton.svelte'; import IconButton from '$lib/ui/IconButton.svelte';
import Icon from '$lib/ui/Icon.svelte'; import Icon from '$lib/ui/Icon.svelte';
@@ -118,18 +119,18 @@
{ label: $t('Copy image'), icon: 'copy', run: action('copyImage') }, { label: $t('Copy image'), icon: 'copy', run: action('copyImage') },
{ label: $t('Copy image address'), icon: 'copy', disabled: !context.srcURL, run: action('copyImageAddress') }, { separator: true }); { label: $t('Copy image address'), icon: 'copy', disabled: !context.srcURL, run: action('copyImageAddress') }, { separator: true });
if (context.isEditable) items.push( if (context.isEditable) items.push(
{ label: $t('Undo'), icon: 'undo', shortcut: 'Ctrl+Z', disabled: !context.editFlags.canUndo, run: edit('undo') }, { label: $t('Undo'), icon: 'undo', shortcut: keys('Mod+Z'), disabled: !context.editFlags.canUndo, run: edit('undo') },
{ label: $t('Redo'), icon: 'redo', shortcut: 'Ctrl+Shift+Z', disabled: !context.editFlags.canRedo, run: edit('redo') }, { separator: true }, { label: $t('Redo'), icon: 'redo', shortcut: keys('Mod+Shift+Z'), disabled: !context.editFlags.canRedo, run: edit('redo') }, { separator: true },
{ label: $t('Cut'), icon: 'cut', shortcut: 'Ctrl+X', disabled: !context.editFlags.canCut, run: edit('cut') }); { label: $t('Cut'), icon: 'cut', shortcut: keys('Mod+X'), disabled: !context.editFlags.canCut, run: edit('cut') });
if (context.isEditable || context.selectionText) items.push({ label: $t('Copy'), icon: 'copy', shortcut: 'Ctrl+C', disabled: !context.editFlags.canCopy, run: edit('copy') }); if (context.isEditable || context.selectionText) items.push({ label: $t('Copy'), icon: 'copy', shortcut: keys('Mod+C'), disabled: !context.editFlags.canCopy, run: edit('copy') });
if (context.isEditable) items.push( if (context.isEditable) items.push(
{ label: $t('Paste'), icon: 'paste', shortcut: 'Ctrl+V', disabled: !context.editFlags.canPaste, run: edit('paste') }, { label: $t('Paste'), icon: 'paste', shortcut: keys('Mod+V'), disabled: !context.editFlags.canPaste, run: edit('paste') },
{ label: $t('Paste as plain text'), icon: 'paste-text', shortcut: 'Ctrl+Shift+V', disabled: !context.editFlags.canPaste, run: edit('pasteAndMatchStyle') }, { label: $t('Paste as plain text'), icon: 'paste-text', shortcut: keys('Mod+Shift+V'), disabled: !context.editFlags.canPaste, run: edit('pasteAndMatchStyle') },
{ label: $t('Select all'), icon: 'task', shortcut: 'Ctrl+A', run: edit('selectAll') }, { separator: true }); { label: $t('Select all'), icon: 'task', shortcut: keys('Mod+A'), run: edit('selectAll') }, { separator: true });
items.push({ label: $t('Back'), icon: 'arrow-left', disabled: !current?.canBack, run: () => void send('back') }, items.push({ label: $t('Back'), icon: 'arrow-left', disabled: !current?.canBack, run: () => void send('back') },
{ label: $t('Forward'), icon: 'arrow-right', disabled: !current?.canForward, run: () => void send('forward') }, { label: $t('Forward'), icon: 'arrow-right', disabled: !current?.canForward, run: () => void send('forward') },
{ label: $t('Reload'), icon: 'refresh', run: () => void send('reload') }, { label: $t('Reload'), icon: 'refresh', run: () => void send('reload') },
{ label: $t('Find in page'), icon: 'search', shortcut: 'Ctrl+F', run: () => void find() }); { label: $t('Find in page'), icon: 'search', shortcut: keys('Mod+F'), run: () => void find() });
const rect = surface.getBoundingClientRect(); const rect = surface.getBoundingClientRect();
const menu = showActionMenu({ x: rect.left + imageBox.x + context.x, y: rect.top + imageBox.y + context.y, const menu = showActionMenu({ x: rect.left + imageBox.x + context.x, y: rect.top + imageBox.y + context.y,
items, label: $t('Browser page actions') }); items, label: $t('Browser page actions') });
+2 -1
View File
@@ -1,4 +1,5 @@
import { tr } from "../i18n/index.ts"; import { tr } from "../i18n/index.ts";
import { keys } from '../ui/shortcuts.ts';
import { mount, unmount } from 'svelte'; import { mount, unmount } from 'svelte';
import { get } from 'svelte/store'; import { get } from 'svelte/store';
import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow'; import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow';
@@ -65,7 +66,7 @@ export async function activate(api: PluginApi) {
{ label: tr("Split right"), icon: 'split-right', disabled: !ready, run: () => split('right') }, { label: tr("Split right"), icon: 'split-right', disabled: !ready, run: () => split('right') },
{ label: tr("Split down"), icon: 'split-down', disabled: !ready, run: () => split('down') }, { label: tr("Split down"), icon: 'split-down', disabled: !ready, run: () => split('down') },
{ separator: true }, { separator: true },
{ label: tr("Find…"), icon: 'search', shortcut: 'Ctrl+F', disabled: !ready, run: () => { api.openView(id); void saved.control?.find(); } }, { label: tr("Find…"), icon: 'search', shortcut: keys('Mod+F'), disabled: !ready, run: () => { api.openView(id); void saved.control?.find(); } },
{ label: tr("Open in default browser"), icon: 'external', disabled: !web, run: () => run('openExternal') }, { label: tr("Open in default browser"), icon: 'external', disabled: !web, run: () => run('openExternal') },
{ label: tr("Bookmark"), icon: 'bookmark', disabled: !web, run: () => run('bookmark') }, { label: tr("Bookmark"), icon: 'bookmark', disabled: !web, run: () => run('bookmark') },
]; ];
+2 -1
View File
@@ -35,6 +35,7 @@
import { languageSupport } from "./codeLanguages"; import { languageSupport } from "./codeLanguages";
import { indentListItem, outdentListItem } from "./markdownLists"; import { indentListItem, outdentListItem } from "./markdownLists";
import { insertIndent, sourceChrome, sourceEditing } from "./sourceView"; import { insertIndent, sourceChrome, sourceEditing } from "./sourceView";
import { formatKeymap } from "./formatKeys";
import "./headingFolding.css"; import "./headingFolding.css";
type Mode = "write" | "source"; type Mode = "write" | "source";
@@ -155,7 +156,7 @@
return [ return [
headingFolding, headingFolding,
tableNavigation, tableNavigation,
keymap.of([{ key: "Escape", run: view => { keymap.of([...formatKeymap, { key: "Escape", run: view => {
if (!view.state.field(imageSource)) return false; if (!view.state.field(imageSource)) return false;
view.dispatch({ effects: editImageSource.of(null) }); return true; view.dispatch({ effects: editImageSource.of(null) }); return true;
} }, ...lists, indentWithTab]), } }, ...lists, indentWithTab]),
+2 -1
View File
@@ -1,4 +1,5 @@
import { tr } from '../i18n/index.ts'; import { tr } from '../i18n/index.ts';
import { keys } from "../ui/shortcuts";
import { EditorSelection } from "@codemirror/state"; import { EditorSelection } from "@codemirror/state";
import type { EditorView } from "@codemirror/view"; import type { EditorView } from "@codemirror/view";
import { redo, redoDepth, undo, undoDepth } from "@codemirror/commands"; import { redo, redoDepth, undo, undoDepth } from "@codemirror/commands";
@@ -38,7 +39,7 @@ export function codeMenu(view: EditorView, report: (message: string) => void) {
}; };
menu = showActionMenu({ x, y, label: tr("Code text actions"), items: [ menu = showActionMenu({ x, y, label: tr("Code text actions"), items: [
...historyItems({ canUndo: undoDepth(state) > 0, canRedo: redoDepth(state) > 0, undo: () => undo(view), redo: () => redo(view) }), ...historyItems({ canUndo: undoDepth(state) > 0, canRedo: redoDepth(state) > 0, undo: () => undo(view), redo: () => redo(view) }),
{ label: tr("Change all occurrences"), icon: "select", shortcut: "Ctrl+Shift+L", disabled: !word || word.empty, run: changeAll }, { label: tr("Change all occurrences"), icon: "select", shortcut: keys("Mod+Shift+L"), disabled: !word || word.empty, run: changeAll },
{ separator: true }, { separator: true },
...clipboardItems({ ...clipboardItems({
selected: !!selected, cut: () => void clipboard("cut"), copy: () => void clipboard("copy"), paste: () => void clipboard("paste"), selected: !!selected, cut: () => void clipboard("cut"), copy: () => void clipboard("copy"), paste: () => void clipboard("paste"),
+25
View File
@@ -0,0 +1,25 @@
// Write formatting shortcuts. Each one makes the same edit as its item in the Format menu.
import type { EditorView, KeyBinding } from "@codemirror/view";
import { isolateHistory } from "@codemirror/commands";
import { formatText, type InlineFormat, type MarkdownEdit } from "./markdownCommands";
import { externalLinkText } from "./linkCommands";
/** The shortcut of each format, as written combinations for the menu labels. */
export const FORMAT_KEYS: Partial<Record<InlineFormat, string>> = { bold: "Mod+B", italic: "Mod+I", strike: "Mod+Shift+X", highlight: "Mod+Shift+H" };
export const LINK_KEY = "Mod+K";
function apply(view: EditorView, edit: MarkdownEdit) {
view.dispatch({ changes: { from: edit.from, to: edit.to, insert: edit.insert }, selection: { anchor: edit.anchor, head: edit.head },
userEvent: "input.markdown", annotations: isolateHistory.of("full"), scrollIntoView: true });
return true;
}
const format = (kind: InlineFormat) => (view: EditorView) => apply(view, formatText(view.state.doc.toString(), view.state.selection.main, kind));
export const formatKeymap: KeyBinding[] = [
{ key: "Mod-b", run: format("bold"), preventDefault: true },
{ key: "Mod-i", run: format("italic"), preventDefault: true },
{ key: "Mod-Shift-x", run: format("strike"), preventDefault: true },
{ key: "Mod-Shift-h", run: format("highlight"), preventDefault: true },
{ key: "Mod-k", run: view => apply(view, externalLinkText(view.state.doc.toString(), view.state.selection.main)), preventDefault: true },
];
+6 -2
View File
@@ -1,4 +1,8 @@
import { tr } from '../i18n/index.ts'; import { tr } from '../i18n/index.ts';
import { isMac } from "../ui/shortcuts";
/** The tooltip of a link in Write. A click with Ctrl, or Cmd on macOS, opens the link. */
const linkTooltip = () => tr("{modifier}+click to open link", { modifier: isMac() ? "⌘" : "Ctrl" });
import { EditorSelection, StateEffect, StateField, type EditorState, type Range } from "@codemirror/state"; import { EditorSelection, StateEffect, StateField, type EditorState, type Range } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet } from "@codemirror/view"; import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet } from "@codemirror/view";
import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language"; import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language";
@@ -317,7 +321,7 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
if (!match) return; if (!match) return;
replace(node.from, node.from + 1); replace(node.from, node.from + 1);
replace(node.from + 1 + match[1].length, node.to); replace(node.from + 1 + match[1].length, node.to);
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-href": match[2], "data-kind": "md", "data-editor-tooltip": "Ctrl+click to open link" } }).range(node.from + 1, node.from + 1 + match[1].length)); ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-href": match[2], "data-kind": "md", "data-editor-tooltip": linkTooltip() } }).range(node.from + 1, node.from + 1 + match[1].length));
return false; return false;
} }
} }); } });
@@ -339,7 +343,7 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
const labelStart = from + 2 + (separator < 0 ? 0 : separator + 1); const labelStart = from + 2 + (separator < 0 ? 0 : separator + 1);
replace(from, labelStart); replace(from, labelStart);
replace(to - 2, to); replace(to - 2, to);
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-kind": "wiki", "data-href": match[1].split("|")[0], "data-editor-tooltip": "Ctrl+click to open link" } }).range(labelStart, to - 2)); ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-kind": "wiki", "data-href": match[1].split("|")[0], "data-editor-tooltip": linkTooltip() } }).range(labelStart, to - 2));
} }
for (const link of documentLinks(source)) { for (const link of documentLinks(source)) {
if (!selected(link.from, link.to) || hidden(link.from, link.to)) continue; if (!selected(link.from, link.to) || hidden(link.from, link.to)) continue;
+4 -2
View File
@@ -10,6 +10,8 @@ import { documentLinkAt } from "./documentLinks";
import { linkMenuItems, type DocumentLinkActions } from "./linkMenu"; import { linkMenuItems, type DocumentLinkActions } from "./linkMenu";
import { htmlToMarkdown } from "../workspace/htmlToMarkdown"; import { htmlToMarkdown } from "../workspace/htmlToMarkdown";
import { cellFormats, type TableContextActions } from "./tableCellActions"; import { cellFormats, type TableContextActions } from "./tableCellActions";
import { FORMAT_KEYS, LINK_KEY } from "./formatKeys";
import { keys } from "../ui/shortcuts";
import { formatText, insertBlock, paragraphText, replacement, type MarkdownEdit, type TextSelection, type ParagraphStyle, type InsertBlock } from "./markdownCommands"; import { formatText, insertBlock, paragraphText, replacement, type MarkdownEdit, type TextSelection, type ParagraphStyle, type InsertBlock } from "./markdownCommands";
export type MarkdownMenuEditor = { export type MarkdownMenuEditor = {
@@ -89,7 +91,7 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
}), { separator: true as const }] : []), }), { separator: true as const }] : []),
...(editor.undo ? historyItems({ canUndo: !!editor.canUndo?.(), canRedo: !!editor.canRedo?.(), undo: () => editor.undo?.(), redo: () => editor.redo?.() }) : []), ...(editor.undo ? historyItems({ canUndo: !!editor.canUndo?.(), canRedo: !!editor.canRedo?.(), undo: () => editor.undo?.(), redo: () => editor.redo?.() }) : []),
{ label: tr("Add link"), icon: "link", run: () => link(false) }, { label: tr("Add link"), icon: "link", run: () => link(false) },
{ label: tr("Add external link"), icon: "external", run: () => link(true) }, { label: tr("Add external link"), icon: "external", shortcut: keys(LINK_KEY), run: () => link(true) },
{ separator: true }, { separator: true },
searchItem(text, actions.onSearch), searchItem(text, actions.onSearch),
{ label: tr("Extract current selection…"), icon: "extract", disabled: !text || !actions.onExtract, run: () => void request(async () => { { label: tr("Extract current selection…"), icon: "extract", disabled: !text || !actions.onExtract, run: () => void request(async () => {
@@ -98,7 +100,7 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
}) }, }) },
{ label: tr("Format"), icon: "format", children: cellFormats.flatMap(([label, kind]) => [ { label: tr("Format"), icon: "format", children: cellFormats.flatMap(([label, kind]) => [
...(kind === "code" || kind === "clear" ? [{ separator: true } as const] : []), ...(kind === "code" || kind === "clear" ? [{ separator: true } as const] : []),
{ label: tr(label), icon: kind, disabled: kind === "clear" && !text, run: () => apply(formatText(source, selection, kind)) }, { label: tr(label), icon: kind, ...(FORMAT_KEYS[kind] ? { shortcut: keys(FORMAT_KEYS[kind]) } : {}), disabled: kind === "clear" && !text, run: () => apply(formatText(source, selection, kind)) },
]) }, ]) },
{ label: tr("Paragraph"), icon: "paragraph", children: [ { label: tr("Paragraph"), icon: "paragraph", children: [
paragraph(tr("Bullet list"), "bullet", "bullet"), paragraph(tr("Numbered list"), "number", "number"), paragraph(tr("Task list"), "task", "task"), paragraph(tr("Bullet list"), "bullet", "bullet"), paragraph(tr("Numbered list"), "number", "number"), paragraph(tr("Task list"), "task", "task"),
+2 -1
View File
@@ -1,4 +1,5 @@
import { tr } from '../i18n/index.ts'; import { tr } from '../i18n/index.ts';
import { keys } from "../ui/shortcuts";
import type { ActionMenuItem } from "../ui/actionMenu"; import type { ActionMenuItem } from "../ui/actionMenu";
import { showActionMenu, type MenuHandle } from "../ui/managedActionMenu"; import { showActionMenu, type MenuHandle } from "../ui/managedActionMenu";
import { clipboardItems, searchItem } from "../ui/menuItems"; import { clipboardItems, searchItem } from "../ui/menuItems";
@@ -30,7 +31,7 @@ export function readingMenu(host: HTMLElement, actions: DocumentLinkActions, sea
previousFocus = document.activeElement instanceof HTMLElement && host.contains(document.activeElement) ? document.activeElement : host; previousFocus = document.activeElement instanceof HTMLElement && host.contains(document.activeElement) ? document.activeElement : host;
const items: ActionMenuItem[] = []; const items: ActionMenuItem[] = [];
if (text) items.push( if (text) items.push(
...clipboardItems({ selected: true, copy: () => void navigator.clipboard.writeText(text).catch(() => report(tr("Clipboard unavailable. Use Ctrl+C to copy."))) }), ...clipboardItems({ selected: true, copy: () => void navigator.clipboard.writeText(text).catch(() => report(tr("Clipboard unavailable. Use {shortcut} to copy.", { shortcut: keys("Mod+C") }))) }),
searchItem(text, search), searchItem(text, search),
); );
if (anchor) { if (anchor) {
+1 -1
View File
@@ -275,7 +275,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
next.scrollIntoView({ block: "nearest", inline: "nearest" }); next.scrollIntoView({ block: "nearest", inline: "nearest" });
return true; return true;
} }
// Keep formatting shortcuts local; the workbench also binds Ctrl+B. // Keep formatting shortcuts in the cell. The Writer around the table also binds Ctrl+B.
if ((event.ctrlKey || event.metaKey) && ["b", "i"].includes(event.key.toLowerCase())) event.stopPropagation(); if ((event.ctrlKey || event.metaKey) && ["b", "i"].includes(event.key.toLowerCase())) event.stopPropagation();
if ((event.ctrlKey || event.metaKey) && (event.key === "Home" || event.key === "End")) { if ((event.ctrlKey || event.metaKey) && (event.key === "Home" || event.key === "End")) {
event.preventDefault(); event.stopPropagation(); event.preventDefault(); event.stopPropagation();
+2 -1
View File
@@ -1,4 +1,5 @@
import { tr } from '../i18n/index.ts'; import { tr } from '../i18n/index.ts';
import { keys } from "../ui/shortcuts";
import type { EditorView } from "@codemirror/view"; import type { EditorView } from "@codemirror/view";
import { isolateHistory, redo, undo } from "@codemirror/commands"; import { isolateHistory, redo, undo } from "@codemirror/commands";
import type { Editor } from "@tiptap/core"; import type { Editor } from "@tiptap/core";
@@ -87,7 +88,7 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
} }
} catch { } catch {
const status = root.querySelector<HTMLElement>(".table-edit-help"); const status = root.querySelector<HTMLElement>(".table-edit-help");
if (status) { status.hidden = false; status.setAttribute("role", "status"); status.textContent = `Clipboard unavailable here. Use ${navigator.platform.includes("Mac") ? "⌘" : "Ctrl"}+${action === "paste" ? "V" : action === "cut" ? "X" : "C"}.`; } if (status) { status.hidden = false; status.setAttribute("role", "status"); status.textContent = tr("Clipboard unavailable here. Use {shortcut}.", { shortcut: keys(`Mod+${action === "paste" ? "V" : action === "cut" ? "X" : "C"}`) }); }
} }
} }
function showMenu(x: number, y: number, at = range?.head, textEditor?: Editor) { function showMenu(x: number, y: number, at = range?.head, textEditor?: Editor) {
+60 -41
View File
@@ -192,10 +192,10 @@ export const messageRows: [string, string, string, string][] = [
"仅保存已更改的文件。" "仅保存已更改的文件。"
], ],
[ [
"Auto-save is off. Use Ctrl+S to save your changes.", "Auto-save is off. Use {shortcut} to save your changes.",
"L’enregistrement automatique est désactivé. Utilisez Ctrl+S pour enregistrer.", "L’enregistrement automatique est désactivé. Utilisez {shortcut} pour enregistrer.",
"自動保存はオフです。Ctrl+Sで変更を保存してください。", "自動保存はオフです。{shortcut}で変更を保存してください。",
"自动保存已关闭。请使用 Ctrl+S 保存更改。" "自动保存已关闭。请使用 {shortcut} 保存更改。"
], ],
[ [
"Disk conflicts keep your edits for review.", "Disk conflicts keep your edits for review.",
@@ -594,10 +594,10 @@ export const messageRows: [string, string, string, string][] = [
"大纲" "大纲"
], ],
[ [
"Find in outline (Ctrl+F)", "Find in outline ({shortcut})",
"Rechercher dans le plan (Ctrl+F)", "Rechercher dans le plan ({shortcut})",
"アウトライン内を検索 (Ctrl+F)", "アウトライン内を検索 ({shortcut})",
"在大纲中查找 (Ctrl+F)" "在大纲中查找 ({shortcut})"
], ],
[ [
"Find in outline", "Find in outline",
@@ -888,10 +888,10 @@ export const messageRows: [string, string, string, string][] = [
"添加书签" "添加书签"
], ],
[ [
"New tab (Ctrl T)", "New tab ({shortcut})",
"Nouvel onglet (Ctrl T)", "Nouvel onglet ({shortcut})",
"新しいタブ (Ctrl T)", "新しいタブ ({shortcut})",
"新建标签页 (Ctrl T)" "新建标签页 ({shortcut})"
], ],
[ [
"New browser tab", "New browser tab",
@@ -948,16 +948,16 @@ export const messageRows: [string, string, string, string][] = [
"无工作区" "无工作区"
], ],
[ [
"Help and about (F1)", "Help and about ({shortcut})",
"Aide et à propos (F1)", "Aide et à propos ({shortcut})",
"ヘルプと情報 (F1)", "ヘルプと情報 ({shortcut})",
"帮助与关于 (F1)" "帮助与关于 ({shortcut})"
], ],
[ [
"Settings (Ctrl+,)", "Settings ({shortcut})",
"Paramètres (Ctrl+,)", "Paramètres ({shortcut})",
"設定 (Ctrl+,)", "設定 ({shortcut})",
"设置 (Ctrl+,)" "设置 ({shortcut})"
], ],
[ [
"Save a copy", "Save a copy",
@@ -1590,22 +1590,22 @@ export const messageRows: [string, string, string, string][] = [
"使用文件夹按钮打开或创建工作区。笔记和脚本以普通文件形式存储在磁盘上。" "使用文件夹按钮打开或创建工作区。笔记和脚本以普通文件形式存储在磁盘上。"
], ],
[ [
"Use the + beside the tabs for a new tab. Press Ctrl+N to create a file, or Ctrl+P to find one.", "Use the + beside the tabs for a new tab. Press {newFile} to create a file, or {quickOpen} to find one.",
"Utilisez le + près des onglets pour créer un onglet. Ctrl+N crée un fichier et Ctrl+P en recherche un.", "Utilisez le + près des onglets pour créer un onglet. {newFile} crée un fichier et {quickOpen} en recherche un.",
"タブの横の+で新しいタブを開きます。Ctrl+Nでファイルを作成し、Ctrl+Pで検索します。", "タブの横の+で新しいタブを開きます。{newFile}でファイルを作成し、{quickOpen}で検索します。",
"点击标签页旁的 + 新建标签页。按 Ctrl+N 创建文件,或按 Ctrl+P 查找文件。" "点击标签页旁的 + 新建标签页。按 {newFile} 创建文件,或按 {quickOpen} 查找文件。"
], ],
[ [
"Press Ctrl+E to switch between writing and source editing. Use the terminal button to work with a shell beside your files.", "Press {shortcut} to switch between writing and source editing. Use the terminal button to work with a shell beside your files.",
"Ctrl+E alterne entre rédaction et code source. Le bouton de terminal ouvre un shell à côté de vos fichiers.", "{shortcut} alterne entre rédaction et code source. Le bouton de terminal ouvre un shell à côté de vos fichiers.",
"Ctrl+Eで文章編集とソース編集を切り替えます。ターミナルボタンでファイルと並べてシェルを操作できます。", "{shortcut}で文章編集とソース編集を切り替えます。ターミナルボタンでファイルと並べてシェルを操作できます。",
"按 Ctrl+E 切换写作和源码编辑。使用终端按钮在文件旁操作命令行。" "按 {shortcut} 切换写作和源码编辑。使用终端按钮在文件旁操作命令行。"
], ],
[ [
"Auto-save saves changed files at the interval in Settings → General. Ctrl+S saves the active file immediately.", "Auto-save saves changed files at the interval in Settings → General. {shortcut} saves the active file immediately.",
"L’enregistrement automatique suit l’intervalle dans Paramètres → Général. Ctrl+S enregistre immédiatement le fichier actif.", "L’enregistrement automatique suit l’intervalle dans Paramètres → Général. {shortcut} enregistre immédiatement le fichier actif.",
"自動保存は「設定 → 一般」の間隔で変更を保存します。Ctrl+Sで現在のファイルをすぐに保存します。", "自動保存は「設定 → 一般」の間隔で変更を保存します。{shortcut}で現在のファイルをすぐに保存します。",
"自动保存按照“设置 → 常规”中的间隔保存更改。Ctrl+S 可立即保存当前文件。" "自动保存按照“设置 → 常规”中的间隔保存更改。{shortcut} 可立即保存当前文件。"
], ],
[ [
"If another app changes a file, RuneStone keeps your edits and offers both versions for review.", "If another app changes a file, RuneStone keeps your edits and offers both versions for review.",
@@ -1782,10 +1782,10 @@ export const messageRows: [string, string, string, string][] = [
"RuneStone 浏览器" "RuneStone 浏览器"
], ],
[ [
"New browser tab (Ctrl T)", "New browser tab ({shortcut})",
"Nouvel onglet du navigateur (Ctrl T)", "Nouvel onglet du navigateur ({shortcut})",
"新しいブラウザータブ (Ctrl T)", "新しいブラウザータブ ({shortcut})",
"新建浏览器标签页 (Ctrl T)" "新建浏览器标签页 ({shortcut})"
], ],
[ [
"Open link in new tab", "Open link in new tab",
@@ -2700,10 +2700,10 @@ export const messageRows: [string, string, string, string][] = [
"第一行是 Markdown 表头" "第一行是 Markdown 表头"
], ],
[ [
"Clipboard unavailable. Use Ctrl+C to copy.", "Clipboard unavailable. Use {shortcut} to copy.",
"Presse-papiers indisponible. Utilisez Ctrl+C pour copier.", "Presse-papiers indisponible. Utilisez {shortcut} pour copier.",
"クリップボードを使用できません。Ctrl+Cでコピーしてください。", "クリップボードを使用できません。{shortcut}でコピーしてください。",
"剪贴板不可用。请使用 Ctrl+C 复制。" "剪贴板不可用。请使用 {shortcut} 复制。"
], ],
[ [
"Open plugins folder", "Open plugins folder",
@@ -3491,7 +3491,26 @@ export const messageRows: [string, string, string, string][] = [
["Text", "Texte", "テキスト", "文本"], ["Text", "Texte", "テキスト", "文本"],
["Accents", "Accents", "アクセント", "强调色"], ["Accents", "Accents", "アクセント", "强调色"],
["Selection and highlight", "Sélection et surlignage", "選択と強調表示", "选择和高亮"], ["Selection and highlight", "Sélection et surlignage", "選択と強調表示", "选择和高亮"],
["Status", "État", "ステータス", "状态"] ["Status", "État", "ステータス", "状态"],
["{modifier}+click to open link", "{modifier}+clic pour ouvrir le lien", "{modifier}+クリックでリンクを開く", "{modifier}+单击以打开链接"],
["Clipboard unavailable here. Use {shortcut}.", "Presse-papiers indisponible ici. Utilisez {shortcut}.", "ここではクリップボードを使用できません。{shortcut}を使用してください。", "此处剪贴板不可用。请使用 {shortcut}。"],
["Find a command", "Rechercher une commande", "コマンドを検索", "查找命令"],
["Find a command…", "Rechercher une commande…", "コマンドを検索…", "查找命令…"],
["No matching commands.", "Aucune commande correspondante.", "一致するコマンドはありません。", "没有匹配的命令。"],
["{count} commands", "{count} commandes", "{count} 個のコマンド", "{count} 个命令"],
["run", "exécuter", "実行", "运行"],
["Show all commands", "Afficher toutes les commandes", "すべてのコマンドを表示", "显示所有命令"],
["Switch between writing and source editing", "Alterner entre rédaction et code source", "文章編集とソース編集を切り替え", "在写作和源码编辑之间切换"],
["Show or hide the terminal", "Afficher ou masquer le terminal", "ターミナルを表示または非表示", "显示或隐藏终端"],
["Close the tab", "Fermer l’onglet", "タブを閉じる", "关闭标签页"],
["Show or hide the side pane", "Afficher ou masquer le panneau latéral", "サイドパネルを表示または非表示", "显示或隐藏侧边栏"],
["Rename the active file", "Renommer le fichier actif", "現在のファイルの名前を変更", "重命名当前文件"],
["Next tab", "Onglet suivant", "次のタブ", "下一个标签页"],
["Previous tab", "Onglet précédent", "前のタブ", "上一个标签页"],
["Write", "Écrire", "書く", "写作"],
["Find in the document", "Rechercher dans le document", "ドキュメント内を検索", "在文档中查找"],
["Move to the Recycle Bin", "Placer dans la Corbeille", "ごみ箱に移動", "移到回收站"],
["Open the context menu", "Ouvrir le menu contextuel", "コンテキストメニューを開く", "打开上下文菜单"]
]; ];
export const catalogs: Record<Exclude<Locale, 'en'>, Record<string, string>> = { export const catalogs: Record<Exclude<Locale, 'en'>, Record<string, string>> = {
fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])), fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])),
+2 -1
View File
@@ -1,5 +1,6 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n"; import { t } from "$lib/i18n";
import { keys } from "$lib/ui/shortcuts";
import { tick, untrack } from "svelte"; import { tick, untrack } from "svelte";
import { getCurrentWindow } from "@tauri-apps/api/window"; import { getCurrentWindow } from "@tauri-apps/api/window";
import { pluginHost } from "$lib/plugins/registry"; import { pluginHost } from "$lib/plugins/registry";
@@ -81,7 +82,7 @@
<TabBar {tabs} activePath={active} onSelect={select} onClose={close} onCloseTabs={close} <TabBar {tabs} activePath={active} onSelect={select} onClose={close} onCloseTabs={close}
onMove={move} onPin={pinPluginEditor} fileActions={() => []} tabActions={actions} onMove={move} onPin={pinPluginEditor} fileActions={() => []} tabActions={actions}
tabDragData={dragData} onDropTab={(data, index) => void receive(data, index)} /> tabDragData={dragData} onDropTab={(data, index) => void receive(data, index)} />
<IconButton icon="plus" label={$t("New browser tab (Ctrl T)")} disabled={!browser?.newTab || opening} onclick={() => void newTab()} /> <IconButton icon="plus" label={$t("New browser tab ({shortcut})", { shortcut: keys("Mod+T") })} disabled={!browser?.newTab || opening} onclick={() => void newTab()} />
<div class="window-drag-space" data-tauri-drag-region></div> <div class="window-drag-space" data-tauri-drag-region></div>
<WindowControls onError={message => error = message} /> <WindowControls onError={message => error = message} />
</header> </header>
+69
View File
@@ -0,0 +1,69 @@
<script lang="ts" module>
export type PaletteCommand = { id: string; label: string; detail?: string; shortcut?: string; run: () => void };
</script>
<script lang="ts">
// The command palette (Ctrl+Shift+P): every app command and plugin command, with its shortcut.
import { t } from "$lib/i18n";
import { onMount } from "svelte";
let { commands, onClose }: { commands: PaletteCommand[]; onClose: () => void } = $props();
let query = $state("");
let selected = $state(0);
let dialog: HTMLDialogElement;
let input: HTMLInputElement;
let picked = false;
// Every word of the query must appear in the label or the detail.
const matches = $derived(commands.filter(command => {
const text = `${command.label} ${command.detail ?? ""}`.toLowerCase();
return query.toLowerCase().split(/\s+/).every(part => text.includes(part));
}));
function pick(command?: PaletteCommand) {
if (!command) return;
picked = true;
onClose();
// Run after the dialog closes, so the command can move focus or open another dialog.
queueMicrotask(command.run);
}
onMount(() => {
const origin = document.activeElement instanceof HTMLElement ? document.activeElement : null;
dialog.showModal(); input.focus();
return () => { if (!picked && origin?.isConnected) origin.focus({ preventScroll: true }); };
});
</script>
<dialog class="rs-picker" bind:this={dialog} aria-label={$t("Commands")} onpointerdown={(event) => {
const bounds = dialog.getBoundingClientRect();
if (event.target === dialog && (event.clientX < bounds.left || event.clientX > bounds.right || event.clientY < bounds.top || event.clientY > bounds.bottom)) onClose();
}} oncancel={onClose}>
<input bind:this={input} bind:value={query} oninput={() => selected = 0} aria-label={$t("Find a command")} placeholder={$t("Find a command…")}
aria-controls="command-results" aria-activedescendant={matches.length ? `command-${selected}` : undefined} onkeydown={(event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault(); selected = Math.max(0, Math.min(matches.length - 1, selected + (event.key === "ArrowDown" ? 1 : -1)));
dialog.querySelector(`[data-index="${selected}"]`)?.scrollIntoView({ block: "nearest" });
}
if (event.key === "Enter") { event.preventDefault(); pick(matches[selected]); }
}} />
<div class="results" id="command-results">
{#each matches as command, index (command.id)}
<button class="rs-picker-row" id={`command-${index}`} data-index={index} aria-current={selected === index ? 'true' : undefined} onclick={() => pick(command)}>
<span class="command-label">{command.label}{#if command.detail}<span class="rs-picker-hint">{command.detail}</span>{/if}</span>
{#if command.shortcut}<kbd>{command.shortcut}</kbd>{/if}
</button>
{/each}
{#if !matches.length}<p>{$t("No matching commands.")}</p>{/if}
</div>
<footer><span>{$t("{count} commands", { count: commands.length })}</span> <span>{$t("↑ ↓ select · Enter {action} · Esc close", { action: $t("run") })}</span></footer>
</dialog>
<style>
dialog { margin-top: 12vh; width: min(640px, 85vw); }
dialog::backdrop { background: var(--rs-scrim); }
input { width: 100%; padding: 16px; border: 0; background: var(--rs-bg); color: var(--rs-text-strong); }
.results { max-height: 50vh; overflow: auto; }
.results p { margin: 12px 14px; color: var(--rs-text-dim); }
.command-label { flex: 1; min-width: 0; overflow-wrap: anywhere; }
.command-label .rs-picker-hint { display: inline; margin-left: 8px; }
kbd { flex: 0 0 auto; color: var(--rs-text-dim); font: 12px var(--rs-font-ui); white-space: nowrap; }
footer { padding: 10px 14px; display: flex; justify-content: space-between; gap: 12px; border-top: 1px solid var(--rs-border); color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); }
</style>
+5 -4
View File
@@ -1,5 +1,6 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n"; import { t } from "$lib/i18n";
import { commandShortcut } from "./workbenchKeys";
import { pluginHost } from "$lib/plugins/registry"; import { pluginHost } from "$lib/plugins/registry";
import type { GitLineInfo } from "$lib/git/contracts"; import type { GitLineInfo } from "$lib/git/contracts";
import FindPanel from "$lib/editor/FindPanel.svelte"; import FindPanel from "$lib/editor/FindPanel.svelte";
@@ -158,13 +159,13 @@
<div class="welcome-actions"> <div class="welcome-actions">
{#if hasWorkspace} {#if hasWorkspace}
<div class="welcome-row"> <div class="welcome-row">
<button onclick={onNewFile}><Icon icon="file-plus" /> {$t("New file")} <kbd>Ctrl N</kbd></button> <button onclick={onNewFile}><Icon icon="file-plus" /> {$t("New file")} <kbd>{commandShortcut("new-file")}</kbd></button>
{#if onNewNote}<button onclick={onNewNote}><Icon icon="pen" /> {$t("New note")}</button>{/if} {#if onNewNote}<button onclick={onNewNote}><Icon icon="pen" /> {$t("New note")}</button>{/if}
<button onclick={onQuickOpen}><Icon icon="search" /> {$t("Find file")} <kbd>Ctrl P</kbd></button> <button onclick={onQuickOpen}><Icon icon="search" /> {$t("Find file")} <kbd>{commandShortcut("quick-open")}</kbd></button>
</div> </div>
{/if} {/if}
<div class="welcome-row"> <div class="welcome-row">
<button onclick={onOpenWorkspace}><Icon icon="folder-open" /> {$t("Open folder")} <kbd>Ctrl O</kbd></button> <button onclick={onOpenWorkspace}><Icon icon="folder-open" /> {$t("Open folder")} <kbd>{commandShortcut("open-workspace")}</kbd></button>
{#if onOpenBrowser}<button onclick={onOpenBrowser} disabled={browserOpening}><Icon icon="globe" /> {browserOpening ? $t("Opening browser…") : $t("Open browser")}</button>{/if} {#if onOpenBrowser}<button onclick={onOpenBrowser} disabled={browserOpening}><Icon icon="globe" /> {browserOpening ? $t("Opening browser…") : $t("Open browser")}</button>{/if}
</div> </div>
</div> </div>
@@ -200,7 +201,7 @@
{ value: "Ide", label: $t("IDE"), icon: "code" }, { value: "Ide", label: $t("IDE"), icon: "code" },
{ value: "Writing", label: $t("Writer"), icon: "text" }, { value: "Writing", label: $t("Writer"), icon: "text" },
]} ]}
shortcut=" (Ctrl E)" shortcut={` (${commandShortcut("toggle-layout")})`}
onchange={(mode) => { if (mode !== chrome) onToggleChrome?.(); }} onchange={(mode) => { if (mode !== chrome) onToggleChrome?.(); }}
/> />
</div> </div>
+3 -2
View File
@@ -10,6 +10,7 @@
import FileTree from "./FileTree.svelte"; import FileTree from "./FileTree.svelte";
import SearchPane from "./SearchPane.svelte"; import SearchPane from "./SearchPane.svelte";
import BookmarksPane from "./BookmarksPane.svelte"; import BookmarksPane from "./BookmarksPane.svelte";
import { commandShortcut } from "./workbenchKeys";
type Props = { type Props = {
workspace: WorkspaceInfo | null; workspace: WorkspaceInfo | null;
@@ -74,8 +75,8 @@
<span class="ws">{workspace ? workspace.name : $t("No workspace")}</span> <span class="ws">{workspace ? workspace.name : $t("No workspace")}</span>
</div> </div>
<div class="footer-actions"> <div class="footer-actions">
<IconButton icon="help" label={$t("Help and about (F1)")} onclick={onHelp} /> <IconButton icon="help" label={$t("Help and about ({shortcut})", { shortcut: commandShortcut("help") })} onclick={onHelp} />
<IconButton icon="settings" label={$t("Settings (Ctrl+,)")} onclick={onSettings} /> <IconButton icon="settings" label={$t("Settings ({shortcut})", { shortcut: commandShortcut("settings") })} onclick={onSettings} />
</div> </div>
</div> </div>
</aside> </aside>
+2 -1
View File
@@ -1,5 +1,6 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n"; import { t } from "$lib/i18n";
import { keys } from "$lib/ui/shortcuts";
import { tick } from "svelte"; import { tick } from "svelte";
import type { OutlineItem } from "$lib/workspace/outline"; import type { OutlineItem } from "$lib/workspace/outline";
import Icon from "$lib/ui/Icon.svelte"; import Icon from "$lib/ui/Icon.svelte";
@@ -51,7 +52,7 @@
<section class="outline" aria-label={$t("Outline")} tabindex="0" bind:this={pane} onkeydown={keydown}> <section class="outline" aria-label={$t("Outline")} tabindex="0" bind:this={pane} onkeydown={keydown}>
<div class="pane-label"> <div class="pane-label">
<span>{$t("Outline")}</span> <span>{$t("Outline")}</span>
<IconButton icon="search" label={$t("Find in outline (Ctrl+F)")} active={searchOpen} onclick={() => void openSearch()} /> <IconButton icon="search" label={$t("Find in outline ({shortcut})", { shortcut: keys("Mod+F") })} active={searchOpen} onclick={() => void openSearch()} />
</div> </div>
{#if searchOpen} {#if searchOpen}
<div class="rs-find-bar outline-search"> <div class="rs-find-bar outline-search">
+19 -4
View File
@@ -14,6 +14,15 @@
import { DEFAULT_SETTINGS, MIN_AUTOSAVE_SECONDS, MAX_AUTOSAVE_SECONDS, validAutosaveSeconds, type AppSettings } from "$lib/workspace/settings"; import { DEFAULT_SETTINGS, MIN_AUTOSAVE_SECONDS, MAX_AUTOSAVE_SECONDS, validAutosaveSeconds, type AppSettings } from "$lib/workspace/settings";
import { license } from "../../../package.json"; import { license } from "../../../package.json";
import { appVersion as version } from "../appVersion"; import { appVersion as version } from "../appVersion";
import { COMMAND_LABELS, OTHER_SHORTCUTS, commandShortcut, shortcutKeys, type WorkbenchCommand } from "./workbenchKeys";
import { isMac } from "$lib/ui/shortcuts";
// Help lists every shortcut: the workbench commands, then the editor and file tree shortcuts.
const shortcutSections = (() => {
const general = (Object.keys(COMMAND_LABELS) as WorkbenchCommand[]).map(command => ({ label: COMMAND_LABELS[command], keys: commandShortcut(command) })).filter(item => item.keys);
const others = new Map<string, { label: string; keys: string }[]>();
for (const item of OTHER_SHORTCUTS) others.set(item.section, [...(others.get(item.section) ?? []), { label: item.label, keys: shortcutKeys(isMac() && item.macKeys ? item.macKeys : item.keys) }]);
return [{ name: "General", items: general }, ...[...others].map(([name, items]) => ({ name, items }))];
})();
let { settings, help = false, standalone = false, windowError = "", windowControls, onSave, onClose }: { let { settings, help = false, standalone = false, windowError = "", windowControls, onSave, onClose }: {
settings: AppSettings; settings: AppSettings;
@@ -151,7 +160,7 @@
<div class="interval"><input id="autosave-seconds" type="number" min={MIN_AUTOSAVE_SECONDS} max={MAX_AUTOSAVE_SECONDS} step="1" required disabled={!settings.autosaveEnabled} aria-describedby="interval-description" aria-invalid={!!error} bind:value={seconds} onchange={changeInterval} /><span>{$t("seconds")}</span></div> <div class="interval"><input id="autosave-seconds" type="number" min={MIN_AUTOSAVE_SECONDS} max={MAX_AUTOSAVE_SECONDS} step="1" required disabled={!settings.autosaveEnabled} aria-describedby="interval-description" aria-invalid={!!error} bind:value={seconds} onchange={changeInterval} /><span>{$t("seconds")}</span></div>
</div> </div>
</div> </div>
<p class="note">{settings.autosaveEnabled ? $t("Only changed files are saved.") : $t("Auto-save is off. Use Ctrl+S to save your changes.")} {$t("Disk conflicts keep your edits for review.")}</p> <p class="note">{settings.autosaveEnabled ? $t("Only changed files are saved.") : $t("Auto-save is off. Use {shortcut} to save your changes.", { shortcut: commandShortcut("save") })} {$t("Disk conflicts keep your edits for review.")}</p>
<div class="section-footer"><button class="text-button" onclick={() => { seconds = DEFAULT_SETTINGS.autosaveSeconds; apply({ ...DEFAULT_SETTINGS }); }}>{$t("Restore defaults")}</button><span>{$t("Default: every 5 seconds")}</span></div> <div class="section-footer"><button class="text-button" onclick={() => { seconds = DEFAULT_SETTINGS.autosaveSeconds; apply({ ...DEFAULT_SETTINGS }); }}>{$t("Restore defaults")}</button><span>{$t("Default: every 5 seconds")}</span></div>
{#if error}<p class="error" role="alert">{error}</p>{/if} {#if error}<p class="error" role="alert">{error}</p>{/if}
<p class="saved" role="status">{message}</p> <p class="saved" role="status">{message}</p>
@@ -166,9 +175,14 @@
{:else} {:else}
<div class="brand"><img src="/runestone.svg" alt="" width="88" height="88" /><h2>RuneStone</h2><p>{$t("Version {version}", { version })}</p></div> <div class="brand"><img src="/runestone.svg" alt="" width="88" height="88" /><h2>RuneStone</h2><p>{$t("Version {version}", { version })}</p></div>
<div class="card help-card"> <div class="card help-card">
<details><summary><Icon icon="book-open" /> {$t("Get started")}</summary><div class="help-copy"><p>{$t("Use the folder button to open a workspace or create one. Your notes and scripts stay as ordinary files on disk.")}</p><p>{$t("Use the + beside the tabs for a new tab. Press Ctrl+N to create a file, or Ctrl+P to find one.")}</p><p>{$t("Press Ctrl+E to switch between writing and source editing. Use the terminal button to work with a shell beside your files.")}</p></div></details> <details><summary><Icon icon="book-open" /> {$t("Get started")}</summary><div class="help-copy"><p>{$t("Use the folder button to open a workspace or create one. Your notes and scripts stay as ordinary files on disk.")}</p><p>{$t("Use the + beside the tabs for a new tab. Press {newFile} to create a file, or {quickOpen} to find one.", { newFile: commandShortcut("new-file"), quickOpen: commandShortcut("quick-open") })}</p><p>{$t("Press {shortcut} to switch between writing and source editing. Use the terminal button to work with a shell beside your files.", { shortcut: commandShortcut("toggle-layout") })}</p></div></details>
<details><summary><Icon icon="save" /> {$t("Save your work")}</summary><div class="help-copy"><p>{$t("Auto-save saves changed files at the interval in Settings → General. Ctrl+S saves the active file immediately.")}</p><p>{$t("If another app changes a file, RuneStone keeps your edits and offers both versions for review.")}</p></div></details> <details><summary><Icon icon="save" /> {$t("Save your work")}</summary><div class="help-copy"><p>{$t("Auto-save saves changed files at the interval in Settings → General. {shortcut} saves the active file immediately.", { shortcut: commandShortcut("save") })}</p><p>{$t("If another app changes a file, RuneStone keeps your edits and offers both versions for review.")}</p></div></details>
<details><summary><Icon icon="code" /> {$t("Keyboard shortcuts")}</summary><dl><div><dt>{$t("Open a workspace")}</dt><dd><kbd>Ctrl+O</kbd></dd></div><div><dt>{$t("Find a file")}</dt><dd><kbd>Ctrl+P</kbd></dd></div><div><dt>{$t("Save the active file")}</dt><dd><kbd>Ctrl+S</kbd></dd></div><div><dt>{$t("Search the workspace")}</dt><dd><kbd>Ctrl+Shift+F</kbd></dd></div><div><dt>{$t("Open settings")}</dt><dd><kbd>Ctrl+,</kbd></dd></div><div><dt>{$t("Help and about")}</dt><dd><kbd>F1</kbd></dd></div></dl></details> <details open><summary><Icon icon="code" /> {$t("Keyboard shortcuts")}</summary>
{#each shortcutSections as section (section.name)}
<h3 class="shortcut-section">{$t(section.name)}</h3>
<dl>{#each section.items as item (item.label)}<div><dt>{$t(item.label)}</dt><dd><kbd>{item.keys}</kbd></dd></div>{/each}</dl>
{/each}
</details>
</div> </div>
<p class="about-note">{$t("RuneStone is under development. Maintained by kwyvern-gh.")}</p> <p class="about-note">{$t("RuneStone is under development. Maintained by kwyvern-gh.")}</p>
{/if} {/if}
@@ -233,6 +247,7 @@
.help-copy p:first-child { margin-top: 0; } .help-copy p:first-child { margin-top: 0; }
dl div { display: flex; justify-content: space-between; gap: 12px; margin: 10px 0; } dl div { display: flex; justify-content: space-between; gap: 12px; margin: 10px 0; }
dd { margin: 0; } dd { margin: 0; }
.shortcut-section { margin: 4px 0 0 28px; font-size: 12px; color: var(--rs-text-dim); text-transform: none; }
kbd { font-family: var(--rs-font-mono); color: var(--rs-text-dim); } kbd { font-family: var(--rs-font-mono); color: var(--rs-text-dim); }
.about-note { text-align: center; margin: 20px 0 0; } .about-note { text-align: center; margin: 20px 0 0; }
@media (max-width: 660px) { @media (max-width: 660px) {
+18 -2
View File
@@ -2,7 +2,7 @@
import { t } from "$lib/i18n"; import { t } from "$lib/i18n";
import TerminalSlot from "$lib/plugins/TerminalSlot.svelte"; import TerminalSlot from "$lib/plugins/TerminalSlot.svelte";
import type PluginEditor from "$lib/plugins/PluginEditor.svelte"; import type PluginEditor from "$lib/plugins/PluginEditor.svelte";
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, waitForPluginStartup } from "$lib/plugins/external"; import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, waitForPluginStartup, pluginTools, installedPlugins, runPluginCommand } from "$lib/plugins/external";
import { containsPane, paneBounds } from "$lib/workspace/splitLayout"; import { containsPane, paneBounds } from "$lib/workspace/splitLayout";
import { pluginSidebar, closePluginSidebar, pluginNavigation, openPluginView, pluginView, pluginEditors, pluginEditorActive, selectPluginEditor, closePluginEditor, openPluginDocument, renamePluginDocuments, removePluginDocuments, notifyPluginWorkspace, guardPluginWrites, handlePluginFileOpen, handlePluginDocumentRename, cancelPluginDocumentOpen, type OpenPluginView } from "$lib/plugins/external"; import { pluginSidebar, closePluginSidebar, pluginNavigation, openPluginView, pluginView, pluginEditors, pluginEditorActive, selectPluginEditor, closePluginEditor, openPluginDocument, renamePluginDocuments, removePluginDocuments, notifyPluginWorkspace, guardPluginWrites, handlePluginFileOpen, handlePluginDocumentRename, cancelPluginDocumentOpen, type OpenPluginView } from "$lib/plugins/external";
import { onMount, onDestroy, tick, untrack } from "svelte"; import { onMount, onDestroy, tick, untrack } from "svelte";
@@ -26,6 +26,7 @@
import { requestText } from "$lib/workspace/dialogs.svelte"; import { requestText } from "$lib/workspace/dialogs.svelte";
import TextDialog from "./TextDialog.svelte"; import TextDialog from "./TextDialog.svelte";
import QuickOpen from "./QuickOpen.svelte"; import QuickOpen from "./QuickOpen.svelte";
import CommandPalette, { type PaletteCommand } from "./CommandPalette.svelte";
import TemplateManager from "./TemplateManager.svelte"; import TemplateManager from "./TemplateManager.svelte";
import WorkspacePicker from "./WorkspacePicker.svelte"; import WorkspacePicker from "./WorkspacePicker.svelte";
import SettingsDialog from "./SettingsDialog.svelte"; import SettingsDialog from "./SettingsDialog.svelte";
@@ -35,7 +36,7 @@
import { TAB_TRANSFER_ID, cancelTabTransfer, finishTabTransfer, offerTabTransfer, onTabTransferAccepted, parseTabTransfer, takeTabTransfer } from "$lib/workspace/tabTransfer"; import { TAB_TRANSFER_ID, cancelTabTransfer, finishTabTransfer, offerTabTransfer, onTabTransferAccepted, parseTabTransfer, takeTabTransfer } from "$lib/workspace/tabTransfer";
import { DEFAULT_WORKBENCH_LAYOUT, WORKBENCH_LAYOUT_KEY, parseWorkbenchLayout, saveWorkbenchLayout, type WorkbenchLayout } from "$lib/workspace/workbenchLayout"; import { DEFAULT_WORKBENCH_LAYOUT, WORKBENCH_LAYOUT_KEY, parseWorkbenchLayout, saveWorkbenchLayout, type WorkbenchLayout } from "$lib/workspace/workbenchLayout";
import type FileTree from "./FileTree.svelte"; import type FileTree from "./FileTree.svelte";
import { preferenceKeys, workbenchCommand, type WorkbenchCommand } from "./workbenchKeys"; import { COMMAND_LABELS, commandShortcut, preferenceKeys, workbenchCommand, type WorkbenchCommand } from "./workbenchKeys";
import type EditorPane from "./EditorPane.svelte"; import type EditorPane from "./EditorPane.svelte";
import WorkbenchHeader from "./WorkbenchHeader.svelte"; import WorkbenchHeader from "./WorkbenchHeader.svelte";
import PluginRibbon from "./PluginRibbon.svelte"; import PluginRibbon from "./PluginRibbon.svelte";
@@ -147,6 +148,19 @@
let documentPanes = $state(initialDocumentPanes()); let documentPanes = $state(initialDocumentPanes());
const reading = $derived(documentPanes.panes.find(pane => pane.id === documentPanes.active)?.reading ?? false); const reading = $derived(documentPanes.panes.find(pane => pane.id === documentPanes.active)?.reading ?? false);
let quickOpen = $state(false); let quickOpen = $state(false);
let palette = $state(false);
/** The commands of the palette: the app commands that apply here, then the plugin commands. */
function paletteCommands(): PaletteCommand[] {
const hidden = new Set<WorkbenchCommand>(["command-palette", ...(terminalEnabled ? [] : ["toggle-terminal" as const]), ...(workspace ? [] : ["quick-open" as const])]);
const app = (Object.keys(COMMAND_LABELS) as WorkbenchCommand[]).filter(command => !hidden.has(command)).map(command => ({
id: command, label: $t(COMMAND_LABELS[command]), shortcut: commandShortcut(command) || undefined, run: () => { runCommand(command); },
}));
const plugins = $pluginTools.filter(tool => tool.kind === "command" && tool.surface === "commands").map(tool => ({
id: `plugin:${tool.owner}:${tool.id}`, label: tool.title, detail: $installedPlugins.plugins.find(row => row.manifest.id === tool.owner)?.manifest.name ?? tool.owner,
run: () => { void runPluginCommand(tool.owner, tool.id).catch(reason => error = String(reason)); },
}));
return [...app, ...plugins];
}
let templateManager = $state(false); let templateManager = $state(false);
let terminalStarted = $state(false); let terminalStarted = $state(false);
let terminalMaximized = $state(false); let terminalMaximized = $state(false);
@@ -858,6 +872,7 @@
selectWorkingTab(workingTabs[next].relPath); selectWorkingTab(workingTabs[next].relPath);
return true; return true;
} }
case "command-palette": palette = true; return true;
case "settings": void openSettings(); return true; case "settings": void openSettings(); return true;
case "help": preferences = "help"; return true; case "help": preferences = "help"; return true;
case "quick-open": if (workspace) quickOpen = true; return true; case "quick-open": if (workspace) quickOpen = true; return true;
@@ -1162,6 +1177,7 @@
<WorkspacePicker bind:this={workspacePicker} currentRoot={workspace?.root} anchor={workspaceAnchor} onOpen={openPath} /> <WorkspacePicker bind:this={workspacePicker} currentRoot={workspace?.root} anchor={workspaceAnchor} onOpen={openPath} />
{#if preferences}<SettingsDialog {settings} help={preferences === "help"} onSave={updateSettings} onClose={() => preferences = null} />{/if} {#if preferences}<SettingsDialog {settings} help={preferences === "help"} onSave={updateSettings} onClose={() => preferences = null} />{/if}
{#if quickOpen && workspace}<QuickOpen onOpen={(entry) => void openFile(entry)} onClose={() => quickOpen = false} />{/if} {#if quickOpen && workspace}<QuickOpen onOpen={(entry) => void openFile(entry)} onClose={() => quickOpen = false} />{/if}
{#if palette}<CommandPalette commands={paletteCommands()} onClose={() => palette = false} />{/if}
{#if templateManager && workspace}<TemplateManager {session} onClose={() => templateManager = false} {#if templateManager && workspace}<TemplateManager {session} onClose={() => templateManager = false}
onEdit={(entry) => { templateManager = false; void openFile(entry, undefined, "new"); }} />{/if} onEdit={(entry) => { templateManager = false; void openFile(entry, undefined, "new"); }} />{/if}
+2 -1
View File
@@ -8,6 +8,7 @@
import PluginAccessMenu from "$lib/plugins/PluginAccessMenu.svelte"; import PluginAccessMenu from "$lib/plugins/PluginAccessMenu.svelte";
import { openPluginView, pluginSidebar } from "$lib/plugins/external"; import { openPluginView, pluginSidebar } from "$lib/plugins/external";
import TabBar from "./TabBar.svelte"; import TabBar from "./TabBar.svelte";
import { commandShortcut } from "./workbenchKeys";
type LeftView = "files" | "search" | "bookmarks"; type LeftView = "files" | "search" | "bookmarks";
type Props = { type Props = {
@@ -53,7 +54,7 @@
</div> </div>
<div class="header-center" data-tauri-drag-region> <div class="header-center" data-tauri-drag-region>
<TabBar {...tabBar} /> <TabBar {...tabBar} />
<IconButton icon="plus" label={$t("New tab (Ctrl T)")} onclick={onNewTab} /> <IconButton icon="plus" label={$t("New tab ({shortcut})", { shortcut: commandShortcut("new-tab") })} onclick={onNewTab} />
{#if desktop}<div class="window-drag-space" data-tauri-drag-region></div>{/if} {#if desktop}<div class="window-drag-space" data-tauri-drag-region></div>{/if}
</div> </div>
<div class="header-right" data-tauri-drag-region> <div class="header-right" data-tauri-drag-region>
+54 -4
View File
@@ -1,15 +1,20 @@
import { message } from "../i18n/index.ts";
import { keys, shortcutLabel } from "../ui/shortcuts.ts";
/** The commands of the workbench shortcuts. Workbench.svelte runs them. */ /** The commands of the workbench shortcuts. Workbench.svelte runs them. */
export type WorkbenchCommand = export type WorkbenchCommand =
| "quick-open" | "new-tab" | "search-workspace" | "save" | "open-workspace" | "new-file" | "toggle-layout" | "command-palette" | "quick-open" | "new-tab" | "search-workspace" | "save" | "open-workspace" | "new-file" | "toggle-layout"
| "toggle-terminal" | "close-tab" | "toggle-sidebar" | "rename" | "next-tab" | "previous-tab" | "settings" | "help"; | "toggle-terminal" | "close-tab" | "toggle-sidebar" | "rename" | "next-tab" | "previous-tab" | "settings" | "help";
/** /**
* One shortcut. `mod` is Ctrl, or Cmd on macOS. `ctrl` is Ctrl only. * One shortcut. `mod` is Ctrl, or Cmd on macOS. `ctrl` is Ctrl only.
* `shift` and `alt` must match when they are set. A missing value accepts both states. * `shift` and `alt` must match when they are set. A missing value accepts both states.
* `code` matches the physical key, for keys that move between keyboard layouts.
* `outsideFields` ignores the key in text inputs, where it has its own meaning. * `outsideFields` ignores the key in text inputs, where it has its own meaning.
*/ */
export type WorkbenchKey = { export type WorkbenchKey = {
key: string; key: string;
code?: string;
command: WorkbenchCommand; command: WorkbenchCommand;
mod?: boolean; mod?: boolean;
ctrl?: boolean; ctrl?: boolean;
@@ -20,6 +25,7 @@ export type WorkbenchKey = {
/** Shortcuts of the main window. The first match wins. */ /** Shortcuts of the main window. The first match wins. */
export const workbenchKeys: WorkbenchKey[] = [ export const workbenchKeys: WorkbenchKey[] = [
{ key: "p", mod: true, shift: true, command: "command-palette" },
{ key: "p", mod: true, command: "quick-open" }, { key: "p", mod: true, command: "quick-open" },
{ key: "t", mod: true, shift: false, alt: false, command: "new-tab" }, { key: "t", mod: true, shift: false, alt: false, command: "new-tab" },
{ key: "f", mod: true, shift: true, command: "search-workspace" }, { key: "f", mod: true, shift: true, command: "search-workspace" },
@@ -29,7 +35,8 @@ export const workbenchKeys: WorkbenchKey[] = [
{ key: "e", mod: true, command: "toggle-layout" }, { key: "e", mod: true, command: "toggle-layout" },
{ key: "`", mod: true, command: "toggle-terminal" }, { key: "`", mod: true, command: "toggle-terminal" },
{ key: "w", mod: true, command: "close-tab" }, { key: "w", mod: true, command: "close-tab" },
{ key: "b", mod: true, command: "toggle-sidebar" }, // Ctrl+B makes text bold in Write, so the side pane toggle uses Ctrl+\.
{ key: "\\", code: "Backslash", mod: true, command: "toggle-sidebar" },
{ key: "F2", mod: false, alt: false, outsideFields: true, command: "rename" }, { key: "F2", mod: false, alt: false, outsideFields: true, command: "rename" },
]; ];
@@ -41,11 +48,54 @@ export const preferenceKeys: WorkbenchKey[] = [
{ key: "F1", mod: false, shift: false, alt: false, command: "help" }, { key: "F1", mod: false, shift: false, alt: false, command: "help" },
]; ];
type KeyEvent = Pick<KeyboardEvent, "key" | "ctrlKey" | "metaKey" | "shiftKey" | "altKey" | "target">; /** The name of each command in the command palette and in Help. */
export const COMMAND_LABELS: Record<WorkbenchCommand, string> = {
"command-palette": message("Show all commands"),
"quick-open": message("Find a file"),
"new-tab": message("New tab"),
"search-workspace": message("Search the workspace"),
save: message("Save the active file"),
"open-workspace": message("Open a workspace"),
"new-file": message("New file"),
"toggle-layout": message("Switch between writing and source editing"),
"toggle-terminal": message("Show or hide the terminal"),
"close-tab": message("Close the tab"),
"toggle-sidebar": message("Show or hide the side pane"),
rename: message("Rename the active file"),
"next-tab": message("Next tab"),
"previous-tab": message("Previous tab"),
settings: message("Open settings"),
help: message("Help and about"),
};
/** The label of the first shortcut of a command, or an empty string. */
export function commandShortcut(command: WorkbenchCommand): string {
const binding = [...workbenchKeys, ...preferenceKeys].find(item => item.command === command);
return binding ? shortcutLabel(binding) : "";
}
/** Shortcuts of the editors and the file tree, for Help. `keys` uses Mod for Ctrl, or Cmd on macOS. `macKeys` replaces `keys` on macOS. */
export const OTHER_SHORTCUTS: readonly { section: string; label: string; keys: string; macKeys?: string }[] = [
{ section: message("Write"), label: message("Bold"), keys: "Mod+B" },
{ section: message("Write"), label: message("Italic"), keys: "Mod+I" },
{ section: message("Write"), label: message("Add external link"), keys: "Mod+K" },
{ section: message("Write"), label: message("Strikethrough"), keys: "Mod+Shift+X" },
{ section: message("Write"), label: message("Highlight"), keys: "Mod+Shift+H" },
{ section: message("Write"), label: message("Find in the document"), keys: "Mod+F" },
{ section: message("Files"), label: message("Rename"), keys: "F2" },
{ section: message("Files"), label: message("Move to the Recycle Bin"), keys: "Delete", macKeys: "Mod+Backspace" },
{ section: message("Files"), label: message("Delete permanently"), keys: "Shift+Delete", macKeys: "Mod+Alt+Backspace" },
{ section: message("Files"), label: message("Open the context menu"), keys: "Shift+F10" },
];
/** The label of a written combination, such as "Mod+Shift+X". */
export { keys as shortcutKeys };
type KeyEvent = Pick<KeyboardEvent, "key" | "ctrlKey" | "metaKey" | "shiftKey" | "altKey" | "target"> & { code?: string };
function matches(binding: WorkbenchKey, event: KeyEvent): boolean { function matches(binding: WorkbenchKey, event: KeyEvent): boolean {
const key = binding.key.length === 1 ? event.key.toLowerCase() : event.key; const key = binding.key.length === 1 ? event.key.toLowerCase() : event.key;
if (key !== binding.key) return false; if (key !== binding.key && !(binding.code && event.code === binding.code)) return false;
if (binding.mod !== undefined && (event.ctrlKey || event.metaKey) !== binding.mod) return false; if (binding.mod !== undefined && (event.ctrlKey || event.metaKey) !== binding.mod) return false;
if (binding.ctrl && (!event.ctrlKey || event.metaKey)) return false; if (binding.ctrl && (!event.ctrlKey || event.metaKey)) return false;
if (binding.shift !== undefined && event.shiftKey !== binding.shift) return false; if (binding.shift !== undefined && event.shiftKey !== binding.shift) return false;
+7 -6
View File
@@ -1,4 +1,5 @@
import { tr } from "../i18n/index.ts"; import { tr } from "../i18n/index.ts";
import { keys } from "./shortcuts.ts";
import type { ActionMenuItem } from "./actionMenu.ts"; import type { ActionMenuItem } from "./actionMenu.ts";
// The common text actions of the editor and reading menus. Each menu supplies only its commands. // The common text actions of the editor and reading menus. Each menu supplies only its commands.
@@ -6,8 +7,8 @@ import type { ActionMenuItem } from "./actionMenu.ts";
/** Undo and Redo, then a separator. */ /** Undo and Redo, then a separator. */
export function historyItems(history: { canUndo: boolean; canRedo: boolean; undo(): void; redo(): void }): ActionMenuItem[] { export function historyItems(history: { canUndo: boolean; canRedo: boolean; undo(): void; redo(): void }): ActionMenuItem[] {
return [ return [
{ label: tr("Undo"), icon: "undo", shortcut: "Ctrl+Z", disabled: !history.canUndo, run: history.undo }, { label: tr("Undo"), icon: "undo", shortcut: keys("Mod+Z"), disabled: !history.canUndo, run: history.undo },
{ label: tr("Redo"), icon: "redo", shortcut: "Ctrl+Shift+Z", disabled: !history.canRedo, run: history.redo }, { label: tr("Redo"), icon: "redo", shortcut: keys("Mod+Shift+Z"), disabled: !history.canRedo, run: history.redo },
{ separator: true }, { separator: true },
]; ];
} }
@@ -32,10 +33,10 @@ export type ClipboardActions = {
/** The clipboard actions in their shared order. A menu leaves out an action that it does not supply. */ /** The clipboard actions in their shared order. A menu leaves out an action that it does not supply. */
export function clipboardItems(actions: ClipboardActions): ActionMenuItem[] { export function clipboardItems(actions: ClipboardActions): ActionMenuItem[] {
const items: ActionMenuItem[] = []; const items: ActionMenuItem[] = [];
if (actions.cut) items.push({ label: tr("Cut"), icon: "cut", shortcut: "Ctrl+X", disabled: !actions.selected, run: actions.cut }); if (actions.cut) items.push({ label: tr("Cut"), icon: "cut", shortcut: keys("Mod+X"), disabled: !actions.selected, run: actions.cut });
items.push({ label: tr("Copy"), icon: "copy", shortcut: "Ctrl+C", disabled: !actions.selected, run: actions.copy }); items.push({ label: tr("Copy"), icon: "copy", shortcut: keys("Mod+C"), disabled: !actions.selected, run: actions.copy });
if (actions.paste) items.push({ label: tr("Paste"), icon: "paste", shortcut: "Ctrl+V", run: actions.paste }); if (actions.paste) items.push({ label: tr("Paste"), icon: "paste", shortcut: keys("Mod+V"), run: actions.paste });
if (actions.pastePlain) items.push({ label: tr("Paste as plain text"), icon: "paste-text", run: actions.pastePlain }); if (actions.pastePlain) items.push({ label: tr("Paste as plain text"), icon: "paste-text", run: actions.pastePlain });
if (actions.selectAll) items.push({ label: tr("Select all"), icon: "select", shortcut: "Ctrl+A", run: actions.selectAll }); if (actions.selectAll) items.push({ label: tr("Select all"), icon: "select", shortcut: keys("Mod+A"), run: actions.selectAll });
return items; return items;
} }
+31
View File
@@ -0,0 +1,31 @@
// Shortcut labels for the platform: "Ctrl+Shift+P" on Windows and Linux, "⇧⌘P" on macOS.
/** One key combination. `mod` is Ctrl, or Cmd on macOS. `ctrl` is the Ctrl key on every platform. */
export type Shortcut = { key: string; mod?: boolean; ctrl?: boolean; shift?: boolean; alt?: boolean };
export function isMac(): boolean {
if (typeof navigator === 'undefined') return false;
const platform = (navigator as Navigator & { userAgentData?: { platform?: string } }).userAgentData?.platform || navigator.platform || '';
return /mac|iphone|ipad/i.test(platform);
}
/** Key names as [Windows and Linux, macOS]. */
const NAMES: Record<string, [string, string]> = {
Escape: ['Esc', '⎋'], Enter: ['Enter', '↩'], Tab: ['Tab', '⇥'], Backspace: ['Backspace', '⌫'], Delete: ['Delete', '⌦'],
ArrowUp: ['Up', '↑'], ArrowDown: ['Down', '↓'], ArrowLeft: ['Left', '←'], ArrowRight: ['Right', '→'], ' ': ['Space', 'Space'],
};
export function shortcutLabel(shortcut: Shortcut, mac = isMac()): string {
const name = NAMES[shortcut.key]?.[mac ? 1 : 0] ?? (shortcut.key.length === 1 ? shortcut.key.toUpperCase() : shortcut.key);
// macOS orders the symbols Control, Option, Shift, Command. Windows orders Ctrl, Alt, Shift.
if (mac) return `${shortcut.ctrl ? '⌃' : ''}${shortcut.alt ? '⌥' : ''}${shortcut.shift ? '⇧' : ''}${shortcut.mod ? '⌘' : ''}${name}`;
return [shortcut.mod || shortcut.ctrl ? 'Ctrl' : '', shortcut.alt ? 'Alt' : '', shortcut.shift ? 'Shift' : '', name].filter(Boolean).join('+');
}
/** The label of a written combination, such as "Mod+Shift+Z". */
export function keys(text: string, mac = isMac()): string {
const parts = text.split('+');
const key = parts.pop() || '+';
const modifiers = new Set(parts.map(part => part.toLowerCase()));
return shortcutLabel({ key, mod: modifiers.has('mod'), ctrl: modifiers.has('ctrl'), shift: modifiers.has('shift'), alt: modifiers.has('alt') }, mac);
}
+2 -1
View File
@@ -95,7 +95,8 @@ export function settle(page) {
*/ */
export function mockTauri(target, { label = "main", state = {}, commands, strict = true } = {}) { export function mockTauri(target, { label = "main", state = {}, commands, strict = true } = {}) {
const options = JSON.stringify({ label, state, strict }); const options = JSON.stringify({ label, state, strict });
return target.addInitScript(`(${installMock})(${options}, ${commands ? commands.toString() : "undefined"});`); // Tests find module URLs in the resource entries. The default buffer of 250 entries is too small for the app.
return target.addInitScript(`performance.setResourceTimingBufferSize(5000); (${installMock})(${options}, ${commands ? commands.toString() : "undefined"});`);
} }
// This function runs in the page. Keep it self-contained. // This function runs in the page. Keep it self-contained.
@@ -123,9 +123,10 @@ await runSmoke('appearance/backgroundImages', async ({ browser }) => {
await main.setViewportSize({ width: 600, height: 700 }); await main.setViewportSize({ width: 600, height: 700 });
await main.keyboard.press('F1'); await main.keyboard.press('F1');
await main.getByRole('dialog', { name: 'Help and about' }).waitFor(); await main.getByRole('dialog', { name: 'Help and about' }).waitFor();
assert.equal(await main.locator('.help-card details[open]').count(), 0); // The shortcut list is open by default (src/lib/layout/SettingsDialog.svelte).
await main.locator('.help-card summary').first().focus(); await main.keyboard.press('Enter');
assert.equal(await main.locator('.help-card details[open]').count(), 1); assert.equal(await main.locator('.help-card details[open]').count(), 1);
await main.locator('.help-card summary').first().focus(); await main.keyboard.press('Enter');
assert.equal(await main.locator('.help-card details[open]').count(), 2);
await main.keyboard.press('Enter'); await main.keyboard.press('Enter');
await main.screenshot({ path: `${output}/help-${theme}-narrow.png` }); await main.screenshot({ path: `${output}/help-${theme}-narrow.png` });
await main.getByRole('button', { name: 'Close help', exact: true }).click(); await main.getByRole('button', { name: 'Close help', exact: true }).click();
@@ -24,7 +24,7 @@ await runSmoke("appearance/colorThemeMenu", async ({ browser }) => {
await settings.waitForFunction(() => document.documentElement.dataset.palette === "claude"); await settings.waitForFunction(() => document.documentElement.dataset.palette === "claude");
assert.equal(await settings.evaluate(() => document.documentElement.dataset.palette), "claude"); assert.equal(await settings.evaluate(() => document.documentElement.dataset.palette), "claude");
assert.equal(await settings.locator("input[type=color]").count(), 0); assert.equal(await settings.locator("input[type=color]").count(), 0);
await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click(); await page.getByRole("button", { name: "New tab (Ctrl+T)", exact: true }).click();
await page.locator(".empty").waitFor(); await page.locator(".empty").waitFor();
await page.waitForFunction(() => document.documentElement.dataset.palette === "claude"); await page.waitForFunction(() => document.documentElement.dataset.palette === "claude");
// The empty tab is transparent over the work area layer, which paints the theme background (src/lib/layout/Workbench.svelte:1258, :1548). // The empty tab is transparent over the work area layer, which paints the theme background (src/lib/layout/Workbench.svelte:1258, :1548).
@@ -18,7 +18,7 @@ await runSmoke(name, async ({ browser }) => {
const page = await openPage(context); const page = await openPage(context);
await page.goto(smokeUrl); await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').waitFor(); await page.locator('[data-tree-rel="a.md"]').waitFor();
await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click(); await page.getByRole("button", { name: "New tab (Ctrl+T)", exact: true }).click();
await page.locator(".empty").waitFor(); await page.locator(".empty").waitFor();
const settings = await openPage(context); const settings = await openPage(context);
await settings.goto(smokeUrl + "/?settingsWindow=true"); await settings.goto(smokeUrl + "/?settingsWindow=true");
@@ -60,7 +60,7 @@ await runSmoke("appearance/tooltipsAndSelection", async ({ page }) => {
assert.equal(colors.pluginBg.trim(), "transparent"); assert.equal(colors.pluginBg.trim(), "transparent");
console.log(mode, colors); console.log(mode, colors);
await page.screenshot({ path: path.join(output, `${mode}-selection.png`) }); await page.screenshot({ path: path.join(output, `${mode}-selection.png`) });
await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click(); await page.getByRole("button", { name: "New tab (Ctrl+T)", exact: true }).click();
await page.locator(".empty").waitFor(); await page.locator(".empty").waitFor();
await page.screenshot({ path: path.join(output, `${mode}-zero-background.png`) }); await page.screenshot({ path: path.join(output, `${mode}-zero-background.png`) });
await page.getByRole("tab", { name: /welcome\.md/ }).click(); await page.getByRole("tab", { name: /welcome\.md/ }).click();
+5 -5
View File
@@ -35,14 +35,14 @@ await runSmoke("editor/emptyMenu", async ({ page }) => {
await setSource(''); await setSource('');
await page.locator('.cm-line').first().click({button:'right'}); await page.locator('.cm-line').first().click({button:'right'});
await menu().waitFor(); await menu().waitFor();
for (const label of ['Add link','Add external link','Format','Paragraph','Insert','Paste Ctrl+V','Paste as plain text','Select all Ctrl+A']) assert.equal(await menu().getByRole('menuitem', {name:label,exact:true}).count(),1,label); for (const label of ['Add link','Add external link Ctrl+K','Format','Paragraph','Insert','Paste Ctrl+V','Paste as plain text','Select all Ctrl+A']) assert.equal(await menu().getByRole('menuitem', {name:label,exact:true}).count(),1,label);
assert.equal(await menu().getByRole('menuitem',{name:'Cut Ctrl+X',exact:true}).isDisabled(),true); assert.equal(await menu().getByRole('menuitem',{name:'Cut Ctrl+X',exact:true}).isDisabled(),true);
assert.equal(await menu().getByRole('menuitem',{name:'Copy Ctrl+C',exact:true}).isDisabled(),true); assert.equal(await menu().getByRole('menuitem',{name:'Copy Ctrl+C',exact:true}).isDisabled(),true);
await page.screenshot({path:`${output}/empty-${theme}.png`}); await page.screenshot({path:`${output}/empty-${theme}.png`});
await menu().getByRole('menuitem',{name:'Format',exact:true}).focus(); await menu().getByRole('menuitem',{name:'Format',exact:true}).focus();
await page.keyboard.press('ArrowRight'); await page.keyboard.press('ArrowRight');
const format = page.getByRole('menu',{name:'Format',exact:true}); const format = page.getByRole('menu',{name:'Format',exact:true});
for (const label of ['Bold','Italic','Strikethrough','Highlight','Code','Math','Comment','Clear formatting']) assert.equal(await format.getByRole('menuitem',{name:label,exact:true}).count(),1); for (const label of ['Bold Ctrl+B','Italic Ctrl+I','Strikethrough Ctrl+Shift+X','Highlight Ctrl+Shift+H','Code','Math','Comment','Clear formatting']) assert.equal(await format.getByRole('menuitem',{name:label,exact:true}).count(),1);
await page.keyboard.press('End'); await page.keyboard.press('End');
assert.equal(await page.getByRole('menuitem',{name:'Comment',exact:true}).evaluate(el=>el===document.activeElement),true); assert.equal(await page.getByRole('menuitem',{name:'Comment',exact:true}).evaluate(el=>el===document.activeElement),true);
await page.screenshot({path:`${output}/format-${theme}.png`}); await page.screenshot({path:`${output}/format-${theme}.png`});
@@ -59,12 +59,12 @@ await runSmoke("editor/emptyMenu", async ({ page }) => {
await page.getByRole('menu',{name:'Insert',exact:true}).getByRole('menuitem',{name:'Code block',exact:true}).click(); await page.getByRole('menu',{name:'Insert',exact:true}).getByRole('menuitem',{name:'Code block',exact:true}).click();
assert.match(await source(),/^```\nCode\n```/); assert.match(await source(),/^```\nCode\n```/);
await setSource(''); await openKeyboard(); await setSource(''); await openKeyboard();
await menu().getByRole('menuitem',{name:'Add external link',exact:true}).click(); await menu().getByRole('menuitem',{name:'Add external link Ctrl+K',exact:true}).click();
assert.equal(await source(),'[]()'); assert.equal(await source(),'[]()');
assert.equal(await page.evaluate(()=>window.__CM__.state.selection.main.head),1); assert.equal(await page.evaluate(()=>window.__CM__.state.selection.main.head),1);
assert.equal(await page.getByRole('dialog').count(),0); assert.equal(await page.getByRole('dialog').count(),0);
await setSource('label',0,5); await openKeyboard(); await setSource('label',0,5); await openKeyboard();
await menu().getByRole('menuitem',{name:'Add external link',exact:true}).click(); await menu().getByRole('menuitem',{name:'Add external link Ctrl+K',exact:true}).click();
assert.equal(await source(),'[label]()'); assert.equal(await source(),'[label]()');
assert.equal(await page.evaluate(()=>window.__CM__.state.selection.main.head),8); assert.equal(await page.evaluate(()=>window.__CM__.state.selection.main.head),8);
await setSource(''); await openKeyboard(); await setSource(''); await openKeyboard();
@@ -101,7 +101,7 @@ await runSmoke("editor/emptyMenu", async ({ page }) => {
await page.locator('.source-editor .cm-content').focus(); await page.locator('.source-editor .cm-content').focus();
await page.keyboard.press('Shift+F10'); await page.keyboard.press('Shift+F10');
await menu().waitFor(); await menu().waitFor();
await menu().getByRole('menuitem',{name:'Add external link',exact:true}).click(); await menu().getByRole('menuitem',{name:'Add external link Ctrl+K',exact:true}).click();
assert.equal(await page.getByRole('dialog').count(),0); assert.equal(await page.getByRole('dialog').count(),0);
await page.locator('.source-editor .cm-content').focus(); await page.locator('.source-editor .cm-content').focus();
await page.keyboard.press('Control+a'); await page.keyboard.press('Control+a');
+4 -4
View File
@@ -52,7 +52,7 @@ await runSmoke("editor/markdownMenu", async ({ page }) => {
await page.keyboard.press("Shift+F10"); await page.keyboard.press("Shift+F10");
await menu.waitFor(); await menu.waitFor();
await menu.getByRole("menuitem", { name: "Format", exact: true }).hover(); await menu.getByRole("menuitem", { name: "Format", exact: true }).hover();
await menu.getByRole("menuitem", { name: "Bold", exact: true }).click(); await menu.getByRole("menuitem", { name: "Bold Ctrl+B", exact: true }).click();
await waitForText("**First** paragraph.\n\nSecond paragraph.\n"); await waitForText("**First** paragraph.\n\nSecond paragraph.\n");
await page.keyboard.press("Control+z"); await waitForText(source); await page.keyboard.press("Control+z"); await waitForText(source);
await page.getByRole("tab", { selected: true }).click({ button: "right" }); await page.getByRole("tab", { selected: true }).click({ button: "right" });
@@ -62,7 +62,7 @@ await runSmoke("editor/markdownMenu", async ({ page }) => {
await page.keyboard.press("Control+Shift+ArrowRight"); await page.keyboard.press("Control+Shift+ArrowRight");
await page.keyboard.press("Shift+F10"); await menu.waitFor(); await page.keyboard.press("Shift+F10"); await menu.waitFor();
await menu.getByRole("menuitem", { name: "Format", exact: true }).hover(); await menu.getByRole("menuitem", { name: "Format", exact: true }).hover();
await menu.getByRole("menuitem", { name: "Italic", exact: true }).click(); await menu.getByRole("menuitem", { name: "Italic Ctrl+I", exact: true }).click();
await page.keyboard.press("Control+s"); await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md") === "*First* paragraph.\n\nSecond paragraph.\n"); await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md") === "*First* paragraph.\n\nSecond paragraph.\n");
await page.keyboard.press("Control+z"); await page.keyboard.press("Control+z");
@@ -85,7 +85,7 @@ await runSmoke("editor/markdownMenu", async ({ page }) => {
await page.locator(".cm-line").filter({ hasText: "First paragraph." }).click({ button: "right", position: { x: 12, y: 10 } }); await page.locator(".cm-line").filter({ hasText: "First paragraph." }).click({ button: "right", position: { x: 12, y: 10 } });
await menu.waitFor(); await menu.waitFor();
await menu.getByRole("menuitem", { name: "Format", exact: true }).hover(); await menu.getByRole("menuitem", { name: "Format", exact: true }).hover();
await menu.getByRole("menuitem", { name: "Highlight", exact: true }).click(); await menu.getByRole("menuitem", { name: "Highlight Ctrl+Shift+H", exact: true }).click();
await page.keyboard.press("Control+s"); await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("==First== paragraph.")); await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("==First== paragraph."));
await page.keyboard.press("Control+End"); await page.keyboard.press("Control+End");
@@ -113,7 +113,7 @@ await runSmoke("editor/markdownMenu", async ({ page }) => {
await page.keyboard.press("Control+Home"); await page.keyboard.press("Control+Home");
await page.keyboard.press("Control+Shift+ArrowRight"); await page.keyboard.press("Control+Shift+ArrowRight");
await page.keyboard.press("Shift+F10"); await page.keyboard.press("Shift+F10");
await menu.getByRole("menuitem", { name: "Add external link", exact: true }).click(); await menu.getByRole("menuitem", { name: "Add external link Ctrl+K", exact: true }).click();
// External links insert `[label]()` with the caret in the URL, without a dialog (src/lib/editor/markdownMenu.ts:57, src/lib/editor/linkCommands.ts:3-8). // External links insert `[label]()` with the caret in the URL, without a dialog (src/lib/editor/markdownMenu.ts:57, src/lib/editor/linkCommands.ts:3-8).
assert.equal(await page.getByRole("dialog").count(), 0); assert.equal(await page.getByRole("dialog").count(), 0);
await page.keyboard.type("https://example.com/a"); await page.keyboard.type("https://example.com/a");
+2 -2
View File
@@ -49,7 +49,7 @@ await runSmoke("editor/surfaces", async ({ page }) => {
await text.click({ button: 'right', position: { x: 20, y: 8 } }); await text.click({ button: 'right', position: { x: 20, y: 8 } });
const writer = menu('Markdown text actions'); const writer = menu('Markdown text actions');
assert.deepEqual(await styles(writer), reference); assert.deepEqual(await styles(writer), reference);
for (const name of ['Add link', 'Add external link', 'Format', 'Paragraph', 'Insert', 'Paste Ctrl+V', 'Select all Ctrl+A']) assert.equal(await item(name).count(), 1); for (const name of ['Add link', 'Add external link Ctrl+K', 'Format', 'Paragraph', 'Insert', 'Paste Ctrl+V', 'Select all Ctrl+A']) assert.equal(await item(name).count(), 1);
await item('Corrected').waitFor(); await item('Corrected').waitFor();
assert.equal(await item('Spelling').count(), 0, 'Corrections appear directly in the main menu'); assert.equal(await item('Spelling').count(), 0, 'Corrections appear directly in the main menu');
assert.equal(await writer.locator(':scope > button').first().textContent(), 'Corrected'); assert.equal(await writer.locator(':scope > button').first().textContent(), 'Corrected');
@@ -78,7 +78,7 @@ await runSmoke("editor/surfaces", async ({ page }) => {
await page.locator('.cm-content').click({ button: 'right', position: { x: 600, y: 150 } }); await page.locator('.cm-content').click({ button: 'right', position: { x: 600, y: 150 } });
assert.deepEqual(await styles(writer), reference, 'Blank space uses the same actions'); assert.deepEqual(await styles(writer), reference, 'Blank space uses the same actions');
await item('Format').focus(); await page.keyboard.press('ArrowRight'); await item('Format').focus(); await page.keyboard.press('ArrowRight');
await item('Bold').click(); await item('Bold Ctrl+B').click();
await page.locator('.cm-content').click({ button: 'right', position: { x: 600, y: 150 } }); await page.locator('.cm-content').click({ button: 'right', position: { x: 600, y: 150 } });
await page.getByRole('menuitem', { name: 'Undo Ctrl+Z', exact: true }).click(); await page.getByRole('menuitem', { name: 'Undo Ctrl+Z', exact: true }).click();
assert.equal(await page.locator('.cm-content').textContent().then(s => s.includes('**')), false, 'Undo reverses the menu edit'); assert.equal(await page.locator('.cm-content').textContent().then(s => s.includes('**')), false, 'Undo reverses the menu edit');
@@ -36,7 +36,7 @@ await runSmoke("editor/templatesAndTasks", async ({ page }) => {
const { saveNoteTemplate } = await import('/src/lib/workspace/templates.ts'); const { saveNoteTemplate } = await import('/src/lib/workspace/templates.ts');
await saveNoteTemplate('To Do', '- [ ] \n'.repeat(10)); await saveNoteTemplate('To Do', '- [ ] \n'.repeat(10));
}); });
await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click(); await page.getByRole('button', { name: 'New tab (Ctrl+T)', exact: true }).click();
await page.getByRole('button', { name: 'New note', exact: true }).last().click(); await page.getByRole('button', { name: 'New note', exact: true }).last().click();
await page.getByRole('menuitem', { name: 'To Do', exact: true }).click(); await page.getByRole('menuitem', { name: 'To Do', exact: true }).click();
const title = page.getByRole('textbox', { name: 'Note filename', exact: true }); const title = page.getByRole('textbox', { name: 'Note filename', exact: true });
+73
View File
@@ -0,0 +1,73 @@
// The command palette (Ctrl+Shift+P), the side pane on Ctrl+\, the generated shortcut list in Help, and the Write formatting shortcuts.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const name = "layout/commands";
await runSmoke(name, async ({ page }) => {
const output = await outputDir(name);
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({ root: "C:\\commands", files: { "a.md": "# Note\n\nalpha beta gamma delta epsilon\n" } });
test.files = workspace.files;
return { ...workspace, plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }), spelling_menu_install: () => null };
},
});
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator(".live-writer .cm-content").waitFor();
// The palette lists the app commands with their shortcuts and runs the chosen one.
await page.keyboard.press("Control+Shift+P");
const palette = page.getByRole("dialog", { name: "Commands", exact: true });
await palette.waitFor();
assert.equal(await palette.getByRole("button", { name: "Save the active file Ctrl+S", exact: true }).count(), 1);
assert.match(await palette.locator("footer").textContent(), /\d+ commands/);
await page.screenshot({ path: path.join(output, "palette.png") });
await page.getByRole("textbox", { name: "Find a command", exact: true }).fill("side pane");
assert.deepEqual((await palette.locator(".rs-picker-row").allTextContents()).map(text => text.replace(/\s+/g, " ").trim()), ["Show or hide the side pane Ctrl+\\"]);
assert.equal(await page.locator("aside.left").count(), 1);
await page.keyboard.press("Enter");
await palette.waitFor({ state: "detached" });
await page.locator("aside.left").waitFor({ state: "detached" });
// Ctrl+\ shows the side pane again. Ctrl+B no longer toggles it.
await page.keyboard.press("Control+Backslash");
await page.locator("aside.left").waitFor();
// Write formatting shortcuts make the same edits as the Format menu.
const select = word => page.evaluate(async word => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
const view = EditorView.findFromDOM(document.querySelector(".live-writer .cm-content"));
const from = view.state.doc.toString().indexOf(word);
view.dispatch({ selection: { anchor: from, head: from + word.length } });
view.focus();
}, word);
for (const [word, keys] of [["beta", "Control+b"], ["gamma", "Control+i"], ["delta", "Control+Shift+X"], ["epsilon", "Control+Shift+H"], ["alpha", "Control+k"]]) {
await select(word);
await page.keyboard.press(keys);
}
assert.equal(await page.locator("aside.left").count(), 1, "Ctrl+B in Write does not hide the side pane");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("a.md").includes("==epsilon=="));
assert.equal(await page.evaluate(() => window.__TEST__.files.get("a.md")), "# Note\n\n[alpha]() **beta** *gamma* ~~delta~~ ==epsilon==\n");
// The Format menu shows the shortcuts.
await page.locator(".live-writer .cm-line").filter({ hasText: "beta" }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Format", exact: true }).hover();
for (const label of ["Bold Ctrl+B", "Italic Ctrl+I", "Strikethrough Ctrl+Shift+X", "Highlight Ctrl+Shift+H"]) await page.getByRole("menuitem", { name: label, exact: true }).waitFor();
assert.equal(await page.getByRole("menuitem", { name: "Add external link Ctrl+K", exact: true }).count(), 1);
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
// Help lists every shortcut, open, in groups.
await page.keyboard.press("F1");
const help = page.getByRole("dialog", { name: "Help and about", exact: true });
await help.waitFor();
const list = help.locator("details").filter({ hasText: "Keyboard shortcuts" });
assert.equal(await list.getAttribute("open"), "");
for (const heading of ["General", "Write", "Files"]) await list.getByRole("heading", { name: heading, exact: true }).waitFor();
const rows = await list.locator("dl div").allTextContents();
for (const row of ["Show all commandsCtrl+Shift+P", "Show or hide the side paneCtrl+\\", "BoldCtrl+B", "Delete permanentlyShift+Delete", "Help and aboutF1"]) assert(rows.includes(row), `Help lists ${row}`);
await page.screenshot({ path: path.join(output, "help-shortcuts.png") });
console.log("PASS: the command palette, Ctrl+\\ for the side pane, Write formatting shortcuts, menu shortcut labels, and the Help shortcut list");
});
+1 -1
View File
@@ -69,7 +69,7 @@ await runSmoke("layout/outline", async ({ browser }) => {
await page.getByRole("button", { name: "Hide outline", exact: true }).click(); await page.getByRole("button", { name: "Hide outline", exact: true }).click();
await reopen(); await reopen();
assert.equal(await page.locator(".left, .right").count(), 0); assert.equal(await page.locator(".left, .right").count(), 0);
await page.keyboard.press("Control+b"); await page.keyboard.press("Control+Backslash");
assert.equal(await page.getByRole("button", { name: "Bookmarks", exact: true }).getAttribute("aria-pressed"), "true"); assert.equal(await page.getByRole("button", { name: "Bookmarks", exact: true }).getAttribute("aria-pressed"), "true");
await page.getByRole("button", { name: "Show outline", exact: true }).click(); await page.getByRole("button", { name: "Show outline", exact: true }).click();
assert.deepEqual(await widths(), resized); assert.deepEqual(await widths(), resized);
+1 -1
View File
@@ -144,7 +144,7 @@ await runSmoke("settings/general", async ({ browser }) => {
await help.getByText(`Version ${version}`, { exact: false }).waitFor(); await help.getByText(`Version ${version}`, { exact: false }).waitFor();
await page.screenshot({ path: path.join(output, "help.png") }); await page.screenshot({ path: path.join(output, "help.png") });
await page.keyboard.press("Escape"); await page.keyboard.press("Escape");
await page.keyboard.press("Control+b"); await page.keyboard.press("Control+Backslash");
await showSettings(true); await showSettings(true);
await settings.waitFor(); await settings.waitFor();
await closeSettings(); await closeSettings();
@@ -130,7 +130,7 @@ await runSmoke("tabs/lastTabAndSiteIcons", async ({ browser }) => {
const dimensions = await page.locator(".header").evaluate(header => { const dimensions = await page.locator(".header").evaluate(header => {
const bar = header.querySelector('[role="tablist"]'); const bar = header.querySelector('[role="tablist"]');
const rows = [...bar.querySelectorAll(".tab")]; const rows = [...bar.querySelectorAll(".tab")];
const plus = header.querySelector('[aria-label="New tab (Ctrl T)"]'); const plus = header.querySelector('[aria-label="New tab (Ctrl+T)"]');
const bounds = bar.getBoundingClientRect(); const bounds = bar.getBoundingClientRect();
return { return {
overflow: bar.scrollWidth - bar.clientWidth, overflow: bar.scrollWidth - bar.clientWidth,
@@ -146,10 +146,10 @@ await runSmoke("tabs/lastTabAndSiteIcons", async ({ browser }) => {
assert.ok(dimensions.tabWidth >= 96, JSON.stringify(dimensions)); assert.ok(dimensions.tabWidth >= 96, JSON.stringify(dimensions));
assert.ok(dimensions.gap >= 0 && dimensions.gap <= 8, JSON.stringify(dimensions)); assert.ok(dimensions.gap >= 0 && dimensions.gap <= 8, JSON.stringify(dimensions));
assert.ok(dimensions.fits); assert.ok(dimensions.fits);
const plus = page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }); const plus = page.getByRole("button", { name: "New tab (Ctrl+T)", exact: true });
await plus.evaluate(button => button.blur()); await plus.evaluate(button => button.blur());
await plus.focus(); await plus.focus();
await page.locator('[role="tooltip"]:popover-open').filter({ hasText: "New tab (Ctrl T)" }).waitFor(); await page.locator('[role="tooltip"]:popover-open').filter({ hasText: "New tab (Ctrl+T)" }).waitFor();
await page.keyboard.press("Escape"); await page.keyboard.press("Escape");
await page.locator(".header").screenshot({ path: path.join(output, `compact-tabs-${width}-${theme}.png`) }); await page.locator(".header").screenshot({ path: path.join(output, `compact-tabs-${width}-${theme}.png`) });
} }
+1 -1
View File
@@ -109,7 +109,7 @@ await runSmoke("tabs/menus", async ({ page }) => {
await tab("b.md").waitFor({ state: "detached" }); await tab("b.md").waitFor({ state: "detached" });
// Closing the last tab leaves an empty tab (src/lib/layout/Workbench.svelte:291), so the plus button adds a second one. // Closing the last tab leaves an empty tab (src/lib/layout/Workbench.svelte:291), so the plus button adds a second one.
await tab("New tab").waitFor(); await tab("New tab").waitFor();
await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click(); await page.getByRole("button", { name: "New tab (Ctrl+T)", exact: true }).click();
const added = page.getByRole("tab", { name: "New tab", exact: true, selected: true }); const added = page.getByRole("tab", { name: "New tab", exact: true, selected: true });
await page.waitForFunction(() => document.querySelectorAll('[role="tab"][data-path^="empty:"]').length === 2); await page.waitForFunction(() => document.querySelectorAll('[role="tab"][data-path^="empty:"]').length === 2);
await added.click({ button: "right" }); await added.click({ button: "right" });
+1 -1
View File
@@ -71,7 +71,7 @@ await runSmoke("tabs/order", async ({ page }) => {
assert.equal(await page.getByRole("menu", { name: "Tab actions" }).count(), 0); assert.equal(await page.getByRole("menu", { name: "Tab actions" }).count(), 0);
console.log("PASS: pointer moves, cancellation, keyboard moves, and tab menus"); console.log("PASS: pointer moves, cancellation, keyboard moves, and tab menus");
await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click(); await page.getByRole("button", { name: "New tab (Ctrl+T)", exact: true }).click();
await tab("New tab").press("Alt+Shift+Home"); await tab("New tab").press("Alt+Shift+Home");
assert.match((await order())[0], /^empty:/); assert.match((await order())[0], /^empty:/);
await page.getByRole("button", { name: "Close New tab", exact: true }).click(); await page.getByRole("button", { name: "Close New tab", exact: true }).click();
+1 -1
View File
@@ -90,7 +90,7 @@ await runSmoke("tabs/ribbonDrop", async ({ browser }) => {
return page.locator(".header").evaluate((header, kind) => { return page.locator(".header").evaluate((header, kind) => {
const bounds = header.getBoundingClientRect(); const bounds = header.getBoundingClientRect();
const bar = header.querySelector('[role="tablist"]').getBoundingClientRect(); const bar = header.querySelector('[role="tablist"]').getBoundingClientRect();
const plus = header.querySelector('[aria-label="New tab (Ctrl T)"]').getBoundingClientRect(); const plus = header.querySelector('[aria-label="New tab (Ctrl+T)"]').getBoundingClientRect();
const first = header.querySelector('.tab').getBoundingClientRect(); const first = header.querySelector('.tab').getBoundingClientRect();
if (kind === "near") return { x: first.left + first.width / 2, y: bounds.bottom + 18 }; if (kind === "near") return { x: first.left + first.width / 2, y: bounds.bottom + 18 };
if (kind === "outside") return { x: first.left + first.width / 2, y: bounds.bottom + 80 }; if (kind === "outside") return { x: first.left + first.width / 2, y: bounds.bottom + 80 };
+2 -2
View File
@@ -43,7 +43,7 @@ await runSmoke('tree/navigation', async ({ browser }) => {
const welcome = page.locator('.welcome-actions'); const welcome = page.locator('.welcome-actions');
await welcome.waitFor(); await welcome.waitFor();
await welcome.getByRole('button', { name: 'Open browser', exact: true }).waitFor(); await welcome.getByRole('button', { name: 'Open browser', exact: true }).waitFor();
assert.deepEqual(await welcome.locator('button').allTextContents().then(values => values.map(value => value.replace(/Ctrl [NOP]/g, '').trim())), ['New file', 'New note', 'Find file', 'Open folder', 'Open browser']); assert.deepEqual(await welcome.locator('button').allTextContents().then(values => values.map(value => value.replace(/Ctrl\+[NOP]/g, '').trim())), ['New file', 'New note', 'Find file', 'Open folder', 'Open browser']);
const firstRow = welcome.locator('.welcome-row').first(); const firstRow = welcome.locator('.welcome-row').first();
assert.equal(await firstRow.locator('button').count(), 3); assert.equal(await firstRow.locator('button').count(), 3);
const tops = await firstRow.locator('button').evaluateAll(nodes => nodes.map(node => node.getBoundingClientRect().top)); const tops = await firstRow.locator('button').evaluateAll(nodes => nodes.map(node => node.getBoundingClientRect().top));
@@ -103,7 +103,7 @@ await runSmoke('tree/navigation', async ({ browser }) => {
await emptyPage.goto(smokeUrl); await emptyPage.goto(smokeUrl);
await emptyPage.locator('.welcome-actions').waitFor(); await emptyPage.locator('.welcome-actions').waitFor();
await emptyPage.locator('.welcome-actions').getByRole('button', { name: 'Open browser', exact: true }).waitFor(); await emptyPage.locator('.welcome-actions').getByRole('button', { name: 'Open browser', exact: true }).waitFor();
assert.deepEqual(await emptyPage.locator('.welcome-actions button').allTextContents().then(values => values.map(value => value.replace(/Ctrl O/g, '').trim())), ['Open folder', 'Open browser']); assert.deepEqual(await emptyPage.locator('.welcome-actions button').allTextContents().then(values => values.map(value => value.replace(/Ctrl\+O/g, '').trim())), ['Open folder', 'Open browser']);
await emptyPage.screenshot({ path: path.join(output, 'splash-no-workspace.png') }); await emptyPage.screenshot({ path: path.join(output, 'splash-no-workspace.png') });
await emptyPage.close(); await emptyPage.close();
const errors = [...page.errors, ...emptyPage.errors]; const errors = [...page.errors, ...emptyPage.errors];
+1 -1
View File
@@ -159,7 +159,7 @@ await runSmoke('tree/renameUndo', async ({ browser }) => {
assert.equal(await detached.getByRole('button', { name: 'Show outline', exact: true }).count(), 0); assert.equal(await detached.getByRole('button', { name: 'Show outline', exact: true }).count(), 0);
assert.equal(await detached.evaluate(() => localStorage.getItem('runestone.workbenchLayout')), saved); assert.equal(await detached.evaluate(() => localStorage.getItem('runestone.workbenchLayout')), saved);
assert.equal(await detached.getByRole('button', { name: 'Files', exact: true }).count(), 0); assert.equal(await detached.getByRole('button', { name: 'Files', exact: true }).count(), 0);
await detached.keyboard.press('Control+b'); await detached.keyboard.press('Control+Backslash');
await detached.keyboard.press('Control+Shift+f'); await detached.keyboard.press('Control+Shift+f');
assert.equal(await detached.locator('aside.left,aside.right,.plugin-ribbon,.gutter-v').count(), 0); assert.equal(await detached.locator('aside.left,aside.right,.plugin-ribbon,.gutter-v').count(), 0);
await detached.keyboard.press('Escape'); await detached.keyboard.press('Escape');
@@ -12,12 +12,12 @@ await runSmoke("workspace/dialogDismissal", async ({ page }) => {
}); });
await page.goto(smokeUrl); await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').waitFor(); await page.locator('[data-tree-rel="a.md"]').waitFor();
await page.getByRole("button", { name: "New file Ctrl N" }).click(); await page.getByRole("button", { name: "New file Ctrl+N" }).click();
await page.getByRole("textbox", { name: "New file path relative to the workspace" }).waitFor(); await page.getByRole("textbox", { name: "New file path relative to the workspace" }).waitFor();
await page.mouse.click(5, 700); await page.mouse.click(5, 700);
assert.equal(await page.locator("dialog").count(), 0, "Outside click dismisses new-file dialog"); assert.equal(await page.locator("dialog").count(), 0, "Outside click dismisses new-file dialog");
// The empty tab's button is now "Find file" (src/lib/layout/EditorPane.svelte:167). // The empty tab's button is now "Find file" (src/lib/layout/EditorPane.svelte:167).
await page.getByRole("button", { name: "Find file Ctrl P" }).click(); await page.getByRole("button", { name: "Find file Ctrl+P" }).click();
await page.getByRole("textbox", { name: "Find a file" }).click(); await page.getByRole("textbox", { name: "Find a file" }).click();
assert.equal(await page.locator("dialog").count(), 1, "Inside click keeps file search open"); assert.equal(await page.locator("dialog").count(), 1, "Inside click keeps file search open");
await page.mouse.click(5, 700); await page.mouse.click(5, 700);
@@ -128,7 +128,7 @@ await runSmoke("workspace/openAndCreate", async ({ page }) => {
await page.evaluate(() => window.__TEST__.clear()); await page.evaluate(() => window.__TEST__.clear());
await trigger.click(); await trigger.click();
await menu.getByText("No recent workspaces yet.").waitFor(); await menu.getByText("No recent workspaces yet.").waitFor();
await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click(); await page.getByRole("button", { name: "New tab (Ctrl+T)", exact: true }).click();
await menu.waitFor({ state: "hidden" }); await menu.waitFor({ state: "hidden" });
console.log("Workspace smoke passed: history, opening and creating in new windows, original workspace preserved, cancellation, errors, keyboard and empty state."); console.log("Workspace smoke passed: history, opening and creating in new windows, original workspace preserved, cancellation, errors, keyboard and empty state.");
}, { viewport: { width: 1100, height: 800 }, timeout: 30000 }); }, { viewport: { width: 1100, height: 800 }, timeout: 30000 });
@@ -25,7 +25,7 @@ await runSmoke("workspace/saveAsTemplate", async ({ page }) => {
await page.getByRole("textbox", { name: "Template name" }).fill("Meeting"); await page.getByRole("textbox", { name: "Template name" }).fill("Meeting");
await page.getByRole("button", { name: "Continue", exact: true }).click(); await page.getByRole("button", { name: "Continue", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.files.has(".runestone/templates/Meeting.md")); await page.waitForFunction(() => window.__TEST__.files.has(".runestone/templates/Meeting.md"));
await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click(); await page.getByRole("button", { name: "New tab (Ctrl+T)", exact: true }).click();
// The file tree toolbar also has a "New note" button (src/lib/layout/FileTree.svelte:886); this one is in the empty tab (src/lib/layout/EditorPane.svelte:166). // The file tree toolbar also has a "New note" button (src/lib/layout/FileTree.svelte:886); this one is in the empty tab (src/lib/layout/EditorPane.svelte:166).
await page.getByRole("main").getByRole("button", { name: "New note", exact: true }).click(); await page.getByRole("main").getByRole("button", { name: "New note", exact: true }).click();
await menu("Meeting").click(); await menu("Meeting").click();
+17 -4
View File
@@ -1,13 +1,15 @@
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import test from "node:test"; import test from "node:test";
import { preferenceKeys, workbenchCommand } from "../../../src/lib/layout/workbenchKeys.ts"; import { COMMAND_LABELS, commandShortcut, preferenceKeys, workbenchCommand, workbenchKeys } from "../../../src/lib/layout/workbenchKeys.ts";
import { shortcutLabel } from "../../../src/lib/ui/shortcuts.ts";
const press = (key: string, modifiers: { ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean } = {}) => const press = (key: string, modifiers: { ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean } = {}, code?: string) =>
({ key, ctrlKey: !!modifiers.ctrl, metaKey: !!modifiers.meta, shiftKey: !!modifiers.shift, altKey: !!modifiers.alt, target: null }); ({ key, code, ctrlKey: !!modifiers.ctrl, metaKey: !!modifiers.meta, shiftKey: !!modifiers.shift, altKey: !!modifiers.alt, target: null });
test("main shortcuts accept Ctrl and Cmd and keep their shift rules", () => { test("main shortcuts accept Ctrl and Cmd and keep their shift rules", () => {
assert.equal(workbenchCommand(press("p", { ctrl: true })), "quick-open"); assert.equal(workbenchCommand(press("p", { ctrl: true })), "quick-open");
assert.equal(workbenchCommand(press("P", { meta: true, shift: true })), "quick-open"); assert.equal(workbenchCommand(press("P", { meta: true, shift: true })), "command-palette");
assert.equal(workbenchCommand(press("P", { ctrl: true, shift: true })), "command-palette");
assert.equal(workbenchCommand(press("t", { ctrl: true })), "new-tab"); assert.equal(workbenchCommand(press("t", { ctrl: true })), "new-tab");
assert.equal(workbenchCommand(press("T", { ctrl: true, shift: true })), null); assert.equal(workbenchCommand(press("T", { ctrl: true, shift: true })), null);
assert.equal(workbenchCommand(press("F", { ctrl: true, shift: true })), "search-workspace"); assert.equal(workbenchCommand(press("F", { ctrl: true, shift: true })), "search-workspace");
@@ -15,6 +17,17 @@ test("main shortcuts accept Ctrl and Cmd and keep their shift rules", () => {
assert.equal(workbenchCommand(press("`", { ctrl: true })), "toggle-terminal"); assert.equal(workbenchCommand(press("`", { ctrl: true })), "toggle-terminal");
}); });
test("Ctrl+B belongs to the editor, and Ctrl+\\ toggles the side pane on every layout", () => {
assert.equal(workbenchCommand(press("b", { ctrl: true })), null);
assert.equal(workbenchCommand(press("\\", { ctrl: true }, "Backslash")), "toggle-sidebar");
assert.equal(workbenchCommand(press("#", { ctrl: true }, "Backslash")), "toggle-sidebar", "The physical key matches on other layouts");
});
test("Each command has a label, and its shortcut label comes from the table", () => {
for (const binding of [...workbenchKeys, ...preferenceKeys]) assert.ok(COMMAND_LABELS[binding.command], binding.command);
assert.equal(commandShortcut("save"), shortcutLabel({ key: "s", mod: true }));
});
test("F2 renames outside text fields only", () => { test("F2 renames outside text fields only", () => {
assert.equal(workbenchCommand(press("F2")), "rename"); assert.equal(workbenchCommand(press("F2")), "rename");
assert.equal(workbenchCommand(press("F2", { alt: true })), null); assert.equal(workbenchCommand(press("F2", { alt: true })), null);
+22
View File
@@ -0,0 +1,22 @@
// Platform shortcut labels (src/lib/ui/shortcuts.ts).
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { keys, shortcutLabel } from '../../../src/lib/ui/shortcuts.ts';
test('Windows and Linux labels use Ctrl, Alt, and Shift with plus signs', () => {
assert.equal(keys('Mod+Shift+P', false), 'Ctrl+Shift+P');
assert.equal(keys('Mod+\\', false), 'Ctrl+\\');
assert.equal(keys('Mod+,', false), 'Ctrl+,');
assert.equal(keys('F1', false), 'F1');
assert.equal(keys('Shift+Delete', false), 'Shift+Delete');
assert.equal(shortcutLabel({ key: 'Tab', ctrl: true, shift: true }, false), 'Ctrl+Shift+Tab');
assert.equal(shortcutLabel({ key: 'z', mod: true, alt: true, shift: true }, false), 'Ctrl+Alt+Shift+Z');
});
test('macOS labels use the symbols in the Apple order', () => {
assert.equal(keys('Mod+Shift+P', true), '⇧⌘P');
assert.equal(keys('Mod+B', true), '⌘B');
assert.equal(shortcutLabel({ key: 'Tab', ctrl: true, shift: true }, true), '⌃⇧⇥');
assert.equal(shortcutLabel({ key: 'z', mod: true, alt: true, shift: true }, true), '⌥⇧⌘Z');
assert.equal(keys('Escape', true), '⎋');
});