feat: keyboard shortcuts
This commit is contained in:
1 parent
445d1c505f
commit
9483d598fc
19 files changed
+366
-59
No files matched your search
@@ -67,6 +67,7 @@
|
||||
- Show formatting marks (spaces, tabs, paragraph marks)
|
||||
|
||||
**Editing aids**
|
||||
- Word/LibreOffice keyboard shortcuts throughout: Ctrl+L/E/R/J alignment, Ctrl+Alt+1–5 headings and Ctrl+Shift+N default style, Ctrl+1/2/5 line spacing, Ctrl+Shift+P / Ctrl+Shift+B super/subscript, Ctrl+Shift+. / Ctrl+Shift+, grow/shrink font, Ctrl+Space clear formatting, Ctrl+Shift+Space non-breaking space, Ctrl+Shift+- soft hyphen, Alt+Shift+D / Alt+Shift+T date & time field, Ctrl+O open, F3 / Shift+F3 find next/previous, Ctrl+F10 formatting marks — alongside the existing Ctrl+B/I/U, Ctrl+M, Ctrl+K, Ctrl+Enter, Ctrl+F/H, Ctrl+S/P and Tab/Shift+Tab. All bindings live in one table, so tooltips stay in sync and they can be remapped later
|
||||
- Undo / Redo with a labelled history dropdown
|
||||
- Search & Replace (Ctrl+F / Ctrl+H): live match highlighting, match count, next / previous, match-case and whole-word options, replace current / replace all
|
||||
- Spell check in English and German with squiggles and a suggestions context menu (add / ignore word); selectable document language. Powered by Hunspell (WASM), so German compound words (Fußgänger, Krankenversicherung …) are recognised; dictionaries are lazy-loaded per language on demand
|
||||
|
||||
+24
-31
@@ -35,6 +35,7 @@
|
||||
import AboutDialog from './lib/components/AboutDialog.svelte';
|
||||
import { t } from './lib/i18n/i18n.svelte';
|
||||
import { withShortcut } from './lib/i18n/shortcut';
|
||||
import { DEFAULT_SHORTCUTS, matchesEvent, shortcutHint } from './lib/editor/shortcuts';
|
||||
import { localizeImportMessage } from './lib/i18n/importMessages';
|
||||
import { unavailableFonts } from './lib/utils/fontDetect';
|
||||
import { registerEmbeddedFonts, clearEmbeddedFonts } from './lib/fonts/embeddedFonts';
|
||||
@@ -670,38 +671,30 @@
|
||||
// FontFace load fires 'loadingdone', which Editor.svelte re-paginates on.
|
||||
void loadEmbeddedFonts().then(registerEmbeddedFonts);
|
||||
|
||||
// Shortcuts that must work regardless of focus and that suppress the browser's
|
||||
// own binding (save page, find, open, zoom). Everything editor-scoped lives in
|
||||
// the Shortcuts extension instead.
|
||||
const appActions: [string, () => void][] = [
|
||||
[DEFAULT_SHORTCUTS.save, handleSave],
|
||||
[DEFAULT_SHORTCUTS.open, handleOpen],
|
||||
[DEFAULT_SHORTCUTS.print, handlePrint],
|
||||
[DEFAULT_SHORTCUTS.find, () => openFind('find')],
|
||||
[DEFAULT_SHORTCUTS.replace, () => openFind('replace')],
|
||||
// Closing the bar clears the search, so F3 with no bar starts one.
|
||||
[DEFAULT_SHORTCUTS.findNext, () => (findOpen ? editor?.commands.findNext() : openFind('find'))],
|
||||
[DEFAULT_SHORTCUTS.findPrevious, () => (findOpen ? editor?.commands.findPrevious() : openFind('find'))],
|
||||
[DEFAULT_SHORTCUTS.formattingMarks, () => (showFormattingMarks = !showFormattingMarks)],
|
||||
[DEFAULT_SHORTCUTS.zoomIn, () => setZoom(zoom + 10)],
|
||||
[DEFAULT_SHORTCUTS.zoomOut, () => setZoom(zoom - 10)],
|
||||
[DEFAULT_SHORTCUTS.zoomReset, () => setZoom(100)],
|
||||
];
|
||||
|
||||
function onKeydown(e: KeyboardEvent) {
|
||||
// Ctrl/Cmd+S → Save (suppress the browser's save-page dialog).
|
||||
if ((e.ctrlKey || e.metaKey) && !e.shiftKey && (e.key === 's' || e.key === 'S')) {
|
||||
for (const [combo, run] of appActions) {
|
||||
if (!matchesEvent(e, combo)) continue;
|
||||
e.preventDefault();
|
||||
handleSave();
|
||||
}
|
||||
// Ctrl/Cmd+P → Print the paginated document (not the whole app UI).
|
||||
if ((e.ctrlKey || e.metaKey) && !e.shiftKey && (e.key === 'p' || e.key === 'P')) {
|
||||
e.preventDefault();
|
||||
handlePrint();
|
||||
}
|
||||
// Ctrl/Cmd+F → Find, Ctrl/Cmd+H → Find & Replace (suppress the browser's own find).
|
||||
if ((e.ctrlKey || e.metaKey) && !e.shiftKey && (e.key === 'f' || e.key === 'F')) {
|
||||
e.preventDefault();
|
||||
openFind('find');
|
||||
}
|
||||
if ((e.ctrlKey || e.metaKey) && !e.shiftKey && (e.key === 'h' || e.key === 'H')) {
|
||||
e.preventDefault();
|
||||
openFind('replace');
|
||||
}
|
||||
// Ctrl/Cmd +/−/0 → zoom the document, not the browser window.
|
||||
if ((e.ctrlKey || e.metaKey) && !e.shiftKey && !e.altKey) {
|
||||
if (e.key === '+' || e.key === '=' || e.code === 'NumpadAdd') {
|
||||
e.preventDefault();
|
||||
setZoom(zoom + 10);
|
||||
} else if (e.key === '-' || e.code === 'NumpadSubtract') {
|
||||
e.preventDefault();
|
||||
setZoom(zoom - 10);
|
||||
} else if (e.key === '0' || e.code === 'Numpad0') {
|
||||
e.preventDefault();
|
||||
setZoom(100);
|
||||
}
|
||||
run();
|
||||
return;
|
||||
}
|
||||
// Escape closes the bar (when it isn't handled inside an input).
|
||||
if (e.key === 'Escape' && findOpen) closeFind();
|
||||
@@ -808,7 +801,7 @@
|
||||
<path d="M8 8v3.5M6.25 9.75h3.5" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/>
|
||||
</svg>
|
||||
</button>
|
||||
<button class="file-action-btn" onclick={handleOpen} disabled={!editor} title={t().app.openOdt}>
|
||||
<button class="file-action-btn" onclick={handleOpen} disabled={!editor} title={`${t().app.openOdt} (${shortcutHint('open')})`}>
|
||||
<!-- Folder -->
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
|
||||
<path d="M1.75 12.5V4a1 1 0 0 1 1-1h3.2a1 1 0 0 1 .8.4l.7.95a1 1 0 0 0 .8.4h4.2a1 1 0 0 1 1 1v6.75a1 1 0 0 1-1 1H2.75a1 1 0 0 1-1-1z" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/>
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import type { Editor } from '@tiptap/core';
|
||||
import { t } from '../i18n/i18n.svelte';
|
||||
import AlignIcon from './AlignIcon.svelte';
|
||||
import { shortcutHint, type ShortcutId } from '../editor/shortcuts';
|
||||
|
||||
import type { AlignValue } from './AlignIcon.svelte';
|
||||
|
||||
@@ -9,6 +10,10 @@
|
||||
|
||||
const ALIGNMENTS: AlignValue[] = ['left', 'center', 'right', 'justify'];
|
||||
|
||||
const ALIGN_SHORTCUTS: Record<AlignValue, ShortcutId> = {
|
||||
left: 'alignLeft', center: 'alignCenter', right: 'alignRight', justify: 'alignJustify',
|
||||
};
|
||||
|
||||
// Empty string when the selection spans paragraphs/headings with different alignments.
|
||||
let currentAlign = $derived.by<AlignValue | ''>(() => {
|
||||
if (tick < 0 || !editor) return 'left';
|
||||
@@ -65,7 +70,7 @@
|
||||
class="align-option"
|
||||
class:active={currentAlign === a}
|
||||
onclick={() => pickAlign(a)}
|
||||
title={t().align.alignTo(t().align[a])}
|
||||
title={`${t().align.alignTo(t().align[a])} (${shortcutHint(ALIGN_SHORTCUTS[a])})`}
|
||||
>
|
||||
<AlignIcon value={a} />
|
||||
<span>{t().align[a]}</span>
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
<script lang="ts">
|
||||
import type { Editor } from '@tiptap/core';
|
||||
import {
|
||||
DATE_FORMATS, TIME_FORMATS, renderFormat, localeTag, type DtFormat,
|
||||
DATE_FORMATS, TIME_FORMATS, DEFAULT_DATE_FORMAT, DEFAULT_TIME_FORMAT,
|
||||
renderFormat, localeTag, type DtFormat,
|
||||
} from '../utils/dateTime';
|
||||
import { shortcutHint } from '../editor/shortcuts';
|
||||
import { t, locale } from '../i18n/i18n.svelte';
|
||||
|
||||
let {
|
||||
@@ -91,13 +93,13 @@
|
||||
<div class="dt-col">
|
||||
<div class="dt-section-label">{t().dateTime.dateHeading}</div>
|
||||
{#each DATE_FORMATS as fmt (fmt.key)}
|
||||
<button class="dt-cell" onclick={() => pick(fmt)}>{sample(fmt)}</button>
|
||||
<button class="dt-cell" onclick={() => pick(fmt)} title={fmt.key === DEFAULT_DATE_FORMAT ? shortcutHint('dateField') : undefined}>{sample(fmt)}</button>
|
||||
{/each}
|
||||
</div>
|
||||
<div class="dt-col">
|
||||
<div class="dt-section-label">{t().dateTime.timeHeading}</div>
|
||||
{#each TIME_FORMATS as fmt (fmt.key)}
|
||||
<button class="dt-cell" onclick={() => pick(fmt)}>{sample(fmt)}</button>
|
||||
<button class="dt-cell" onclick={() => pick(fmt)} title={fmt.key === DEFAULT_TIME_FORMAT ? shortcutHint('timeField') : undefined}>{sample(fmt)}</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -8,11 +8,12 @@
|
||||
import { isInHeaderCell } from '../editor/extensions/tableHeaderRow';
|
||||
import { blockStyleName } from '../editor/extensions/paragraphStyle';
|
||||
import { activeCharacterStyle } from '../editor/extensions/characterStyle';
|
||||
import { DEFAULT_STYLE, resolveStyle, styleOrder } from '../styles/styleSheet';
|
||||
import { DEFAULT_STYLE, headingStyleName, resolveStyle, styleOrder } from '../styles/styleSheet';
|
||||
import { styleSheet } from '../styles/sheet.svelte';
|
||||
import StyleManagerDialog from './StyleManagerDialog.svelte';
|
||||
import { t } from '../i18n/i18n.svelte';
|
||||
import { withShortcut } from '../i18n/shortcut';
|
||||
import { shortcutHint, type ShortcutId } from '../editor/shortcuts';
|
||||
|
||||
// Bullet-marker tooltip by char, with the char itself as fallback.
|
||||
function bulletName(char: string): string {
|
||||
@@ -69,6 +70,15 @@
|
||||
return blockStyleName(editor.state.selection.$from.parent as never);
|
||||
});
|
||||
|
||||
// Only the styles the Shortcuts extension binds carry a hint.
|
||||
function styleShortcut(name: string): string | undefined {
|
||||
if (name === DEFAULT_STYLE) return shortcutHint('styleStandard');
|
||||
const level = sheet.paragraph[name]?.outlineLevel;
|
||||
// The keys apply the built-in heading styles, not any style at that level.
|
||||
if (!level || level > 5 || name !== headingStyleName(level)) return undefined;
|
||||
return shortcutHint(`heading${level}` as ShortcutId);
|
||||
}
|
||||
|
||||
function applyStyle(name: string) {
|
||||
stylesOpen = false;
|
||||
if (!editor) return;
|
||||
@@ -222,6 +232,7 @@
|
||||
onclick={() => applyStyle(s.name)}
|
||||
role="menuitemradio"
|
||||
aria-checked={currentStyle === s.name}
|
||||
title={styleShortcut(s.name)}
|
||||
style="font-size: {previewSize(s.name)}; font-weight: {preview.text.bold ? 600 : 400}; font-style: {preview.text.italic ? 'italic' : 'normal'}"
|
||||
>
|
||||
{styleLabel(s.name)}
|
||||
|
||||
@@ -18,11 +18,11 @@
|
||||
import type { Orientation } from '../storage/pageOrientation';
|
||||
import { pageDimsCm, PAGE_FORMAT_CM, type PageFormat } from '../storage/pageFormat';
|
||||
import { DEFAULT_HF_DISTANCES, clampHfDistance, type HfDistances } from '../storage/headerFooter';
|
||||
import { blockFontSize, DEFAULT_FONT_SIZE, type SizedBlock } from '../utils/fontSize';
|
||||
import { blockFontSize, coversWholeBlock, DEFAULT_FONT_SIZE, FONT_SIZES, type SizedBlock } from '../utils/fontSize';
|
||||
import { listContext } from '../editor/extensions/indent';
|
||||
import { findColumns, DEFAULT_COLUMN_GAP_CM } from '../editor/extensions/columns';
|
||||
import { t } from '../i18n/i18n.svelte';
|
||||
import { withShortcut } from '../i18n/shortcut';
|
||||
import { shortcutHint, type ShortcutId } from '../editor/shortcuts';
|
||||
|
||||
let { editor, tick, showFormattingMarks = $bindable(), pageMargins = $bindable(DEFAULT_MARGINS), pageOrientation = $bindable<Orientation>('portrait'), pageFormat = $bindable<PageFormat>('A4'), hfDistances = $bindable(DEFAULT_HF_DISTANCES), differentFirstPage = $bindable(false), differentOddEven = $bindable(false), hfActive = null, onEditZone, onDebugDump }:
|
||||
{ editor: Editor | null; tick: number; showFormattingMarks: boolean; pageMargins?: PageMargins; pageOrientation?: Orientation; pageFormat?: PageFormat; hfDistances?: HfDistances; differentFirstPage?: boolean; differentOddEven?: boolean; hfActive?: 'header' | 'footer' | null; onEditZone?: (zone: 'header' | 'footer') => void; onDebugDump?: () => void } = $props();
|
||||
@@ -129,8 +129,6 @@
|
||||
return mixed ? '' : (font ?? DEFAULT_EDITOR_FONT);
|
||||
});
|
||||
|
||||
const FONT_SIZES = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 36, 48, 72];
|
||||
|
||||
function effectiveSize(node: { isText: boolean; marks: readonly { type: { name: string }; attrs: Record<string, string> }[] }, parent: SizedBlock): string {
|
||||
const explicit = node.marks.find(m => m.type.name === 'textStyle')?.attrs.fontSize;
|
||||
return explicit || blockFontSize(parent);
|
||||
@@ -161,6 +159,11 @@
|
||||
const DEFAULT_LINE_HEIGHT = '1';
|
||||
const LINE_HEIGHTS = ['1', '1.15', '1.5', '2'];
|
||||
|
||||
// Word binds only these three; 1.15 has no key.
|
||||
const LH_SHORTCUTS: Record<string, ShortcutId | undefined> = {
|
||||
'1': 'lineHeight1', '1.5': 'lineHeight15', '2': 'lineHeight2',
|
||||
};
|
||||
|
||||
// Numeric values show verbatim; the single/double presets are localized.
|
||||
function lineHeightLabel(value: string): string {
|
||||
if (value === '1') return t().toolbarExpanded.lineSingle;
|
||||
@@ -403,14 +406,7 @@
|
||||
savedFrom = null;
|
||||
savedTo = null;
|
||||
const chain = editor.chain().focus().setTextSelection({ from, to }).setFontSize(`${size}pt`);
|
||||
// An empty line or a fully covered block also gets its paragraph-mark size, so what
|
||||
// the block renders can't diverge from the shown size (and empty lines keep it).
|
||||
const rFrom = editor.state.doc.resolve(from);
|
||||
const rTo = editor.state.doc.resolve(to);
|
||||
const wholeBlock = from === to
|
||||
? rFrom.parent.content.size === 0
|
||||
: rFrom.parentOffset === 0 && rTo.parentOffset === rTo.parent.content.size;
|
||||
if (wholeBlock) chain.setBlockFontSize(`${size}pt`);
|
||||
if (coversWholeBlock(editor.state.doc, from, to)) chain.setBlockFontSize(`${size}pt`);
|
||||
chain.run();
|
||||
}
|
||||
|
||||
@@ -1160,7 +1156,7 @@
|
||||
<button
|
||||
class:active={isSuperscript}
|
||||
onclick={toggleSuperscript}
|
||||
title={`${t().toolbarExpanded.superscript} (${withShortcut('Ctrl+.')})`}
|
||||
title={`${t().toolbarExpanded.superscript} (${shortcutHint('superscript')})`}
|
||||
aria-pressed={isSuperscript}
|
||||
>
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
|
||||
@@ -1171,7 +1167,7 @@
|
||||
<button
|
||||
class:active={isSubscript}
|
||||
onclick={toggleSubscript}
|
||||
title={`${t().toolbarExpanded.subscript} (${withShortcut('Ctrl+,')})`}
|
||||
title={`${t().toolbarExpanded.subscript} (${shortcutHint('subscript')})`}
|
||||
aria-pressed={isSubscript}
|
||||
>
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
|
||||
@@ -1225,6 +1221,7 @@
|
||||
class="lh-option"
|
||||
class:active={currentLineHeight === lh}
|
||||
onclick={() => pickLineHeight(lh)}
|
||||
title={LH_SHORTCUTS[lh] ? shortcutHint(LH_SHORTCUTS[lh]) : undefined}
|
||||
>{lineHeightLabel(lh)}</button>
|
||||
{/each}
|
||||
|
||||
@@ -1442,7 +1439,7 @@
|
||||
<button
|
||||
class:active={showFormattingMarks}
|
||||
onclick={() => (showFormattingMarks = !showFormattingMarks)}
|
||||
title={t().toolbarExpanded.formattingMarks}
|
||||
title={`${t().toolbarExpanded.formattingMarks} (${shortcutHint('formattingMarks')})`}
|
||||
aria-pressed={showFormattingMarks}
|
||||
>
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
|
||||
@@ -1606,7 +1603,7 @@
|
||||
class:active={isLink}
|
||||
onclick={openLinkDialog}
|
||||
disabled={!!hfActive}
|
||||
title={hfActive ? t().toolbarExpanded.linkNotInHf : `${t().toolbarExpanded.insertLink} (${withShortcut('Ctrl+K')})`}
|
||||
title={hfActive ? t().toolbarExpanded.linkNotInHf : `${t().toolbarExpanded.insertLink} (${shortcutHint('link')})`}
|
||||
aria-label={t().toolbarExpanded.insertLink}
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={linkDialogOpen}
|
||||
@@ -1633,7 +1630,7 @@
|
||||
<div class="toolbar-group">
|
||||
<button
|
||||
onclick={() => editor?.commands.clearDirectFormatting()}
|
||||
title={`${t().toolbarExpanded.clearFormatting} (${withShortcut('Ctrl+M')})`}
|
||||
title={`${t().toolbarExpanded.clearFormatting} (${shortcutHint('clearFormatting')})`}
|
||||
>
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
|
||||
<!-- bold + italic A -->
|
||||
|
||||
@@ -48,6 +48,7 @@ import { TextBox } from './extensions/textBox';
|
||||
import { Columns } from './extensions/columns';
|
||||
import { ColumnsFlow } from './extensions/columnsFlow';
|
||||
import { TableOfContents } from './extensions/tableOfContents';
|
||||
import { Shortcuts } from './extensions/shortcuts';
|
||||
import { styleSheet } from '../styles/sheet.svelte';
|
||||
|
||||
export const extensions = [
|
||||
@@ -143,4 +144,7 @@ export const extensions = [
|
||||
FormattingMarks,
|
||||
SpellCheck,
|
||||
SearchReplace,
|
||||
// Word/LibreOffice key bindings that aren't TipTap defaults; body:true adds the
|
||||
// ones the header/footer schema has no commands for (headings, line spacing, fields).
|
||||
Shortcuts.configure({ body: true }),
|
||||
];
|
||||
@@ -19,6 +19,7 @@ import { ParagraphBox } from './paragraphBox';
|
||||
import { CharacterStyle } from './characterStyle';
|
||||
import { PageNumber, PageCount } from './pageField';
|
||||
import { Image } from './image';
|
||||
import { Shortcuts } from './shortcuts';
|
||||
|
||||
// Schema for the header/footer mini editors: exactly one paragraph of formatted
|
||||
// runs, line breaks, page fields, and inline (as-character) images. Marks mirror
|
||||
@@ -71,5 +72,7 @@ export function hfExtensions(placeholder = '') {
|
||||
alignments: ['left', 'center', 'right', 'justify'],
|
||||
defaultAlignment: 'left',
|
||||
}),
|
||||
// Only the shared bindings: this schema has no headings, line spacing or fields.
|
||||
Shortcuts,
|
||||
];
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Extension, type CommandProps } from '@tiptap/core';
|
||||
import type { Node as PMNode, ResolvedPos } from '@tiptap/pm/model';
|
||||
import type { EditorState, Transaction } from '@tiptap/pm/state';
|
||||
import { DEFAULT_SHORTCUTS } from '../shortcuts';
|
||||
|
||||
// Left indent in cm: maps to fo:margin-left on paragraphs/headings; on lists it shifts
|
||||
// the whole list block (list items nest instead via sinkListItem/liftListItem).
|
||||
@@ -219,7 +220,7 @@ export const Indent = Extension.create({
|
||||
addKeyboardShortcuts() {
|
||||
const inCell = () => this.editor.isActive('tableCell') || this.editor.isActive('tableHeader');
|
||||
return {
|
||||
Tab: () => {
|
||||
[DEFAULT_SHORTCUTS.indentMore]: () => {
|
||||
if (inCell()) return false;
|
||||
if (listContext(this.editor.state).inList) {
|
||||
this.editor.commands.indentListForward();
|
||||
@@ -228,7 +229,7 @@ export const Indent = Extension.create({
|
||||
this.editor.commands.insertContent('\t');
|
||||
return true;
|
||||
},
|
||||
'Shift-Tab': () => {
|
||||
[DEFAULT_SHORTCUTS.indentLess]: () => {
|
||||
if (inCell()) return false;
|
||||
if (listContext(this.editor.state).inList) {
|
||||
this.editor.commands.indentListBackward();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import LinkBase from '@tiptap/extension-link';
|
||||
import { DEFAULT_SHORTCUTS } from '../shortcuts';
|
||||
|
||||
// Event the toolbar listens for to open the link dialog (Ctrl/Cmd+K). The extension
|
||||
// can't reach Svelte state directly, so it dispatches this on window instead.
|
||||
@@ -16,7 +17,7 @@ export const Link = LinkBase.configure({
|
||||
}).extend({
|
||||
addKeyboardShortcuts() {
|
||||
return {
|
||||
'Mod-k': () => {
|
||||
[DEFAULT_SHORTCUTS.link]: () => {
|
||||
window.dispatchEvent(new CustomEvent(OPEN_LINK_DIALOG_EVENT));
|
||||
return true;
|
||||
},
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Extension } from '@tiptap/core';
|
||||
import { DEFAULT_SHORTCUTS } from '../shortcuts';
|
||||
|
||||
// Manual page break before a paragraph/heading, stored as breakBefore: 'page' | null and
|
||||
// rendered as data-page-break-before. Round-trips to ODF fo:break-before="page" (import
|
||||
@@ -77,7 +78,7 @@ export const PageBreak = Extension.create({
|
||||
|
||||
addKeyboardShortcuts() {
|
||||
return {
|
||||
'Mod-Enter': () => this.editor.commands.insertPageBreak(),
|
||||
[DEFAULT_SHORTCUTS.pageBreak]: () => this.editor.commands.insertPageBreak(),
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Extension } from '@tiptap/core';
|
||||
import { headingStyleName, type StyleSheet } from '../../styles/styleSheet';
|
||||
import { DEFAULT_SHORTCUTS } from '../shortcuts';
|
||||
|
||||
// The named paragraph style a block uses (LibreOffice's style:style / Word's w:pStyle).
|
||||
// Rendered as data-style so the generated document stylesheet (styleCss) can target it;
|
||||
@@ -75,7 +76,7 @@ export const ParagraphStyle = Extension.create<{ types: string[]; sheet: () => S
|
||||
},
|
||||
|
||||
addKeyboardShortcuts() {
|
||||
return { 'Mod-m': () => this.editor.commands.clearDirectFormatting() };
|
||||
return { [DEFAULT_SHORTCUTS.clearFormatting]: () => this.editor.commands.clearDirectFormatting() };
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { Extension, type Editor } from '@tiptap/core';
|
||||
import { Plugin } from '@tiptap/pm/state';
|
||||
import type { Mark } from '@tiptap/pm/model';
|
||||
import { DEFAULT_SHORTCUTS, type ShortcutId } from '../shortcuts';
|
||||
import { FONT_SIZES, blockFontSize, coversWholeBlock } from '../../utils/fontSize';
|
||||
import { headingStyleName } from '../../styles/styleSheet';
|
||||
import { DEFAULT_DATE_FORMAT, DEFAULT_TIME_FORMAT } from '../../utils/dateTime';
|
||||
|
||||
// The Word/LibreOffice shortcuts that aren't already a TipTap default, bound from
|
||||
// the central table. priority 1000 so Mod-Alt-N beats Heading's toggleHeading and
|
||||
// Mod-Shift-b beats Bold's Mod-B alias.
|
||||
|
||||
type Binding = (editor: Editor) => boolean;
|
||||
|
||||
// The size to step from — the selection's first run, like the toolbar's size box.
|
||||
// A range selection can't use $head: after Ctrl+A it sits outside the paragraph,
|
||||
// where marks() is empty and every step would restart from the style default.
|
||||
function currentSizePt(editor: Editor): number {
|
||||
const { state } = editor;
|
||||
const { from, to, empty, $head } = state.selection;
|
||||
const markSize = (marks: readonly Mark[]) =>
|
||||
marks.find((m) => m.type.name === 'textStyle')?.attrs.fontSize as string | undefined;
|
||||
|
||||
let size: string | undefined;
|
||||
if (empty) size = markSize(state.storedMarks ?? $head.marks());
|
||||
else {
|
||||
state.doc.nodesBetween(from, to, (node, _pos, parent) => {
|
||||
if (size || !node.isText) return;
|
||||
size = markSize(node.marks) ?? blockFontSize(parent);
|
||||
});
|
||||
}
|
||||
return parseFloat(size || blockFontSize($head.parent)) || 12;
|
||||
}
|
||||
|
||||
// Word's Ctrl+Shift+> / <: jump to the next size on the toolbar's ladder.
|
||||
function stepFontSize(editor: Editor, dir: 1 | -1): boolean {
|
||||
const cur = currentSizePt(editor);
|
||||
const ladder = dir > 0 ? FONT_SIZES : [...FONT_SIZES].reverse();
|
||||
const next = ladder.find((s) => (dir > 0 ? s > cur : s < cur));
|
||||
if (next === undefined) return false;
|
||||
const { from, to } = editor.state.selection;
|
||||
const chain = editor.chain().focus().setFontSize(`${next}pt`);
|
||||
if ('setBlockFontSize' in editor.commands && coversWholeBlock(editor.state.doc, from, to)) {
|
||||
chain.setBlockFontSize(`${next}pt`);
|
||||
}
|
||||
return chain.run();
|
||||
}
|
||||
|
||||
// Available in the body and in the header/footer editors.
|
||||
const SHARED: Partial<Record<ShortcutId, Binding>> = {
|
||||
alignLeft: (e) => e.chain().focus().setTextAlign('left').run(),
|
||||
alignCenter: (e) => e.chain().focus().setTextAlign('center').run(),
|
||||
alignRight: (e) => e.chain().focus().setTextAlign('right').run(),
|
||||
alignJustify: (e) => e.chain().focus().setTextAlign('justify').run(),
|
||||
superscript: (e) => e.chain().focus().unsetSubscript().toggleSuperscript().run(),
|
||||
subscript: (e) => e.chain().focus().unsetSuperscript().toggleSubscript().run(),
|
||||
fontGrow: (e) => stepFontSize(e, 1),
|
||||
fontShrink: (e) => stepFontSize(e, -1),
|
||||
// Escaped: both characters are invisible in source.
|
||||
nbsp: (e) => e.chain().focus().insertContent('\u00A0').run(),
|
||||
softHyphen: (e) => e.chain().focus().insertContent('\u00AD').run(),
|
||||
};
|
||||
|
||||
// Commands the single-paragraph header/footer schema doesn't have.
|
||||
const BODY_ONLY: Partial<Record<ShortcutId, Binding>> = {
|
||||
clearFormattingAlt: (e) => e.commands.clearDirectFormatting(),
|
||||
lineHeight1: (e) => e.chain().focus().setLineHeight('1').run(),
|
||||
lineHeight2: (e) => e.chain().focus().setLineHeight('2').run(),
|
||||
lineHeight15: (e) => e.chain().focus().setLineHeight('1.5').run(),
|
||||
styleStandard: (e) => e.commands.setParagraphStyle('Standard'),
|
||||
dateField: (e) =>
|
||||
e.chain().focus().insertDateTimeField({ kind: 'date', format: DEFAULT_DATE_FORMAT, fixed: false }).run(),
|
||||
timeField: (e) =>
|
||||
e.chain().focus().insertDateTimeField({ kind: 'time', format: DEFAULT_TIME_FORMAT, fixed: false }).run(),
|
||||
};
|
||||
|
||||
export const Shortcuts = Extension.create<{ body: boolean }>({
|
||||
name: 'shortcuts',
|
||||
priority: 1000,
|
||||
|
||||
addOptions() {
|
||||
return { body: false };
|
||||
},
|
||||
|
||||
addKeyboardShortcuts() {
|
||||
const bindings = { ...SHARED, ...(this.options.body ? BODY_ONLY : {}) };
|
||||
return Object.fromEntries(
|
||||
Object.entries(bindings).map(([id, run]) => [
|
||||
DEFAULT_SHORTCUTS[id as ShortcutId],
|
||||
() => run(this.editor),
|
||||
]),
|
||||
);
|
||||
},
|
||||
|
||||
addProseMirrorPlugins() {
|
||||
if (!this.options.body) return [];
|
||||
const editor = this.editor;
|
||||
return [
|
||||
new Plugin({
|
||||
props: {
|
||||
// Ctrl+Alt+N can't go through the keymap: Windows reads Ctrl+Alt as AltGr, so
|
||||
// event.key is layout-dependent (German AltGr+2 = '²') and prosemirror-keymap
|
||||
// skips its keyCode fallback for exactly this combination.
|
||||
handleKeyDown(_view, event) {
|
||||
if (!(event.ctrlKey || event.metaKey) || !event.altKey || event.shiftKey) return false;
|
||||
const digit = /^Digit([0-5])$/.exec(event.code);
|
||||
if (!digit) return false;
|
||||
const level = Number(digit[1]);
|
||||
event.preventDefault();
|
||||
return editor.commands.setParagraphStyle(level ? headingStyleName(level) : 'Standard');
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import { withShortcut } from '../i18n/shortcut';
|
||||
|
||||
// Every shortcut this app binds itself, in ProseMirror keymap syntax ('Mod' =
|
||||
// Ctrl/Cmd). Ids are stable so a later remapping UI only overrides this map.
|
||||
// TipTap's own defaults (Mod-b/i/u, Mod-Shift-s/h, Mod-z, Mod-Shift-7/8,
|
||||
// Mod-Shift-l/e/r/j, Tab in tables) are not listed — they are not ours to bind.
|
||||
|
||||
export const DEFAULT_SHORTCUTS = {
|
||||
// Character formatting — LibreOffice's sub/superscript keys; Word's Ctrl+= pair
|
||||
// would collide with zoom. Mod-Shift-b deliberately shadows TipTap's Mod-B bold alias.
|
||||
superscript: 'Mod-Shift-p',
|
||||
subscript: 'Mod-Shift-b',
|
||||
fontGrow: 'Mod-Shift-.',
|
||||
fontShrink: 'Mod-Shift-,',
|
||||
clearFormatting: 'Mod-m',
|
||||
clearFormattingAlt: 'Mod-Space',
|
||||
|
||||
// Paragraph
|
||||
alignLeft: 'Mod-l',
|
||||
alignCenter: 'Mod-e',
|
||||
alignRight: 'Mod-r',
|
||||
alignJustify: 'Mod-j',
|
||||
lineHeight1: 'Mod-1',
|
||||
lineHeight2: 'Mod-2',
|
||||
lineHeight15: 'Mod-5',
|
||||
heading1: 'Mod-Alt-1',
|
||||
heading2: 'Mod-Alt-2',
|
||||
heading3: 'Mod-Alt-3',
|
||||
heading4: 'Mod-Alt-4',
|
||||
heading5: 'Mod-Alt-5',
|
||||
styleStandard: 'Mod-Shift-n',
|
||||
indentMore: 'Tab',
|
||||
indentLess: 'Shift-Tab',
|
||||
|
||||
// Insert
|
||||
link: 'Mod-k',
|
||||
pageBreak: 'Mod-Enter',
|
||||
nbsp: 'Mod-Shift-Space',
|
||||
softHyphen: 'Mod-Shift--',
|
||||
dateField: 'Alt-Shift-d',
|
||||
timeField: 'Alt-Shift-t',
|
||||
|
||||
// Application (window keydown in App.svelte)
|
||||
open: 'Mod-o',
|
||||
save: 'Mod-s',
|
||||
print: 'Mod-p',
|
||||
find: 'Mod-f',
|
||||
replace: 'Mod-h',
|
||||
findNext: 'F3',
|
||||
findPrevious: 'Shift-F3',
|
||||
formattingMarks: 'Mod-F10',
|
||||
zoomIn: 'Mod-+',
|
||||
zoomOut: 'Mod--',
|
||||
zoomReset: 'Mod-0',
|
||||
} as const;
|
||||
|
||||
export type ShortcutId = keyof typeof DEFAULT_SHORTCUTS;
|
||||
|
||||
type Parsed = { mod: boolean; shift: boolean; alt: boolean; key: string };
|
||||
|
||||
// Split like ProseMirror does: a trailing '-' is the key, not a separator.
|
||||
function parse(combo: string): Parsed {
|
||||
const parts = combo.split(/-(?!$)/);
|
||||
const key = parts.pop() ?? '';
|
||||
return {
|
||||
mod: parts.includes('Mod'),
|
||||
shift: parts.includes('Shift'),
|
||||
alt: parts.includes('Alt'),
|
||||
key,
|
||||
};
|
||||
}
|
||||
|
||||
// Layouts put these on different keys; accept every spelling of the same intent.
|
||||
const KEY_ALIASES: Record<string, string[]> = {
|
||||
'+': ['+', '=', 'NumpadAdd'],
|
||||
'-': ['-', 'NumpadSubtract'],
|
||||
};
|
||||
|
||||
// For the window-level handler in App.svelte, which has no ProseMirror keymap.
|
||||
// Digits and function keys match by code so keyboard layouts can't break them.
|
||||
export function matchesEvent(e: KeyboardEvent, combo: string): boolean {
|
||||
const { mod, shift, alt, key } = parse(combo);
|
||||
if (mod !== (e.ctrlKey || e.metaKey) || shift !== e.shiftKey || alt !== e.altKey) return false;
|
||||
const aliases = KEY_ALIASES[key];
|
||||
if (aliases) return aliases.includes(e.key) || aliases.includes(e.code);
|
||||
if (/^\d$/.test(key)) return e.code === `Digit${key}` || e.code === `Numpad${key}`;
|
||||
if (/^F\d+$/.test(key) || key === 'Enter' || key === 'Tab') return e.key === key;
|
||||
if (key === 'Space') return e.code === 'Space';
|
||||
return e.key.toLowerCase() === key.toLowerCase();
|
||||
}
|
||||
|
||||
// Tooltip hint: 'Mod-Alt-1' → 'Strg+Alt+1' (or '⌘+⌥+1' on Mac).
|
||||
export function shortcutHint(id: ShortcutId): string {
|
||||
const parts = DEFAULT_SHORTCUTS[id].split(/-(?!$)/);
|
||||
const key = parts.pop() ?? '';
|
||||
const combo = [
|
||||
...parts.map((p) => (p === 'Mod' ? 'Ctrl' : p)),
|
||||
key.length === 1 ? key.toUpperCase() : key,
|
||||
].join('+');
|
||||
return withShortcut(combo);
|
||||
}
|
||||
@@ -23,6 +23,7 @@ const de: Messages = {
|
||||
shortcut: {
|
||||
ctrl: 'Strg',
|
||||
shift: 'Umschalt',
|
||||
alt: 'Alt',
|
||||
},
|
||||
align: {
|
||||
title: 'Textausrichtung',
|
||||
|
||||
@@ -24,6 +24,7 @@ const en = {
|
||||
shortcut: {
|
||||
ctrl: 'Ctrl',
|
||||
shift: 'Shift',
|
||||
alt: 'Alt',
|
||||
},
|
||||
align: {
|
||||
title: 'Text alignment',
|
||||
|
||||
@@ -10,5 +10,6 @@ const IS_MAC = /Mac|iPhone|iPad|iPod/.test(navigator.platform);
|
||||
export function withShortcut(combo: string): string {
|
||||
const mod = IS_MAC ? '⌘' : t().shortcut.ctrl;
|
||||
const shift = IS_MAC ? '⇧' : t().shortcut.shift;
|
||||
return combo.replace('Ctrl', mod).replace('Shift', shift);
|
||||
const alt = IS_MAC ? '⌥' : t().shortcut.alt;
|
||||
return combo.replace('Ctrl', mod).replace('Shift', shift).replace('Alt', alt);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { Node as PMNode } from '@tiptap/pm/model';
|
||||
import { resolveStyle } from '../styles/styleSheet';
|
||||
import { styleSheet } from '../styles/sheet.svelte';
|
||||
import { blockStyleName } from '../editor/extensions/paragraphStyle';
|
||||
@@ -6,6 +7,9 @@ import { blockStyleName } from '../editor/extensions/paragraphStyle';
|
||||
|
||||
export const DEFAULT_FONT_SIZE = '12pt';
|
||||
|
||||
// The size box's steps; also the grow/shrink shortcut's ladder.
|
||||
export const FONT_SIZES = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 36, 48, 72];
|
||||
|
||||
export type SizedBlock = { type: { name: string }; attrs?: Record<string, unknown> } | null;
|
||||
|
||||
// Paragraph-mark size (blockFontSize attr) wins, else the block's named style.
|
||||
@@ -15,3 +19,13 @@ export function blockFontSize(block: SizedBlock): string {
|
||||
const size = resolveStyle(styleSheet(), blockStyleName(block)).text.fontSizePt;
|
||||
return size != null ? `${size}pt` : DEFAULT_FONT_SIZE;
|
||||
}
|
||||
|
||||
// An empty line or a fully covered block also takes the paragraph-mark size, so what
|
||||
// the block renders can't diverge from the shown size (and empty lines keep it).
|
||||
export function coversWholeBlock(doc: PMNode, from: number, to: number): boolean {
|
||||
const rFrom = doc.resolve(from);
|
||||
const rTo = doc.resolve(to);
|
||||
return from === to
|
||||
? rFrom.parent.content.size === 0
|
||||
: rFrom.parentOffset === 0 && rTo.parentOffset === rTo.parent.content.size;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { DEFAULT_SHORTCUTS, matchesEvent, shortcutHint } from '../../src/lib/editor/shortcuts';
|
||||
|
||||
// Two ids on one combo means one of them silently never fires — the table is the only
|
||||
// place that can catch it, since the bindings are spread over extensions and App.svelte.
|
||||
describe('shortcut table', () => {
|
||||
it('binds every combo exactly once', () => {
|
||||
const seen = new Map<string, string>();
|
||||
for (const [id, combo] of Object.entries(DEFAULT_SHORTCUTS)) {
|
||||
expect(seen.get(combo), `${id} collides with ${seen.get(combo)}`).toBeUndefined();
|
||||
seen.set(combo, id);
|
||||
}
|
||||
});
|
||||
|
||||
it('renders hints in Word/LibreOffice notation', () => {
|
||||
expect(shortcutHint('heading1')).toBe('Ctrl+Alt+1');
|
||||
expect(shortcutHint('alignCenter')).toBe('Ctrl+E');
|
||||
expect(shortcutHint('softHyphen')).toBe('Ctrl+Shift+-');
|
||||
});
|
||||
});
|
||||
|
||||
function press(init: KeyboardEventInit): KeyboardEvent {
|
||||
return new KeyboardEvent('keydown', init);
|
||||
}
|
||||
|
||||
describe('matchesEvent', () => {
|
||||
it('requires every modifier to agree', () => {
|
||||
expect(matchesEvent(press({ key: 'o', ctrlKey: true }), DEFAULT_SHORTCUTS.open)).toBe(true);
|
||||
expect(matchesEvent(press({ key: 'o', metaKey: true }), DEFAULT_SHORTCUTS.open)).toBe(true);
|
||||
expect(matchesEvent(press({ key: 'o' }), DEFAULT_SHORTCUTS.open)).toBe(false);
|
||||
// Ctrl+Shift+S must stay free for strikethrough.
|
||||
expect(matchesEvent(press({ key: 'S', ctrlKey: true, shiftKey: true }), DEFAULT_SHORTCUTS.save)).toBe(false);
|
||||
});
|
||||
|
||||
it('distinguishes F3 from Shift+F3', () => {
|
||||
expect(matchesEvent(press({ key: 'F3' }), DEFAULT_SHORTCUTS.findNext)).toBe(true);
|
||||
expect(matchesEvent(press({ key: 'F3', shiftKey: true }), DEFAULT_SHORTCUTS.findNext)).toBe(false);
|
||||
expect(matchesEvent(press({ key: 'F3', shiftKey: true }), DEFAULT_SHORTCUTS.findPrevious)).toBe(true);
|
||||
});
|
||||
|
||||
it('matches digits by code, so keyboard layouts cannot break zoom reset', () => {
|
||||
expect(matchesEvent(press({ key: '0', code: 'Digit0', ctrlKey: true }), DEFAULT_SHORTCUTS.zoomReset)).toBe(true);
|
||||
expect(matchesEvent(press({ key: ')', code: 'Numpad0', ctrlKey: true }), DEFAULT_SHORTCUTS.zoomReset)).toBe(true);
|
||||
});
|
||||
|
||||
it('accepts every spelling of the zoom keys', () => {
|
||||
for (const init of [{ key: '+' }, { key: '=' }, { key: 'Unidentified', code: 'NumpadAdd' }]) {
|
||||
expect(matchesEvent(press({ ...init, ctrlKey: true }), DEFAULT_SHORTCUTS.zoomIn)).toBe(true);
|
||||
}
|
||||
expect(matchesEvent(press({ key: '-', ctrlKey: true }), DEFAULT_SHORTCUTS.zoomOut)).toBe(true);
|
||||
expect(matchesEvent(press({ key: '+', ctrlKey: true }), DEFAULT_SHORTCUTS.zoomOut)).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user