fix: an AutoText entry keeps a text box

Entries were stored as an HTML string, where any block tag inside a <p>
closes it — so a copied text box, which holds blocks, lost its place in
the line. They now keep the slice's nodes; an entry written earlier keeps
its HTML string, which insertContent takes just as well.
This commit is contained in:
Steffen Becker committed 2026-09-04 19:30:01 +02:00
1 parent 8d3139439c
commit 572e3a760d
7 files changed
+94 -20

No files matched your search

+9 -6
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import { getHTMLFromFragment, type Editor } from '@tiptap/core';
import type { Editor, JSONContent } from '@tiptap/core';
import type { AutoTextEntry } from '../storage/autoText';
import { autoTextEntries, putAutoText, removeAutoText } from '../storage/autoText.svelte';
import { t } from '../i18n/i18n.svelte';
@@ -25,14 +26,16 @@
function add() {
const slice = editor?.state.selection.content();
if (!editor || !slice || !name.trim()) return;
const html = getHTMLFromFragment(slice.content, editor.schema);
putAutoText({ name: name.trim(), shortcut: shortcut.trim(), html });
// The nodes themselves, not HTML: a text box holds blocks, and in an HTML string
// any block tag inside a <p> closes it, so the frame would not survive the trip.
const content = (slice.content.toJSON() ?? []) as JSONContent[];
putAutoText({ name: name.trim(), shortcut: shortcut.trim(), content });
name = '';
shortcut = '';
}
function insert(html: string) {
editor?.chain().focus().insertContent(html).run();
function insert(content: AutoTextEntry['content']) {
editor?.chain().focus().insertContent(content).run();
open = false;
}
</script>
@@ -50,7 +53,7 @@
<ul>
{#each autoTextEntries() as entry (entry.name)}
<li>
<button class="entry" onclick={() => insert(entry.html)} title={t().autoText.insertEntry}>
<button class="entry" onclick={() => insert(entry.content)} title={t().autoText.insertEntry}>
<span class="entry-name">{entry.name}</span>
{#if entry.shortcut}<span class="entry-key">{entry.shortcut}</span>{/if}
</button>
+1 -1
View File
@@ -151,7 +151,7 @@ reject in place through `acceptRevision`/`rejectRevision`. Opened from the Revie
LibreOffice's Tools ▸ AutoText, reachable where Word puts it too (the ribbon's Insert ▸
Text group, the modern chrome's Tools menu): the library, a click to insert, and "new
from selection" — the selected slice serialized to HTML. `hasSelection` is derived off
from selection" — the selected slice's nodes as JSON. `hasSelection` is derived off
`open` because the dialog stays mounted and a modal freezes the selection it opened on.
## Synonyms (`ThesaurusDialog.svelte`, `spell/thesaurus.ts`)
+1 -1
View File
@@ -47,7 +47,7 @@ Five topics are large enough to have their own deep-dive — read the file befor
- **`pageField.ts`** — inline atoms `pageNumber`/`pageCount`/`chapterField`, rendered as `<span data-page-field>`; `HeaderFooterLayer.svelte` patches each span's text to the real per-page value. `chapterField` is the running head (ODF `text:chapter`, Word `STYLEREF`): its `level` is the outline level to show, `text` the file's cached name. The page's chapter follows LibreOffice (probed): a **header** shows the one in force at the page's top (a heading counts once it opens a page — the `atTop` bit), a **footer** the last one begun on the page (`Editor.svelte` collects the heading→page map on each pagination pass, only when a zone shows one).
- **`autoCorrect.ts`** — AutoCorrect while typing (LibreOffice's Tools ▸ AutoCorrect Options): typographic quotes per document language, its dash matrix, its replacement table, sentence capitalization and TWo INitials. One `handleTextInput` plugin, listed **last** in `extensions.ts` so every input rule (list markers, the rule line) still fires first; `autoCorrectFix(before, opts, lang)` is pure — the whole table is `tests/unit/autocorrect.test.ts`. URL recognition and auto-list are TipTap's own (`Link autolink` — gated by the same options — and the list input rules).
- **`wordCompletion.ts`** — LibreOffice's Word Completion (its AutoCorrect dialog's own tab): every word of at least `minLength` letters is collected as it is finished, and typing its first three letters offers the rest. Drawn as a **widget decoration** after the caret, not LibreOffice's tooltip and not its selected-text insert — the offer is outside the document until Enter takes it, so nothing has to be undone when it is not. Only while **typing**: the offer is dropped on a bare caret move, or an Enter meant to split the paragraph would complete a word instead. `priority: 1000`, so its `handleKeyDown` sees Enter ahead of the keymaps. The list and its settings live in `storage/wordCompletion.svelte.ts`, the collection and matching rules in `utils/wordCompletion.ts`.
- **`autoText.ts`** — LibreOffice's AutoText / Word's Quick Parts: a named block of text, inserted from the library (`AutoTextDialog.svelte`) or by typing its shortcut and pressing **F3**, which is both products' key for it — and which the app also binds to find-next: the editor sees the key first, so it expands a shortcut where the caret has one and leaves the key alone otherwise (`App.svelte`'s window handler returns on `defaultPrevented`). An entry is stored as HTML and parsed back through the schema, so it keeps its marks and blocks and survives a schema that has grown. The library belongs to the app, not to a document (`storage/autoText.svelte.ts`) — as it does in both products, which keep it in a template of their own; nothing about it reaches a saved file.
- **`autoText.ts`** — LibreOffice's AutoText / Word's Quick Parts: a named block of text, inserted from the library (`AutoTextDialog.svelte`) or by typing its shortcut and pressing **F3**, which is both products' key for it — and which the app also binds to find-next: the editor sees the key first, so it expands a shortcut where the caret has one and leaves the key alone otherwise (`App.svelte`'s window handler returns on `defaultPrevented`). An entry is stored as the **nodes themselves** (`Fragment.toJSON()`), so it keeps a text box: in an HTML string any block tag inside a `<p>` closes it, and the box holds blocks. An entry written before that keeps its HTML string, which `insertContent` takes just as well. The library belongs to the app, not to a document (`storage/autoText.svelte.ts`) — as it does in both products, which keep it in a template of their own; nothing about it reaches a saved file.
- **`shortcuts.ts`** — see `src/lib/editor/CLAUDE.md`.
`extensions.ts` deliberately keeps TipTap's `resizable: false` (its columnResizing plugin stays
+2 -2
View File
@@ -30,11 +30,11 @@ export const AutoText = Extension.create({
addCommands() {
return {
insertAutoText: (entry) => ({ commands }) => commands.insertContent(entry.html),
insertAutoText: (entry) => ({ commands }) => commands.insertContent(entry.content),
expandAutoText: () => ({ editor, chain }) => {
const hit = shortcutAt(editor);
if (!hit) return false;
return chain().focus().deleteRange({ from: hit.from, to: hit.to }).insertContent(hit.entry.html).run();
return chain().focus().deleteRange({ from: hit.from, to: hit.to }).insertContent(hit.entry.content).run();
},
};
},
+1 -1
View File
@@ -14,7 +14,7 @@
- **`pageNumbering.ts`** — the page-number field's format and start value (`edentext-page-numbering`, absent at the 1/1 default). `HeaderFooterLayer.svelte` formats each page through `formatOrdinal`; the page **count** stays decimal, as the field both word processors write does. ODF keeps the format on the page layout and the start on the first paragraph's own style (`style:page-number` — probed, ODF has no document-level start); Word keeps both in the first section's `w:pgNumType`. A **later section** can restart the count (`HfSet.pageNumberStart`): ODF writes `style:page-number` on the same paragraph that switches master page, Word a `w:pgNumType w:start` — and that section is then exported as a page-starting break, since both word processors ignore a start on a continuous one (probed: LibreOffice drops it).
- **`hyphenation.ts`** — automatic hyphenation for the whole document (`edentext-hyphenation`, off by default as in both word processors). `Editor.svelte` puts `hyphens: auto` and the document `lang` on the body host — the browser needs the language to pick its patterns. ODF keeps it as `fo:hyphenate` in the **text** properties of the base paragraph style (probed: in paragraph-properties LibreOffice ignores it and drops it on the next save), Word as `w:autoHyphenation` in settings.xml. A **paragraph** can only opt *out* (`noHyphenation`, pageBreak.ts): Word has no per-paragraph "on", and both importers drop the flag under a document that does not hyphenate, where it says what is already true.
- **`wordCompletion.ts`** / **`.svelte.ts`** — the word-completion settings *and* the collected words (`edentext-word-completion`), LibreOffice's defaults: on, no appended space, words from eight letters, 1000 of them. The list outlives the document that filled it, as LibreOffice's profile copy does; a reactive singleton, since the extension both reads it and adds to it on every keystroke while the AutoCorrect dialog edits it.
- **`autoText.ts`** / **`.svelte.ts`** — the AutoText library (`edentext-autotext`, the key removed when empty): name, shortcut and the entry's HTML. App-level, not document-level, so no exporter looks at it.
- **`autoText.ts`** / **`.svelte.ts`** — the AutoText library (`edentext-autotext`, the key removed when empty): name, shortcut and the entry's nodes (an older entry's HTML string is read as the content it is). App-level, not document-level, so no exporter looks at it.
- **`tableOptions.svelte.ts`** — table number recognition (`edentext-number-recognition`, the key removed when off, as it is by default in LibreOffice). A reactive singleton like `trackChanges.svelte.ts`: the extension reads it on every transaction, both table surfaces flip it. It also holds the **number locale** — the document's language, which is what LibreOffice reads and writes a cell's number in — pushed by `App.svelte`'s language effect; the exporters take that locale from their own `language` argument instead, so they stay store-free. See `docs/architecture/tables.md`.
- **`pageDecor.ts`** — the page's own decoration (`edentext-page-decor`, the key removed when all three are off): background colour, a border around the text area at `paddingCm` from it, and a text watermark (LibreOffice's Format ▸ Watermark, field for field). All three ride the ODF page layout — the watermark as a `fontwork-plain-text` `<draw:custom-shape>` named `PowerPlusWaterMarkObject` in the **master page's header**, the only place LibreOffice reads one from (probed: hung off the master page directly it is dropped, and an undeclared `xmlns:draw` in styles.xml drops it too). Word keeps the background on `w:document` (plus `w:displayBackgroundShape`), the border in `w:sectPr` **after `w:pgMar`** — the child order is fixed, and ahead of the header references Word's reader loses those — and the watermark as the VML `_x0000_t136` shape, whose definition has to travel or LibreOffice cannot resolve it. `PageDecorLayer.svelte` draws border and watermark per page; the background is a `--color-page-bg` override on `.paper`. ODF lays border + `fo:padding` out *inside* the page margin, shrinking the text area — the editor and Word (`offsetFrom="text"`) keep text at the margin — so the ODT export shrinks every `fo:margin-*` by border + padding and the import grows them back (`decorInsetCm`).
- **`trackChanges.svelte.ts`** — whether the **document** records revisions (`edentext-record-changes`, the key removed when off, as it is by default in both word processors). It travels with the file — ODF `text:track-changes` on the change registry, Word `w:trackRevisions` in settings.xml (both probed against soffice) — so an import adopts the file's flag and a new document starts off; only the open document's state lives under the key. A reactive singleton because the extension reads it on every transaction while the Review tab flips it; the recorded changes themselves live in the document, on the marks.
+15 -6
View File
@@ -3,24 +3,33 @@
// their own (`.bau`, a `.dotx`); here they live in localStorage, so they outlive the
// document that made them.
import type { JSONContent } from '@tiptap/core';
export type AutoTextEntry = {
name: string;
/** Typed in the text, then F3 — LibreOffice's shortcut, case-insensitive. */
shortcut: string;
/** The entry's content as HTML, parsed back through the schema on insert. */
html: string;
/** The entry's nodes, or the HTML an entry stored before they were kept as JSON. */
content: JSONContent[] | string;
};
const KEY = 'edentext-autotext';
/** The entry's content, taking an older entry's `html` as the string it already is. */
function contentOf(e: AutoTextEntry & { html?: unknown }): AutoTextEntry['content'] | null {
if (Array.isArray(e.content) || typeof e.content === 'string') return e.content;
return typeof e.html === 'string' ? e.html : null;
}
export function loadAutoText(): AutoTextEntry[] {
try {
const raw = localStorage.getItem(KEY);
const data = raw ? (JSON.parse(raw) as AutoTextEntry[]) : [];
return Array.isArray(data)
? data.filter((e) => e && typeof e.name === 'string' && typeof e.html === 'string')
.map((e) => ({ name: e.name, shortcut: String(e.shortcut ?? ''), html: e.html }))
: [];
if (!Array.isArray(data)) return [];
return data.flatMap((e) => {
const content = e && typeof e.name === 'string' ? contentOf(e) : null;
return content === null ? [] : [{ name: e.name, shortcut: String(e.shortcut ?? ''), content }];
});
} catch {
return [];
}
+65 -3
View File
@@ -1,16 +1,21 @@
// LibreOffice's AutoText: a stored block of text, inserted by name or by typing its
// shortcut and pressing F3. The entries belong to the app, not to a document.
import { describe, it, expect, beforeEach } from 'vitest';
import { Editor } from '@tiptap/core';
import { Editor, getHTMLFromFragment } from '@tiptap/core';
import Document from '@tiptap/extension-document';
import Paragraph from '@tiptap/extension-paragraph';
import Text from '@tiptap/extension-text';
import Bold from '@tiptap/extension-bold';
import Heading from '@tiptap/extension-heading';
import ListItem from '@tiptap/extension-list-item';
import { BulletList } from '../../src/lib/editor/extensions/bulletList';
import { OrderedList } from '../../src/lib/editor/extensions/orderedList';
import { TextBox } from '../../src/lib/editor/extensions/textBox';
import { AutoText } from '../../src/lib/editor/extensions/autoText';
import { entryForShortcut } from '../../src/lib/storage/autoText';
import { entryForShortcut, loadAutoText } from '../../src/lib/storage/autoText';
import { setAutoTextEntries } from '../../src/lib/storage/autoText.svelte';
const entry = { name: 'Greeting', shortcut: 'mfg', html: '<p>Yours, <strong>Ada</strong></p>' };
const entry = { name: 'Greeting', shortcut: 'mfg', content: '<p>Yours, <strong>Ada</strong></p>' };
describe('the shortcut', () => {
it('matches ignoring case, and only whole', () => {
@@ -54,3 +59,60 @@ describe('expanding in the editor', () => {
e.destroy();
});
});
// An entry keeps the nodes themselves. Serialized to an HTML string a text box loses
// its place in the line: any block tag inside a <p> closes it, and the box holds blocks.
describe('an entry holding a text box', () => {
const box = {
type: 'textBox',
attrs: { width: 160, height: 60 },
content: [{ type: 'paragraph', content: [{ type: 'text', text: 'KASTEN' }] }],
};
const line = [{ type: 'paragraph', content: [{ type: 'text', text: 'vor ' }, box, { type: 'text', text: ' nach' }] }];
(globalThis as any).ResizeObserver ??= class {
observe() {}
unobserve() {}
disconnect() {}
};
function boxEditor(content: any[]) {
const el = document.createElement('div');
document.body.appendChild(el);
return new Editor({
element: el,
extensions: [Document, Paragraph, Text, Bold, Heading, BulletList, OrderedList, ListItem, TextBox, AutoText],
content: { type: 'doc', content },
});
}
it('puts the box back where it stood in the line', () => {
const src = boxEditor(line);
const stored = src.state.doc.slice(0, src.state.doc.content.size).content.toJSON() as any[];
const dst = boxEditor([{ type: 'paragraph' }]);
dst.commands.insertAutoText({ name: 'Box', shortcut: '', content: stored });
const para = dst.state.doc.child(0);
expect(dst.state.doc.childCount).toBe(1);
expect(para.content.child(1).type.name).toBe('textBox');
src.destroy();
dst.destroy();
});
it('would not, as an HTML string', () => {
const src = boxEditor(line);
const html = getHTMLFromFragment(src.state.doc.content, src.schema);
const dst = boxEditor([{ type: 'paragraph' }]);
dst.commands.insertAutoText({ name: 'Box', shortcut: '', content: html });
expect(dst.state.doc.childCount).toBeGreaterThan(1);
src.destroy();
dst.destroy();
});
});
describe('an entry stored before the nodes were kept', () => {
it('loads with its HTML as the content', () => {
localStorage.setItem('edentext-autotext', JSON.stringify([{ name: 'Old', shortcut: 'o', html: '<p>hi</p>' }]));
expect(loadAutoText()).toEqual([{ name: 'Old', shortcut: 'o', content: '<p>hi</p>' }]);
localStorage.removeItem('edentext-autotext');
});
});