fix: the editor holds no shape either file would drop

A page break reaches the file only from a body block or a list item — a cell,
a frame and a note body all drop it — and an indent on a list item's paragraph
is the same; a plugin sweeps both. A note anchor keeps no marks and stays out
of a text box. Sub- and superscript exclude each other, a font stack the
contenteditable leaves behind keeps its first family, and a weight Bold already
claims is no second attribute. A table's first row is all header cells or none
(the promotion carrying each cell's own attrs), a replace into a table reads the
lost column weight back from the column, and a list item holds no table.
This commit is contained in:
Steffen Becker committed 2026-09-06 19:07:20 +02:00
1 parent 7e2eb53ddc
commit 611ec76ba4
12 files changed
+289 -23

No files matched your search

+1 -1
View File
@@ -5,7 +5,7 @@ list markers, paragraph boxes, date/time fields and cross-references.
- **`textEffects.ts`** (`TextEffects`, `UnderlineStyled`, `StrikeStyled`) — the character effects beyond bold/italic that both formats carry and CSS can draw: `caps` (`uppercase`/`lowercase`/`capitalize`/`smallCaps` → `text-transform`/`font-variant-caps`) and `textPosition` (pt above the baseline → `vertical-align`, independent of sub/superscript) as TextStyle attrs, plus `lineStyle`/`lineColor` on the **underline** mark and `lineStyle` on **strike** (the `<u>`/`<s>` element draws the line, so its shape belongs there). Replaces TipTap's bare Underline/Strike in `extensions.ts` **and** `hfExtensions`. `caps` is also a `TextProps` key, so a named style can carry it. **DOCX**: `w:caps`/`w:smallCaps` (toggles — a run may switch a style's off), `w:u w:val`+`w:color`, `w:dstrike`, `w:position` (`ST_SignedHpsMeasure`: a bare number is half-points, else a measure with its unit). **ODF**: `fo:text-transform`/`fo:font-variant`, `style:text-underline-style`/`-type`/`-color`, `style:text-line-through-type`, `style:text-position` (a percentage of the font size, so the pt value is converted against the run's own size). odf-kit's run formatting has a field for none of them, so `markTextEffects` prefixes the `TEF` sentinel (U+E00F) on the run and `applyTextEffects` folds the attributes into that run's automatic text style — before `applyCharacterStyles`, which then clones the style that already carries them. `tests/lo-roundtrip.test.ts` is what proves LibreOffice reads each one back. **Sub- and superscript** are TipTap's own marks, but their `<sup>`/`<sub>` need `editor.css`'s `font-size: 58%; line-height: 0` on `.paper` (a header/footer zone carries the marks too, and its height is what pagination reserves) — the size both exporters write as `style:text-position`, and the zero line height keeps the raised run out of the line box the way LibreOffice does (measured: its raised run stays within 0.25pt of the plain line's box). The browser's `smaller` + `vertical-align: super` instead grew every such line by ~4px, which is enough to push a block that ends near the page edge onto the next page.
- **`paragraphBox.ts`** (`ParagraphBox`) — paragraph/heading **background** (`backgroundColor`, "colored field") + per-side **borders** (`borderTop/Right/Bottom/Left`, "rule line"), as in Word/LibreOffice letterheads. Borders reuse table cells' canonical `'<W>pt solid #RRGGBB'` (from `tableCellBorders.ts`), but here `null`/absent = no border. Commands `setParagraphBackground`/`setParagraphBorders(preset, spec)`; `activeParagraphBorderPresets` drives the picker states. An input rule turns a paragraph typed as `---`/`___`/`===` into an empty bottom-rule line (the border-line AutoCorrect); attrs are `keepOnSplit: false` so the box doesn't cascade onto the next paragraph on Enter. In both `extensions.ts` (body) and `hfExtensions` (header/footer). **ODF**: import reads `fo:background-color`/`fo:border-*` in `blockAttrs` (body) and merges them across the collapsed header/footer paragraphs (`convertHfZone`, first/last heuristic — bottom rule from the last line); export emits them via `ParaStyle`/`paraStyleProps` for cells/lists, a `PBX`-sentinel post-process (`applyParagraphBoxes`, odf-kit has no such options) for top-level body paragraphs, and `applyHfPostProcess` for the Header/Footer styles. **DOCX**: `w:shd`/`w:pBdr` (import `readParaBox`, export `paraShadingOf`/`paraBordersOf`). A *style's* box is not the block's: it goes to the **style registry** (`ParaProps.borderTop…`, `stylePara`/`DocxStyles.paragraphBorders`), so every paragraph the style governs draws it. `ParaProps.borderPadding` (pt) is the gap the file keeps between the text and its rule — Word's per-side `w:pBdr w:space`, ODF's `fo:padding-*` — and `declarations` puts it on the **ruled sides only**: a bottom rule that also padded the top would push the paragraph's first line down (measured: a Title's next block sat 1.4mm low). Where no file value exists, `editor.css`'s flat 0.04/0.08cm on a bordered block still applies. UI: a paragraph-shading `ColorPicker` + `ParagraphBorderPicker.svelte` in `ToolbarExpanded.svelte` (route via `activeEditor`, so body and the active HF zone).
- **`indent.ts`** (`Indent`) — `indent` attr in **cm** (rendered as `margin-left`), on paragraph/heading **and** bulletList/orderedList. `indentMore`/`indentLess` step a paragraph/heading by `INDENT_STEP_CM = 1.25` → `fo:margin-left` (odf-kit `indentLeft`); `indentListMore`/`indentListLess` step the innermost list's `indent`, shifting the whole list (export adds it to the L# list-style level margins, see `applyListIndents`). On a list the attr is **one level's step past the level above**, not its absolute position: both formats store a level's indent absolutely (`w:lvl/w:pPr/w:ind w:left`, the label-alignment `fo:margin-left`) while the editor nests one 1.27cm step per level, so import subtracts the level above and the ODF export adds the running sum back per level. That is what lets a file's own level geometry survive at any depth — measured, a 0.5cm/−0.6cm pair puts LibreOffice's two levels at 1.77cm and 2.44cm, where the editor draws them. `indentListForward`/`indentListBackward` apply one Word/LibreOffice step to the list point (bullet + text): **forward** shifts the whole list when the cursor is in the first item or the whole list is selected (`indentListMore`), otherwise nests the item (`sinkListItem`); **backward** is the inverse — it peels back the innermost list's own `indent` first (`indentListLess`), then lifts a *nested* item out one level (`liftListItem`), and at the base level (no margin, not nested) does nothing. So a list point steps left one tab-stop at a time and never gets dissolved into a paragraph — Shift-Tab keeps list points as list points. They return false outside a list. `indentRight` is the mirror of `indent` (`fo:margin-right` / `w:ind w:right`; ODF export rides the PBX sentinel, since odf-kit has no right-indent option). `setIndent(cm)`/`setIndentRight(cm)`/`setIndentFirst(cm)` write one indent outright (what the ruler drags; the buttons step relatively) — all go through the same `write` walk. The exported `listContext(state)` (cursor in a list? whole list targeted? innermost list indent? list nested inside a parent list item?) is their shared helper. Both the toolbar's `changeIndent` and the **Tab**/**Shift-Tab** keymap call these: in a list Tab/Shift-Tab run `indentListForward`/`indentListBackward`; outside a list Tab inserts a real tab character (`\t`, rendered via the document's `tab-size`) and Shift-Tab runs `indentLess` (`changeIndent` uses `indentMore`/`indentLess`). The keymap bails inside table cells so the Table extension's Tab keeps navigating between cells. `Indent` sets `priority: 1000` so its Tab/Shift-Tab win over `ListItem`'s built-in sink/lift bindings — without it, TipTap's reverse-then-priority-sort lets the later-registered `ListItem` handle the key first (its `liftListItem` would dissolve a top-level list item into a paragraph on Shift-Tab).
- **`indent.ts`** (`Indent`) — `indent` attr in **cm** (rendered as `margin-left`), on paragraph/heading **and** bulletList/orderedList. `indentMore`/`indentLess` step a paragraph/heading by `INDENT_STEP_CM = 1.25` → `fo:margin-left` (odf-kit `indentLeft`); `indentListMore`/`indentListLess` step the innermost list's `indent`, shifting the whole list (export adds it to the L# list-style level margins, see `applyListIndents`). On a list the attr is **one level's step past the level above**, not its absolute position: both formats store a level's indent absolutely (`w:lvl/w:pPr/w:ind w:left`, the label-alignment `fo:margin-left`) while the editor nests one 1.27cm step per level, so import subtracts the level above and the ODF export adds the running sum back per level. That is what lets a file's own level geometry survive at any depth — measured, a 0.5cm/−0.6cm pair puts LibreOffice's two levels at 1.77cm and 2.44cm, where the editor draws them. `indentListForward`/`indentListBackward` apply one Word/LibreOffice step to the list point (bullet + text): **forward** shifts the whole list when the cursor is in the first item or the whole list is selected (`indentListMore`), otherwise nests the item (`sinkListItem`); **backward** is the inverse — it peels back the innermost list's own `indent` first (`indentListLess`), then lifts a *nested* item out one level (`liftListItem`), and at the base level (no margin, not nested) does nothing. So a list point steps left one tab-stop at a time and never gets dissolved into a paragraph — Shift-Tab keeps list points as list points. They return false outside a list. `indentRight` is the mirror of `indent` (`fo:margin-right` / `w:ind w:right`; ODF export rides the PBX sentinel, since odf-kit has no right-indent option). `setIndent(cm)`/`setIndentRight(cm)`/`setIndentFirst(cm)` write one indent outright (what the ruler drags; the buttons step relatively) — all go through the same `write` walk. The exported `listContext(state)` (cursor in a list? whole list targeted? innermost list indent? list nested inside a parent list item?) is their shared helper. Both the toolbar's `changeIndent` and the **Tab**/**Shift-Tab** keymap call these: in a list Tab/Shift-Tab run `indentListForward`/`indentListBackward`; outside a list Tab inserts a real tab character (`\t`, rendered via the document's `tab-size`) and Shift-Tab runs `indentLess` (`changeIndent` uses `indentMore`/`indentLess`). The keymap bails inside table cells so the Table extension's Tab keeps navigating between cells. `Indent` sets `priority: 1000` so its Tab/Shift-Tab win over `ListItem`'s built-in sink/lift bindings — without it, TipTap's reverse-then-priority-sort lets the later-registered `ListItem` handle the key first (its `liftListItem` would dissolve a top-level list item into a paragraph on Shift-Tab). A **list item's paragraph** carries no indent of its own: the `write` walk skips it, and an `appendTransaction` clears the three attrs wherever one lands there anyway — wrapping an indented paragraph into a list would otherwise keep an indent that neither exporter writes (`collectListItemStyles` passes `withIndents: false`) and neither importer reads back (a list level's own indent is what `fo:margin-left`/`w:ind` means there).
- **`tabStops.ts`** (`TabStops`) — per-paragraph tab stops (Word's `w:tabs`, ODF `style:tab-stops`). Global attr `tabStops` on paragraph/heading, rendered as `data-tab-stops`; canonical string `'<cm><align code>'` per stop, `;`-separated (`'6c;12r;16d'`, codes `l|c|r|d`), parsed only by the exported `parseTabStops`/`formatTabStops`. Positions are **cm from the left text margin** — the origin Word and ODF share, verified by probe (a Word stop at 100mm in a 30mm-indented paragraph stays 100mm in ODF and LibreOffice renders it there), so neither I/O side shifts them by the paragraph indent. **Rendering**: CSS only has the fixed `tab-size` grid, so a rAF measuring plugin (shaped like `pageBreaks.ts`, whose `FORCE_PAGE_RECALC` it both listens to and fires) computes each tab's advance from `coordsAtPos` against `.tiptap`'s content edge and emits `Decoration.inline(tab, tab+1, {style:'tab-size:0;margin-left:Npx'})` — `tab-size:0` collapses the tab's own advance, the inline margin supplies the exact width, so no `display` change and no baseline/line-height side effects. The margin is on the **left** because the gap is the tab's own advance: as `margin-right` a caret placed after the tab rendered before the gap, i.e. at the pre-tab x until the next keystroke. The pen is read from the DOM only at the **first tab of a line** (side −1, the end of the content before it) and then **carried along the line**: stop + the natural width of the segment that follows it. Reading each tab off the DOM instead measures the advance the *previous* pass gave the tab before it, so the layout takes another pass to settle — and on a long document, where pagination keeps moving lines for seconds, it may never get a stable one; the Math Guide's contributor columns landed 18mm out in one run of three. `nextStop` takes the first custom stop right of the tab, else leaves the tab undecorated (past the last custom stop the CSS grid already does the right thing, which is also why custom stops suppress the default ones to their left). A **negative `indentFirst` implies a stop at the block's indent** (the hanging-indent stop). Centre/right/decimal take back the segment up to the next tab, measured by `rangeWidth` as the **extent of each line it covers**, added up — a range crossing an inline element yields a rect for the element's box *and* for the text inside it, and adding those counts the text twice. The scale comes from the editor's **width**: `offsetHeight` is rounded, and a one-line zone is short enough for that to be half a percent. Passes converge (one more tab settles per pass, `MAX_PASSES`), since a stop can rewrap the line. The measured layout is kept as a string key and a pass matching it dispatches nothing — but that key alone is **not** enough to decide the decorations are still applied: replacing the document maps them all away, so the guard also compares the live decoration count, or two documents with the same tab layout (the two DIN 5008 forms, an undo, a reopened file) would leave every tab on the CSS grid. **UI**: `Ruler.svelte`. A **header/footer zone** carries stops too — the left⇥centre⇥right layout rides on them — but an inactive one is static `generateHTML` output no plugin reaches, so `layOutZoneTabs` measures it straight on the DOM (`HeaderFooterLayer.svelte`, `use:layOutTabs`), wrapping each tab in a span of its own. Advances are layout px, so the zoom transform doesn't invalidate them. A decimal stop there behaves as right. Three things that zone needs and the body doesn't: the wrap marker is matched with `hasAttribute` (its value is `''`, which reads as falsy, and every pass nested another span with its own advance), the segment is measured with wrapping off (one already wrapped reads short by the space its break swallowed, which keeps it wrapped), and a stop past the line is drawn at the line's end — LibreOffice's own footer style puts its right stop at 18cm in a 17cm column. The body clamps the same way. A stop may carry a **leader** (`w:tab w:leader` / `style:leader-text`, one of `. - _ ·`), drawn as a `::before` clipped to the measured gap so the fill stays out of the document's text; on the ODF side odf-kit has no leader option and mints one automatic style per option set, so the leader rides `style:type` behind a `LEAD` sentinel that `applyTabLeaders` unpacks — a bare position+type lookup would give two stops that agree on both the same leader. Past the last custom stop the grid is the document's own **default tab interval** (`storage/tabInterval.ts`, 1.25cm for a new document — LibreOffice's; Word's is 1.27): imported from `w:defaultTabStop` / the paragraph default-style's `style:tab-stop-distance`, applied as the `--tab-interval` CSS var, and **always** written back on export. A file that declares none falls back to its format's own value — measured, LibreOffice puts a bare `A⇥X` at **2cm**, not at its UI default — so leaving ours implied would render differently everywhere Line truncated
A **run of tabs wider than the line** continues on the next one with the grid starting over, as LibreOffice lays it out; Chromium instead hangs the leftover tabs and starts the next line at the margin. `runBreaks` walks the run analytically from the pen *before* it — the one thing the fix can't move, so the answer is the same whether or not the break is already in place — and emits a `<br>` widget where the line runs out. Only runs of two or more are considered: reading a block's geometry forces a reflow, and doing it for every tab in a 48-page document slowed pagination enough to skew the parity harness.
+10 -4
View File
@@ -10,7 +10,8 @@ import Highlight from '@tiptap/extension-highlight';
import { Link } from './extensions/link';
import { Bookmark } from './extensions/bookmark';
import { Comment } from './extensions/comment';
import { TextStyle, FontFamily, FontSize } from '@tiptap/extension-text-style';
import { TextStyle, FontSize } from '@tiptap/extension-text-style';
import { FontFamily } from './extensions/fontFamily';
import { FontWeight } from './extensions/fontWeight';
import { FontColor } from './extensions/fontColor';
import HardBreak from '@tiptap/extension-hard-break';
@@ -82,6 +83,7 @@ import { loadDocProperties } from '../storage/docProperties';
import { Insertion, Deletion, TrackChanges } from './extensions/trackChanges';
const CELL_CONTENT = '(paragraph | heading | bulletList | orderedList)+';
const LIST_ITEM_CONTENT = 'paragraph (paragraph | heading | bulletList | orderedList)*';
export const extensions = [
// columns has its own group so only the document (not cells/lists) admits it; the
@@ -105,8 +107,10 @@ export const extensions = [
// An annotation on a range of text; round-trips to ODF office:annotation and DOCX
// w:commentRangeStart/-End + word/comments.xml.
Comment,
Subscript,
Superscript,
// Neither format can raise and lower the same run, and the file keeps whichever it
// writes last — so each drops the other instead of stacking with it.
Subscript.extend({ excludes: 'subscript superscript' }),
Superscript.extend({ excludes: 'subscript superscript' }),
TextStyle,
FontFamily,
FontSize,
@@ -191,7 +195,9 @@ export const extensions = [
Heading.extend({ addKeyboardShortcuts: () => ({}) }).configure({ levels: HEADING_LEVELS as Level[] }),
BulletList,
OrderedList,
ListItem,
// The tail is narrower than `block*`: neither file keeps a table (or a table of
// contents) in a list item, and a list toggle over one would wrap it in silently.
ListItem.extend({ content: LIST_ITEM_CONTENT }),
// Bullet/number formatting: it follows the item's first text portion, as in
// LibreOffice (the sheet resolves a character style on that portion).
ListMarker.configure({ sheet: styleSheet }),
+23 -3
View File
@@ -20,11 +20,12 @@ Five topics are large enough to have their own deep-dive — read the file befor
## 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).
- **`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.
- **`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`.
- **`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).
@@ -59,6 +60,25 @@ note (nothing exports a nested one, ODF's list item holds no table, and ProseMir
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.
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`).
+29
View File
@@ -0,0 +1,29 @@
import { FontFamily as FontFamilyBase } from '@tiptap/extension-text-style';
// Typing over a mixed selection makes the contenteditable insert a span carrying the
// computed style — a whole CSS stack, which is no font name the picker or either file
// can use. The first family is what renders, so that is the name the mark keeps.
export function firstFontFamily(value: string | null | undefined): string | null {
const first = String(value ?? '').split(',')[0].trim().replace(/^['"]|['"]$/g, '');
return first && !first.startsWith('var(') ? first : null;
}
// The raw style attribute first, as upstream does: element.style canonicalizes a
// single-quoted multi-word name into double quotes.
const declared = (el: HTMLElement): string | null =>
el.getAttribute('style')?.match(/(?:^|;)\s*font-family\s*:([^;]*)/i)?.[1] ?? el.style.fontFamily ?? null;
export const FontFamily = FontFamilyBase.extend({
addGlobalAttributes() {
return (this.parent?.() ?? []).map((group) => ({
...group,
attributes: {
...group.attributes,
fontFamily: {
...(group.attributes as Record<string, object>).fontFamily,
parseHTML: (element: HTMLElement) => firstFontFamily(declared(element)),
},
},
}));
},
});
+6 -2
View File
@@ -26,8 +26,12 @@ export const FontWeight = Extension.create({
attributes: {
fontWeight: {
default: null,
parseHTML: element =>
element.style.fontWeight?.replace(/['"]+/g, '') || null,
// Bold's own parse rule claims bold/bolder/500+, and both files spell a
// run's weight as bold or not — an attr repeating that is dropped on save.
parseHTML: element => {
const w = element.style.fontWeight?.replace(/['"]+/g, '') || null;
return w && !/^(bold(er)?|[5-9]\d{2,})$/.test(w) ? w : null;
},
renderHTML: attributes => {
if (!attributes.fontWeight) return {};
return { style: `font-weight: ${attributes.fontWeight}` };
+20 -1
View File
@@ -1,6 +1,6 @@
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 { Plugin, type EditorState, type 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
@@ -285,4 +285,23 @@ export const Indent = Extension.create({
},
};
},
// A list indents by nesting, so an item's paragraph carries no indent of its own —
// the commands above refuse to set one, and neither file can express it. Wrapping an
// indented paragraph into a list (or pasting one in) is the door this closes.
addProseMirrorPlugins() {
const attrs = ['indent', 'indentRight', 'indentFirst'] as const;
return [new Plugin({
appendTransaction: (trs, _old, state) => {
if (!trs.some((t) => t.docChanged)) return null;
const tr = state.tr;
state.doc.descendants((node, pos, parent) => {
if (node.isInline) return false; // a run holds no indent; skip the text of every block
if (parent?.type.name !== 'listItem' || attrs.every((a) => node.attrs[a] == null)) return;
tr.setNodeMarkup(pos, undefined, { ...node.attrs, indent: null, indentRight: null, indentFirst: null });
});
return tr.steps.length ? tr : null;
},
})];
},
});
+30 -9
View File
@@ -48,6 +48,9 @@ export const NoteRef = Node.create({
group: 'inline',
inline: true,
atom: true,
// The anchor wears its note class's own look, not the run's: ODF's text:note-citation
// holds bare text (no span, no style name), so no mark on it could be saved.
marks: '',
addAttributes() {
return {
@@ -181,16 +184,21 @@ export function findNoteSection(doc: PMNode): { node: PMNode; pos: number } | nu
return { node: last, pos: doc.content.size - last.nodeSize };
}
// Anchors that ended up inside a note — a paste, since inserting one there is refused.
// They reference nothing and carry no number, so the sync pass drops them.
function strayRefsInNotes(doc: PMNode): number[] {
const section = findNoteSection(doc);
if (!section) return [];
// Anchors where a note cannot live: inside a note (a paste — inserting one there is
// refused), or inside a text box, which a list toggle can pull one into. They reference
// nothing a file could carry, so the sync pass drops them.
function strayRefs(doc: PMNode): number[] {
const out: number[] = [];
section.node.descendants((node, pos) => {
const section = findNoteSection(doc);
if (section) section.node.descendants((node, pos) => {
if (node.type.name === 'noteRef') out.push(section.pos + 1 + pos);
});
return out;
doc.descendants((node, pos) => {
if (node.type.name !== 'textBox') return;
node.descendants((inner, at) => { if (inner.type.name === 'noteRef') out.push(pos + 1 + at); });
return false;
});
return out.sort((a, b) => a - b);
}
export function inNote(state: EditorState): boolean {
@@ -377,13 +385,26 @@ export const Notes = Extension.create<NotesOptions>({
if (clamped) return clamped;
}
if (!trs.some((tr) => tr.docChanged || tr.getMeta(RESYNC_NOTES))) return null;
return syncStructure(newState) ?? syncNumbers(newState, getSettings());
return syncStructure(newState) ?? syncNumbers(newState, getSettings()) ?? stripAnchorMarks(newState);
},
}),
];
},
});
// The anchor takes no marks (`marks: ''`): ODF's text:note-citation is bare text, so
// none could be saved, and the anchor draws its note class's look. A mark applied to a
// range is only checked against the parent, so marking across one still reaches it.
function stripAnchorMarks(state: EditorState): Transaction | null {
let tr: Transaction | null = null;
state.doc.descendants((node, pos) => {
if (node.type.name !== 'noteRef' || !node.marks.length) return;
tr ??= state.tr;
tr.setNodeMarkup(pos, undefined, node.attrs, []);
});
return tr;
}
// A selection reaching across the notes' boundary stops at it: a replace over the
// boundary would carry body content into a note, or a note's out — neither product lets
// a selection span the two. The anchor's side wins.
@@ -409,7 +430,7 @@ function syncStructure(state: EditorState): Transaction | null {
// Strays first and on their own: they shift every position after them, and the rest
// of this pass reads positions out of the document it was handed.
const strays = strayRefsInNotes(state.doc);
const strays = strayRefs(state.doc);
if (strays.length) {
const tr = state.tr;
for (let i = strays.length - 1; i >= 0; i--) tr.delete(strays[i], strays[i] + 1);
+25 -2
View File
@@ -1,4 +1,5 @@
import { Extension } from '@tiptap/core';
import { Plugin } from '@tiptap/pm/state';
import { DEFAULT_SHORTCUTS } from '../shortcuts';
// The text-flow attrs of a paragraph/heading, null = default: breakBefore 'page', widow
@@ -137,8 +138,7 @@ export const PageBreak = Extension.create({
.some((r) => r);
},
// Ctrl+Enter: start a new page at the cursor. Splits the block (unless already at its
// start) and marks the following block. Top-level blocks only — breakBefore is ignored
// inside lists/table cells, so there it does nothing.
// start) and marks the following block. Top-level blocks only.
insertPageBreak: () => ({ state, chain }) => {
const { $from, empty } = state.selection;
if ($from.depth !== 1) return false;
@@ -155,4 +155,27 @@ export const PageBreak = Extension.create({
[DEFAULT_SHORTCUTS.pageBreak]: () => this.editor.commands.insertPageBreak(),
};
},
addProseMirrorPlugins() {
// A break only reaches the file from a body block or a list item: inside a table cell,
// a frame or a note body both formats drop it, so the editor holds none there either.
const carriers = ['doc', 'columns', 'bulletList', 'orderedList', 'listItem'];
return [new Plugin({
appendTransaction: (trs, _old, state) => {
if (!trs.some((t) => t.docChanged)) return null;
const tr = state.tr;
state.doc.descendants((node, pos) => {
if (node.isText) return false; // a text box holds blocks, so only a run is a dead end
if (node.attrs.breakBefore !== 'page') return;
const $pos = state.doc.resolve(pos);
for (let d = $pos.depth; d >= 0; d--) {
if (carriers.includes($pos.node(d).type.name)) continue;
tr.setNodeMarkup(pos, undefined, { ...node.attrs, breakBefore: null });
break;
}
});
return tr.steps.length ? tr : null;
},
})];
},
});
@@ -4,6 +4,7 @@ import type { EditorState, Transaction } from '@tiptap/pm/state';
import { Decoration, DecorationSet } from '@tiptap/pm/view';
import type { EditorView } from '@tiptap/pm/view';
import { TableMap, cellAround, pointsAtCell } from '@tiptap/pm/tables';
import type { Node as PMNode } from '@tiptap/pm/model';
import { columnWeightsFromRow, columnPercents } from './tableView';
import { PX_PER_CM } from '../../storage/pageMargins';
@@ -362,6 +363,31 @@ function handleDecorations(state: EditorState, cell: number, edge: EdgeSide): De
// ─── Plugin / extension ──────────────────────────────────────────────────────
// A replace reaching into a table rebuilds the cell it lands in from the type's defaults,
// so that column loses the weight its other rows still carry (redo, which replays the
// recorded step, keeps it — the two then differ). Read the weight back from the column.
function refillColumnWeights(table: PMNode, start: number, tr: Transaction): void {
const map = TableMap.get(table);
const known: (number | null)[] = new Array(map.width).fill(null);
const cells = new Map<number, PMNode>();
for (const pos of new Set(map.map)) {
const cell = table.nodeAt(pos);
if (!cell) continue;
cells.set(pos, cell);
const at = map.colCount(pos);
const cw = cell.attrs.colwidth as number[] | null;
for (let k = 0; k < ((cell.attrs.colspan as number) ?? 1); k++) known[at + k] ??= cw?.[k] || null;
}
for (const [pos, cell] of cells) {
const at = map.colCount(pos);
const cw = cell.attrs.colwidth as number[] | null;
const next = Array.from({ length: (cell.attrs.colspan as number) ?? 1 }, (_, k) => cw?.[k] || known[at + k]);
if (next.every((w) => w) && next.some((w, k) => w !== cw?.[k])) {
tr.setNodeMarkup(start + pos, undefined, { ...cell.attrs, colwidth: next });
}
}
}
export const TableColumnResize = Extension.create({
name: 'tableColumnResize',
@@ -445,6 +471,19 @@ export const TableColumnResize = Extension.create({
},
},
}),
new Plugin({
appendTransaction: (trs, _old, state) => {
if (!trs.some((t) => t.docChanged)) return null;
const tr = state.tr;
state.doc.descendants((node, pos) => {
if (node.isTextblock) return false;
if (node.type.name !== 'table') return true;
refillColumnWeights(node, pos + 1, tr);
return false;
});
return tr.steps.length ? tr : null;
},
}),
];
},
});
+30 -1
View File
@@ -1,7 +1,7 @@
import { Extension } from '@tiptap/core';
import type { CommandProps } from '@tiptap/core';
import type { Node as PMNode } from '@tiptap/pm/model';
import type { EditorState } from '@tiptap/pm/state';
import { Plugin, type EditorState } from '@tiptap/pm/state';
import { selectedRect, isInTable } from '@tiptap/pm/tables';
import { parseTableLook, type TableRegion } from '../../styles/tableStyles';
@@ -116,4 +116,33 @@ export const TableHeaderRow = Extension.create({
toggleHeaderColumnStyle: () => toggleHeaderStyle('column'),
};
},
// Both formats spell a repeating header as the whole first row (ODF's
// table-header-rows, Word's w:tblHeader), so a row of some header cells is a shape no
// file keeps — typing over a selection spanning two of them leaves one behind.
addProseMirrorPlugins() {
return [new Plugin({
appendTransaction: (trs, _old, state) => {
if (!trs.some((t) => t.docChanged)) return null;
const headerType = state.schema.nodes.tableHeader;
if (!headerType) return null;
const tr = state.tr;
state.doc.descendants((node, pos) => {
if (node.isTextblock) return false;
if (node.type.name !== 'table') return true;
const cells: { cell: PMNode; pos: number }[] = [];
let at = pos + 2; // the table's first row starts at pos + 1, its first cell one in
node.firstChild?.forEach((cell) => { cells.push({ cell, pos: at }); at += cell.nodeSize; });
const some = cells.some((c) => c.cell.type === headerType);
if (some && !cells.every((c) => c.cell.type === headerType)) {
// Its own attrs ride along: setNodeMarkup takes the type's defaults without them,
// which would drop the cell's column weight, its shading and its borders.
for (const c of cells) if (c.cell.type !== headerType) tr.setNodeMarkup(c.pos, headerType, c.cell.attrs);
}
return false;
});
return tr.steps.length ? tr : null;
},
})];
},
});
+38
View File
@@ -0,0 +1,38 @@
// A cell rebuilt by a replace loses its column weight; the plugin reads it back from
// the column's other rows, so undo/redo and the saved widths stay put.
import { describe, it, expect } from 'vitest';
import { getSchema } from '@tiptap/core';
import { EditorState } from '@tiptap/pm/state';
import Document from '@tiptap/extension-document';
import Paragraph from '@tiptap/extension-paragraph';
import Text from '@tiptap/extension-text';
import { Table, TableCell, TableHeader } from '@tiptap/extension-table';
import { ResizableTableRow } from '../../src/lib/editor/extensions/tableRow';
import { TableColumnResize } from '../../src/lib/editor/extensions/tableColumnResize';
type N = any;
const schema = getSchema([Document, Paragraph, Text, Table, ResizableTableRow, TableCell, TableHeader, TableColumnResize]);
const cell = (w: number[] | null, t: string): N => ({ type: 'tableCell', attrs: { colspan: 1, rowspan: 1, colwidth: w },
content: [{ type: 'paragraph', content: [{ type: 'text', text: t }] }] });
const row = (...cells: N[]): N => ({ type: 'tableRow', content: cells });
const widths = (doc: N): unknown[] => {
const out: unknown[] = [];
doc.descendants((n: N) => { if (n.type.name === 'tableCell') { out.push(n.attrs.colwidth); return false; } });
return out;
};
describe('column weight refill', () => {
it('fills a lost weight from the column and leaves a new column alone', () => {
const doc = schema.nodeFromJSON({ type: 'doc', content: [
{ type: 'paragraph', content: [{ type: 'text', text: 'x' }] },
{ type: 'table', content: [
row(cell(null, 'a'), cell([20000], 'b'), cell(null, 'c')),
row(cell([30000], 'd'), cell([20000], 'e'), cell(null, 'f'))] }] });
const plugins = (TableColumnResize as N).config.addProseMirrorPlugins.call({ options: {} });
let state = EditorState.create({ schema, doc, plugins });
state = state.apply(state.tr.insertText('!', 1));
// The first column's weight comes back from row two; the third has none anywhere.
expect(widths(state.doc)).toEqual([[30000], [20000], null, [30000], [20000], null]);
});
});
+38
View File
@@ -0,0 +1,38 @@
// The break attr survives only where a file can hold it: a body block or a list item.
import { describe, it, expect } from 'vitest';
import { getSchema } from '@tiptap/core';
import { EditorState } from '@tiptap/pm/state';
import Document from '@tiptap/extension-document';
import Paragraph from '@tiptap/extension-paragraph';
import Text from '@tiptap/extension-text';
import { BulletList, ListItem } from '@tiptap/extension-list';
import { Table, TableCell, TableHeader } from '@tiptap/extension-table';
import { ResizableTableRow } from '../../src/lib/editor/extensions/tableRow';
import { PageBreak } from '../../src/lib/editor/extensions/pageBreak';
type N = any;
const exts = [Document, Paragraph, Text, BulletList, ListItem, Table, ResizableTableRow, TableCell, TableHeader, PageBreak];
const schema = getSchema(exts);
const P = (text: string): N => ({ type: 'paragraph', attrs: { breakBefore: 'page' }, content: [{ type: 'text', text }] });
const doc = schema.nodeFromJSON({
type: 'doc',
content: [
P('body'),
{ type: 'bulletList', content: [{ type: 'listItem', content: [P('item')] }] },
{ type: 'table', content: [{ type: 'tableRow', content: [
{ type: 'tableCell', attrs: { colspan: 1, rowspan: 1, colwidth: null }, content: [P('cell')] }] }] },
],
});
describe('page break carriers', () => {
it('clears the break in a table cell and keeps the body ones', () => {
const plugins = (PageBreak as N).config.addProseMirrorPlugins.call({ options: { types: [] } });
const state = EditorState.create({ schema, doc, plugins });
// Any doc change runs the sweep; the insert itself carries no break.
const after = state.apply(state.tr.insertText('!', 1));
const kept: string[] = [];
after.doc.descendants((n) => { if (n.attrs.breakBefore === 'page') kept.push(n.textContent); });
expect(kept).toEqual(['!body', 'item']);
});
});