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:
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import { keys } from '$lib/ui/shortcuts';
|
||||
import { onMount, untrack, tick } from 'svelte';
|
||||
import IconButton from '$lib/ui/IconButton.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 address'), icon: 'copy', disabled: !context.srcURL, run: action('copyImageAddress') }, { separator: true });
|
||||
if (context.isEditable) items.push(
|
||||
{ label: $t('Undo'), icon: 'undo', shortcut: 'Ctrl+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('Cut'), icon: 'cut', shortcut: 'Ctrl+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') });
|
||||
{ label: $t('Undo'), icon: 'undo', shortcut: keys('Mod+Z'), disabled: !context.editFlags.canUndo, run: edit('undo') },
|
||||
{ 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: keys('Mod+X'), disabled: !context.editFlags.canCut, run: edit('cut') });
|
||||
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(
|
||||
{ label: $t('Paste'), icon: 'paste', shortcut: 'Ctrl+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('Select all'), icon: 'task', shortcut: 'Ctrl+A', run: edit('selectAll') }, { separator: true });
|
||||
{ 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: keys('Mod+Shift+V'), disabled: !context.editFlags.canPaste, run: edit('pasteAndMatchStyle') },
|
||||
{ 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') },
|
||||
{ label: $t('Forward'), icon: 'arrow-right', disabled: !current?.canForward, run: () => void send('forward') },
|
||||
{ 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 menu = showActionMenu({ x: rect.left + imageBox.x + context.x, y: rect.top + imageBox.y + context.y,
|
||||
items, label: $t('Browser page actions') });
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { tr } from "../i18n/index.ts";
|
||||
import { keys } from '../ui/shortcuts.ts';
|
||||
import { mount, unmount } from 'svelte';
|
||||
import { get } from 'svelte/store';
|
||||
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 down"), icon: 'split-down', disabled: !ready, run: () => split('down') },
|
||||
{ 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("Bookmark"), icon: 'bookmark', disabled: !web, run: () => run('bookmark') },
|
||||
];
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
import { languageSupport } from "./codeLanguages";
|
||||
import { indentListItem, outdentListItem } from "./markdownLists";
|
||||
import { insertIndent, sourceChrome, sourceEditing } from "./sourceView";
|
||||
import { formatKeymap } from "./formatKeys";
|
||||
import "./headingFolding.css";
|
||||
|
||||
type Mode = "write" | "source";
|
||||
@@ -155,7 +156,7 @@
|
||||
return [
|
||||
headingFolding,
|
||||
tableNavigation,
|
||||
keymap.of([{ key: "Escape", run: view => {
|
||||
keymap.of([...formatKeymap, { key: "Escape", run: view => {
|
||||
if (!view.state.field(imageSource)) return false;
|
||||
view.dispatch({ effects: editImageSource.of(null) }); return true;
|
||||
} }, ...lists, indentWithTab]),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { tr } from '../i18n/index.ts';
|
||||
import { keys } from "../ui/shortcuts";
|
||||
import { EditorSelection } from "@codemirror/state";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
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: [
|
||||
...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 },
|
||||
...clipboardItems({
|
||||
selected: !!selected, cut: () => void clipboard("cut"), copy: () => void clipboard("copy"), paste: () => void clipboard("paste"),
|
||||
|
||||
@@ -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 },
|
||||
];
|
||||
@@ -1,4 +1,8 @@
|
||||
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 { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet } from "@codemirror/view";
|
||||
import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language";
|
||||
@@ -317,7 +321,7 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
if (!match) return;
|
||||
replace(node.from, node.from + 1);
|
||||
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;
|
||||
}
|
||||
} });
|
||||
@@ -339,7 +343,7 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
const labelStart = from + 2 + (separator < 0 ? 0 : separator + 1);
|
||||
replace(from, labelStart);
|
||||
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)) {
|
||||
if (!selected(link.from, link.to) || hidden(link.from, link.to)) continue;
|
||||
|
||||
@@ -10,6 +10,8 @@ import { documentLinkAt } from "./documentLinks";
|
||||
import { linkMenuItems, type DocumentLinkActions } from "./linkMenu";
|
||||
import { htmlToMarkdown } from "../workspace/htmlToMarkdown";
|
||||
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";
|
||||
|
||||
export type MarkdownMenuEditor = {
|
||||
@@ -89,7 +91,7 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
|
||||
}), { separator: true as const }] : []),
|
||||
...(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 external link"), icon: "external", run: () => link(true) },
|
||||
{ label: tr("Add external link"), icon: "external", shortcut: keys(LINK_KEY), run: () => link(true) },
|
||||
{ separator: true },
|
||||
searchItem(text, actions.onSearch),
|
||||
{ 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]) => [
|
||||
...(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: [
|
||||
paragraph(tr("Bullet list"), "bullet", "bullet"), paragraph(tr("Numbered list"), "number", "number"), paragraph(tr("Task list"), "task", "task"),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { tr } from '../i18n/index.ts';
|
||||
import { keys } from "../ui/shortcuts";
|
||||
import type { ActionMenuItem } from "../ui/actionMenu";
|
||||
import { showActionMenu, type MenuHandle } from "../ui/managedActionMenu";
|
||||
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;
|
||||
const items: ActionMenuItem[] = [];
|
||||
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),
|
||||
);
|
||||
if (anchor) {
|
||||
|
||||
@@ -275,7 +275,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
||||
next.scrollIntoView({ block: "nearest", inline: "nearest" });
|
||||
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) && (event.key === "Home" || event.key === "End")) {
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { tr } from '../i18n/index.ts';
|
||||
import { keys } from "../ui/shortcuts";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { isolateHistory, redo, undo } from "@codemirror/commands";
|
||||
import type { Editor } from "@tiptap/core";
|
||||
@@ -87,7 +88,7 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
|
||||
}
|
||||
} catch {
|
||||
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) {
|
||||
|
||||
+60
-41
@@ -192,10 +192,10 @@ export const messageRows: [string, string, string, string][] = [
|
||||
"仅保存已更改的文件。"
|
||||
],
|
||||
[
|
||||
"Auto-save is off. Use Ctrl+S to save your changes.",
|
||||
"L’enregistrement automatique est désactivé. Utilisez Ctrl+S pour enregistrer.",
|
||||
"自動保存はオフです。Ctrl+Sで変更を保存してください。",
|
||||
"自动保存已关闭。请使用 Ctrl+S 保存更改。"
|
||||
"Auto-save is off. Use {shortcut} to save your changes.",
|
||||
"L’enregistrement automatique est désactivé. Utilisez {shortcut} pour enregistrer.",
|
||||
"自動保存はオフです。{shortcut}で変更を保存してください。",
|
||||
"自动保存已关闭。请使用 {shortcut} 保存更改。"
|
||||
],
|
||||
[
|
||||
"Disk conflicts keep your edits for review.",
|
||||
@@ -594,10 +594,10 @@ export const messageRows: [string, string, string, string][] = [
|
||||
"大纲"
|
||||
],
|
||||
[
|
||||
"Find in outline (Ctrl+F)",
|
||||
"Rechercher dans le plan (Ctrl+F)",
|
||||
"アウトライン内を検索 (Ctrl+F)",
|
||||
"在大纲中查找 (Ctrl+F)"
|
||||
"Find in outline ({shortcut})",
|
||||
"Rechercher dans le plan ({shortcut})",
|
||||
"アウトライン内を検索 ({shortcut})",
|
||||
"在大纲中查找 ({shortcut})"
|
||||
],
|
||||
[
|
||||
"Find in outline",
|
||||
@@ -888,10 +888,10 @@ export const messageRows: [string, string, string, string][] = [
|
||||
"添加书签"
|
||||
],
|
||||
[
|
||||
"New tab (Ctrl T)",
|
||||
"Nouvel onglet (Ctrl T)",
|
||||
"新しいタブ (Ctrl T)",
|
||||
"新建标签页 (Ctrl T)"
|
||||
"New tab ({shortcut})",
|
||||
"Nouvel onglet ({shortcut})",
|
||||
"新しいタブ ({shortcut})",
|
||||
"新建标签页 ({shortcut})"
|
||||
],
|
||||
[
|
||||
"New browser tab",
|
||||
@@ -948,16 +948,16 @@ export const messageRows: [string, string, string, string][] = [
|
||||
"无工作区"
|
||||
],
|
||||
[
|
||||
"Help and about (F1)",
|
||||
"Aide et à propos (F1)",
|
||||
"ヘルプと情報 (F1)",
|
||||
"帮助与关于 (F1)"
|
||||
"Help and about ({shortcut})",
|
||||
"Aide et à propos ({shortcut})",
|
||||
"ヘルプと情報 ({shortcut})",
|
||||
"帮助与关于 ({shortcut})"
|
||||
],
|
||||
[
|
||||
"Settings (Ctrl+,)",
|
||||
"Paramètres (Ctrl+,)",
|
||||
"設定 (Ctrl+,)",
|
||||
"设置 (Ctrl+,)"
|
||||
"Settings ({shortcut})",
|
||||
"Paramètres ({shortcut})",
|
||||
"設定 ({shortcut})",
|
||||
"设置 ({shortcut})"
|
||||
],
|
||||
[
|
||||
"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.",
|
||||
"Utilisez le + près des onglets pour créer un onglet. Ctrl+N crée un fichier et Ctrl+P en recherche un.",
|
||||
"タブの横の+で新しいタブを開きます。Ctrl+Nでファイルを作成し、Ctrl+Pで検索します。",
|
||||
"点击标签页旁的 + 新建标签页。按 Ctrl+N 创建文件,或按 Ctrl+P 查找文件。"
|
||||
"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. {newFile} crée un fichier et {quickOpen} en recherche un.",
|
||||
"タブの横の+で新しいタブを開きます。{newFile}でファイルを作成し、{quickOpen}で検索します。",
|
||||
"点击标签页旁的 + 新建标签页。按 {newFile} 创建文件,或按 {quickOpen} 查找文件。"
|
||||
],
|
||||
[
|
||||
"Press Ctrl+E 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.",
|
||||
"Ctrl+Eで文章編集とソース編集を切り替えます。ターミナルボタンでファイルと並べてシェルを操作できます。",
|
||||
"按 Ctrl+E 切换写作和源码编辑。使用终端按钮在文件旁操作命令行。"
|
||||
"Press {shortcut} to switch between writing and source editing. Use the terminal button to work with a shell beside your files.",
|
||||
"{shortcut} alterne entre rédaction et code source. Le bouton de terminal ouvre un shell à côté de vos fichiers.",
|
||||
"{shortcut}で文章編集とソース編集を切り替えます。ターミナルボタンでファイルと並べてシェルを操作できます。",
|
||||
"按 {shortcut} 切换写作和源码编辑。使用终端按钮在文件旁操作命令行。"
|
||||
],
|
||||
[
|
||||
"Auto-save saves changed files at the interval in Settings → General. Ctrl+S 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.",
|
||||
"自動保存は「設定 → 一般」の間隔で変更を保存します。Ctrl+Sで現在のファイルをすぐに保存します。",
|
||||
"自动保存按照“设置 → 常规”中的间隔保存更改。Ctrl+S 可立即保存当前文件。"
|
||||
"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. {shortcut} enregistre immédiatement le fichier actif.",
|
||||
"自動保存は「設定 → 一般」の間隔で変更を保存します。{shortcut}で現在のファイルをすぐに保存します。",
|
||||
"自动保存按照“设置 → 常规”中的间隔保存更改。{shortcut} 可立即保存当前文件。"
|
||||
],
|
||||
[
|
||||
"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 浏览器"
|
||||
],
|
||||
[
|
||||
"New browser tab (Ctrl T)",
|
||||
"Nouvel onglet du navigateur (Ctrl T)",
|
||||
"新しいブラウザータブ (Ctrl T)",
|
||||
"新建浏览器标签页 (Ctrl T)"
|
||||
"New browser tab ({shortcut})",
|
||||
"Nouvel onglet du navigateur ({shortcut})",
|
||||
"新しいブラウザータブ ({shortcut})",
|
||||
"新建浏览器标签页 ({shortcut})"
|
||||
],
|
||||
[
|
||||
"Open link in new tab",
|
||||
@@ -2700,10 +2700,10 @@ export const messageRows: [string, string, string, string][] = [
|
||||
"第一行是 Markdown 表头"
|
||||
],
|
||||
[
|
||||
"Clipboard unavailable. Use Ctrl+C to copy.",
|
||||
"Presse-papiers indisponible. Utilisez Ctrl+C pour copier.",
|
||||
"クリップボードを使用できません。Ctrl+Cでコピーしてください。",
|
||||
"剪贴板不可用。请使用 Ctrl+C 复制。"
|
||||
"Clipboard unavailable. Use {shortcut} to copy.",
|
||||
"Presse-papiers indisponible. Utilisez {shortcut} pour copier.",
|
||||
"クリップボードを使用できません。{shortcut}でコピーしてください。",
|
||||
"剪贴板不可用。请使用 {shortcut} 复制。"
|
||||
],
|
||||
[
|
||||
"Open plugins folder",
|
||||
@@ -3491,7 +3491,26 @@ export const messageRows: [string, string, string, string][] = [
|
||||
["Text", "Texte", "テキスト", "文本"],
|
||||
["Accents", "Accents", "アクセント", "强调色"],
|
||||
["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>> = {
|
||||
fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import { keys } from "$lib/ui/shortcuts";
|
||||
import { tick, untrack } from "svelte";
|
||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import { pluginHost } from "$lib/plugins/registry";
|
||||
@@ -81,7 +82,7 @@
|
||||
<TabBar {tabs} activePath={active} onSelect={select} onClose={close} onCloseTabs={close}
|
||||
onMove={move} onPin={pinPluginEditor} fileActions={() => []} tabActions={actions}
|
||||
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>
|
||||
<WindowControls onError={message => error = message} />
|
||||
</header>
|
||||
|
||||
@@ -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>
|
||||
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import { commandShortcut } from "./workbenchKeys";
|
||||
import { pluginHost } from "$lib/plugins/registry";
|
||||
import type { GitLineInfo } from "$lib/git/contracts";
|
||||
import FindPanel from "$lib/editor/FindPanel.svelte";
|
||||
@@ -158,13 +159,13 @@
|
||||
<div class="welcome-actions">
|
||||
{#if hasWorkspace}
|
||||
<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}
|
||||
<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>
|
||||
{/if}
|
||||
<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}
|
||||
</div>
|
||||
</div>
|
||||
@@ -200,7 +201,7 @@
|
||||
{ value: "Ide", label: $t("IDE"), icon: "code" },
|
||||
{ value: "Writing", label: $t("Writer"), icon: "text" },
|
||||
]}
|
||||
shortcut=" (Ctrl E)"
|
||||
shortcut={` (${commandShortcut("toggle-layout")})`}
|
||||
onchange={(mode) => { if (mode !== chrome) onToggleChrome?.(); }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
import FileTree from "./FileTree.svelte";
|
||||
import SearchPane from "./SearchPane.svelte";
|
||||
import BookmarksPane from "./BookmarksPane.svelte";
|
||||
import { commandShortcut } from "./workbenchKeys";
|
||||
|
||||
type Props = {
|
||||
workspace: WorkspaceInfo | null;
|
||||
@@ -74,8 +75,8 @@
|
||||
<span class="ws">{workspace ? workspace.name : $t("No workspace")}</span>
|
||||
</div>
|
||||
<div class="footer-actions">
|
||||
<IconButton icon="help" label={$t("Help and about (F1)")} onclick={onHelp} />
|
||||
<IconButton icon="settings" label={$t("Settings (Ctrl+,)")} onclick={onSettings} />
|
||||
<IconButton icon="help" label={$t("Help and about ({shortcut})", { shortcut: commandShortcut("help") })} onclick={onHelp} />
|
||||
<IconButton icon="settings" label={$t("Settings ({shortcut})", { shortcut: commandShortcut("settings") })} onclick={onSettings} />
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import { keys } from "$lib/ui/shortcuts";
|
||||
import { tick } from "svelte";
|
||||
import type { OutlineItem } from "$lib/workspace/outline";
|
||||
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}>
|
||||
<div class="pane-label">
|
||||
<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>
|
||||
{#if searchOpen}
|
||||
<div class="rs-find-bar outline-search">
|
||||
|
||||
@@ -14,6 +14,15 @@
|
||||
import { DEFAULT_SETTINGS, MIN_AUTOSAVE_SECONDS, MAX_AUTOSAVE_SECONDS, validAutosaveSeconds, type AppSettings } from "$lib/workspace/settings";
|
||||
import { license } from "../../../package.json";
|
||||
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 }: {
|
||||
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>
|
||||
</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>
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
<p class="saved" role="status">{message}</p>
|
||||
@@ -166,9 +175,14 @@
|
||||
{: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="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="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="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><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. {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 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>
|
||||
<p class="about-note">{$t("RuneStone is under development. Maintained by kwyvern-gh.")}</p>
|
||||
{/if}
|
||||
@@ -233,6 +247,7 @@
|
||||
.help-copy p:first-child { margin-top: 0; }
|
||||
dl div { display: flex; justify-content: space-between; gap: 12px; margin: 10px 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); }
|
||||
.about-note { text-align: center; margin: 20px 0 0; }
|
||||
@media (max-width: 660px) {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { t } from "$lib/i18n";
|
||||
import TerminalSlot from "$lib/plugins/TerminalSlot.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 { 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";
|
||||
@@ -26,6 +26,7 @@
|
||||
import { requestText } from "$lib/workspace/dialogs.svelte";
|
||||
import TextDialog from "./TextDialog.svelte";
|
||||
import QuickOpen from "./QuickOpen.svelte";
|
||||
import CommandPalette, { type PaletteCommand } from "./CommandPalette.svelte";
|
||||
import TemplateManager from "./TemplateManager.svelte";
|
||||
import WorkspacePicker from "./WorkspacePicker.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 { DEFAULT_WORKBENCH_LAYOUT, WORKBENCH_LAYOUT_KEY, parseWorkbenchLayout, saveWorkbenchLayout, type WorkbenchLayout } from "$lib/workspace/workbenchLayout";
|
||||
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 WorkbenchHeader from "./WorkbenchHeader.svelte";
|
||||
import PluginRibbon from "./PluginRibbon.svelte";
|
||||
@@ -147,6 +148,19 @@
|
||||
let documentPanes = $state(initialDocumentPanes());
|
||||
const reading = $derived(documentPanes.panes.find(pane => pane.id === documentPanes.active)?.reading ?? 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 terminalStarted = $state(false);
|
||||
let terminalMaximized = $state(false);
|
||||
@@ -858,6 +872,7 @@
|
||||
selectWorkingTab(workingTabs[next].relPath);
|
||||
return true;
|
||||
}
|
||||
case "command-palette": palette = true; return true;
|
||||
case "settings": void openSettings(); return true;
|
||||
case "help": preferences = "help"; 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} />
|
||||
{#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 palette}<CommandPalette commands={paletteCommands()} onClose={() => palette = false} />{/if}
|
||||
{#if templateManager && workspace}<TemplateManager {session} onClose={() => templateManager = false}
|
||||
onEdit={(entry) => { templateManager = false; void openFile(entry, undefined, "new"); }} />{/if}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
import PluginAccessMenu from "$lib/plugins/PluginAccessMenu.svelte";
|
||||
import { openPluginView, pluginSidebar } from "$lib/plugins/external";
|
||||
import TabBar from "./TabBar.svelte";
|
||||
import { commandShortcut } from "./workbenchKeys";
|
||||
|
||||
type LeftView = "files" | "search" | "bookmarks";
|
||||
type Props = {
|
||||
@@ -53,7 +54,7 @@
|
||||
</div>
|
||||
<div class="header-center" data-tauri-drag-region>
|
||||
<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}
|
||||
</div>
|
||||
<div class="header-right" data-tauri-drag-region>
|
||||
|
||||
@@ -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. */
|
||||
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";
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* `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.
|
||||
*/
|
||||
export type WorkbenchKey = {
|
||||
key: string;
|
||||
code?: string;
|
||||
command: WorkbenchCommand;
|
||||
mod?: boolean;
|
||||
ctrl?: boolean;
|
||||
@@ -20,6 +25,7 @@ export type WorkbenchKey = {
|
||||
|
||||
/** Shortcuts of the main window. The first match wins. */
|
||||
export const workbenchKeys: WorkbenchKey[] = [
|
||||
{ key: "p", mod: true, shift: true, command: "command-palette" },
|
||||
{ key: "p", mod: true, command: "quick-open" },
|
||||
{ key: "t", mod: true, shift: false, alt: false, command: "new-tab" },
|
||||
{ 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: "`", mod: true, command: "toggle-terminal" },
|
||||
{ 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" },
|
||||
];
|
||||
|
||||
@@ -41,11 +48,54 @@ export const preferenceKeys: WorkbenchKey[] = [
|
||||
{ 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 {
|
||||
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.ctrl && (!event.ctrlKey || event.metaKey)) return false;
|
||||
if (binding.shift !== undefined && event.shiftKey !== binding.shift) return false;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { tr } from "../i18n/index.ts";
|
||||
import { keys } from "./shortcuts.ts";
|
||||
import type { ActionMenuItem } from "./actionMenu.ts";
|
||||
|
||||
// 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. */
|
||||
export function historyItems(history: { canUndo: boolean; canRedo: boolean; undo(): void; redo(): void }): ActionMenuItem[] {
|
||||
return [
|
||||
{ label: tr("Undo"), icon: "undo", shortcut: "Ctrl+Z", disabled: !history.canUndo, run: history.undo },
|
||||
{ label: tr("Redo"), icon: "redo", shortcut: "Ctrl+Shift+Z", disabled: !history.canRedo, run: history.redo },
|
||||
{ label: tr("Undo"), icon: "undo", shortcut: keys("Mod+Z"), disabled: !history.canUndo, run: history.undo },
|
||||
{ label: tr("Redo"), icon: "redo", shortcut: keys("Mod+Shift+Z"), disabled: !history.canRedo, run: history.redo },
|
||||
{ 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. */
|
||||
export function clipboardItems(actions: ClipboardActions): ActionMenuItem[] {
|
||||
const items: ActionMenuItem[] = [];
|
||||
if (actions.cut) items.push({ label: tr("Cut"), icon: "cut", shortcut: "Ctrl+X", disabled: !actions.selected, run: actions.cut });
|
||||
items.push({ label: tr("Copy"), icon: "copy", shortcut: "Ctrl+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.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: keys("Mod+C"), disabled: !actions.selected, run: actions.copy });
|
||||
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.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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
Reference in New Issue
Block a user