@quillmark/svelte 0.28.0 → 0.29.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.
@@ -3,6 +3,7 @@ import { Plugin } from 'prosemirror-state';
3
3
  import { usvLength } from './decode.js';
4
4
  import { scanDoc } from './encode.js';
5
5
  import { ISLAND_SLOT } from './islands.js';
6
+ import { isRemote } from './remote.js';
6
7
  /** The characters `doc` holds as `FieldSchema::char_count` counts them: Unicode scalar
7
8
  * values of the plain projection, islands counting nothing and trailing line breaks
8
9
  * none. */
@@ -20,7 +21,7 @@ export function capPlugin(cap) {
20
21
  const count = (doc) => capCount(doc, cap.trimEnd);
21
22
  return new Plugin({
22
23
  filterTransaction: (tr) => {
23
- if (!tr.docChanged || isHistoryTransaction(tr))
24
+ if (!tr.docChanged || isHistoryTransaction(tr) || isRemote(tr))
24
25
  return true;
25
26
  const after = count(tr.doc);
26
27
  return after <= cap.max || after <= count(tr.before);
@@ -1,7 +1,7 @@
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, Quill } from '@quillmark/wasm';
4
+ import type { Document, Content, Addr, Delta, Quill } from '@quillmark/wasm';
5
5
  import type { EditorErrorHandler } from '../errors.js';
6
6
  import { type TextCap } from './cap.js';
7
7
  import { type TableChromeStrings } from './table-view.js';
@@ -99,9 +99,13 @@ export interface FieldController {
99
99
  readonly el: HTMLElement;
100
100
  /** Place the caret at USV `pos` (preview onPick → usvToPM → here). */
101
101
  setCaret(pos: number): void;
102
- /** External content change → re-hydrate this leaf (gated by reconcile), and
103
- * re-evaluate its hold against the value now stored. */
104
- applyExternal(): void;
102
+ /**
103
+ * External content change → re-hydrate this leaf (gated by reconcile), and re-evaluate its
104
+ * hold against the value now stored. Where the hold stands, the difference lands as one
105
+ * step outside the undo history, so the leaf keeps its own undo and its caret; `delta`, the
106
+ * change's text delta over what the leaf held, places the caret where the change moved it.
107
+ */
108
+ applyExternal(delta?: Delta): void;
105
109
  /**
106
110
  * Move the empty-leaf ghost after mount (a card retyped to another kind takes its new wording;
107
111
  * a remount would cost the caret). Refreshes the decoration without a transaction, which would
@@ -14,6 +14,7 @@ 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';
16
16
  import { Decoration, DecorationSet, EditorView } from 'prosemirror-view';
17
+ import { core } from '../lifecycle.js';
17
18
  import { reportError, errorMessage } from '../errors.js';
18
19
  import { decode, fitsLeaf } from './decode.js';
19
20
  import { usvToPM, pmToUsv, buildLineIndex, lineIndexOf } from './positions.js';
@@ -25,6 +26,7 @@ import { contentEqual, createReconciler } from './reconcile.js';
25
26
  import { inputRulesPlugin, undoRuleKeymap } from './inputrules.js';
26
27
  import { linebreakPlugin } from './breaks.js';
27
28
  import { bodyKeymap } from './keymap.js';
29
+ import { remoteKey } from './remote.js';
28
30
  import { blockSchema, isBlockSchema, isInlineSchema, leafSchema, plainSchema } from './schema.js';
29
31
  import { linkPastePlugin } from './link-paste.js';
30
32
  import { linePastePlugin } from './line-paste.js';
@@ -59,6 +61,8 @@ function anchorPlugin(seed) {
59
61
  next = [...next, { id: edit.id, pos: edit.pos }];
60
62
  else if (edit?.op === 'remove')
61
63
  next = next.filter((a) => a.id !== edit.id);
64
+ else if (edit?.op === 'reset')
65
+ next = edit.anchors;
62
66
  return next;
63
67
  }
64
68
  }
@@ -358,6 +362,47 @@ export function createField(opts) {
358
362
  return false;
359
363
  }
360
364
  }
365
+ /**
366
+ * Land `rt` as one replace over the span where it differs from the leaf, outside history and
367
+ * past the filters (`remote.ts`), with the anchors reset to the ones `rt` holds. False where
368
+ * the replace does not fit, which a rebuild answers instead.
369
+ */
370
+ function landRemote(rt, delta) {
371
+ const before = view.state;
372
+ const next = decode(rt, schema);
373
+ const tr = before.tr.setMeta('addToHistory', false).setMeta(remoteKey, true);
374
+ const start = before.doc.content.findDiffStart(next.content);
375
+ try {
376
+ if (start != null) {
377
+ let { a: endA, b: endB } = before.doc.content.findDiffEnd(next.content);
378
+ const overlap = start - Math.min(endA, endB);
379
+ if (overlap > 0) {
380
+ endA += overlap;
381
+ endB += overlap;
382
+ }
383
+ tr.replace(start, endA, next.slice(start, endB));
384
+ }
385
+ if (!tr.doc.eq(next))
386
+ return false;
387
+ const after = buildLineIndex(tr.doc);
388
+ if (delta && before.selection instanceof TextSelection) {
389
+ const { mapPos } = core();
390
+ const at = (pm) => usvToPM(after, mapPos(delta, pmToUsv(index, pm), 'after'));
391
+ tr.setSelection(TextSelection.between(tr.doc.resolve(at(before.selection.anchor)), tr.doc.resolve(at(before.selection.head))));
392
+ }
393
+ if (!plaintext)
394
+ tr.setMeta(anchorKey, {
395
+ op: 'reset',
396
+ anchors: anchorsFromContent(rt).map((a) => ({ id: a.id, pos: usvToPM(after, a.pos) }))
397
+ });
398
+ view.updateState(before.apply(tr));
399
+ index = view.state.doc.eq(tr.doc) ? after : buildLineIndex(view.state.doc);
400
+ return true;
401
+ }
402
+ catch {
403
+ return false;
404
+ }
405
+ }
361
406
  /** The anchors the plugin currently holds (PM coords); `[]` before the first apply. */
362
407
  const heldAnchors = () => anchorKey.getState(view.state) ?? [];
363
408
  /** The plugin's anchor positions as USV, against `index` — which `dispatchTransaction`
@@ -378,7 +423,7 @@ export function createField(opts) {
378
423
  view.focus();
379
424
  view.dispatch(view.state.tr.setSelection(sel).scrollIntoView());
380
425
  },
381
- applyExternal() {
426
+ applyExternal(delta) {
382
427
  const current = shown();
383
428
  const flipped = holds(current) !== held;
384
429
  const wasDefaulted = defaulted;
@@ -389,6 +434,12 @@ export function createField(opts) {
389
434
  view.setProps({});
390
435
  return;
391
436
  }
437
+ if (!flipped && !held && landRemote(current, delta)) {
438
+ reconciler.commit(current);
439
+ if (defaulted !== wasDefaulted)
440
+ view.setProps({});
441
+ return;
442
+ }
392
443
  if (flipped)
393
444
  held = !held;
394
445
  const caretUsv = pmToUsv(index, view.state.selection.head);
@@ -1,5 +1,6 @@
1
1
  import { Plugin } from 'prosemirror-state';
2
2
  import { ReplaceAroundStep, ReplaceStep } from 'prosemirror-transform';
3
+ import { isRemote } from './remote.js';
3
4
  /** The store's bound on the containers around one line: a commit nesting past it is
4
5
  * refused, and `@quillmark/wasm` exports no constant to read it from. */
5
6
  export const MAX_NESTING_DEPTH = 12;
@@ -53,7 +54,7 @@ export function mayNest(tr) {
53
54
  export function nestingPlugin() {
54
55
  return new Plugin({
55
56
  filterTransaction: (tr) => {
56
- if (!tr.docChanged || !mayNest(tr))
57
+ if (!tr.docChanged || isRemote(tr) || !mayNest(tr))
57
58
  return true;
58
59
  const after = nestingDepth(tr.doc);
59
60
  return after <= MAX_NESTING_DEPTH || after <= nestingDepth(tr.before);
@@ -0,0 +1,3 @@
1
+ import { PluginKey, type Transaction } from 'prosemirror-state';
2
+ export declare const remoteKey: PluginKey<any>;
3
+ export declare function isRemote(tr: Transaction): boolean;
@@ -0,0 +1,7 @@
1
+ // A transaction that lands what another writer committed: the store already holds it, so no
2
+ // filter refuses it, and history maps the local steps through it rather than recording it.
3
+ import { PluginKey } from 'prosemirror-state';
4
+ export const remoteKey = new PluginKey('quill-remote');
5
+ export function isRemote(tr) {
6
+ return tr.getMeta(remoteKey) === true;
7
+ }
@@ -5,13 +5,17 @@
5
5
  import { closeHistory, isHistoryTransaction } from 'prosemirror-history';
6
6
  import { Plugin } from 'prosemirror-state';
7
7
  import { mayNest } from './nesting.js';
8
+ import { isRemote } from './remote.js';
8
9
  /** Marks each block-moving transaction as the start of an undo step. `filterTransaction`
9
10
  * is the one hook that sees a transaction before history's `apply` does; it passes
10
11
  * every one. A transaction a plugin appended stays in its root's step. */
11
12
  export function undoStepPlugin() {
12
13
  return new Plugin({
13
14
  filterTransaction: (tr) => {
14
- if (!tr.docChanged || isHistoryTransaction(tr) || tr.getMeta('appendedTransaction'))
15
+ if (!tr.docChanged ||
16
+ isHistoryTransaction(tr) ||
17
+ isRemote(tr) ||
18
+ tr.getMeta('appendedTransaction'))
15
19
  return true;
16
20
  if (mayNest(tr))
17
21
  closeHistory(tr);
@@ -26,7 +26,8 @@
26
26
  import { untrack } from 'svelte';
27
27
  import { reportRebindIgnored } from '../core/rebind.svelte.js';
28
28
  import type { DocPath, Landing } from '../core/address.js';
29
- import type { CardId } from './signals.js';
29
+ import type { Delta } from '@quillmark/wasm';
30
+ import type { CardId, CardOp } from './signals.js';
30
31
  import type { VisualEditorProps } from './props.js';
31
32
  import VisualEditorInner from './VisualEditorInner.svelte';
32
33
 
@@ -88,6 +89,19 @@
88
89
  export function setKind(cardId: CardId, kind: string): void {
89
90
  inner?.setKind(cardId, kind);
90
91
  }
92
+ /** Re-read the prose leaf at `field` after the host changed it in the document, as one
93
+ * step outside its undo history; `delta` carries the caret. */
94
+ export function applyExternal(field: DocPath, delta?: Delta): void {
95
+ inner?.applyExternal(field, delta);
96
+ }
97
+ /** Re-read the cards' kinds, titles and form fields after the host changed them. */
98
+ export function refresh(): void {
99
+ inner?.refresh();
100
+ }
101
+ /** Move the card keys in step with card-list changes the host made in the document. */
102
+ export function applyCardOps(ops: readonly CardOp[]): void {
103
+ inner?.applyCardOps(ops);
104
+ }
91
105
  </script>
92
106
 
93
107
  {#key props.doc}
@@ -1,5 +1,6 @@
1
1
  import type { DocPath, Landing } from '../core/address.js';
2
- import type { CardId } from './signals.js';
2
+ import type { Delta } from '@quillmark/wasm';
3
+ import type { CardId, CardOp } from './signals.js';
3
4
  import type { VisualEditorProps } from './props.js';
4
5
  declare const VisualEditor: import("svelte").Component<VisualEditorProps, {
5
6
  setCaret: (at: Landing) => Promise<void>;
@@ -8,6 +9,9 @@ declare const VisualEditor: import("svelte").Component<VisualEditorProps, {
8
9
  removeCard: (cardId: CardId) => void;
9
10
  moveCard: (cardId: CardId, dir: -1 | 1) => void;
10
11
  setKind: (cardId: CardId, kind: string) => void;
12
+ applyExternal: (field: DocPath, delta?: Delta) => void;
13
+ refresh: () => void;
14
+ applyCardOps: (ops: readonly CardOp[]) => void;
11
15
  }, "">;
12
16
  type VisualEditor = ReturnType<typeof VisualEditor>;
13
17
  export default VisualEditor;
@@ -37,6 +37,7 @@
37
37
  import type {
38
38
  Addr,
39
39
  CardAddr,
40
+ Delta,
40
41
  Diagnostic,
41
42
  PathStep,
42
43
  PayloadItem,
@@ -46,7 +47,7 @@
46
47
  } from '@quillmark/wasm';
47
48
  import type { VisualEditorProps } from './props.js';
48
49
  import { mergeStrings, setWording } from './strings.js';
49
- import type { CardId, ChangeSource } from './signals.js';
50
+ import type { CardId, CardOp, ChangeSource } from './signals.js';
50
51
  import type { FieldController, LeafViews } from '../core/codec/index.js';
51
52
  import {
52
53
  IdSeq,
@@ -157,12 +158,15 @@
157
158
  * addressable against the tree the bump re-derived: an insert's card does not exist
158
159
  * in the previous one, and a retype's kind is the previous kind.
159
160
  */
160
- function bump(source: ChangeSource, cardId?: CardId, at?: Addr | number): void {
161
- revision++;
162
- liveTitles = {};
161
+ function bump(source: ChangeSource, cardId?: CardId, at?: Addr | number, op?: CardOp): void {
162
+ rederive();
163
163
  const path =
164
164
  at == null ? undefined : typeof at === 'number' ? cardPath(at, liveKinds()) : pathFor(at);
165
- onChange?.({ source, cardId, path });
165
+ onChange?.({ source, cardId, path, ...(op ? { op } : {}) });
166
+ }
167
+ function rederive(): void {
168
+ revision++;
169
+ liveTitles = {};
166
170
  }
167
171
  /** Read at the mutation boundary, never cached (VISUAL_EDITOR §"The address is the
168
172
  * spine"). */
@@ -420,7 +424,7 @@
420
424
  const id = seq.next();
421
425
  arm.arm();
422
426
  cardIds = [...cardIds.slice(0, atIndex), id, ...cardIds.slice(atIndex)];
423
- bump('structure', id, atIndex);
427
+ bump('structure', id, atIndex, { op: 'insert', at: atIndex });
424
428
  // Centred: the new card is the subject, and the neighbours it landed between
425
429
  // are what say where it went.
426
430
  const scrolled = scrollCardIntoView(id, 'center');
@@ -483,7 +487,7 @@
483
487
  const [x] = w.splice(from, 1);
484
488
  w.splice(to, 0, x);
485
489
  cardIds = w;
486
- bump('structure', id, to);
490
+ bump('structure', id, to, { op: 'move', from, to });
487
491
  // `nearest`: the card was already in view and only needs to stay there, so one
488
492
  // that never left the viewport moves it not at all.
489
493
  void scrollCardIntoView(id, 'nearest');
@@ -498,20 +502,23 @@
498
502
  doc.removeCard(i);
499
503
  arm.arm();
500
504
  cardIds = cardIds.filter((_, k) => k !== i);
505
+ forget(id);
506
+ // No addr: the removed card has none left and every survivor's shifted. The
507
+ // stack changed, not a leaf, and the id is the only handle the removal leaves.
508
+ bump('structure', id, undefined, { op: 'remove', at: i });
509
+ if (held) void focusAfterRemove(i);
510
+ }
511
+ /** Drop what the surface holds for a removed card. Ids are never reused, so an entry
512
+ * keyed to the gone card is unreachable rather than mis-attributed to whichever card
513
+ * takes this position: it needs dropping because nothing else will ever clear it. */
514
+ function forget(id: CardId): void {
501
515
  if (activeCardId === id) {
502
516
  activeCardId = undefined;
503
517
  activeAddr = undefined;
504
518
  }
505
- // Ids are never reused, so an entry keyed to the gone card is unreachable rather
506
- // than mis-attributed to whichever card takes this position: it needs dropping
507
- // because nothing else will ever clear it.
508
519
  const prefix = `${id}:`;
509
520
  const stale = [...commitErrors.keys()].filter((k) => k.startsWith(prefix));
510
521
  for (const k of stale) commitErrors.delete(k);
511
- // No addr: the removed card has none left and every survivor's shifted. The
512
- // stack changed, not a leaf, and the id is the only handle the removal leaves.
513
- bump('structure', id);
514
- if (held) void focusAfterRemove(i);
515
522
  }
516
523
  /** Hand the focus a removed card held to the title of the card before it, else the
517
524
  * one that took its place, else the strip that adds one: a focused node the flush
@@ -849,6 +856,38 @@
849
856
  retypeCardById(cardId, kind);
850
857
  }
851
858
 
859
+ // ── Changes the host made ───────────────────────────────────────────────────
860
+ // A live session writes another client's edits into the document itself and then
861
+ // says what it moved. The surface re-reads, keeps every mounted leaf and caret it can,
862
+ // and reports none of it through `onChange`: the edit is not this surface's.
863
+
864
+ /** Re-read the prose leaf at `field` from the document, landing the difference as one
865
+ * step outside its undo history; `delta`, the change's text delta over what the leaf
866
+ * held, carries the caret. */
867
+ export function applyExternal(field: DocPath, delta?: Delta): void {
868
+ if (!span.alive) return;
869
+ const target = leafTargetFor(field);
870
+ if (target && !target.steps) leaves.prose(target.key)?.applyExternal(delta);
871
+ rederive();
872
+ }
873
+ /** Re-read the cards' kinds, titles and form fields from the document. */
874
+ export function refresh(): void {
875
+ if (span.alive) rederive();
876
+ }
877
+ /** Move the card keys in step with card-list changes the document already holds, in the
878
+ * order it applied them, so every card that stays keeps its leaves. */
879
+ export function applyCardOps(ops: readonly CardOp[]): void {
880
+ if (!span.alive) return;
881
+ const ids = cardIds.slice();
882
+ for (const op of ops) {
883
+ if (op.op === 'insert') ids.splice(op.at, 0, seq.next());
884
+ else if (op.op === 'remove') forget(ids.splice(op.at, 1)[0]);
885
+ else ids.splice(op.to, 0, ...ids.splice(op.from, 1));
886
+ }
887
+ cardIds = ids;
888
+ rederive();
889
+ }
890
+
852
891
  function holds(cardId: CardId): boolean {
853
892
  if (cardIndexOf(cardId) >= 0) return true;
854
893
  missed(`no card ${cardId} in this session`);
@@ -1,6 +1,7 @@
1
1
  import { type DocPath, type Landing } from '../core/address.js';
2
+ import type { Delta } from '@quillmark/wasm';
2
3
  import type { VisualEditorProps } from './props.js';
3
- import type { CardId } from './signals.js';
4
+ import type { CardId, CardOp } from './signals.js';
4
5
  import { type ActiveProse } from './leaves.js';
5
6
  declare const VisualEditorInner: import("svelte").Component<VisualEditorProps, {
6
7
  setCaret: (at: Landing) => Promise<void>;
@@ -10,6 +11,9 @@ declare const VisualEditorInner: import("svelte").Component<VisualEditorProps, {
10
11
  removeCard: (cardId: CardId) => void;
11
12
  moveCard: (cardId: CardId, dir: -1 | 1) => void;
12
13
  setKind: (cardId: CardId, kind: string) => void;
14
+ applyExternal: (field: DocPath, delta?: Delta) => void;
15
+ refresh: () => void;
16
+ applyCardOps: (ops: readonly CardOp[]) => void;
13
17
  }, "">;
14
18
  type VisualEditorInner = ReturnType<typeof VisualEditorInner>;
15
19
  export default VisualEditorInner;
@@ -6,4 +6,4 @@ export { DEFAULT_VISUAL_STRINGS } from './strings.js';
6
6
  export type { VisualStrings, VisualStringsInput, FormatDiagnostic } from './strings.js';
7
7
  export type { BodyPlaceholder, BodyPlaceholderContext } from './structure.js';
8
8
  export { patchEditorExt } from './ext.js';
9
- export type { ActiveLeaf, CardId, ChangeSource, EditorChange } from './signals.js';
9
+ export type { ActiveLeaf, CardId, CardOp, ChangeSource, EditorChange } from './signals.js';
@@ -24,13 +24,24 @@ export type ChangeSource =
24
24
  * carries no card handle): it is minted at mount and dies with the surface, so it
25
25
  * does not survive a reload and a host persisting one is persisting a session key.
26
26
  *
27
- * The editor owns structural mutation for the session. The keys track the inserts,
28
- * moves and removals the editor performs; a host that mutates the card array behind
29
- * it (its own `doc.insertCard`) desyncs them, and the answer is to re-seed the
30
- * surface rather than expect the keys to follow. There is nothing document-side to
31
- * reconcile against, so this is a contract rather than a mechanism.
27
+ * The keys track the inserts, moves and removals the editor performs, and the ones a
28
+ * host reports through `applyCardOps` after making them itself (a live session's
29
+ * remote edits). A host that mutates the card array behind the editor and reports
30
+ * nothing desyncs them: there is nothing document-side to reconcile against.
32
31
  */
33
32
  export type CardId = string;
33
+ /** A change to the composable card list, by index, as the document applied it. */
34
+ export type CardOp = {
35
+ op: 'insert';
36
+ at: number;
37
+ } | {
38
+ op: 'remove';
39
+ at: number;
40
+ } | {
41
+ op: 'move';
42
+ from: number;
43
+ to: number;
44
+ };
34
45
  /** An edit that landed on the document, and which lane it came down. */
35
46
  export interface EditorChange {
36
47
  source: ChangeSource;
@@ -49,6 +60,9 @@ export interface EditorChange {
49
60
  * dismissal, which is document-level chrome and names no card.
50
61
  */
51
62
  cardId?: CardId;
63
+ /** The card-list change a structure op made: an add, a move or a removal. A retype
64
+ * and a rename leave the list as it was and carry none. */
65
+ op?: CardOp;
52
66
  }
53
67
  /** The leaf that has focus: where it sits, and which card holds it. */
54
68
  export interface ActiveLeaf {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quillmark/svelte",
3
- "version": "0.28.0",
3
+ "version": "0.29.0",
4
4
  "description": "Editor, live-preview and source surfaces over a Quillmark WASM session.",
5
5
  "repository": {
6
6
  "type": "git",