@quillmark/svelte 0.29.3 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +3 -3
  2. package/dist/core/address.d.ts +3 -3
  3. package/dist/core/address.js +1 -1
  4. package/dist/core/codec/decode.d.ts +4 -5
  5. package/dist/core/codec/decode.js +151 -208
  6. package/dist/core/codec/encode.d.ts +13 -35
  7. package/dist/core/codec/encode.js +127 -408
  8. package/dist/core/codec/field.d.ts +11 -10
  9. package/dist/core/codec/field.js +190 -92
  10. package/dist/core/codec/index.d.ts +2 -2
  11. package/dist/core/codec/index.js +4 -4
  12. package/dist/core/codec/islands.d.ts +13 -9
  13. package/dist/core/codec/islands.js +54 -49
  14. package/dist/core/codec/marks.d.ts +12 -18
  15. package/dist/core/codec/marks.js +16 -26
  16. package/dist/core/codec/positions.d.ts +25 -7
  17. package/dist/core/codec/positions.js +43 -50
  18. package/dist/core/codec/prose.css +0 -8
  19. package/dist/core/codec/schema.d.ts +3 -3
  20. package/dist/core/codec/schema.js +29 -11
  21. package/dist/core/codec/slash.d.ts +4 -2
  22. package/dist/core/codec/slash.js +13 -3
  23. package/dist/core/codec/table-copy.d.ts +3 -3
  24. package/dist/core/codec/table-copy.js +6 -4
  25. package/dist/core/codec/table-paste.js +13 -9
  26. package/dist/core/codec/table-view.js +19 -12
  27. package/dist/core/codec/table.d.ts +77 -43
  28. package/dist/core/codec/table.js +157 -48
  29. package/dist/core/index.d.ts +1 -0
  30. package/dist/core/theme.css +14 -6
  31. package/dist/visual/ArrayField.svelte +168 -83
  32. package/dist/visual/BooleanField.svelte +2 -2
  33. package/dist/visual/Card.svelte +65 -44
  34. package/dist/visual/DateField.svelte +16 -1
  35. package/dist/visual/DiagnosticList.svelte +34 -2
  36. package/dist/visual/EnumField.svelte +58 -44
  37. package/dist/visual/Field.svelte +13 -3
  38. package/dist/visual/Field.svelte.d.ts +3 -1
  39. package/dist/visual/FieldHint.svelte +10 -3
  40. package/dist/visual/FormatPopover.svelte +1 -1
  41. package/dist/visual/MatrixAdd.svelte +3 -18
  42. package/dist/visual/MatrixField.svelte +20 -12
  43. package/dist/visual/ObjectField.svelte +164 -145
  44. package/dist/visual/ProseField.svelte +6 -1
  45. package/dist/visual/ProseValue.svelte +8 -8
  46. package/dist/visual/SlashMenu.svelte +24 -12
  47. package/dist/visual/SlashMenu.svelte.d.ts +2 -0
  48. package/dist/visual/VisualEditor.svelte +1 -1
  49. package/dist/visual/VisualEditor.svelte.d.ts +1 -1
  50. package/dist/visual/VisualEditorInner.svelte +159 -18
  51. package/dist/visual/VisualEditorInner.svelte.d.ts +1 -1
  52. package/dist/visual/controls.css +42 -4
  53. package/dist/visual/leaves.d.ts +1 -1
  54. package/dist/visual/leaves.js +1 -1
  55. package/dist/visual/strings.d.ts +27 -10
  56. package/dist/visual/strings.js +40 -6
  57. package/dist/visual/structure.d.ts +17 -9
  58. package/dist/visual/structure.js +20 -26
  59. package/dist/visual/undo.svelte.d.ts +36 -0
  60. package/dist/visual/undo.svelte.js +119 -0
  61. package/package.json +2 -2
  62. package/dist/visual/hold.d.ts +0 -17
  63. package/dist/visual/hold.js +0 -39
@@ -1,8 +1,9 @@
1
1
  import { type Schema } from 'prosemirror-model';
2
2
  import { Plugin } from 'prosemirror-state';
3
3
  import { EditorView } from 'prosemirror-view';
4
- import type { Document, Content, Addr, Delta, Quill } from '@quillmark/wasm';
4
+ import type { Document, Content, Addr, Quill } from '@quillmark/wasm';
5
5
  import type { EditorErrorHandler } from '../errors.js';
6
+ import { type Delta } from './positions.js';
6
7
  import { type TextCap } from './cap.js';
7
8
  import { type TableChromeStrings } from './table-view.js';
8
9
  import { type SlashState, type SlashStrings } from './slash.js';
@@ -80,7 +81,7 @@ export interface CreateFieldOpts {
80
81
  * unanswered `none` is what the empty leaf draws and an empty answer would hide. */
81
82
  emptyUnsets?: boolean;
82
83
  onFocus?(addr: Addr): void;
83
- /** Fired with the new USV caret after an edit or a selection move. */
84
+ /** Fired with the new caret offset after an edit or a selection move. */
84
85
  onCaretMove?(addr: Addr, pos: number): void;
85
86
  /**
86
87
  * Fired after an edit committed to the document: the leaf's change signal. Unlike `onCaretMove`
@@ -97,7 +98,7 @@ export interface FieldController {
97
98
  /** The mounted `container`: the leaf's element, for a caller that has to reach the
98
99
  * DOM the view sits in (the arrival wash, `core/bloom.ts`) rather than re-find it. */
99
100
  readonly el: HTMLElement;
100
- /** Place the caret at USV `pos` (preview onPick → usvToPM → here). */
101
+ /** Place the caret at content offset `pos` (preview onPick → offsetToPM → here). */
101
102
  setCaret(pos: number): void;
102
103
  /**
103
104
  * External content change → re-hydrate this leaf (gated by reconcile), and re-evaluate its
@@ -119,14 +120,14 @@ export interface FieldController {
119
120
  /** The current stored content for this addr (for tests / reconcile). */
120
121
  getContent(): Content;
121
122
  /**
122
- * Insert an identity anchor `id` at USV `pos`. Zero-width; it folds into the plugin's position
123
- * set and commits through the mark-diff `anchor` op. The id is caller-supplied and must be
124
- * unique and invariant; a duplicate id is a no-op.
123
+ * Insert an identity anchor `id` over content offsets `[pos, end)`, a point where `end` is
124
+ * absent. It folds into the plugin's set and commits with the next change. The id is
125
+ * caller-supplied and must be unique and invariant; a duplicate id is a no-op.
125
126
  */
126
- insertAnchor(id: string, pos: number): void;
127
+ insertAnchor(id: string, pos: number, end?: number): void;
127
128
  /** Remove the identity anchor `id` (the inverse of {@link insertAnchor}); a no-op if absent. */
128
129
  removeAnchor(id: string): void;
129
- /** Ids of the anchors within USV range `[from, to]`: a selection's anchor state. */
130
+ /** Ids of the anchors touching content range `[from, to]`: a selection's anchor state. */
130
131
  anchorsInRange(from: number, to: number): string[];
131
132
  /**
132
133
  * Move the slash menu's cursor onto the command `name` (a pointer entering an item): the
@@ -136,7 +137,7 @@ export interface FieldController {
136
137
  /** Run the command `name` (a click on its item): the same path Enter takes. A no-op
137
138
  * with no menu open, which is the state a stale click lands in. */
138
139
  slashPick(name: string): void;
139
- /** The current PM selection as a USV `{ from, to }` range (the boundary currency). */
140
+ /** The current PM selection as a content `{ from, to }` range (the boundary currency). */
140
141
  selectionRange(): {
141
142
  from: number;
142
143
  to: number;
@@ -156,7 +157,7 @@ export interface LeafViews {
156
157
  /** Every view nested inside this leaf, in mount order: one per table cell. */
157
158
  nestedViews(): EditorView[];
158
159
  }
159
- /** The canonical empty `Content`: one empty `para` line. */
160
+ /** The canonical empty `Content`: one empty `para` block. */
160
161
  export declare function emptyContent(): Content;
161
162
  /** Whether `rt` is the empty leaf: {@link emptyContent}, nothing typed and no shape left. */
162
163
  export declare function isEmptyContent(rt: Content): boolean;
@@ -1,15 +1,15 @@
1
1
  // The prose leaf: `createField` (VISUAL_EDITOR §Surface). One content field, one PM view wired to
2
2
  // the WASM edit surface.
3
3
  //
4
- // `dispatchTransaction` applies the transaction optimistically, lowers it to a `ChangeBundle` (or
5
- // `overwrite` for a field not yet at content rest, which has nothing to splice), commits via
6
- // `doc.applyChange` (a `text` leaf's whole text through the typed writer), then fires `onChange` if
7
- // it committed and `onCaretMove`. A throw keeps the optimistic PM state and reports through
8
- // `onError`. An external change re-hydrates through `applyExternal`, gated by `reconcile` except
9
- // where the hold it re-evaluates flips.
4
+ // `dispatchTransaction` applies the transaction optimistically, lowers it to a `Change` (or
5
+ // `replace` for a field not yet at content rest, which has nothing to change), commits via
6
+ // `doc.apply` (a `text` leaf's whole text through the typed writer), then fires `onChange` if it
7
+ // committed and `onCaretMove`. A throw keeps the optimistic PM state and reports through `onError`.
8
+ // An external change re-hydrates through `applyExternal`, gated by `reconcile` except where the
9
+ // hold it re-evaluates flips.
10
10
  import { baseKeymap, toggleMark } from 'prosemirror-commands';
11
11
  import { gapCursor } from 'prosemirror-gapcursor';
12
- import { history, redo, undo } from 'prosemirror-history';
12
+ import { history, isHistoryTransaction, redo, undo } from 'prosemirror-history';
13
13
  import { keymap } from 'prosemirror-keymap';
14
14
  import { Fragment, Slice } from 'prosemirror-model';
15
15
  import { EditorState, NodeSelection, Plugin, PluginKey, Selection, TextSelection } from 'prosemirror-state';
@@ -18,8 +18,8 @@ import { revealProps } from './reveal.js';
18
18
  import { core } from '../lifecycle.js';
19
19
  import { reportError, errorMessage } from '../errors.js';
20
20
  import { decode, fitsLeaf } from './decode.js';
21
- import { usvToPM, pmToUsv, buildLineIndex, lineIndexOf } from './positions.js';
22
- import { lower, pmToContent, scanContent, scanDoc, contentEdit } from './encode.js';
21
+ import { offsetToPM, pmToOffset, buildLineIndex, lineIndexOf, mapThroughDelta } from './positions.js';
22
+ import { lower, pmToContent, scanContent, scanDoc } from './encode.js';
23
23
  import { capPlugin } from './cap.js';
24
24
  import { islandPastePlugin } from './islands.js';
25
25
  import { anchorsFromContent } from './marks.js';
@@ -42,33 +42,110 @@ import { taskPlugin } from './tasks.js';
42
42
  import { DEFAULT_TABLE_STRINGS, tableNodeView } from './table-view.js';
43
43
  import { DEFAULT_SLASH_STRINGS, focusSlashItem, runSlashItem, slashPlugin } from './slash.js';
44
44
  const anchorKey = new PluginKey('quill-anchors');
45
- /** Plugin-held anchor positions (PM coords), mapped through every edit's `StepMap`
46
- * and mutated by an {@link AnchorEdit} meta (an insert/remove at a selection).
47
- *
48
- * The `-1` is the store's rule for a point, not PM's default: `applyChange` rebases a
49
- * zero-width mark `before`, so text typed at an anchor's own position lands after it
50
- * and the mark diff has no op to spend reconciling this set with the store. */
45
+ const GHOSTS = 100;
46
+ /**
47
+ * Plugin-held anchors (PM coords), mapped through every edit's `StepMap` and mutated by an {@link
48
+ * AnchorEdit} meta. The store's rule, so the commit has nothing to reconcile: a range keeps its
49
+ * edges, text typed at either landing outside it, and a point stays left of text typed at it. A
50
+ * range whose text is wholly deleted goes, and comes back with its text when history puts the
51
+ * deleted slice back ({@link Ghost}); a point never goes.
52
+ */
51
53
  function anchorPlugin(seed) {
52
54
  return new Plugin({
53
55
  key: anchorKey,
54
56
  state: {
55
- init: () => seed,
56
- apply: (tr, anchors) => {
57
- let next = tr.docChanged
58
- ? anchors.map((a) => ({ id: a.id, pos: tr.mapping.map(a.pos, -1) }))
59
- : anchors;
57
+ init: () => ({ anchors: seed, ghosts: [] }),
58
+ apply: (tr, held) => {
59
+ let { anchors, ghosts } = held;
60
+ if (tr.docChanged) {
61
+ const undoing = isHistoryTransaction(tr);
62
+ for (const map of tr.mapping.maps)
63
+ ({ anchors, ghosts } = mapAnchors(map, anchors, ghosts, undoing));
64
+ }
60
65
  const edit = tr.getMeta(anchorKey);
61
66
  if (edit?.op === 'add')
62
- next = [...next, { id: edit.id, pos: edit.pos }];
63
- else if (edit?.op === 'remove')
64
- next = next.filter((a) => a.id !== edit.id);
67
+ anchors = [...anchors, { id: edit.id, start: edit.start, end: edit.end }];
68
+ else if (edit?.op === 'remove') {
69
+ anchors = anchors.filter((a) => a.id !== edit.id);
70
+ ghosts = ghosts.filter((g) => g.id !== edit.id);
71
+ }
65
72
  else if (edit?.op === 'reset')
66
- next = edit.anchors;
67
- return next;
73
+ anchors = edit.anchors;
74
+ return { anchors, ghosts: ghosts.slice(-GHOSTS) };
68
75
  }
69
76
  }
70
77
  });
71
78
  }
79
+ /** The replaced range of `map` holding `[from, to]`, where one does. */
80
+ function rangeOf(map, from, to) {
81
+ let hit;
82
+ map.forEach((oldStart, oldEnd, newStart, newEnd) => {
83
+ if (!hit && oldStart <= from && to <= oldEnd)
84
+ hit = { oldStart, oldEnd, newStart, newEnd };
85
+ });
86
+ return hit;
87
+ }
88
+ /** One step's map over the anchors and ghosts: a range the step deletes whole becomes a ghost,
89
+ * and under a history step a ghost whose slice comes back whole becomes its anchor again. */
90
+ function mapAnchors(map, anchors, ghosts, undoing) {
91
+ const nextAnchors = [];
92
+ const nextGhosts = [];
93
+ for (const g of ghosts) {
94
+ const range = rangeOf(map, g.at, g.at);
95
+ if (!range) {
96
+ nextGhosts.push({ ...g, at: map.map(g.at, -1) });
97
+ continue;
98
+ }
99
+ const { oldStart, oldEnd, newStart, newEnd } = range;
100
+ if (undoing && newEnd - newStart === g.lead + g.len + g.trail) {
101
+ if (g.inner)
102
+ nextGhosts.push({ ...g.inner, at: newStart + g.lead });
103
+ else
104
+ nextAnchors.push({ id: g.id, start: newStart + g.lead, end: newStart + g.lead + g.len });
105
+ continue;
106
+ }
107
+ if (oldEnd === oldStart) {
108
+ nextGhosts.push({ ...g, at: map.map(g.at, -1) });
109
+ continue;
110
+ }
111
+ nextGhosts.push({
112
+ id: g.id,
113
+ at: newStart,
114
+ lead: g.at - oldStart,
115
+ len: 0,
116
+ trail: oldEnd - g.at,
117
+ inner: g
118
+ });
119
+ }
120
+ for (const a of anchors) {
121
+ if (a.start === a.end) {
122
+ const at = map.map(a.start, -1);
123
+ nextAnchors.push({ id: a.id, start: at, end: at });
124
+ continue;
125
+ }
126
+ const start = map.map(a.start, 1);
127
+ const end = map.map(a.end, -1);
128
+ if (start < end) {
129
+ nextAnchors.push({ id: a.id, start, end });
130
+ continue;
131
+ }
132
+ const range = rangeOf(map, a.start, a.end);
133
+ nextGhosts.push(range
134
+ ? {
135
+ id: a.id,
136
+ at: range.newStart,
137
+ lead: a.start - range.oldStart,
138
+ len: a.end - a.start,
139
+ trail: range.oldEnd - a.end
140
+ }
141
+ : { id: a.id, at: start, lead: 0, len: a.end - a.start, trail: 0 });
142
+ }
143
+ return { anchors: nextAnchors, ghosts: nextGhosts };
144
+ }
145
+ /** An anchor in content offsets at its PM positions over `index`. */
146
+ function toPM(index, a) {
147
+ return { id: a.id, start: offsetToPM(index, a.start), end: offsetToPM(index, a.end) };
148
+ }
72
149
  /**
73
150
  * Read the leaf's `Content` for `addr` through `reader.getContent` (DOCUMENT_MODEL): the body when
74
151
  * `addr.field` is absent. Bound by the declared type rather than a verbatim read, since a string a
@@ -80,21 +157,27 @@ function anchorPlugin(seed) {
80
157
  function readLeaf(reader, addr) {
81
158
  return reader.getContent(addr) ?? emptyContent();
82
159
  }
83
- /** The canonical empty `Content`: one empty `para` line. */
160
+ /** `addr` as a content write takes it: a card named by its `$id`, which a write requires. */
161
+ function writeAddr(doc, addr) {
162
+ if (typeof addr.card !== 'number')
163
+ return addr;
164
+ return { ...addr, card: doc.card(addr.card).id ?? addr.card };
165
+ }
166
+ /** The canonical empty `Content`: one empty `para` block. */
84
167
  export function emptyContent() {
85
- return { text: '', lines: [{ containers: [], kind: 'para' }], marks: [], islands: [] };
168
+ return { text: '', blocks: [{ id: 'b0', kind: 'para' }] };
86
169
  }
87
170
  /** Whether `rt` is the empty leaf: {@link emptyContent}, nothing typed and no shape left. */
88
171
  export function isEmptyContent(rt) {
89
172
  return contentEqual(rt, emptyContent());
90
173
  }
91
174
  /**
92
- * Whether ops may commit here: the stored value is a `Content` object, so `applyChange` splices
93
- * exactly what PM shows. The other rest forms take `overwrite`: an unset field has nothing to
94
- * splice, and an authored string carries no anchors to pay. A body always rests as `Content`; a
95
- * `text` leaf commits through the writer ({@link createField}).
175
+ * Whether a change may commit here: the stored value is a `Content` object, so `apply` changes
176
+ * exactly what PM shows. The other rest forms take `replace`: an unset field has nothing to change,
177
+ * and an authored string carries no anchors to pay. A body always rests as `Content`; a `text` leaf
178
+ * commits through the writer ({@link createField}).
96
179
  */
97
- function opsCommittable(doc, addr) {
180
+ function changeCommittable(doc, addr) {
98
181
  const stored = doc.getStored(addr);
99
182
  return stored !== null && typeof stored === 'object';
100
183
  }
@@ -125,6 +208,11 @@ export function heldAttributes(opts, noteId) {
125
208
  tabindex: '0'
126
209
  };
127
210
  }
211
+ /** A plain leaf's value as the literal text its `text` field takes: a paragraph break a blank
212
+ * line and a hard break a lone `\n`, as the engine spells a `codec: "plain"` value. */
213
+ function literalOf(rt) {
214
+ return core().exportMarkdown({ ...rt, codec: 'plain' });
215
+ }
128
216
  export function createField(opts) {
129
217
  const { doc, addr, container } = opts;
130
218
  const inline = !!opts.inline;
@@ -213,12 +301,13 @@ export function createField(opts) {
213
301
  // (`docChanged` false), so the `anchorKey` meta routes it.
214
302
  if (!held && (tr.docChanged || tr.getMeta(anchorKey))) {
215
303
  // (d) the change signal, only for what actually landed.
216
- const newRt = scan ? scanContent(scan) : pmToContent(next.doc);
304
+ const anchors = plaintext ? [] : readAnchors();
305
+ const newRt = scan ? scanContent(scan, anchors) : pmToContent(next.doc, anchors);
217
306
  if (commitEdit(oldRt, newRt))
218
307
  opts.onChange?.(addr);
219
308
  }
220
309
  // The caret, for structural and selection-only changes, reported after the commit.
221
- opts.onCaretMove?.(addr, pmToUsv(index, next.selection.head));
310
+ opts.onCaretMove?.(addr, pmToOffset(index, next.selection.head));
222
311
  },
223
312
  handleDOMEvents: {
224
313
  focus: () => {
@@ -243,10 +332,7 @@ export function createField(opts) {
243
332
  const anchors = plaintext ? [] : anchorsFromContent(rt);
244
333
  // Seed anchor plugin positions in PM coords via a fresh index over pmDoc.
245
334
  const seedIndex = buildLineIndex(pmDoc);
246
- const seededAnchors = anchors.map((a) => ({
247
- id: a.id,
248
- pos: usvToPM(seedIndex, a.pos)
249
- }));
335
+ const seededAnchors = anchors.map((a) => toPM(seedIndex, a));
250
336
  const built = EditorState.create({
251
337
  doc: pmDoc,
252
338
  plugins: proseLeafPlugins(schema, {
@@ -264,45 +350,40 @@ export function createField(opts) {
264
350
  });
265
351
  return { state: built, index: seedIndex };
266
352
  }
267
- // (b)+(c): lower the edit to ops and commit, or `overwrite` a field not yet at content rest.
353
+ // (b)+(c): lower the edit to a change and commit, or `replace` a field not yet at content rest.
268
354
  // Keeps the optimistic PM on throw. Returns whether anything landed, independent of which
269
355
  // branch ran.
270
356
  function commitEdit(oldRt, newRt) {
357
+ const at = writeAddr(doc, addr);
271
358
  if (opts.emptyUnsets && heldAnchors().length === 0 && isEmptyContent(newRt))
272
359
  return commitUnset();
273
360
  if (plaintext)
274
- return commitPlain(newRt.text);
275
- // The text splice, computed once per keystroke and shared by the gate, both overwrite
276
- // fallbacks and `lower`.
277
- const edit = contentEdit(oldRt, newRt);
361
+ return commitPlain(literalOf(newRt));
278
362
  try {
279
- // Only a field not yet at content rest overwrites by choice: `applyChange` throws on an
280
- // absent declared field, and neither it nor an authored string has anchors to lose
281
- // (`opsCommittable`). Every structural edit lowers; the island channel places a slot
282
- // the `delta` may not carry.
283
- if (!opsCommittable(doc, addr)) {
284
- doc.overwrite(addr, edit.newRt); // brings the field to content rest
285
- }
363
+ // Only a field not yet at content rest replaces by choice: neither an absent declared
364
+ // field nor an authored string has anchors to lose (`changeCommittable`).
365
+ if (!changeCommittable(doc, addr))
366
+ doc.replace(at, newRt);
286
367
  else {
287
- // Post-edit anchors are the plugin's positions (mapped through the tr) as
288
- // USV; the pre-edit set is `oldRt`'s own, which `lower` reads for itself.
289
- doc.applyChange(addr, lower(edit, { newAnchors: readAnchorsUsv() }));
368
+ const change = lower(oldRt, newRt);
369
+ if (change)
370
+ doc.apply(at, change);
290
371
  }
291
372
  reconciler.commit(readLeaf(reader, addr));
292
373
  return true;
293
374
  }
294
375
  catch (e) {
295
- // Bound the damage: after an op path the gates missed, the reconciler re-diffs from
296
- // stale content and every later edit would re-throw. Install the full projection
297
- // (correct store, pays this field's anchors).
376
+ // Bound the damage: after a change the store refused, the reconciler re-diffs from stale
377
+ // content and every later edit would re-throw. Replace with the full projection, which
378
+ // carries each anchor where its text survives.
298
379
  reportError(opts.onError, {
299
380
  code: 'commit-fallback',
300
381
  severity: 'error',
301
- message: `applyChange refused; overwrote the whole field: ${errorMessage(e)}`,
382
+ message: `apply refused; replaced the whole field: ${errorMessage(e)}`,
302
383
  cause: e
303
384
  });
304
385
  try {
305
- doc.overwrite(addr, edit.newRt);
386
+ doc.replace(at, newRt);
306
387
  reconciler.commit(readLeaf(reader, addr));
307
388
  return true;
308
389
  }
@@ -311,7 +392,7 @@ export function createField(opts) {
311
392
  reportError(opts.onError, {
312
393
  code: 'commit-lost',
313
394
  severity: 'error',
314
- message: `overwrite fallback failed; the stored value is stale while the editor keeps the edit: ${errorMessage(e2)}`,
395
+ message: `replace fallback failed; the stored value is stale while the editor keeps the edit: ${errorMessage(e2)}`,
315
396
  cause: e2
316
397
  });
317
398
  return false;
@@ -329,6 +410,8 @@ export function createField(opts) {
329
410
  const name = addr.field;
330
411
  if (name === undefined)
331
412
  throw new Error('a text leaf names a field');
413
+ if (typeof addr.card === 'string')
414
+ throw new Error('a text leaf names its card by index');
332
415
  (addr.card === undefined ? writer : writer.card(addr.card)).set(name, text);
333
416
  reconciler.commit(readLeaf(reader, addr));
334
417
  return true;
@@ -384,14 +467,13 @@ export function createField(opts) {
384
467
  return false;
385
468
  const after = buildLineIndex(tr.doc);
386
469
  if (delta && before.selection instanceof TextSelection) {
387
- const { mapPos } = core();
388
- const at = (pm) => usvToPM(after, mapPos(delta, pmToUsv(index, pm), 'after'));
470
+ const at = (pm) => offsetToPM(after, mapThroughDelta(delta, pmToOffset(index, pm)));
389
471
  tr.setSelection(TextSelection.between(tr.doc.resolve(at(before.selection.anchor)), tr.doc.resolve(at(before.selection.head))));
390
472
  }
391
473
  if (!plaintext)
392
474
  tr.setMeta(anchorKey, {
393
475
  op: 'reset',
394
- anchors: anchorsFromContent(rt).map((a) => ({ id: a.id, pos: usvToPM(after, a.pos) }))
476
+ anchors: anchorsFromContent(rt).map((a) => toPM(after, a))
395
477
  });
396
478
  view.updateState(before.apply(tr));
397
479
  index = view.state.doc.eq(tr.doc) ? after : buildLineIndex(view.state.doc);
@@ -402,16 +484,20 @@ export function createField(opts) {
402
484
  }
403
485
  }
404
486
  /** The anchors the plugin currently holds (PM coords); `[]` before the first apply. */
405
- const heldAnchors = () => anchorKey.getState(view.state) ?? [];
406
- /** The plugin's anchor positions as USV, against `index` — which `dispatchTransaction`
487
+ const heldAnchors = () => anchorKey.getState(view.state)?.anchors ?? [];
488
+ /** The plugin's anchors as content offsets, against `index` — which `dispatchTransaction`
407
489
  * rebuilt over the new document before the commit this reads for. */
408
- function readAnchorsUsv() {
409
- return heldAnchors().map((a) => ({ id: a.id, pos: pmToUsv(index, a.pos) }));
490
+ function readAnchors() {
491
+ return heldAnchors().map((a) => ({
492
+ id: a.id,
493
+ start: pmToOffset(index, a.start),
494
+ end: pmToOffset(index, a.end)
495
+ }));
410
496
  }
411
497
  const controller = {
412
498
  el: container,
413
499
  setCaret(pos) {
414
- const pm = usvToPM(index, pos);
500
+ const pm = offsetToPM(index, pos);
415
501
  // `Selection.near`: the mapped position can be non-inline, where a raw TextSelection is
416
502
  // invalid.
417
503
  const sel = Selection.near(view.state.doc.resolve(pm));
@@ -440,12 +526,12 @@ export function createField(opts) {
440
526
  }
441
527
  if (flipped)
442
528
  held = !held;
443
- const caretUsv = pmToUsv(index, view.state.selection.head);
529
+ const caret = pmToOffset(index, view.state.selection.head);
444
530
  const fresh = buildState(current);
445
531
  index = fresh.index;
446
- // Best-effort caret continuity across an external change: keep the USV. Set
532
+ // Best-effort caret continuity across an external change: keep the offset. Set
447
533
  // rather than dispatched, so a leaf the caret is not in reports no caret move.
448
- const sel = Selection.near(fresh.state.doc.resolve(usvToPM(index, caretUsv)));
534
+ const sel = Selection.near(fresh.state.doc.resolve(offsetToPM(index, caret)));
449
535
  view.updateState(fresh.state.apply(fresh.state.tr.setSelection(sel)));
450
536
  reconciler.commit(current);
451
537
  if (flipped)
@@ -474,18 +560,14 @@ export function createField(opts) {
474
560
  getContent() {
475
561
  return readLeaf(reader, addr);
476
562
  },
477
- insertAnchor(id, pos) {
478
- // A text field carries no marks (§Inline mode), and a held one commits nothing.
563
+ insertAnchor(id, pos, end = pos) {
564
+ // A text field carries no anchors (§Inline mode), and a held one commits nothing.
479
565
  if (plaintext || held)
480
566
  return;
481
567
  if (heldAnchors().some((a) => a.id === id))
482
- return; // ids are unique + invariant (0.97 policy)
483
- // An anchor commits through `applyChange`, so the field is brought to content rest
484
- // first or the overwrite branch would drop it.
485
- if (!opsCommittable(doc, addr))
486
- doc.overwrite(addr, reconciler.last);
487
- const pm = usvToPM(index, pos);
488
- view.dispatch(view.state.tr.setMeta(anchorKey, { op: 'add', id, pos: pm }));
568
+ return; // ids are unique and invariant
569
+ const at = toPM(index, { id, start: Math.min(pos, end), end: Math.max(pos, end) });
570
+ view.dispatch(view.state.tr.setMeta(anchorKey, { op: 'add', ...at }));
489
571
  },
490
572
  removeAnchor(id) {
491
573
  if (plaintext)
@@ -496,10 +578,7 @@ export function createField(opts) {
496
578
  },
497
579
  anchorsInRange(from, to) {
498
580
  return heldAnchors()
499
- .filter((a) => {
500
- const u = pmToUsv(index, a.pos);
501
- return u >= from && u <= to;
502
- })
581
+ .filter((a) => pmToOffset(index, a.end) >= from && pmToOffset(index, a.start) <= to)
503
582
  .map((a) => a.id);
504
583
  },
505
584
  slashFocus(name) {
@@ -513,8 +592,8 @@ export function createField(opts) {
513
592
  selectionRange() {
514
593
  const { from, to } = view.state.selection;
515
594
  return {
516
- from: pmToUsv(index, from),
517
- to: pmToUsv(index, to)
595
+ from: pmToOffset(index, from),
596
+ to: pmToOffset(index, to)
518
597
  };
519
598
  },
520
599
  destroy() {
@@ -576,17 +655,36 @@ export function proseLeafPlugins(schema, opts) {
576
655
  return list;
577
656
  }
578
657
  /**
579
- * A plain leaf's clipboard text is literal, one line per `\n` both ways; upstream's defaults split
580
- * pasted text on any run of newlines and write a copy's blocks joined by a blank line.
658
+ * A plain leaf's clipboard text is literal both ways, spelled as the engine spells a `text` value:
659
+ * a lone `\n` a hard break, a blank line a paragraph boundary, and a run of `\n` its pairs as
660
+ * paragraph boundaries, an odd one over a hard break before them. Upstream's defaults split pasted
661
+ * text on any run of newlines and write a copy's breaks as nothing.
581
662
  */
582
663
  function plainClipboardPlugin() {
583
- const { paragraph } = plainSchema.nodes;
664
+ const { paragraph, hard_break } = plainSchema.nodes;
665
+ const line = (text) => paragraph.create(null, text
666
+ .split('\n')
667
+ .flatMap((part, i) => [
668
+ ...(i ? [hard_break.create()] : []),
669
+ ...(part ? [plainSchema.text(part)] : [])
670
+ ]));
584
671
  return new Plugin({
585
672
  props: {
586
- clipboardTextParser: (text) => new Slice(Fragment.from(text
587
- .split(/\r\n?|\n/)
588
- .map((line) => paragraph.create(null, line ? plainSchema.text(line) : null))), 1, 1),
589
- clipboardTextSerializer: (slice) => slice.content.textBetween(0, slice.content.size, '\n', '\n')
673
+ clipboardTextParser: (text) => {
674
+ const paragraphs = [''];
675
+ for (const piece of text.replace(/\r\n?/g, '\n').split(/(\n+)/)) {
676
+ if (!piece.startsWith('\n')) {
677
+ paragraphs[paragraphs.length - 1] += piece;
678
+ continue;
679
+ }
680
+ if (piece.length % 2)
681
+ paragraphs[paragraphs.length - 1] += '\n';
682
+ for (let k = 0; k < piece.length >> 1; k++)
683
+ paragraphs.push('');
684
+ }
685
+ return new Slice(Fragment.from(paragraphs.map(line)), 1, 1);
686
+ },
687
+ clipboardTextSerializer: (slice) => slice.content.textBetween(0, slice.content.size, '\n\n', '\n')
590
688
  }
591
689
  });
592
690
  }
@@ -12,8 +12,8 @@ export type { SlashState, SlashStrings } from './slash.js';
12
12
  export { blockSchema, inlineSchema, plaintextSchema, plainSchema, leafSchema, hasMarks } from './schema.js';
13
13
  export { rendersHref, storableUrl } from './urls.js';
14
14
  export { decode, fitsInline, fitsLeaf, fitsPlain, renderContent, usvLength } from './decode.js';
15
- export { pmToContent, contentEdit, lower } from './encode.js';
16
- export { usvToPM, pmToUsv, buildLineIndex } from './positions.js';
15
+ export { pmToContent, lower } from './encode.js';
16
+ export { offsetToPM, pmToOffset, buildLineIndex } from './positions.js';
17
17
  export { createReconciler, contentEqual, valueEqual } from './reconcile.js';
18
18
  export { inputRulesPlugin } from './inputrules.js';
19
19
  export { bodyKeymap } from './keymap.js';
@@ -1,6 +1,6 @@
1
1
  // The codec barrel: the bidirectional bridge between one content field (`Content`)
2
- // and one ProseMirror document (CODEC.md). Decode (content → PM), lower (PM tr → a
3
- // `ChangeBundle` for `applyChange`), the USV↔PM position map, and the `createField`
2
+ // and one ProseMirror document (CODEC.md). Decode (content → PM), lower (PM doc → a
3
+ // `Change` for `apply`), the UTF-16↔PM position map, and the `createField`
4
4
  // prose leaf. Consumed by the VisualEditor and the codec test suite.
5
5
  // ProseMirror's structural base styles and the gap cursor's, then the retint of the
6
6
  // hues they mint. Imported here because `createField` is what mounts a view: a
@@ -35,8 +35,8 @@ export { rendersHref, storableUrl } from './urls.js';
35
35
  // reached only by relative import within `codec/` stays off it: an export nothing
36
36
  // imports is surface that still has to stay honest.
37
37
  export { decode, fitsInline, fitsLeaf, fitsPlain, renderContent, usvLength } from './decode.js';
38
- export { pmToContent, contentEdit, lower } from './encode.js';
39
- export { usvToPM, pmToUsv, buildLineIndex } from './positions.js';
38
+ export { pmToContent, lower } from './encode.js';
39
+ export { offsetToPM, pmToOffset, buildLineIndex } from './positions.js';
40
40
  // Reconciliation gate.
41
41
  export { createReconciler, contentEqual, valueEqual } from './reconcile.js';
42
42
  // Input rules (`createField` mounts them unless `noInputRules`, or over a mark-free schema).
@@ -1,15 +1,17 @@
1
1
  import { type Node as PMNode, type NodeSpec } from 'prosemirror-model';
2
2
  import { Plugin } from 'prosemirror-state';
3
- import type { ContentIsland, TableProps } from '@quillmark/wasm';
3
+ import type { Content, ContentIsland, TableProps } from '@quillmark/wasm';
4
+ /** The `U+2028` line separator that is a break inside a block's text. */
5
+ export declare const HARD_BREAK = "\u2028";
4
6
  /** The `U+FFFC` object-replacement char that occupies one island slot in `text`. */
5
7
  export declare const ISLAND_SLOT = "\uFFFC";
6
- /** Whether an island of `type` is block markup: a `table` stands alone on its line. */
8
+ /** Whether an island of `type` is block markup: a `table` stands alone in its block. */
7
9
  export declare function isBlockIsland(type: ContentIsland['type']): boolean;
8
10
  /** Whether a leaf edits an island of `type`; one holding any other is held (`fitsLeaf`). */
9
11
  export declare function isEditedIsland(type: ContentIsland['type']): boolean;
10
- /** Block island node (a table): a `U+FFFC` slot alone on its `para` line. Atom. */
12
+ /** Block island node (a table): a `U+FFFC` slot alone in its `para` block. Atom. */
11
13
  export declare const islandBlockSpec: NodeSpec;
12
- /** Inline island node (an image, a footnote, an equation): a `U+FFFC` slot inside a `para` line. */
14
+ /** Inline island node (an image, a footnote, an equation): a `U+FFFC` slot inside a `para` block. */
13
15
  export declare const islandInlineSpec: NodeSpec;
14
16
  /**
15
17
  * A PM island node's attributes: the content entry, with `islandType` because `type` on a PM node
@@ -19,20 +21,22 @@ export interface IslandNodeAttrs {
19
21
  id: string;
20
22
  islandType: ContentIsland['type'];
21
23
  props: unknown;
24
+ slots: Record<string, Content> | null;
25
+ /** A block island's: the id of the block its slot fills. */
26
+ block?: string | null;
22
27
  }
23
28
  /**
24
29
  * Build a content island entry from a PM island node's attrs. The cast pairs a closed `type` with a
25
30
  * `props` that crossed the DOM as opaque JSON. The store is lenient about a table's shape, so a
26
31
  * payload the arm does not hold is stored, and `undefined` at its reader draws the placeholder
27
- * (§`tablePropsOfNode`).
32
+ * (`table.ts` §`tableOfNode`).
28
33
  */
29
34
  export declare function islandEntryFromNode(attrs: IslandNodeAttrs): ContentIsland;
30
35
  /**
31
- * A node's `TableProps`, or `undefined` for any other island and for a payload of the wrong shape:
32
- * the boundary's guard, so a `props` that crossed the DOM is read once here. Every caller draws the
33
- * placeholder for `undefined` (`table-view.ts` §`render`).
36
+ * The `TableProps` shape over a value that reached the node off the DOM: the column ids and the
37
+ * rows mapping each to a slot id, which every reader indexes (`table.ts`).
34
38
  */
35
- export declare function tablePropsOfNode(node: PMNode): TableProps | undefined;
39
+ export declare function isTableProps(props: unknown): props is TableProps;
36
40
  /** The next island id for a field: one draw from {@link islandMinter}. */
37
41
  export declare function mintIslandId(doc: PMNode): string;
38
42
  /**