fix: the caret reaches the position a text box occupies
A box that starts its paragraph was a trap: there is no text position beside it, so the browser pulled the caret meant for the box's own place in the line into the frame and everything typed there landed inside it. A frame nobody is editing is now an atom to the browser — a contenteditable node decoration, dropped while the caret is in its text, the frame placing the caret itself on the click that enters it. ArrowLeft/ArrowRight at the box's first and last text position step out to it. The decoration walk enters blocks, without which it never reached an inline box at all.
This commit is contained in:
1 parent
f0cf382fb0
commit
8d3139439c
3 files changed
+102
-10
No files matched your search
@@ -4,7 +4,7 @@ Covers `src/lib/editor/extensions/image.ts` and `textBox.ts` — node views, res
|
||||
handles, wrap modes, frame offsets — and their ODF/DOCX legs.
|
||||
|
||||
- **`image.ts`** (`Image`) — inline, as-character image atom (Word's "in line with text"). Attrs: `src` (data-URI), `alt`, `width`/`height` (**unscaled doc px @96dpi**, like `rowHeight`, and **fractional** — rounding a page-wide picture to whole px costs 0.3mm of height; `framePx` snaps back to a whole one within 0.05px, which is where our own export's 0.001cm quantization lands, so the round trip stays exact), `rotation` (CW degrees). The node view nests an `<img>` in a rotated "rotor" inside an axis-aligned wrapper that reserves the rotated bounding box (so text reflows around it). The rotor's transform makes it a stacking context, so a selected `.image-node` is given a `z-index` above the header/footer layer to keep handles that poke into a margin grabbable. It has eight zoom-aware resize handles — corners aspect-locked, edges single-axis (width- or height-only) — plus a rotation-arrow grip, and shows a live "Width … × Height …" (cm) badge while resizing; resize deltas are un-rotated onto the image's own axes so handles track the pointer at any angle (drag math mirrors `tableRowResize.ts`; width cap = the cell or page-text-column, height cap = the page text height). `setImage` command inserts it; the toolbar button (ToolbarExpanded), drag-drop and paste (Editor.svelte) read the file via `FileReader` → data-URI and clamp the initial size to the page text box. **Text wrap:** the `wrap` attr (`'inline'|'left'|'right'|'topBottom'|'through'`) makes the image a *floating* frame — `ImageToolbar.svelte` (a per-image floating toolbar wired in `Editor.svelte` like `TableToolbar`) sets the mode; `left`/`right` float the wrapper at its anchor paragraph (text flows on the open side via CSS `float`), `topBottom` is a **full-width `float`** (text only above/below), and `through` — Word's in-front-of / behind-text (`wp:wrapNone` + `behindDoc`), ODF's `style:wrap="run-through"` — leaves the flow entirely: `position: absolute` with no offsets keeps the static position it was anchored at, so it reserves neither width nor height, and `inFront` picks the side of the text it lands on. Read as a side float instead it reserved a near-column-wide picture's whole height, which cost the image fixture a page and ~50 reports. A text box in that mode always sits behind the text — the mode has no toolbar entry yet, so only a file can carry it in. All modes use `float` deliberately: an in-flow `display:block` on an inline-atom node view splits the paragraph's inline content into anonymous block boxes, which desyncs ProseMirror's inline view descriptor and makes it drop the following page-break spacer widget; a float is out-of-flow and avoids that. Dragging an **inline** image runs ProseMirror's native node move (the `dropCursor` plugin shows the caret). Dragging a **floating** image runs a custom drag (`ImageView.startReposition`) that **live re-anchors** the node to the text position under the cursor, so the float and text reflow in real time as you drag; it's rAF-throttled and only moves when the cursor's line changes (a float can't move within a line), and stays a single undo step (first move records history, later moves are `addToHistory:false` and get rebased on undo). A paragraph that contains an image paginates **atomically** (`pageBreaks.ts` — pushed whole to the next page, spacer placed before it) so a page break never splits the paragraph next to the image's float (where ProseMirror drops the spacer widget). **Wrap distance:** `wrapDist` is the gap the file keeps beside a float, in cm (Word's `distL`/`distR`, ODF's `fo:margin-left`/`-right` on the graphic style) — only the side the text flows on, since the other one is the frame's own offset. A frame that declares none reserves **nothing**, beside it or above/below it: probed, LibreOffice wraps flush against it, and a gap of our own put every figure in a text box 3mm too tall and broke a line a word early. `setImageWrap` gives a frame the file never floated the 0.32cm a word processor's own wrap command writes. **Vertical alignment (as-char):** `vAlign` carries ODF's `style:vertical-pos`/`-rel` pair for an inline frame — `null` (LibreOffice's `top`/`baseline` and Word's only mode) stands the frame on the text baseline, `middle`/`below` centre it on the baseline or hang it below, and `text-top`/`text-middle`/`text-bottom` measure against the character area instead (CSS `vertical-align: text-top`/`text-bottom`; nothing in CSS centres on that area, so `text-middle` uses 0.36em for half of ascent − descent, which Liberation Serif/Sans, Times and Arial share). `from-top` becomes `vAlign: 'offset'` and puts the frame's top `wrapOffsetY` cm below the baseline whatever the relation says — all probed against LibreOffice, whose formula images use `middle`/`text` and `from-top` almost exclusively. A line an as-char frame has to itself — nothing beside it but whitespace — is as tall as the frame or the block's line height, whichever is more, with **nLine truncated
|
||||
- **`textBox.ts`** (`TextBox`) — an **inline** text box / basic shape carrying editable block content (`group: 'inline'`, `inline: true`, `content: '(paragraph|heading|bulletList|orderedList)+'`, `isolating`) — the frame both formats write, a character in a run that holds paragraphs. It rides a paragraph, so `inline` really is in the line, and a box reaches a table cell or a list item through their paragraphs, as one does in Word. Attrs: `width`/`height` (px @96dpi; height renders as **min-height** — content grows the box), `rotation` (CW deg), `wrap` (image's `WrapMode`), `shapeKind` (see the shape table below), `fillColor`/`strokeColor` (`null` = transparent/no border), `strokeWidthPt`. Padding is the fixed `TEXTBOX_PADDING_CM` (0.15cm). **Wrap** follows `ImageView.applyWrap` exactly: `inline` is an `inline-block` in the line, `left`/`right` are floats, `topBottom` a **full-width float** whose wrapper spans the column while `placeInBand` moves the rotor across it, `through` leaves the flow. Never `display:block` — that splits the paragraph's inline content into anonymous block boxes and ProseMirror drops the following page-break spacer. A paragraph holding a box paginates **atomically** (`pageBreaks.ts`), whichever way the box wraps. `TextBoxView` mirrors `ImageView` (wrapper reserving the rotated bbox → rotor carrying fill/stroke/rotation → `contentDOM`); the rotor is out of flow and auto-grows, so a ResizeObserver refits the wrapper. **Click model (Word-like):** `stopEvent`/`isFrameHit` claim mouse events on a ~6px frame ring (rotation-/zoom-aware) → NodeSelection + handles (the shared `image-*` handle classes/CSS); clicks further inside pass to ProseMirror (caret). The box is browser-`draggable` only while node-selected, so PM's native drag moves it without hijacking text selection. Commands: `insertTextBox()` (at the caret, cursor inside; refused inside a box), `setTextBoxAttrs()` (NodeSelection *or* cursor inside; helper `findTextBox`), `setTextBoxAlign()`. **Two guards** the schema cannot express live in the extension's plugin: a `filterTransaction` refuses a box inside a box — both word processors refuse it and neither format's writer has a place for one — and an `appendTransaction` grows a selection ending inside a box it did not start in out to the box's own bounds, since deleting such a range dissolves the frame and spills its text into the body. `TextBoxToolbar.svelte` (wired in `Editor.svelte` like the image toolbar, also shown while the caret is inside a box) sets wrap/shape/fill/stroke, the alignment and `textVertical` — the box's text running **top-to-bottom, right-to-left** (`writing-mode: vertical-rl` on the content area, which is all the browser needs). It round-trips as the style's own writing mode in ODF — a plain box is a Writer text frame (its `TbxFr` style chains to `Frame`; see `src/lib/export/CLAUDE.md`) and takes it in the graphic properties, a drawing *shape* only in its style's paragraph properties (both probed) — and Word's `w:bodyPr vert`; ODF's bottom-to-top and Word's `vert270` read as the same one direction the browser lays out. **DOCX autofit:** the shape body writes `<a:noAutofit/>`, which is what LibreOffice writes for the same frame — read as `spAutoFit` it gives the frame `fo:min-height="0"` and draws its text detached from the shape, over whatever follows (probed). The cost is the ODF leg's auto-grow: content taller than the declared height is clipped there, DOCX having no `fo:min-height`. **LibreOffice puts a `wrapTopAndBottom` anchor's band above its anchor paragraph** whatever the anchor says — probed against `posOffset` 0/635, `align top`, `relativeFrom` line/column, `allowOverlap`, and against a file LibreOffice exported itself; `wp:inline` is the one form it places right, and a band-wrapped box keeps `wp:anchor` anyway (Word is the reference for `.docx`). **Where it sits across the column:** only a **band-wrapped** box has a place of its own — `wrapAlign` (`null`/`center`/`right`, drawn by `placeInBand`), and the toolbar's three buttons show for that mode alone, dropping any `wrapOffset` when one is picked. A side wrap names the side itself; a box **in the line** is a character its paragraph places, exactly as a picture is, so the ordinary paragraph alignment does it and a second control on the frame toolbar would only be the same thing under a frame icon. That ordinary command needs one correction, though (`TextAlignInFrames`): a **selected** box is one node whose range covers its own paragraphs, so it would align the box's contents along with the block holding it — with the frame selected only that block is meant (`setTextBoxAlign`), while the caret inside the box still aligns that text. An as-char frame must name the **baseline pair** explicitly in ODF (`style:vertical-pos="top" style:vertical-rel="baseline"`): the `Frame` parent hangs a frame that names none below the line, where a style-less as-char frame (an image) stands Line truncated
|
||||
- **`textBox.ts`** (`TextBox`) — an **inline** text box / basic shape carrying editable block content (`group: 'inline'`, `inline: true`, `content: '(paragraph|heading|bulletList|orderedList)+'`, `isolating`) — the frame both formats write, a character in a run that holds paragraphs. It rides a paragraph, so `inline` really is in the line, and a box reaches a table cell or a list item through their paragraphs, as one does in Word. Attrs: `width`/`height` (px @96dpi; height renders as **min-height** — content grows the box), `rotation` (CW deg), `wrap` (image's `WrapMode`), `shapeKind` (see the shape table below), `fillColor`/`strokeColor` (`null` = transparent/no border), `strokeWidthPt`. Padding is the fixed `TEXTBOX_PADDING_CM` (0.15cm). **Wrap** follows `ImageView.applyWrap` exactly: `inline` is an `inline-block` in the line, `left`/`right` are floats, `topBottom` a **full-width float** whose wrapper spans the column while `placeInBand` moves the rotor across it, `through` leaves the flow. Never `display:block` — that splits the paragraph's inline content into anonymous block boxes and ProseMirror drops the following page-break spacer. A paragraph holding a box paginates **atomically** (`pageBreaks.ts`), whichever way the box wraps. `TextBoxView` mirrors `ImageView` (wrapper reserving the rotated bbox → rotor carrying fill/stroke/rotation → `contentDOM`); the rotor is out of flow and auto-grows, so a ResizeObserver refits the wrapper. **Click model (Word-like):** `stopEvent`/`isFrameHit` claim mouse events on a ~6px frame ring (rotation-/zoom-aware) → NodeSelection + handles (the shared `image-*` handle classes/CSS); clicks further inside pass to ProseMirror (caret). The box is browser-`draggable` only while node-selected, so PM's native drag moves it without hijacking text selection. **Reaching the position beside the box:** a frame nobody is editing is an atom to the browser — a `contenteditable="false"` node decoration, dropped while the caret is in its text — and `ArrowLeft`/`ArrowRight` at the box's first/last text position step out to `before`/`after` the node. Without both, a box that starts its paragraph is a trap: there is no text position beside it, so the browser pulls the caret meant for the box's own place in the line into the frame and everything typed there lands inside it. The frame then has to place the caret itself on the click that enters it (`onFrameMouseDown`, `stopEvent`), since a non-editable one gets none from the browser. A nested `contentEditable` island is not the way — ProseMirror's `hasFocus` is `activeElement == view.dom`, and an island holding focus makes it read no selection at all. Commands: `insertTextBox()` (at the caret, cursor inside; refused inside a box), `setTextBoxAttrs()` (NodeSelection *or* cursor inside; helper `findTextBox`), `setTextBoxAlign()`. **Two guards** the schema cannot express live in the extension's plugin: a `filterTransaction` refuses a box inside a box — both word processors refuse it and neither format's writer has a place for one — and an `appendTransaction` grows a selection ending inside a box it did not start in out to the box's own bounds, since deleting such a range dissolves the frame and spills its text into the body. `TextBoxToolbar.svelte` (wired in `Editor.svelte` like the image toolbar, also shown while the caret is inside a box) sets wrap/shape/fill/stroke, the alignment and `textVertical` — the box's text running **top-to-bottom, right-to-left** (`writing-mode: vertical-rl` on the content area, which is all the browser needs). It round-trips as the style's own writing mode in ODF — a plain box is a Writer text frame (its `TbxFr` style chains to `Frame`; see `src/lib/export/CLAUDE.md`) and takes it in the graphic properties, a drawing *shape* only in its style's paragraph properties (both probed) — and Word's `w:bodyPr vert`; ODF's bottom-to-top and Word's `vert270` read as the same one direction the browser lays out. **DOCX autofit:** the shape body writes `<a:noAutofit/>`, which is what LibreOffice writes for the same frame — read as `spAutoFit` it gives the frame `fo:min-height="0"` and draws its text detached from the shape, over whatever follows (probed). The cost is the ODF leg's auto-grow: content taller than the declared height is clipped there, DOCX having no `fo:min-height`. **LibreOffice puts a `wrapTopAndBottom` anchor's band above its anchor paragraph** whatever the anchor says — probed against `posOffset` 0/635, `align top`, `relativeFrom` line/column, `allowOverlap`, and against a file LibreOffice exported itself; `wp:inline` is the one form it places right, and a band-wrapped box keeps `wp:anchor` anyway (Word is the reference for `.docx`). **Where it sits across the column:** only a **band-wrapped** box has a place of its own — `wrapAlign` (`null`/`center`/`right`, drawn by `placeInBand`), and the toolbar's three buttons show for that mode alone, dropping any `wrapOffset` when onLine truncated
|
||||
|
||||
## A box in static HTML
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { CommandProps } from '@tiptap/core';
|
||||
import TextAlign from '@tiptap/extension-text-align';
|
||||
import type { Editor } from '@tiptap/core';
|
||||
import type { Node as PMNode, Slice } from '@tiptap/pm/model';
|
||||
import { NodeSelection, TextSelection, Plugin } from '@tiptap/pm/state';
|
||||
import { NodeSelection, Selection, TextSelection, Plugin } from '@tiptap/pm/state';
|
||||
import type { EditorState } from '@tiptap/pm/state';
|
||||
import { Decoration, DecorationSet } from '@tiptap/pm/view';
|
||||
import type { EditorView } from '@tiptap/pm/view';
|
||||
@@ -318,6 +318,24 @@ export const TextBox = Node.create({
|
||||
};
|
||||
},
|
||||
|
||||
// The frame holds editable blocks, so at its own first or last text position there is
|
||||
// no neighbouring one for the browser to walk to and the caret sits stuck. Step out to
|
||||
// the position the box occupies in its paragraph, which is where a character would be.
|
||||
addKeyboardShortcuts() {
|
||||
const escape = (dir: -1 | 1) => () => {
|
||||
const sel = this.editor.state.selection;
|
||||
if (!(sel instanceof TextSelection) || !sel.empty) return false;
|
||||
const $c = sel.$from;
|
||||
const d = boxDepthAt($c);
|
||||
if (d < 0) return false;
|
||||
const box = $c.node(d);
|
||||
const edge = dir < 0 ? Selection.atStart(box).from : Selection.atEnd(box).to;
|
||||
if (sel.from !== $c.start(d) + edge) return false;
|
||||
return this.editor.commands.setTextSelection(dir < 0 ? $c.before(d) : $c.after(d));
|
||||
};
|
||||
return { ArrowLeft: escape(-1), ArrowRight: escape(1) };
|
||||
},
|
||||
|
||||
addNodeView() {
|
||||
return ({ node, editor, getPos }) => new TextBoxView(node as PMNode, editor, getPos as () => number);
|
||||
},
|
||||
@@ -362,11 +380,18 @@ export const TextBox = Node.create({
|
||||
decorations(state) {
|
||||
const { from, to } = state.selection;
|
||||
const decos: Decoration[] = [];
|
||||
// A box rides a paragraph's inline content, so the walk has to enter blocks.
|
||||
state.doc.descendants((node, pos) => {
|
||||
if (node.type.name !== 'textBox') return false;
|
||||
if (from >= pos && to <= pos + node.nodeSize) {
|
||||
decos.push(Decoration.node(pos, pos + node.nodeSize, { class: 'textbox-active' }));
|
||||
}
|
||||
if (node.type.name !== 'textBox') return node.isBlock;
|
||||
const end = pos + node.nodeSize;
|
||||
const attrs: Record<string, string> = {};
|
||||
if (from >= pos && to <= end) attrs.class = 'textbox-active';
|
||||
// A frame nobody is editing is an atom to the browser. Left editable it
|
||||
// swallows the caret meant for the box's own place in the line — there is
|
||||
// no text position beside a box that starts its paragraph — and what is
|
||||
// typed there lands inside the frame.
|
||||
if (!(from > pos && to < end)) attrs.contenteditable = 'false';
|
||||
decos.push(Decoration.node(pos, end, attrs));
|
||||
return false;
|
||||
});
|
||||
return DecorationSet.create(state.doc, decos);
|
||||
@@ -676,6 +701,13 @@ class TextBoxView {
|
||||
return inside && nearEdge;
|
||||
}
|
||||
|
||||
// Whether the caret sits in this box's text — the one state in which the frame is
|
||||
// editable, and so the one in which the browser places a caret in it by itself.
|
||||
private editing(state: EditorState): boolean {
|
||||
const pos = this.getPos();
|
||||
return typeof pos === 'number' && state.selection.from > pos && state.selection.to < pos + this.node.nodeSize;
|
||||
}
|
||||
|
||||
private onFrameMouseDown(e: MouseEvent): void {
|
||||
if (this.isOwnUi(e.target)) return;
|
||||
const pos = this.getPos();
|
||||
@@ -688,9 +720,9 @@ class TextBoxView {
|
||||
// draggable, so a later ring drag still moves it natively.
|
||||
view.dispatch(view.state.tr.setSelection(NodeSelection.create(view.state.doc, pos)));
|
||||
if (!already) { e.preventDefault(); view.focus(); }
|
||||
} else if (already) {
|
||||
// Body click on an object-selected (draggable) box: the browser won't place a
|
||||
// caret, so do it ourselves at the click point to enter text editing.
|
||||
} else if (!this.editing(view.state)) {
|
||||
// Body click on a box nobody is editing: the frame is not editable yet, so the
|
||||
// browser places no caret in it. Do it ourselves at the click point.
|
||||
e.preventDefault();
|
||||
const from = pos + 1, to = pos + this.node.nodeSize - 1;
|
||||
const hit = view.posAtCoords({ left: e.clientX, top: e.clientY })?.pos;
|
||||
@@ -843,7 +875,9 @@ class TextBoxView {
|
||||
stopEvent(event: Event): boolean {
|
||||
if (!event.type.startsWith('mouse')) return false;
|
||||
if (this.isOwnUi(event.target)) return true;
|
||||
return this.isFrameHit(event as MouseEvent);
|
||||
// Every mouse event on a frame nobody is editing is ours: onFrameMouseDown has
|
||||
// placed the selection already, and ProseMirror would put it somewhere else.
|
||||
return this.isFrameHit(event as MouseEvent) || !this.editing(this.editor.state);
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
|
||||
@@ -156,3 +156,61 @@ describe('aligning a selected box', () => {
|
||||
ed.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
// The frame holds editable blocks, so at its own first and last text position the
|
||||
// browser has no neighbouring one to walk to; without a step out the caret is stuck.
|
||||
describe('leaving a box that is alone in its paragraph', () => {
|
||||
const press = (ed: Editor, key: string): void => {
|
||||
const ev = new KeyboardEvent('keydown', { key, bubbles: true });
|
||||
ed.view.someProp('handleKeyDown', f => f(ed.view, ev));
|
||||
};
|
||||
const alone = (): N[] => [{ type: 'paragraph', content: [box('KASTEN')] }];
|
||||
|
||||
it('steps before the box on ArrowLeft at its start', () => {
|
||||
const ed = makeEditor(...alone());
|
||||
ed.commands.setTextSelection(boxPos(ed) + 2);
|
||||
press(ed, 'ArrowLeft');
|
||||
expect(ed.state.selection.from).toBe(boxPos(ed));
|
||||
expect(boxDepth(ed)).toBe(0);
|
||||
ed.destroy();
|
||||
});
|
||||
|
||||
it('steps after the box on ArrowRight at its end', () => {
|
||||
const ed = makeEditor(...alone());
|
||||
const pos = boxPos(ed);
|
||||
ed.commands.setTextSelection(pos + 2 + 'KASTEN'.length);
|
||||
press(ed, 'ArrowRight');
|
||||
expect(ed.state.selection.from).toBe(pos + ed.state.doc.nodeAt(pos)!.nodeSize);
|
||||
expect(boxDepth(ed)).toBe(0);
|
||||
ed.destroy();
|
||||
});
|
||||
|
||||
it('leaves the caret alone inside the text', () => {
|
||||
const ed = makeEditor(...alone());
|
||||
ed.commands.setTextSelection(boxPos(ed) + 4);
|
||||
press(ed, 'ArrowLeft');
|
||||
expect(ed.state.selection.from).toBe(boxPos(ed) + 4);
|
||||
ed.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
// A box that starts its paragraph has no text position beside it, so an editable frame
|
||||
// swallows the caret meant for the box's own place in the line.
|
||||
describe('the frame as an atom', () => {
|
||||
const frame = (ed: Editor): HTMLElement => ed.view.dom.querySelector('.textbox-node')!;
|
||||
|
||||
it('is not editable while nobody edits it', () => {
|
||||
const ed = makeEditor(...doc());
|
||||
ed.commands.setTextSelection(1);
|
||||
expect(frame(ed).getAttribute('contenteditable')).toBe('false');
|
||||
ed.destroy();
|
||||
});
|
||||
|
||||
it('turns editable, and shows its frame, with the caret in its text', () => {
|
||||
const ed = makeEditor(...doc());
|
||||
ed.commands.setTextSelection(boxPos(ed) + 2);
|
||||
expect(frame(ed).getAttribute('contenteditable')).toBeNull();
|
||||
expect(frame(ed).classList.contains('textbox-active')).toBe(true);
|
||||
ed.destroy();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user