Files
edentext/src/lib/editor/extensions/CLAUDE.md
T
Steffen Becker 1a4b321b5a perf: the spell check re-reads the edited paragraphs, not the document
The dirty ranges ride the plugin state and are mapped through every
transaction; the check after a pause swaps only those textblocks'
squiggles, and the whole document is checked on a language or
dictionary change. The pause after a keystroke in a 124-page document
drops from 363 ms to 11 ms (Chromium) and from 1.4 s to 17 ms (Firefox).
A unit test drives the recheck; the dom run asserts the pause is free.
2026-09-08 18:07:41 +02:00

24 KiB
Raw Blame History

src/lib/editor/extensions/

One file per feature (image.ts, indent.ts, …), never XyzExtension.ts. All are assembled in ../extensions.ts, which also lists the TipTap built-ins in use (Bold, Italic, Highlight multicolor, TextStyle/FontFamily/FontSize, Heading, HardBreak, lists, Table family, History, Placeholder, TextAlign). Document is widened to '(block | textBox | columns)+ noteSection?'.

Five topics are large enough to have their own deep-dive — read the file before changing them:

Extension Deep-dive
pageBreaks.ts, columns.ts, columnsFlow.ts docs/architecture/pagination.md
image.ts, textBox.ts docs/architecture/frames.md
table*.ts, tableStyle.ts docs/architecture/tables.md
textEffects.ts, indent.ts, tabStops.ts, listMarker.ts, paragraphBox.ts, dateTimeField.ts, bookmark.ts, crossReference.ts docs/architecture/formatting.md
formula.ts docs/architecture/formulas.md
notes.ts docs/architecture/notes.md
paragraphStyle.ts, characterStyle.ts src/lib/styles/CLAUDE.md

The rest, one line each

  • fontColor.ts (FontColor) — color attr on the TextStyle mark; also emits data-color so theme CSS (allBlack) can target color-bearing spans.
  • fontWeight.ts (FontWeight) — fontWeight attr on TextStyle (set normal to un-bold a heading without changing the node type). A parsed weight Bold already claims (bold/bolder/500+) is dropped: both files spell a run's weight as bold or not, so the attr would only repeat the mark and be lost on save.
  • fontFamily.ts (FontFamily) — TipTap's, with a parse that keeps the first family of a value. A contenteditable types over a mixed selection by inserting a span carrying the computed style, so an unguarded parse lands a whole CSS stack (Arial, "Liberation Sans", sans-serif) as the font name — no name the picker or either file can use. A paste from the web arrives the same way.
  • lineHeight.ts (LineHeight) — lineHeight attr on paragraph/heading. LINE_HEIGHT_RATIO = 1.15: ODF line spacing multiplies the font's natural line height (Liberation Serif ≈1.15× em), CSS multiplies the font size — so the on-screen value is scaled to match what LibreOffice renders. A spacing above single puts all of its extra leading below each line (probed: at 150% LibreOffice starts line 1 flush under the block above and adds 6.9pt after every line, the last included); CSS half-leads it, so editor.css shifts the block up by that half with position:relative; top:, which leaves the flow alone — but offsetTop reports the drawn position, not the flow one, so pageBreaks.ts (topWithin) takes the shift back off; without that a block pushed to a page top landed half a leading low.
  • paragraphSpacing.ts (ParagraphSpacing) — spaceBefore/spaceAfter in pt, round-tripping 1:1 to fo:margin-top/fo:margin-bottom. Space after is a margin, space before rides --space-before (storage/spacingModel.ts decides padding vs margin); pageBreaks.ts drops it where a page break put the block at a page top, as LibreOffice does. Both also ride --space-after/--space-before so editor.css can swap the pair inside a multi-column section: there the space above is the margin and the space below the padding, because every engine truncates a margin at a column break but keeps padding — so each column starts level (as LibreOffice draws it) and the add model's two spacings still sum. A named style's border padding yields to that swap.
  • blockFontSize.ts — the font of the paragraph mark (Word w:pPr/w:rPr, ODF the paragraph's own text properties).
  • pageBreak.ts — the text-flow attrs of a paragraph/heading: breakBefore: 'page', plus keepNext/keepLines (see docs/architecture/pagination.md). Owns Mod-Enter. A plugin sweeps breakBefore off every block whose ancestors are not all doc/columns/list: inside a table cell, a frame or a note body both formats drop it (probed), so keeping one would be a break that vanishes on save.
  • textDirection.ts — a block's own base direction (dir attr; ODF style:writing-mode, Word w:bidi), overriding the page's (storage/writingMode.ts). The HTML dir is the whole rendering — it resolves the bidi run order and text-align: start follows it, so an unaligned block flips. Both importers suppress the direction the page already has: it is inheritance, not formatting. Set in ParagraphDialog.svelte, where LibreOffice keeps it.
  • formattingMarks.ts (FormattingMarks) — decorations marking spaces (·) and tabs (→) when .paper.show-formatting-marks is set.
  • bulletList.ts / orderedList.ts — the TipTap lists plus a marker-type attr: setBulletChar (innermost list, null = default cycle) and the ordered numbering cycle (utils/orderedListTypes.ts, multilevel targets the outermost list).
  • listStyle.ts — the named list style (listStyleName on the outermost list; nested lists inherit) and the walk resolving every list's effective marker (data-eff-list-style, data-bullet+--bullet, indent, label alignment) from node attr > style level > depth cycle — the style level decides the depth's kind, so a number level numbers a <ul> (counter-offset via counter-reset, since <ul> ignores start); setListStyle assigns (clearing the subtree's direct marker attrs and retyping each list to its level's kind), listStyleNameAt feeds the dropdowns — see src/lib/styles/CLAUDE.md.
  • link.ts — hyperlink mark; owns Mod-k, which fires the event Toolbar.svelte listens for to open the link dialog. A #name href targets a bookmark: Editor.svelte's handleClick scrolls to it instead of opening a tab. The plain attr (data-plain, editor.css) suppresses the editor's own blue: Word paints a link through its Hyperlink character style, which arrives as an ordinary mark, so every DOCX link is plain and one carrying no style is drawn like the text around it — while LibreOffice paints every ODF text:a styled or not (probed), so those never are. The DOCX exporter paints #0563C1 only on a non-plain link, which is how a round trip tells its own links from a file's.
  • comment.ts — an annotation on a range of text, a mark like bookmark: the whole comment (author, date, body, resolved) rides its attrs, so two runs of one comment merge back together and no second store is needed. commentRanges(doc) walks every range (an id split by a paragraph boundary yields several, which is why the commands walk all of them), comments(doc) keeps one per id for CommentsPane.svelte. A point comment — LibreOffice's, made with nothing selected, written with no office:name and no end element — attaches on import to the run before it, else the one after: the editor's comment is a mark and needs a range. A comment carries its thread in the same attrs (replies, one entry per answer, appended by replyToComment): ODF gives an answer its own office:annotation naming its comment in loext:parent-name (probed) and Word its own w:comment tied by w15:paraIdParent in commentsExtended.xml, so both importers fold the answers back into the comment they belong to instead of listing them beside it. commentIdAt(state) is the comment the selection lies within, which a plugin tints heavier (pm-comment-active, skipping a resolved one) and CommentsPane.svelte, ChangeBarLayer.svelte and ConnectorLayer.svelte each mark their own half of. It compares ranges, not the marks at the caret: the mark is non-inclusive, so $pos.marks() is empty at either end of it — and a click on the pane's card selects exactly that range, which would then match nothing.
  • trackChanges.ts — the insertion/deletion marks plus the recording plugin. appendTransaction marks whatever a transaction added, and adjacentInsertion reuses the id of the run just before it when the author matches, so a typed sentence is one change and not one per keystroke. A delete never reaches the document: filterTransaction rejects it and dispatches a mark pass instead (the author's own pending insertion is removed for real, as both word processors do). A replacement — typing or pasting over a selection — goes the same way (replacedRange), the new content landing after the struck-out text it replaces; recorded as the insertion alone, its other half was simply dropped and a reject lost the original. Every transaction of our own carries the RECORDING meta — accept/reject included, or its tr.delete would be read as a fresh user deletion and marked up again. Loading a document carries it too (App.svelte's loadContent, both for a new document and for an import): a setContent is one transaction that inserts the whole file, so without the meta an opened document arrives wholly marked as the reader's own insertion, underlined in the author colour. Both word processors record what is typed after an open, never the file. revisions(doc) merges adjacent runs of one id, so an export writes one change per id. The author's colour is a decoration, not the mark: a mark cannot know the document's other authors, so a plugin walks the revisions, hands out REVISION_AUTHOR_COLORS (LibreOffice's own author palette) in order of first appearance and paints pm-rev-ins/-del + pm-rev-a<n>. That span nests inside the mark's, so it carries the underline/strikethrough too — drawn by the ancestor it would take the fallback colour. Cached on the doc; the walk is the whole document and decorations runs on every view update. The plain option (from storage/markup) drops the decoration entirely where the display mode shows a finished text — and it is part of the cache key, or the set built before the switch would stand. acceptRevision(id)/rejectRevision(id) apply every range of one change, which is what RevisionsPane.svelte lists as one row. revisionIdAt(state) is the change the selection lies within — the row the pane marks and the margin bar ChangeBarLayer.svelte draws heavier — compared by range for the same reason commentIdAt is.
  • placeholderField.ts — a template placeholder, an inline atom drawn gray as ‹label›: a click selects the whole field (NodeSelection) and typing replaces it; Tab/Shift-Tab from a selected field jump to the next/previous one. Round-trips to ODF <text:placeholder> and a tagged DOCX w:sdt content control.
  • caption.ts — a caption is an ordinary paragraph in the Caption style (LibreOffice's, probed: 10pt italic, 0.212cm above and below) holding one sequenceField atom, its running number. sequenceFields(doc) counts one counter per category in document order; the cached number attr is what an export writes, and an appendTransaction (off the undo stack) plus an onCreate pass keep it true — a file's own cached numbers are unreadable wherever the format is not arabic. The counter's name differs per format: ODF Illustration/Table, Word Figure/Table, and ODF_SEQ_CATEGORY reads both back. The caption paragraph is boxed to the frame it captions (captionPlacement), so it stands under the picture instead of at the margin: LibreOffice frames picture and caption together, and a loose paragraph carries that over as indent/indentRight — the frame's own span in the column, measured (frameSpanCm), since that span comes from the wrap, the offset and the column, not from one attr. The indent is also what lifts the caption clear of a side-wrapped frame: a line with no room beside a float drops below it. It is centred in that box only under a frame that is itself centred; a block with no frame at all has only its own alignment to pass on. getFrameDebug reports the same two spans for the debug dump. CaptionDialog.svelte (References tab) owns the insert.
  • ruby.ts — a reading printed over its base (LibreOffice's Format ▸ Asian Phonetic Guide, Word's Phonetic Guide). An inline atom carrying both halves, because that is what both formats write: one element holding a base and a reading, edited as a unit (RubyDialog.svelte). Rendered as a real <ruby>, so the browser sets it. Alignment and position are both products' defaults and are not offered.
  • bookmark.ts / crossReference.ts — a named range of text (a mark) and the live references to it (REF/PAGEREF). ToolbarExpanded.svelte owns both dialogs, as it does the link one.
  • searchReplace.ts — Find & Replace: decorations highlight all matches, commands navigate/replace. Touches the document only for actual replacements. useRegex takes the term as a pattern instead of escaping it (a whole-word search then wraps it in a non-capturing group first, so the \b guards bound the alternation); each match keeps its captures so expandGroups can fill $1…$9/$& in the replacement. A FormatSpec (weight/slant/underline, font, size and colour — LibreOffice's Format… — plus a paragraph style, its Paragraph Styles box) narrows a text search to the runs carrying it, and with no term is the search: every such run, or every paragraph in the style, empty ones included. The same spec on the replacement applies it — and a replacement with no text keeps the text and only reformats, which is how both dialogs restyle a document without retyping it. A style also switches the node type, as setParagraphStyle does, so the extension takes the same sheet option. Font, size and colour live together on one TextStyle mark, and a mark of one type replaces that type whole, so each run's own attrs are the base of the new one — replacing the colour leaves the font alone. Sizes compare by value (12pt and 12.0pt are one size), colours and family names case-insensitively.
  • spellCheck.ts — decorations from spell/controller.ts; spellErrorAt feeds the context menu, wordRangeAt the thesaurus (the word at a position, misspelled or not). Both define a word the same way, so what is looked up is what is highlighted. The check after a pause looks only at the textblocks edited since the last one (the dirty ranges ride the plugin state, mapped through every transaction) and swaps their squiggles in the set; the whole document is checked on a language or dictionary change. Building the whole set walks every block for every squiggle, seconds on a long document.
  • outline.ts — the document's chapters for NavigatorPane.svelte: every top-level heading owning the blocks up to the next heading of its level or above (one inside a cell or a text box is not a chapter — moving it would move it out of its container). The two operations are pure functions the commands only apply: chapterMove returns the range to lift and where to put it back — the insert position for a move down is already corrected for the delete — and chapterLevels the headings a promote/demote rewrites, null when any of the subtree would leave 1…maxLevel. A move swaps with the adjacent chapter at the same level and stops at a heading above it, so a subheading never reparents itself; the level shift rewrites styleName too, or the paragraph would keep the old heading's look.
  • indexEntry.ts — one place marked for the alphabetical index: an inline atom, not a mark, because that is what both formats write (a point text:alphabetical-index-mark, a Word XE field). It carries the term, so the marked text and the word the index lists can differ, plus key1 for the heading it files under. indexRows merges the marks into the index's rows — one per term, its pages de-duplicated and sorted, the terms sorted case-insensitively by locale.
  • bibliographyEntry.ts — one citation, an inline atom carrying the whole source record (identifier, type, and every remaining ODF field in one fields record, so a file's fields we have no UI for still round-trip). ODF puts that record on the mark itself, which is what lets the document travel without a database; Word keeps it in a custom-XML part and cites it by tag, so the same attrs feed both. The citation style (utils/citationStyle.ts — LibreOffice's cite-by-key, numbered, APA, MLA, Chicago) rides the bibliography index's node, which is where both formats keep it: a row is a token list, exactly what an ODF entry template is, so LibreOffice regenerates the same rows (it fills the types the document does not cite with its own default, so the import takes the first template reading as anything but key). Word gets the style as b:Sources StyleName. Each citation's label is derived, kept true by an appendTransaction off the undo stack like the caption numbers. bibliographyRows is the list: one row per source, in document order — LibreOffice's own default is document position, not alphabetical — reading "key: author, title, year", the shape its entry templates produce. DOCX_SOURCE_TYPE/DOCX_BIB_FIELD map onto Word's smaller set, and the fields it has no slot for survive only the ODF leg.
  • tableOfContents.ts — a generated index. The index attr picks the family: toc lists every heading down to maxLevel (ODF text:outline-level, Word's TOC \o range, default 5 — listing deeper than the file asks inflates the block by pages). title: '' is an index that deliberately has none (its heading is a separate paragraph, as Word and LibreOffice write it); only a missing title falls back to "Table of Contents". levelStyles is the named paragraph style each level's entries use (ODF's per-level entry template, which is what LibreOffice regenerates from — the cached body paragraphs point at automatic styles derived from it): the rows carry it as data-style, so the document stylesheet gives them the file's own indent, space-before and font, and editor.css's 0.5cm-per-level fallback applies only to an index that names none. figures/tables instead list every caption paragraph counting that category (caption.ts), single-level as LibreOffice's are — ODF text:illustration-index/text:table-index (found by text:caption-sequence-name, not by outline level), Word the same TOC field with \c "Figure". bibliography lists the sources cited (bibliographyEntry.ts) and is the one family that never has a page number or a leader — a bibliography row is the source and nothing else, which is how both word processors print one. Any other family drops both where the file says so (pageNumbers: false — Word's TOC \n, an ODF entry template naming no <text:index-entry-page-number/>; the export writes the stop out with the number, which is the pair LibreOffice's own dialog switches together).
  • trailingNode.ts — keeps an empty paragraph after a trailing table, text box or columns section (they are isolating, so the caret would otherwise have nowhere to go). Also the trap at the start: Enter at the very first position of a table with nothing before it inserts a paragraph above and moves the caret there.
  • headerFooter.ts (hfExtensions) — the header/footer schema: Document constrained to one paragraph, the body's marks, HardBreak, TextAlign, and the pageField.ts atoms. No image, no date field, no table.
  • 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 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 unloaded) and supplies the custom table view + drag plugins instead.

What a command refuses, and why (found by tests/monkey/): no note in a text box and no text box in a note (neither format holds one there); no table in a table, a list item or a note (nothing exports a nested one, ODF's list item holds no table, and ProseMirror would wrap one in a text box to fit a note's inline content) — and a cell's content expression says the same (CELL_CONTENT, extensions.ts), since a command's refusal is not the only way one gets in; a selection stops at the notes' boundary (clampToSide); the notes plugin's repairs ride the history event they follow. An anchor that lands where a note cannot live — inside a note, or inside a text box, which a list toggle can pull one into — is dropped by strayRefs, and its note goes with it: Word writes no note in a shape's text, so the .docx lost both silently. Blocks wrapped into a columns section lose a manual page break: pagination breaks a fragment as a whole, so nothing there honours one — and only DOCX could write it.

What the schema refuses (same source): subscript and superscript exclude each other — no run is raised and lowered at once, and a file keeps only whichever it writes last; a noteRef takes no marks at all, since ODF's text:note-citation holds bare text (no span, no style name) and the anchor wears its note class's look anyway. A list item's paragraph keeps no indent of its own — the indent commands already refuse to set one, a list indents by nesting, and neither importer reads one there — so indent.ts clears the three indent attrs whenever a transaction leaves one inside a listItem (wrapping an indented paragraph into a list is the usual door). A table's first row is all header cells or none: both formats spell a repeating header as the whole row, and typing over a selection spanning two of them left one behind (tableHeaderRow.ts) — the promotion carries the cell's own attrs, since setNodeMarkup given a type and no attrs takes the type's defaults. A replace reaching into a table rebuilds the cell it lands in the same way, so tableColumnResize.ts reads the lost column weight back from the column's other rows. A list item holds no table: neither file keeps one there, and a list toggle over a table would wrap it in silently (LIST_ITEM_CONTENT, extensions.ts).