@quillmark/svelte 0.29.3 → 0.30.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.
@@ -1,10 +1,113 @@
1
- import { core } from '../lifecycle.js';
2
- import { usvLength } from './decode.js';
3
- import { contentEdit, pmToContent } from './encode.js';
1
+ import { pmToContent } from './encode.js';
2
+ import { HARD_BREAK, isTableProps } from './islands.js';
4
3
  import { valueEqual } from './reconcile.js';
5
4
  /** The alignments a column can take: the four the content declares, `none` first
6
5
  * because it is what a column arrives at and what a set is cleared back to. */
7
6
  export const ALIGNS = ['none', 'left', 'center', 'right'];
7
+ const TABLE_KEYS = new Set(['columns', 'rows', 'head', 'aligns', 'widths', 'align', 'cell_attrs']);
8
+ /** The grid a table island spells, each cell its slot's content and its ids. */
9
+ export function gridOf(props, slots) {
10
+ const attrs = props.cell_attrs ?? {};
11
+ const cells = props.rows.map((row) => props.columns.map((column) => {
12
+ const slot = row.cells[column] ?? '';
13
+ const content = slots?.[slot];
14
+ return {
15
+ ...attrs[slot],
16
+ text: content?.text ?? '',
17
+ marks: content?.marks ?? [],
18
+ ...(content?.anchors?.length && { anchors: content.anchors }),
19
+ ids: { row: row.id, column, slot, block: content?.blocks[0]?.id ?? 'b0' }
20
+ };
21
+ }));
22
+ const extra = Object.fromEntries(Object.entries(props).filter(([k]) => !TABLE_KEYS.has(k)));
23
+ const [header = [], ...rows] = cells;
24
+ return normalizeTable({
25
+ header,
26
+ rows,
27
+ aligns: props.columns.map((c) => props.aligns?.[c] ?? 'none'),
28
+ ...(props.widths && {
29
+ widths: props.widths && props.columns.map((c) => props.widths?.[c] ?? null)
30
+ }),
31
+ ...(props.align && { align: props.align }),
32
+ ...(props.head !== undefined && { head: props.head }),
33
+ ...(Object.keys(extra).length && { extra })
34
+ });
35
+ }
36
+ /** A node's grid, or `undefined` for any other island and for a payload of the wrong shape. */
37
+ export function tableOfNode(node) {
38
+ const attrs = node.attrs;
39
+ return attrs.islandType === 'table' && isTableProps(attrs.props)
40
+ ? gridOf(attrs.props, attrs.slots)
41
+ : undefined;
42
+ }
43
+ /** A minter for one id space: `{prefix}{n}` past the highest `held` names under `prefix`. */
44
+ function minter(held, prefix) {
45
+ const taken = new Set();
46
+ let next = 0;
47
+ for (const id of held) {
48
+ const m = new RegExp(`^${prefix}(\\d+)$`).exec(id);
49
+ if (m)
50
+ next = Math.max(next, Number(m[1]) + 1);
51
+ }
52
+ return (want) => {
53
+ if (want && !taken.has(want)) {
54
+ taken.add(want);
55
+ return want;
56
+ }
57
+ let id = `${prefix}${next++}`;
58
+ while (taken.has(id))
59
+ id = `${prefix}${next++}`;
60
+ taken.add(id);
61
+ return id;
62
+ };
63
+ }
64
+ /** The island a grid spells: its props and slots, each rank's id the first its cells carry. */
65
+ export function islandOf(grid) {
66
+ const g = normalizeTable(grid);
67
+ const rows = allRows(g);
68
+ const every = rows.flat().flatMap((cell) => (cell.ids ? [cell.ids] : []));
69
+ const rowId = minter(every.map((i) => i.row), 'r');
70
+ const columnId = minter(every.map((i) => i.column), 'k');
71
+ const slotId = minter(every.map((i) => i.slot), 's');
72
+ const columns = g.aligns.map((_, c) => columnId(rows.map((row) => row[c]?.ids?.column).find((id) => id !== undefined)));
73
+ const slots = {};
74
+ const cellAttrs = {};
75
+ const out = rows.map((row) => ({
76
+ id: rowId(row.map((cell) => cell.ids?.row).find((id) => id !== undefined)),
77
+ cells: Object.fromEntries(row.map((cell, c) => {
78
+ const slot = slotId(cell.ids?.slot);
79
+ slots[slot] = cellContent(cell);
80
+ const own = cellAttrsOf(cell);
81
+ if (Object.keys(own).length)
82
+ cellAttrs[slot] = own;
83
+ return [columns[c], slot];
84
+ }))
85
+ }));
86
+ const keyed = (xs, skip) => {
87
+ const entries = (xs ?? []).flatMap((x, c) => (skip(x) ? [] : [[columns[c], x]]));
88
+ return entries.length ? Object.fromEntries(entries) : undefined;
89
+ };
90
+ const aligns = keyed(g.aligns, (a) => a === 'none');
91
+ const widths = keyed(g.widths, (w) => w === null);
92
+ return {
93
+ props: {
94
+ ...g.extra,
95
+ columns,
96
+ rows: out,
97
+ ...(g.head !== undefined && g.head !== 1 && { head: g.head }),
98
+ ...(aligns && { aligns }),
99
+ ...(widths && { widths }),
100
+ ...(g.align && { align: g.align }),
101
+ ...(Object.keys(cellAttrs).length && { cell_attrs: cellAttrs })
102
+ },
103
+ slots
104
+ };
105
+ }
106
+ /** A cell's own layout: every key beside its text, marks, anchors and ids. */
107
+ function cellAttrsOf(cell) {
108
+ const { text: _t, marks: _m, anchors: _a, ids: _i, ...layout } = cell;
109
+ return layout;
110
+ }
8
111
  /** The zero cell: empty text, no marks. */
9
112
  export function emptyCell() {
10
113
  return { text: '', marks: [] };
@@ -52,7 +155,8 @@ export function normalizeTable(props) {
52
155
  aligns: Array.from({ length: cols }, (_, c) => props.aligns[c] ?? 'none'),
53
156
  ...(widths.some((w) => w !== null) && { widths }),
54
157
  ...(props.align && { align: props.align }),
55
- ...(props.head !== undefined && props.head !== 1 && { head: props.head })
158
+ ...(props.head !== undefined && props.head !== 1 && { head: props.head }),
159
+ ...(props.extra && { extra: props.extra })
56
160
  };
57
161
  }
58
162
  /** How many rows from the top draw as header rows, absent being one. */
@@ -432,8 +536,8 @@ export function mergeCells(props, block) {
432
536
  if (!grid[r][c] || cell.text === '')
433
537
  continue;
434
538
  if (text)
435
- text += '\n';
436
- const at = usvLength(text);
539
+ text += HARD_BREAK;
540
+ const at = text.length;
437
541
  text += cell.text;
438
542
  for (const m of cell.marks)
439
543
  marks.push({ ...m, start: m.start + at, end: m.end + at });
@@ -477,64 +581,69 @@ export function columnShares(props) {
477
581
  return weights.map((w) => w / total);
478
582
  }
479
583
  // ── The cell codec ──────────────────────────────────────────────────────────
480
- /**
481
- * A cell as a one-paragraph `Content` for `decode` under `cellSchema`: each `\n` opens a
482
- * `continues` line, the hard break it decodes to. The cell's marks are that content's marks.
483
- */
584
+ /** A cell as its slot: one paragraph, for `decode` under `cellSchema`. */
484
585
  export function cellContent(cell) {
485
- const breaks = cell.text.split('\n').length - 1;
486
586
  return {
487
587
  text: cell.text,
488
- lines: [
489
- { containers: [], kind: 'para' },
490
- ...Array.from({ length: breaks }, () => ({
491
- containers: [],
492
- kind: 'para',
493
- continues: true
494
- }))
495
- ],
496
- marks: cell.marks,
497
- islands: []
588
+ blocks: [{ id: cell.ids?.block ?? 'b0', kind: 'para' }],
589
+ ...(cell.marks.length && { marks: cell.marks }),
590
+ ...(cell.anchors?.length && { anchors: cell.anchors })
498
591
  };
499
592
  }
500
593
  /**
501
- * The cell a nested PM doc projects, carrying `prior`'s identity anchors through.
594
+ * Where `pos` in `before` lands in `after`, reading the edit between them as the one replaced run
595
+ * their common prefix and suffix leave: what a keystroke in a cell is. `assoc` says which side of
596
+ * the replaced run a position at its edge or inside it takes.
597
+ */
598
+ function mapThrough(before, after, pos, assoc) {
599
+ const most = Math.min(before.length, after.length);
600
+ let head = 0;
601
+ while (head < most && before[head] === after[head])
602
+ head++;
603
+ let tail = 0;
604
+ while (tail < most - head && before[before.length - 1 - tail] === after[after.length - 1 - tail])
605
+ tail++;
606
+ const oldEnd = before.length - tail;
607
+ const newEnd = after.length - tail;
608
+ if (pos < head || (pos === head && assoc === 'before'))
609
+ return pos;
610
+ if (pos > oldEnd || (pos === oldEnd && assoc === 'after'))
611
+ return pos + newEnd - oldEnd;
612
+ return assoc === 'before' ? head : newEnd;
613
+ }
614
+ /**
615
+ * The cell a nested PM doc projects, carrying `prior`'s layout, ids and anchors through.
502
616
  *
503
- * Anchors inside a cell are preserved verbatim, never minted: they are not in the field plugin's
504
- * coordinate space (its position map holds one `atom` run for the whole table), so the popover
505
- * withholds its `anchor` button in a cell. Preserving still means rebasing: `mapMarks` carries each
506
- * held anchor through the cell's delta by the store's rule, and a mark the splice deleted through
507
- * lands where the splice left it.
617
+ * Anchors inside a cell are preserved, never minted: they are not in the field plugin's coordinate
618
+ * space (its position map holds one `atom` run for the whole table), so the popover withholds its
619
+ * `anchor` button in a cell. Preserving still means rebasing: each held anchor maps through the
620
+ * edit by the store's rule, a range's start after it and its end before, a point before, and a
621
+ * range the edit closes is dropped.
508
622
  */
509
623
  export function cellFromDoc(doc, prior) {
510
624
  const projected = pmToContent(doc);
511
- const text = projected.text;
512
- const layout = cellLayout(prior);
513
- const anchors = prior.marks.filter((m) => m.type === 'anchor');
514
- if (!anchors.length)
515
- return { ...layout, text, marks: projected.marks };
516
- const before = cellContent(prior);
517
- const delta = contentEdit(before, cellContent({ text, marks: [] })).delta;
518
- const rebased = core()
519
- .mapMarks(before, delta ? { delta } : {})
520
- .filter((m) => m.type === 'anchor');
521
- return {
522
- ...layout,
523
- text,
524
- marks: [...projected.marks, ...rebased].sort((a, b) => a.start - b.start || a.end - b.end)
525
- };
526
- }
527
- /** A cell's keys beside its text and marks: what no edit of the text touches. */
528
- function cellLayout(cell) {
529
- const { text: _text, marks: _marks, ...layout } = cell;
530
- return layout;
625
+ const { anchors: held, ...rest } = prior;
626
+ const next = { ...rest, text: projected.text, marks: projected.marks ?? [] };
627
+ if (!held?.length)
628
+ return next;
629
+ const at = (pos, assoc) => mapThrough(prior.text, next.text, pos, assoc);
630
+ const anchors = held.flatMap((a) => {
631
+ if (a.start === a.end) {
632
+ const p = at(a.start, 'before');
633
+ return [{ ...a, start: p, end: p }];
634
+ }
635
+ const start = at(a.start, 'after');
636
+ const end = at(a.end, 'before');
637
+ return start < end ? [{ ...a, start, end }] : [];
638
+ });
639
+ return anchors.length ? { ...next, anchors } : next;
531
640
  }
532
641
  /**
533
642
  * Whether two cells are the same value, telling an own edit from an external one (an undo, a
534
643
  * re-hydrate) without a flag. Marks compare structurally, as `reconcile.ts` states.
535
644
  */
536
645
  export function cellEqual(a, b) {
537
- return a.text === b.text && valueEqual(a.marks, b.marks);
646
+ return a.text === b.text && valueEqual(a.marks, b.marks) && valueEqual(a.anchors, b.anchors);
538
647
  }
539
648
  /** Whether two tables have the same rectangle, alignment, header and widths: the
540
649
  * change that forces a rebuild rather than a per-cell reseed. */
@@ -393,7 +393,7 @@
393
393
  }
394
394
  /**
395
395
  * Land at `steps`: element `steps[0]`, and the rest of the walk inside its subform,
396
- * at USV `pos` where the leaf the walk ends in can take one ({@link
396
+ * at UTF-16 offset `pos` where the leaf the walk ends in can take one ({@link
397
397
  * FieldControl.focusPath}). The index resolves to the element's session id here, at
398
398
  * the call, never carried as one — an index is stale the moment anything above it
399
399
  * splices. Past the live list it falls back to {@link focus}: the field is right and
@@ -8,7 +8,7 @@
8
8
  raises it over that leaf's selection rect; each button dispatches a PM `toggleMark`
9
9
  command straight at the leaf's `EditorView`, whose own `dispatchTransaction` commits
10
10
  the result as it commits a keystroke: a field's lowers it to `markOps` through
11
- `applyChange` (field.ts), a by-value leaf's hands the re-encoded value to its parent
11
+ `apply` (field.ts), a by-value leaf's hands the re-encoded value to its parent
12
12
  (`ProseValue`). This component never touches the content. The keymap mirror
13
13
  (Mod-b/i/u, Mod-Shift-x, Mod-e) lives in the codec's keymap (field.ts); this is
14
14
  the pointer affordance for all six marks. Mod-K is this surface's own key, the
@@ -2,7 +2,7 @@
2
2
  A prose leaf the parent commits by value: an element of a `richtext` (fixture
3
3
  `keywords`) or `text` (`authors`, `errata`) array, and a content cell of a subform — an
4
4
  `object`'s property, a variant's cell ({@link ObjectField}). None of them is
5
- `applyChange`-addressable: `Addr.field` is a flat name, so `keywords[0]` and
5
+ `apply`-addressable: `Addr.field` is a flat name, so `keywords[0]` and
6
6
  `contact.note` have no op address. So this is not a `createField` leaf: it mounts a
7
7
  minimal PM view over the codec's decode/encode and a leaf schema, and on every edit
8
8
  hands the re-encoded `Content` up to the parent — {@link ArrayField}, which commits
@@ -62,8 +62,8 @@
62
62
  proseAttributes,
63
63
  proseLeafPlugins,
64
64
  buildLineIndex,
65
- pmToUsv,
66
- usvToPM,
65
+ pmToOffset,
66
+ offsetToPM,
67
67
  valueEqual,
68
68
  type LeafViews,
69
69
  type TextCap
@@ -151,12 +151,12 @@
151
151
  view.focus();
152
152
  view.dom.scrollIntoView({ block: 'nearest' });
153
153
  }
154
- /** Take the caret to USV `pos` in this leaf's own content: what a landing on an
154
+ /** Take the caret to UTF-16 offset `pos` in this leaf's own content: what a landing on an
155
155
  * element address resolves to when the compile answered a cluster-exact offset
156
156
  * (`leaves.ts`). `createField`'s body over the view this component owns.
157
157
  *
158
158
  * The index is built here rather than held: a landing is a discrete act, and one
159
- * doc walk per click is cheaper than a cache to invalidate per keystroke. `usvToPM`
159
+ * doc walk per click is cheaper than a cache to invalidate per keystroke. `offsetToPM`
160
160
  * clamps, so an offset past a value the compile has moved on from lands the end.
161
161
  *
162
162
  * `Selection.near`, not `TextSelection.create`: the mapped position can be
@@ -164,7 +164,7 @@
164
164
  * reasons are `FieldController.setCaret`'s (`codec/field.ts`). */
165
165
  export function setCaret(pos: number): void {
166
166
  if (!view) return;
167
- const pm = usvToPM(buildLineIndex(view.state.doc), pos);
167
+ const pm = offsetToPM(buildLineIndex(view.state.doc), pos);
168
168
  const sel = Selection.near(view.state.doc.resolve(pm));
169
169
  view.focus();
170
170
  view.dispatch(view.state.tr.setSelection(sel).scrollIntoView());
@@ -292,9 +292,9 @@
292
292
  if (held) seat?.release(views);
293
293
  else if (mounted.hasFocus()) seat?.focus(views);
294
294
  // The caret keeps its offset, clamped, as a field's re-hydrate keeps it.
295
- const caret = pmToUsv(buildLineIndex(mounted.state.doc), mounted.state.selection.head);
295
+ const caret = pmToOffset(buildLineIndex(mounted.state.doc), mounted.state.selection.head);
296
296
  const fresh = build(current);
297
- const sel = Selection.near(fresh.doc.resolve(usvToPM(buildLineIndex(fresh.doc), caret)));
297
+ const sel = Selection.near(fresh.doc.resolve(offsetToPM(buildLineIndex(fresh.doc), caret)));
298
298
  mounted.updateState(fresh.apply(fresh.tr.setSelection(sel)));
299
299
  reconciler.commit(current);
300
300
  };
@@ -178,7 +178,8 @@
178
178
  * key is a host's only handle on a card, so a stale one is dropped rather than
179
179
  * reported. */
180
180
  function cardIdOf(addr: Addr): CardId | undefined {
181
- return addr.card == null ? 'main' : cardIds[addr.card];
181
+ if (addr.card == null) return 'main';
182
+ return typeof addr.card === 'number' ? cardIds[addr.card] : undefined;
182
183
  }
183
184
 
184
185
  // ── Teardown (core/teardown.ts: unregister, cancel, then free) ──────────────
@@ -299,7 +300,7 @@
299
300
  let liveTitles = $state<Record<CardId, string>>({});
300
301
  function refreshTitle(addr: Addr, cardId: CardId): void {
301
302
  const { card: at, field } = addr;
302
- if (at == null || field == null) return;
303
+ if (typeof at !== 'number' || field == null) return;
303
304
  const shown = model.cards[at];
304
305
  const cardSchema = shown && quill.schema.card_kinds?.[shown.kind];
305
306
  if (!cardSchema || cardSchema.title?.trim()) return;
@@ -318,7 +319,7 @@
318
319
  // ── Commit routing ──────────────────────────────────────────────────────────
319
320
  // Scalars / arrays / objects → the typed writer (schema-checked); a cleared entry
320
321
  // arrives as `undefined` and takes the unset lane instead. Prose leaves commit
321
- // themselves via the codec (applyChange) and do not pass through here.
322
+ // themselves via the codec (`apply`) and do not pass through here.
322
323
  //
323
324
  // A bad value makes `writer.set` throw a `QuillmarkError` whose `diagnostics[0]`
324
325
  // carries a `code` and a canonical `path` (`edit::field_coercion_failed` at
@@ -531,12 +532,17 @@
531
532
  const i = cardIndexOf(id);
532
533
  if (i < 0) return;
533
534
  try {
534
- // Insert the retyped card ahead of the original and drop the original after.
535
- // `insertCard` validates the whole card before it mutates and `removeCard`
536
- // cannot throw, so a refusal leaves the document as it was; the reverse order
537
- // would leave it a card short.
538
- doc.insertCard({ ...doc.card(i), kind }, i);
539
- doc.removeCard(i + 1);
535
+ // The retyped card keeps the original's `$id`, which two cards cannot hold at
536
+ // once, so the original goes first and comes back where `insertCard` refuses:
537
+ // it validates the whole card before it mutates, so the document is as it was.
538
+ const card = doc.card(i);
539
+ doc.removeCard(i);
540
+ try {
541
+ doc.insertCard({ ...card, kind }, i);
542
+ } catch (e) {
543
+ doc.insertCard(card, i);
544
+ throw e;
545
+ }
540
546
  bump('structure', id, i);
541
547
  } catch (e) {
542
548
  reportError(onError, {
@@ -788,7 +794,7 @@
788
794
  }
789
795
 
790
796
  /**
791
- * Put the caret in a revealed target, at the finest grain it can take: a USV offset
797
+ * Put the caret in a revealed target, at the finest grain it can take: a UTF-16 offset
792
798
  * in a prose leaf or a nested content cell, a bare focus everywhere else. A form
793
799
  * control has no coordinate to spend an offset in (an `<input type="number">`
794
800
  * refuses a selection outright), which is also the whole of what a click on
@@ -951,7 +957,7 @@
951
957
  * second reading of the schema beside it. */
952
958
  function declaredField(addr: Addr): QuillFieldSchema | undefined {
953
959
  if (addr.field == null) return undefined;
954
- const kind = addr.card == null ? undefined : model.cards[addr.card]?.kind;
960
+ const kind = typeof addr.card === 'number' ? model.cards[addr.card]?.kind : undefined;
955
961
  const schema = quill.schema;
956
962
  const card = addr.card == null ? schema.main : kind ? schema.card_kinds?.[kind] : undefined;
957
963
  return card?.fields?.[addr.field];
@@ -20,7 +20,7 @@ export interface FieldControl {
20
20
  /**
21
21
  * Land at `steps` inside a control that has an inside — an array's element, an
22
22
  * object's property, a variant's cell, a matrix's member, and any of them under any
23
- * other — at USV `pos` where the leaf the walk ends in can take one. Each rung
23
+ * other — at UTF-16 offset `pos` where the leaf the walk ends in can take one. Each rung
24
24
  * resolves its own step at the call (an index to a session id, a key to a mounted
25
25
  * cell) and hands the rest to the control it opened, so nothing positional is
26
26
  * carried. A step the tree does not hold falls back to that rung's own
@@ -4,7 +4,7 @@
4
4
  // Two lanes behind one lookup. Every mounted field registers a {@link FieldControl} —
5
5
  // take the caret, and a box to bloom — which is the whole of what a reveal and a
6
6
  // focus need, and the whole of what a form control has. A prose leaf registers its
7
- // `FieldController` instead: a superset, carrying the codec seam (a caret at a USV
7
+ // `FieldController` instead: a superset, carrying the codec seam (a caret at a UTF-16
8
8
  // offset, the formatting popover's observation) that no `<input>` answers. So
9
9
  // `control` covers every field and `prose` covers the leaves that have one, and the
10
10
  // verbs ask for the half they use: `focusField` never needs the codec, and
@@ -105,16 +105,7 @@ export function declaredContent(v, markdown) {
105
105
  return undefined;
106
106
  if (markdown)
107
107
  return core().importMarkdown(text).content;
108
- return {
109
- text,
110
- lines: text
111
- .split('\n')
112
- .map((_, i) => i === 0
113
- ? { containers: [], kind: 'para' }
114
- : { containers: [], kind: 'para', continues: true }),
115
- marks: [],
116
- islands: []
117
- };
108
+ return { text: text.replaceAll('\n', '\u2028'), blocks: [{ id: 'b0', kind: 'para' }] };
118
109
  }
119
110
  /** A field's `{#each}` key: its name and what a mounted leaf reads once, its type,
120
111
  * {@link oneLine} and `max:`, and its elements'. A retype or a quill swap that changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quillmark/svelte",
3
- "version": "0.29.3",
3
+ "version": "0.30.0",
4
4
  "description": "Editor, live-preview and source surfaces over a Quillmark WASM session.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -69,7 +69,7 @@
69
69
  "check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings"
70
70
  },
71
71
  "peerDependencies": {
72
- "@quillmark/wasm": ">=0.133.0-0 <0.134.0-0",
72
+ "@quillmark/wasm": ">=0.134.1-0 <0.135.0-0",
73
73
  "svelte": "^5.33.0"
74
74
  },
75
75
  "dependencies": {