@inkandswitch/patchwork-pkg-base 0.0.41 → 0.0.42

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 (51) hide show
  1. package/package.json +1 -1
  2. package/packages/account/dist/{InlineContactAvatar-TVDLE2AV.js → InlineContactAvatar-6UAAJ73R.js} +2 -1
  3. package/packages/account/dist/InlineContactAvatar-6UAAJ73R.js.map +7 -0
  4. package/packages/account/dist/index.js +1 -1
  5. package/packages/chat/dist/{ChatRoot-DQkQQvPO.js → ChatRoot-WdCS4aLg.js} +3001 -2807
  6. package/packages/chat/dist/{context-tool-BuY29sJF.js → context-tool-KkwLFr2k.js} +2 -2
  7. package/packages/chat/dist/{index-NiYOPQzY.js → index-P8UuZ1jj.js} +3 -3
  8. package/packages/chat/dist/index.js +1 -1
  9. package/packages/chat/dist/{tool-He3mRTzT.js → tool-DWqQOW59.js} +2 -2
  10. package/packages/chat/package.json +1 -1
  11. package/packages/codemirror-base/dist/chunk-H5POLO74.js +2658 -0
  12. package/packages/codemirror-base/dist/chunk-H5POLO74.js.map +7 -0
  13. package/packages/codemirror-base/dist/lib/codemirror.js +1 -1
  14. package/packages/codemirror-base/dist/tool.js +9 -5
  15. package/packages/codemirror-base/dist/tool.js.map +2 -2
  16. package/packages/codemirror-base/package.json +1 -1
  17. package/packages/codemirror-markdown/dist/extensions/markdown.js +0 -94
  18. package/packages/codemirror-markdown/dist/extensions/markdown.js.map +3 -3
  19. package/packages/drafts/dist/assets/{DraftOverlayProvider-B0Mtq1UF.js → DraftOverlayProvider-VYKlzOy1.js} +85 -25
  20. package/packages/drafts/dist/assets/DraftOverlayProvider-VYKlzOy1.js.map +1 -0
  21. package/packages/drafts/dist/assets/{DraftListProvider-D41q9O5B.js → DraftStateProvider-DX8b_RgQ.js} +270 -39
  22. package/packages/drafts/dist/assets/DraftStateProvider-DX8b_RgQ.js.map +1 -0
  23. package/packages/drafts/dist/assets/{clone-policy-C4pVv5sr.js → clone-policy-CIdEhg7W.js} +5 -2
  24. package/packages/drafts/dist/assets/{clone-policy-C4pVv5sr.js.map → clone-policy-CIdEhg7W.js.map} +1 -1
  25. package/packages/drafts/dist/assets/draft-docs-Bi8K1y3a.js +554 -0
  26. package/packages/drafts/dist/assets/draft-docs-Bi8K1y3a.js.map +1 -0
  27. package/packages/drafts/dist/assets/main-BR_tW0sp.js +3105 -0
  28. package/packages/drafts/dist/assets/main-BR_tW0sp.js.map +1 -0
  29. package/packages/drafts/dist/index.js +14 -14
  30. package/packages/drafts/dist/index.js.map +1 -1
  31. package/packages/drafts/package.json +1 -1
  32. package/packages/threepane/dist/IsolatedDocumentArea-2JIBFDOX.js +2 -0
  33. package/packages/threepane/dist/{PatchworkFrame-4AEBOBRE.js → PatchworkFrame-P5P6JTJE.js} +2 -2
  34. package/packages/threepane/dist/chunk-CGHYPNSB.js +972 -0
  35. package/packages/threepane/dist/chunk-CGHYPNSB.js.map +7 -0
  36. package/packages/threepane/dist/index.js +1 -1
  37. package/packages/tldraw4/dist/tool.js +61 -10
  38. package/packages/tldraw4/dist/tool.js.map +2 -2
  39. package/packages/tldraw4/package.json +2 -2
  40. package/packages/account/dist/InlineContactAvatar-TVDLE2AV.js.map +0 -7
  41. package/packages/codemirror-base/dist/chunk-5IG5TKXV.js +0 -795
  42. package/packages/codemirror-base/dist/chunk-5IG5TKXV.js.map +0 -7
  43. package/packages/drafts/dist/assets/DraftListProvider-D41q9O5B.js.map +0 -1
  44. package/packages/drafts/dist/assets/DraftOverlayProvider-B0Mtq1UF.js.map +0 -1
  45. package/packages/drafts/dist/assets/main-Cp8VsNHh.js +0 -2331
  46. package/packages/drafts/dist/assets/main-Cp8VsNHh.js.map +0 -1
  47. package/packages/threepane/dist/IsolatedDocumentArea-MZBBRFMY.js +0 -2
  48. package/packages/threepane/dist/chunk-HNLVJAZZ.js +0 -972
  49. package/packages/threepane/dist/chunk-HNLVJAZZ.js.map +0 -7
  50. /package/packages/threepane/dist/{IsolatedDocumentArea-MZBBRFMY.js.map → IsolatedDocumentArea-2JIBFDOX.js.map} +0 -0
  51. /package/packages/threepane/dist/{PatchworkFrame-4AEBOBRE.js.map → PatchworkFrame-P5P6JTJE.js.map} +0 -0
@@ -0,0 +1,2658 @@
1
+ // src/lib/codemirror.tsx
2
+ import { onCleanup, createEffect as createEffect7 } from "solid-js";
3
+ import { EditorView as EditorView10 } from "@codemirror/view";
4
+ import { EditorState as EditorState4, Compartment as Compartment6 } from "@codemirror/state";
5
+
6
+ // src/lib/extensions/decorations.ts
7
+ import { createEffect } from "solid-js";
8
+ import { Decoration, EditorView } from "@codemirror/view";
9
+ import { StateEffect, StateField } from "@codemirror/state";
10
+ function createDecorationsExtension(decorations) {
11
+ const setDecorations = StateEffect.define();
12
+ const decorationsField = StateField.define({
13
+ create() {
14
+ return Decoration.none;
15
+ },
16
+ update(value, tr) {
17
+ for (const e of tr.effects) {
18
+ if (e.is(setDecorations)) return e.value;
19
+ }
20
+ if (tr.docChanged) return value.map(tr.changes);
21
+ return value;
22
+ },
23
+ provide: (f) => EditorView.decorations.from(f)
24
+ });
25
+ const createDecorationsEffect = (view) => createEffect(() => {
26
+ decorations() && view.dispatch({
27
+ effects: setDecorations.of(decorations())
28
+ });
29
+ });
30
+ return [decorationsField, createDecorationsEffect];
31
+ }
32
+
33
+ // src/lib/extensions/readOnly.ts
34
+ import { createEffect as createEffect2 } from "solid-js";
35
+ import { EditorView as EditorView2 } from "@codemirror/view";
36
+ import { Compartment, EditorState } from "@codemirror/state";
37
+ function createReadOnlyExtension(force) {
38
+ const compartment = new Compartment();
39
+ const extensions = () => force() ? [EditorState.readOnly.of(true), EditorView2.editable.of(false)] : [];
40
+ const createReconfigureEffect = (view) => createEffect2(() => {
41
+ view.dispatch({
42
+ effects: compartment.reconfigure(extensions())
43
+ });
44
+ });
45
+ return [compartment.of(extensions()), createReconfigureEffect];
46
+ }
47
+
48
+ // src/lib/extensions/automerge.ts
49
+ import { createEffect as createEffect3 } from "solid-js";
50
+ import { Compartment as Compartment4, Transaction as Transaction4 } from "@codemirror/state";
51
+
52
+ // src/vendor/automerge-codemirror/plugin.ts
53
+ import * as A2 from "@automerge/automerge";
54
+ import { ViewPlugin } from "@codemirror/view";
55
+ import { Annotation } from "@codemirror/state";
56
+
57
+ // src/vendor/automerge-codemirror/codeMirrorToAm.ts
58
+ import * as A from "@automerge/automerge";
59
+ var applyCmTransactionsToAmHandle = (handle, path, transactions) => {
60
+ const transactionsWithChanges = transactions.filter(
61
+ (tr) => !isReconcileTx(tr) && !tr.changes.empty
62
+ );
63
+ if (transactionsWithChanges.length === 0) {
64
+ return;
65
+ }
66
+ if (handle.isReadOnly?.()) {
67
+ return;
68
+ }
69
+ handle.change((doc) => {
70
+ transactionsWithChanges.forEach((tr) => {
71
+ tr.changes.iterChanges(
72
+ (fromA, toA, fromB, _toB, inserted) => {
73
+ A.splice(doc, path.slice(), fromB, toA - fromA, inserted.toString());
74
+ }
75
+ );
76
+ });
77
+ });
78
+ return A.getHeads(handle.doc());
79
+ };
80
+
81
+ // src/vendor/automerge-codemirror/amToCodemirror.ts
82
+ import {
83
+ ChangeSet,
84
+ Transaction
85
+ } from "@codemirror/state";
86
+ var applyAmPatchesToCm = (view, target, patches) => {
87
+ let selection = view.state.selection;
88
+ for (const patch of patches) {
89
+ const changeSpec = handlePatch(patch, target, view.state);
90
+ if (changeSpec != null) {
91
+ const changeSet = ChangeSet.of(changeSpec, view.state.doc.length, "\n");
92
+ selection = selection.map(changeSet, 1);
93
+ view.dispatch({
94
+ changes: changeSet,
95
+ annotations: [
96
+ reconcileAnnotationType.of({}),
97
+ Transaction.addToHistory.of(false),
98
+ Transaction.remote.of(true)
99
+ ]
100
+ });
101
+ }
102
+ }
103
+ view.dispatch({
104
+ selection,
105
+ annotations: reconcileAnnotationType.of({})
106
+ });
107
+ };
108
+ function handlePatch(patch, target, state) {
109
+ if (patch.action === "insert") {
110
+ return handleInsert(target, patch);
111
+ } else if (patch.action === "splice") {
112
+ return handleSplice(target, patch);
113
+ } else if (patch.action === "del") {
114
+ return handleDel(target, patch);
115
+ } else if (patch.action === "put") {
116
+ return handlePut(target, patch, state);
117
+ } else {
118
+ return null;
119
+ }
120
+ }
121
+ function handleInsert(target, patch) {
122
+ const index = charPath(target, patch.path);
123
+ if (index == null) {
124
+ return [];
125
+ }
126
+ const text = patch.values.map((v) => v ? v.toString() : "").join("");
127
+ return [{ from: index, to: index, insert: text }];
128
+ }
129
+ function handleSplice(target, patch) {
130
+ const index = charPath(target, patch.path);
131
+ if (index == null) {
132
+ return [];
133
+ }
134
+ return [{ from: index, insert: patch.value }];
135
+ }
136
+ function handleDel(target, patch) {
137
+ const index = charPath(target, patch.path);
138
+ if (index == null) {
139
+ return [];
140
+ }
141
+ const length = patch.length || 1;
142
+ return [{ from: index, to: index + length }];
143
+ }
144
+ function handlePut(target, patch, state) {
145
+ const index = charPath(target, [...patch.path, 0]);
146
+ if (index == null) {
147
+ return [];
148
+ }
149
+ const length = state.doc.length;
150
+ if (typeof patch.value !== "string") {
151
+ return [];
152
+ }
153
+ return [{ from: 0, to: length, insert: patch.value }];
154
+ }
155
+ function charPath(textPath, candidatePath) {
156
+ if (candidatePath.length !== textPath.length + 1) return null;
157
+ for (let i = 0; i < textPath.length; i++) {
158
+ if (textPath[i] !== candidatePath[i]) return null;
159
+ }
160
+ const index = candidatePath[candidatePath.length - 1];
161
+ if (typeof index === "number") return index;
162
+ return null;
163
+ }
164
+
165
+ // src/vendor/automerge-codemirror/plugin.ts
166
+ var reconcileAnnotationType = Annotation.define();
167
+ var isReconcileTx = (tr) => !!tr.annotation(reconcileAnnotationType);
168
+ var automergeSyncPlugin = ({
169
+ handle,
170
+ path
171
+ }) => {
172
+ if (!handle.isReady()) {
173
+ throw new Error(
174
+ "ensure the handle is ready before initializing the automergeSyncPlugin"
175
+ );
176
+ }
177
+ return ViewPlugin.fromClass(
178
+ class {
179
+ view;
180
+ reconciledHeads = A2.getHeads(handle.doc());
181
+ isProcessingCmTransaction = false;
182
+ constructor(view) {
183
+ this.view = view;
184
+ this.onChange = this.onChange.bind(this);
185
+ handle.on("change", this.onChange);
186
+ }
187
+ update(update) {
188
+ this.isProcessingCmTransaction = true;
189
+ const newHeads = applyCmTransactionsToAmHandle(
190
+ handle,
191
+ path,
192
+ update.transactions
193
+ );
194
+ if (newHeads) {
195
+ this.reconciledHeads = newHeads;
196
+ }
197
+ this.isProcessingCmTransaction = false;
198
+ }
199
+ // Changes with a replaced scope (the handle was re-pointed at a
200
+ // different backing document) need no special-casing here. A.diff
201
+ // ignores heads that aren't in the doc's history, treating that side
202
+ // as the empty document: when the backings share history (heads
203
+ // pinning, clones) it yields minimal patches that preserve the
204
+ // selection, and when they share nothing it degenerates into
205
+ // full-document patches that rebuild the editor wholesale. Either
206
+ // way the patches are kept off the undo stack by applyAmPatchesToCm.
207
+ // The history and read-only extensions are the ones that consume the
208
+ // `scopeReplaced` flag.
209
+ onChange = () => {
210
+ if (this.isProcessingCmTransaction) {
211
+ return;
212
+ }
213
+ const currentHeads = A2.getHeads(handle.doc());
214
+ if (A2.equals(currentHeads, this.reconciledHeads)) {
215
+ return;
216
+ }
217
+ const patches = A2.diff(handle.doc(), this.reconciledHeads, currentHeads);
218
+ applyAmPatchesToCm(this.view, path, patches);
219
+ this.reconciledHeads = currentHeads;
220
+ };
221
+ destroy() {
222
+ handle.off("change", this.onChange);
223
+ }
224
+ }
225
+ );
226
+ };
227
+
228
+ // node_modules/.pnpm/@codemirror+commands@6.10.3/node_modules/@codemirror/commands/dist/index.js
229
+ import { Annotation as Annotation2, Facet, combineConfig, StateField as StateField2, Transaction as Transaction3, ChangeSet as ChangeSet2, ChangeDesc, EditorSelection, StateEffect as StateEffect2, Text, findClusterBreak, countColumn, CharCategory } from "@codemirror/state";
230
+ import { EditorView as EditorView4, Direction } from "@codemirror/view";
231
+ import { IndentContext, getIndentation, indentString, matchBrackets, syntaxTree, getIndentUnit, indentUnit } from "@codemirror/language";
232
+
233
+ // node_modules/.pnpm/@lezer+common@1.5.2/node_modules/@lezer/common/dist/index.js
234
+ var DefaultBufferLength = 1024;
235
+ var nextPropID = 0;
236
+ var NodeProp = class {
237
+ /**
238
+ Create a new node prop type.
239
+ */
240
+ constructor(config = {}) {
241
+ this.id = nextPropID++;
242
+ this.perNode = !!config.perNode;
243
+ this.deserialize = config.deserialize || (() => {
244
+ throw new Error("This node type doesn't define a deserialize function");
245
+ });
246
+ this.combine = config.combine || null;
247
+ }
248
+ /**
249
+ This is meant to be used with
250
+ [`NodeSet.extend`](#common.NodeSet.extend) or
251
+ [`LRParser.configure`](#lr.ParserConfig.props) to compute
252
+ prop values for each node type in the set. Takes a [match
253
+ object](#common.NodeType^match) or function that returns undefined
254
+ if the node type doesn't get this prop, and the prop's value if
255
+ it does.
256
+ */
257
+ add(match) {
258
+ if (this.perNode)
259
+ throw new RangeError("Can't add per-node props to node types");
260
+ if (typeof match != "function")
261
+ match = NodeType.match(match);
262
+ return (type) => {
263
+ let result = match(type);
264
+ return result === void 0 ? null : [this, result];
265
+ };
266
+ }
267
+ };
268
+ NodeProp.closedBy = new NodeProp({ deserialize: (str) => str.split(" ") });
269
+ NodeProp.openedBy = new NodeProp({ deserialize: (str) => str.split(" ") });
270
+ NodeProp.group = new NodeProp({ deserialize: (str) => str.split(" ") });
271
+ NodeProp.isolate = new NodeProp({ deserialize: (value) => {
272
+ if (value && value != "rtl" && value != "ltr" && value != "auto")
273
+ throw new RangeError("Invalid value for isolate: " + value);
274
+ return value || "auto";
275
+ } });
276
+ NodeProp.contextHash = new NodeProp({ perNode: true });
277
+ NodeProp.lookAhead = new NodeProp({ perNode: true });
278
+ NodeProp.mounted = new NodeProp({ perNode: true });
279
+ var MountedTree = class {
280
+ constructor(tree, overlay, parser, bracketed = false) {
281
+ this.tree = tree;
282
+ this.overlay = overlay;
283
+ this.parser = parser;
284
+ this.bracketed = bracketed;
285
+ }
286
+ /**
287
+ @internal
288
+ */
289
+ static get(tree) {
290
+ return tree && tree.props && tree.props[NodeProp.mounted.id];
291
+ }
292
+ };
293
+ var noProps = /* @__PURE__ */ Object.create(null);
294
+ var NodeType = class _NodeType {
295
+ /**
296
+ @internal
297
+ */
298
+ constructor(name, props, id, flags = 0) {
299
+ this.name = name;
300
+ this.props = props;
301
+ this.id = id;
302
+ this.flags = flags;
303
+ }
304
+ /**
305
+ Define a node type.
306
+ */
307
+ static define(spec) {
308
+ let props = spec.props && spec.props.length ? /* @__PURE__ */ Object.create(null) : noProps;
309
+ let flags = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0);
310
+ let type = new _NodeType(spec.name || "", props, spec.id, flags);
311
+ if (spec.props)
312
+ for (let src of spec.props) {
313
+ if (!Array.isArray(src))
314
+ src = src(type);
315
+ if (src) {
316
+ if (src[0].perNode)
317
+ throw new RangeError("Can't store a per-node prop on a node type");
318
+ props[src[0].id] = src[1];
319
+ }
320
+ }
321
+ return type;
322
+ }
323
+ /**
324
+ Retrieves a node prop for this type. Will return `undefined` if
325
+ the prop isn't present on this node.
326
+ */
327
+ prop(prop) {
328
+ return this.props[prop.id];
329
+ }
330
+ /**
331
+ True when this is the top node of a grammar.
332
+ */
333
+ get isTop() {
334
+ return (this.flags & 1) > 0;
335
+ }
336
+ /**
337
+ True when this node is produced by a skip rule.
338
+ */
339
+ get isSkipped() {
340
+ return (this.flags & 2) > 0;
341
+ }
342
+ /**
343
+ Indicates whether this is an error node.
344
+ */
345
+ get isError() {
346
+ return (this.flags & 4) > 0;
347
+ }
348
+ /**
349
+ When true, this node type doesn't correspond to a user-declared
350
+ named node, for example because it is used to cache repetition.
351
+ */
352
+ get isAnonymous() {
353
+ return (this.flags & 8) > 0;
354
+ }
355
+ /**
356
+ Returns true when this node's name or one of its
357
+ [groups](#common.NodeProp^group) matches the given string.
358
+ */
359
+ is(name) {
360
+ if (typeof name == "string") {
361
+ if (this.name == name)
362
+ return true;
363
+ let group = this.prop(NodeProp.group);
364
+ return group ? group.indexOf(name) > -1 : false;
365
+ }
366
+ return this.id == name;
367
+ }
368
+ /**
369
+ Create a function from node types to arbitrary values by
370
+ specifying an object whose property names are node or
371
+ [group](#common.NodeProp^group) names. Often useful with
372
+ [`NodeProp.add`](#common.NodeProp.add). You can put multiple
373
+ names, separated by spaces, in a single property name to map
374
+ multiple node names to a single value.
375
+ */
376
+ static match(map) {
377
+ let direct = /* @__PURE__ */ Object.create(null);
378
+ for (let prop in map)
379
+ for (let name of prop.split(" "))
380
+ direct[name] = map[prop];
381
+ return (node) => {
382
+ for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {
383
+ let found = direct[i < 0 ? node.name : groups[i]];
384
+ if (found)
385
+ return found;
386
+ }
387
+ };
388
+ }
389
+ };
390
+ NodeType.none = new NodeType(
391
+ "",
392
+ /* @__PURE__ */ Object.create(null),
393
+ 0,
394
+ 8
395
+ /* NodeFlag.Anonymous */
396
+ );
397
+ var CachedNode = /* @__PURE__ */ new WeakMap();
398
+ var CachedInnerNode = /* @__PURE__ */ new WeakMap();
399
+ var IterMode;
400
+ (function(IterMode2) {
401
+ IterMode2[IterMode2["ExcludeBuffers"] = 1] = "ExcludeBuffers";
402
+ IterMode2[IterMode2["IncludeAnonymous"] = 2] = "IncludeAnonymous";
403
+ IterMode2[IterMode2["IgnoreMounts"] = 4] = "IgnoreMounts";
404
+ IterMode2[IterMode2["IgnoreOverlays"] = 8] = "IgnoreOverlays";
405
+ IterMode2[IterMode2["EnterBracketed"] = 16] = "EnterBracketed";
406
+ })(IterMode || (IterMode = {}));
407
+ var Tree = class _Tree {
408
+ /**
409
+ Construct a new tree. See also [`Tree.build`](#common.Tree^build).
410
+ */
411
+ constructor(type, children, positions, length, props) {
412
+ this.type = type;
413
+ this.children = children;
414
+ this.positions = positions;
415
+ this.length = length;
416
+ this.props = null;
417
+ if (props && props.length) {
418
+ this.props = /* @__PURE__ */ Object.create(null);
419
+ for (let [prop, value] of props)
420
+ this.props[typeof prop == "number" ? prop : prop.id] = value;
421
+ }
422
+ }
423
+ /**
424
+ @internal
425
+ */
426
+ toString() {
427
+ let mounted = MountedTree.get(this);
428
+ if (mounted && !mounted.overlay)
429
+ return mounted.tree.toString();
430
+ let children = "";
431
+ for (let ch of this.children) {
432
+ let str = ch.toString();
433
+ if (str) {
434
+ if (children)
435
+ children += ",";
436
+ children += str;
437
+ }
438
+ }
439
+ return !this.type.name ? children : (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + (children.length ? "(" + children + ")" : "");
440
+ }
441
+ /**
442
+ Get a [tree cursor](#common.TreeCursor) positioned at the top of
443
+ the tree. Mode can be used to [control](#common.IterMode) which
444
+ nodes the cursor visits.
445
+ */
446
+ cursor(mode = 0) {
447
+ return new TreeCursor(this.topNode, mode);
448
+ }
449
+ /**
450
+ Get a [tree cursor](#common.TreeCursor) pointing into this tree
451
+ at the given position and side (see
452
+ [`moveTo`](#common.TreeCursor.moveTo).
453
+ */
454
+ cursorAt(pos, side = 0, mode = 0) {
455
+ let scope = CachedNode.get(this) || this.topNode;
456
+ let cursor = new TreeCursor(scope);
457
+ cursor.moveTo(pos, side);
458
+ CachedNode.set(this, cursor._tree);
459
+ return cursor;
460
+ }
461
+ /**
462
+ Get a [syntax node](#common.SyntaxNode) object for the top of the
463
+ tree.
464
+ */
465
+ get topNode() {
466
+ return new TreeNode(this, 0, 0, null);
467
+ }
468
+ /**
469
+ Get the [syntax node](#common.SyntaxNode) at the given position.
470
+ If `side` is -1, this will move into nodes that end at the
471
+ position. If 1, it'll move into nodes that start at the
472
+ position. With 0, it'll only enter nodes that cover the position
473
+ from both sides.
474
+
475
+ Note that this will not enter
476
+ [overlays](#common.MountedTree.overlay), and you often want
477
+ [`resolveInner`](#common.Tree.resolveInner) instead.
478
+ */
479
+ resolve(pos, side = 0) {
480
+ let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);
481
+ CachedNode.set(this, node);
482
+ return node;
483
+ }
484
+ /**
485
+ Like [`resolve`](#common.Tree.resolve), but will enter
486
+ [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
487
+ pointing into the innermost overlaid tree at the given position
488
+ (with parent links going through all parent structure, including
489
+ the host trees).
490
+ */
491
+ resolveInner(pos, side = 0) {
492
+ let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);
493
+ CachedInnerNode.set(this, node);
494
+ return node;
495
+ }
496
+ /**
497
+ In some situations, it can be useful to iterate through all
498
+ nodes around a position, including those in overlays that don't
499
+ directly cover the position. This method gives you an iterator
500
+ that will produce all nodes, from small to big, around the given
501
+ position.
502
+ */
503
+ resolveStack(pos, side = 0) {
504
+ return stackIterator(this, pos, side);
505
+ }
506
+ /**
507
+ Iterate over the tree and its children, calling `enter` for any
508
+ node that touches the `from`/`to` region (if given) before
509
+ running over such a node's children, and `leave` (if given) when
510
+ leaving the node. When `enter` returns `false`, that node will
511
+ not have its children iterated over (or `leave` called).
512
+ */
513
+ iterate(spec) {
514
+ let { enter, leave, from = 0, to = this.length } = spec;
515
+ let mode = spec.mode || 0, anon = (mode & IterMode.IncludeAnonymous) > 0;
516
+ for (let c = this.cursor(mode | IterMode.IncludeAnonymous); ; ) {
517
+ let entered = false;
518
+ if (c.from <= to && c.to >= from && (!anon && c.type.isAnonymous || enter(c) !== false)) {
519
+ if (c.firstChild())
520
+ continue;
521
+ entered = true;
522
+ }
523
+ for (; ; ) {
524
+ if (entered && leave && (anon || !c.type.isAnonymous))
525
+ leave(c);
526
+ if (c.nextSibling())
527
+ break;
528
+ if (!c.parent())
529
+ return;
530
+ entered = true;
531
+ }
532
+ }
533
+ }
534
+ /**
535
+ Get the value of the given [node prop](#common.NodeProp) for this
536
+ node. Works with both per-node and per-type props.
537
+ */
538
+ prop(prop) {
539
+ return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : void 0;
540
+ }
541
+ /**
542
+ Returns the node's [per-node props](#common.NodeProp.perNode) in a
543
+ format that can be passed to the [`Tree`](#common.Tree)
544
+ constructor.
545
+ */
546
+ get propValues() {
547
+ let result = [];
548
+ if (this.props)
549
+ for (let id in this.props)
550
+ result.push([+id, this.props[id]]);
551
+ return result;
552
+ }
553
+ /**
554
+ Balance the direct children of this tree, producing a copy of
555
+ which may have children grouped into subtrees with type
556
+ [`NodeType.none`](#common.NodeType^none).
557
+ */
558
+ balance(config = {}) {
559
+ return this.children.length <= 8 ? this : balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new _Tree(this.type, children, positions, length, this.propValues), config.makeTree || ((children, positions, length) => new _Tree(NodeType.none, children, positions, length)));
560
+ }
561
+ /**
562
+ Build a tree from a postfix-ordered buffer of node information,
563
+ or a cursor over such a buffer.
564
+ */
565
+ static build(data) {
566
+ return buildTree(data);
567
+ }
568
+ };
569
+ Tree.empty = new Tree(NodeType.none, [], [], 0);
570
+ var FlatBufferCursor = class _FlatBufferCursor {
571
+ constructor(buffer, index) {
572
+ this.buffer = buffer;
573
+ this.index = index;
574
+ }
575
+ get id() {
576
+ return this.buffer[this.index - 4];
577
+ }
578
+ get start() {
579
+ return this.buffer[this.index - 3];
580
+ }
581
+ get end() {
582
+ return this.buffer[this.index - 2];
583
+ }
584
+ get size() {
585
+ return this.buffer[this.index - 1];
586
+ }
587
+ get pos() {
588
+ return this.index;
589
+ }
590
+ next() {
591
+ this.index -= 4;
592
+ }
593
+ fork() {
594
+ return new _FlatBufferCursor(this.buffer, this.index);
595
+ }
596
+ };
597
+ var TreeBuffer = class _TreeBuffer {
598
+ /**
599
+ Create a tree buffer.
600
+ */
601
+ constructor(buffer, length, set) {
602
+ this.buffer = buffer;
603
+ this.length = length;
604
+ this.set = set;
605
+ }
606
+ /**
607
+ @internal
608
+ */
609
+ get type() {
610
+ return NodeType.none;
611
+ }
612
+ /**
613
+ @internal
614
+ */
615
+ toString() {
616
+ let result = [];
617
+ for (let index = 0; index < this.buffer.length; ) {
618
+ result.push(this.childString(index));
619
+ index = this.buffer[index + 3];
620
+ }
621
+ return result.join(",");
622
+ }
623
+ /**
624
+ @internal
625
+ */
626
+ childString(index) {
627
+ let id = this.buffer[index], endIndex = this.buffer[index + 3];
628
+ let type = this.set.types[id], result = type.name;
629
+ if (/\W/.test(result) && !type.isError)
630
+ result = JSON.stringify(result);
631
+ index += 4;
632
+ if (endIndex == index)
633
+ return result;
634
+ let children = [];
635
+ while (index < endIndex) {
636
+ children.push(this.childString(index));
637
+ index = this.buffer[index + 3];
638
+ }
639
+ return result + "(" + children.join(",") + ")";
640
+ }
641
+ /**
642
+ @internal
643
+ */
644
+ findChild(startIndex, endIndex, dir, pos, side) {
645
+ let { buffer } = this, pick = -1;
646
+ for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {
647
+ if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) {
648
+ pick = i;
649
+ if (dir > 0)
650
+ break;
651
+ }
652
+ }
653
+ return pick;
654
+ }
655
+ /**
656
+ @internal
657
+ */
658
+ slice(startI, endI, from) {
659
+ let b = this.buffer;
660
+ let copy = new Uint16Array(endI - startI), len = 0;
661
+ for (let i = startI, j = 0; i < endI; ) {
662
+ copy[j++] = b[i++];
663
+ copy[j++] = b[i++] - from;
664
+ let to = copy[j++] = b[i++] - from;
665
+ copy[j++] = b[i++] - startI;
666
+ len = Math.max(len, to);
667
+ }
668
+ return new _TreeBuffer(copy, len, this.set);
669
+ }
670
+ };
671
+ function checkSide(side, pos, from, to) {
672
+ switch (side) {
673
+ case -2:
674
+ return from < pos;
675
+ case -1:
676
+ return to >= pos && from < pos;
677
+ case 0:
678
+ return from < pos && to > pos;
679
+ case 1:
680
+ return from <= pos && to > pos;
681
+ case 2:
682
+ return to > pos;
683
+ case 4:
684
+ return true;
685
+ }
686
+ }
687
+ function resolveNode(node, pos, side, overlays) {
688
+ var _a;
689
+ while (node.from == node.to || (side < 1 ? node.from >= pos : node.from > pos) || (side > -1 ? node.to <= pos : node.to < pos)) {
690
+ let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;
691
+ if (!parent)
692
+ return node;
693
+ node = parent;
694
+ }
695
+ let mode = overlays ? 0 : IterMode.IgnoreOverlays;
696
+ if (overlays)
697
+ for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) {
698
+ if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, mode)) === null || _a === void 0 ? void 0 : _a.from) != scan.from)
699
+ node = parent;
700
+ }
701
+ for (; ; ) {
702
+ let inner = node.enter(pos, side, mode);
703
+ if (!inner)
704
+ return node;
705
+ node = inner;
706
+ }
707
+ }
708
+ var BaseNode = class {
709
+ cursor(mode = 0) {
710
+ return new TreeCursor(this, mode);
711
+ }
712
+ getChild(type, before = null, after = null) {
713
+ let r = getChildren(this, type, before, after);
714
+ return r.length ? r[0] : null;
715
+ }
716
+ getChildren(type, before = null, after = null) {
717
+ return getChildren(this, type, before, after);
718
+ }
719
+ resolve(pos, side = 0) {
720
+ return resolveNode(this, pos, side, false);
721
+ }
722
+ resolveInner(pos, side = 0) {
723
+ return resolveNode(this, pos, side, true);
724
+ }
725
+ matchContext(context) {
726
+ return matchNodeContext(this.parent, context);
727
+ }
728
+ enterUnfinishedNodesBefore(pos) {
729
+ let scan = this.childBefore(pos), node = this;
730
+ while (scan) {
731
+ let last = scan.lastChild;
732
+ if (!last || last.to != scan.to)
733
+ break;
734
+ if (last.type.isError && last.from == last.to) {
735
+ node = scan;
736
+ scan = last.prevSibling;
737
+ } else {
738
+ scan = last;
739
+ }
740
+ }
741
+ return node;
742
+ }
743
+ get node() {
744
+ return this;
745
+ }
746
+ get next() {
747
+ return this.parent;
748
+ }
749
+ };
750
+ var TreeNode = class _TreeNode extends BaseNode {
751
+ constructor(_tree, from, index, _parent) {
752
+ super();
753
+ this._tree = _tree;
754
+ this.from = from;
755
+ this.index = index;
756
+ this._parent = _parent;
757
+ }
758
+ get type() {
759
+ return this._tree.type;
760
+ }
761
+ get name() {
762
+ return this._tree.type.name;
763
+ }
764
+ get to() {
765
+ return this.from + this._tree.length;
766
+ }
767
+ nextChild(i, dir, pos, side, mode = 0) {
768
+ for (let parent = this; ; ) {
769
+ for (let { children, positions } = parent._tree, e = dir > 0 ? children.length : -1; i != e; i += dir) {
770
+ let next = children[i], start = positions[i] + parent.from, mounted;
771
+ if (!(mode & IterMode.EnterBracketed && next instanceof Tree && (mounted = MountedTree.get(next)) && !mounted.overlay && mounted.bracketed && pos >= start && pos <= start + next.length) && !checkSide(side, pos, start, start + next.length))
772
+ continue;
773
+ if (next instanceof TreeBuffer) {
774
+ if (mode & IterMode.ExcludeBuffers)
775
+ continue;
776
+ let index = next.findChild(0, next.buffer.length, dir, pos - start, side);
777
+ if (index > -1)
778
+ return new BufferNode(new BufferContext(parent, next, i, start), null, index);
779
+ } else if (mode & IterMode.IncludeAnonymous || (!next.type.isAnonymous || hasChild(next))) {
780
+ let mounted2;
781
+ if (!(mode & IterMode.IgnoreMounts) && (mounted2 = MountedTree.get(next)) && !mounted2.overlay)
782
+ return new _TreeNode(mounted2.tree, start, i, parent);
783
+ let inner = new _TreeNode(next, start, i, parent);
784
+ return mode & IterMode.IncludeAnonymous || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side, mode);
785
+ }
786
+ }
787
+ if (mode & IterMode.IncludeAnonymous || !parent.type.isAnonymous)
788
+ return null;
789
+ if (parent.index >= 0)
790
+ i = parent.index + dir;
791
+ else
792
+ i = dir < 0 ? -1 : parent._parent._tree.children.length;
793
+ parent = parent._parent;
794
+ if (!parent)
795
+ return null;
796
+ }
797
+ }
798
+ get firstChild() {
799
+ return this.nextChild(
800
+ 0,
801
+ 1,
802
+ 0,
803
+ 4
804
+ /* Side.DontCare */
805
+ );
806
+ }
807
+ get lastChild() {
808
+ return this.nextChild(
809
+ this._tree.children.length - 1,
810
+ -1,
811
+ 0,
812
+ 4
813
+ /* Side.DontCare */
814
+ );
815
+ }
816
+ childAfter(pos) {
817
+ return this.nextChild(
818
+ 0,
819
+ 1,
820
+ pos,
821
+ 2
822
+ /* Side.After */
823
+ );
824
+ }
825
+ childBefore(pos) {
826
+ return this.nextChild(
827
+ this._tree.children.length - 1,
828
+ -1,
829
+ pos,
830
+ -2
831
+ /* Side.Before */
832
+ );
833
+ }
834
+ prop(prop) {
835
+ return this._tree.prop(prop);
836
+ }
837
+ enter(pos, side, mode = 0) {
838
+ let mounted;
839
+ if (!(mode & IterMode.IgnoreOverlays) && (mounted = MountedTree.get(this._tree)) && mounted.overlay) {
840
+ let rPos = pos - this.from, enterBracketed = mode & IterMode.EnterBracketed && mounted.bracketed;
841
+ for (let { from, to } of mounted.overlay) {
842
+ if ((side > 0 || enterBracketed ? from <= rPos : from < rPos) && (side < 0 || enterBracketed ? to >= rPos : to > rPos))
843
+ return new _TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);
844
+ }
845
+ }
846
+ return this.nextChild(0, 1, pos, side, mode);
847
+ }
848
+ nextSignificantParent() {
849
+ let val = this;
850
+ while (val.type.isAnonymous && val._parent)
851
+ val = val._parent;
852
+ return val;
853
+ }
854
+ get parent() {
855
+ return this._parent ? this._parent.nextSignificantParent() : null;
856
+ }
857
+ get nextSibling() {
858
+ return this._parent && this.index >= 0 ? this._parent.nextChild(
859
+ this.index + 1,
860
+ 1,
861
+ 0,
862
+ 4
863
+ /* Side.DontCare */
864
+ ) : null;
865
+ }
866
+ get prevSibling() {
867
+ return this._parent && this.index >= 0 ? this._parent.nextChild(
868
+ this.index - 1,
869
+ -1,
870
+ 0,
871
+ 4
872
+ /* Side.DontCare */
873
+ ) : null;
874
+ }
875
+ get tree() {
876
+ return this._tree;
877
+ }
878
+ toTree() {
879
+ return this._tree;
880
+ }
881
+ /**
882
+ @internal
883
+ */
884
+ toString() {
885
+ return this._tree.toString();
886
+ }
887
+ };
888
+ function getChildren(node, type, before, after) {
889
+ let cur = node.cursor(), result = [];
890
+ if (!cur.firstChild())
891
+ return result;
892
+ if (before != null)
893
+ for (let found = false; !found; ) {
894
+ found = cur.type.is(before);
895
+ if (!cur.nextSibling())
896
+ return result;
897
+ }
898
+ for (; ; ) {
899
+ if (after != null && cur.type.is(after))
900
+ return result;
901
+ if (cur.type.is(type))
902
+ result.push(cur.node);
903
+ if (!cur.nextSibling())
904
+ return after == null ? result : [];
905
+ }
906
+ }
907
+ function matchNodeContext(node, context, i = context.length - 1) {
908
+ for (let p = node; i >= 0; p = p.parent) {
909
+ if (!p)
910
+ return false;
911
+ if (!p.type.isAnonymous) {
912
+ if (context[i] && context[i] != p.name)
913
+ return false;
914
+ i--;
915
+ }
916
+ }
917
+ return true;
918
+ }
919
+ var BufferContext = class {
920
+ constructor(parent, buffer, index, start) {
921
+ this.parent = parent;
922
+ this.buffer = buffer;
923
+ this.index = index;
924
+ this.start = start;
925
+ }
926
+ };
927
+ var BufferNode = class _BufferNode extends BaseNode {
928
+ get name() {
929
+ return this.type.name;
930
+ }
931
+ get from() {
932
+ return this.context.start + this.context.buffer.buffer[this.index + 1];
933
+ }
934
+ get to() {
935
+ return this.context.start + this.context.buffer.buffer[this.index + 2];
936
+ }
937
+ constructor(context, _parent, index) {
938
+ super();
939
+ this.context = context;
940
+ this._parent = _parent;
941
+ this.index = index;
942
+ this.type = context.buffer.set.types[context.buffer.buffer[index]];
943
+ }
944
+ child(dir, pos, side) {
945
+ let { buffer } = this.context;
946
+ let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);
947
+ return index < 0 ? null : new _BufferNode(this.context, this, index);
948
+ }
949
+ get firstChild() {
950
+ return this.child(
951
+ 1,
952
+ 0,
953
+ 4
954
+ /* Side.DontCare */
955
+ );
956
+ }
957
+ get lastChild() {
958
+ return this.child(
959
+ -1,
960
+ 0,
961
+ 4
962
+ /* Side.DontCare */
963
+ );
964
+ }
965
+ childAfter(pos) {
966
+ return this.child(
967
+ 1,
968
+ pos,
969
+ 2
970
+ /* Side.After */
971
+ );
972
+ }
973
+ childBefore(pos) {
974
+ return this.child(
975
+ -1,
976
+ pos,
977
+ -2
978
+ /* Side.Before */
979
+ );
980
+ }
981
+ prop(prop) {
982
+ return this.type.prop(prop);
983
+ }
984
+ enter(pos, side, mode = 0) {
985
+ if (mode & IterMode.ExcludeBuffers)
986
+ return null;
987
+ let { buffer } = this.context;
988
+ let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);
989
+ return index < 0 ? null : new _BufferNode(this.context, this, index);
990
+ }
991
+ get parent() {
992
+ return this._parent || this.context.parent.nextSignificantParent();
993
+ }
994
+ externalSibling(dir) {
995
+ return this._parent ? null : this.context.parent.nextChild(
996
+ this.context.index + dir,
997
+ dir,
998
+ 0,
999
+ 4
1000
+ /* Side.DontCare */
1001
+ );
1002
+ }
1003
+ get nextSibling() {
1004
+ let { buffer } = this.context;
1005
+ let after = buffer.buffer[this.index + 3];
1006
+ if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))
1007
+ return new _BufferNode(this.context, this._parent, after);
1008
+ return this.externalSibling(1);
1009
+ }
1010
+ get prevSibling() {
1011
+ let { buffer } = this.context;
1012
+ let parentStart = this._parent ? this._parent.index + 4 : 0;
1013
+ if (this.index == parentStart)
1014
+ return this.externalSibling(-1);
1015
+ return new _BufferNode(this.context, this._parent, buffer.findChild(
1016
+ parentStart,
1017
+ this.index,
1018
+ -1,
1019
+ 0,
1020
+ 4
1021
+ /* Side.DontCare */
1022
+ ));
1023
+ }
1024
+ get tree() {
1025
+ return null;
1026
+ }
1027
+ toTree() {
1028
+ let children = [], positions = [];
1029
+ let { buffer } = this.context;
1030
+ let startI = this.index + 4, endI = buffer.buffer[this.index + 3];
1031
+ if (endI > startI) {
1032
+ let from = buffer.buffer[this.index + 1];
1033
+ children.push(buffer.slice(startI, endI, from));
1034
+ positions.push(0);
1035
+ }
1036
+ return new Tree(this.type, children, positions, this.to - this.from);
1037
+ }
1038
+ /**
1039
+ @internal
1040
+ */
1041
+ toString() {
1042
+ return this.context.buffer.childString(this.index);
1043
+ }
1044
+ };
1045
+ function iterStack(heads) {
1046
+ if (!heads.length)
1047
+ return null;
1048
+ let pick = 0, picked = heads[0];
1049
+ for (let i = 1; i < heads.length; i++) {
1050
+ let node = heads[i];
1051
+ if (node.from > picked.from || node.to < picked.to) {
1052
+ picked = node;
1053
+ pick = i;
1054
+ }
1055
+ }
1056
+ let next = picked instanceof TreeNode && picked.index < 0 ? null : picked.parent;
1057
+ let newHeads = heads.slice();
1058
+ if (next)
1059
+ newHeads[pick] = next;
1060
+ else
1061
+ newHeads.splice(pick, 1);
1062
+ return new StackIterator(newHeads, picked);
1063
+ }
1064
+ var StackIterator = class {
1065
+ constructor(heads, node) {
1066
+ this.heads = heads;
1067
+ this.node = node;
1068
+ }
1069
+ get next() {
1070
+ return iterStack(this.heads);
1071
+ }
1072
+ };
1073
+ function stackIterator(tree, pos, side) {
1074
+ let inner = tree.resolveInner(pos, side), layers = null;
1075
+ for (let scan = inner instanceof TreeNode ? inner : inner.context.parent; scan; scan = scan.parent) {
1076
+ if (scan.index < 0) {
1077
+ let parent = scan.parent;
1078
+ (layers || (layers = [inner])).push(parent.resolve(pos, side));
1079
+ scan = parent;
1080
+ } else {
1081
+ let mount = MountedTree.get(scan.tree);
1082
+ if (mount && mount.overlay && mount.overlay[0].from <= pos && mount.overlay[mount.overlay.length - 1].to >= pos) {
1083
+ let root = new TreeNode(mount.tree, mount.overlay[0].from + scan.from, -1, scan);
1084
+ (layers || (layers = [inner])).push(resolveNode(root, pos, side, false));
1085
+ }
1086
+ }
1087
+ }
1088
+ return layers ? iterStack(layers) : inner;
1089
+ }
1090
+ var TreeCursor = class {
1091
+ /**
1092
+ Shorthand for `.type.name`.
1093
+ */
1094
+ get name() {
1095
+ return this.type.name;
1096
+ }
1097
+ /**
1098
+ @internal
1099
+ */
1100
+ constructor(node, mode = 0) {
1101
+ this.buffer = null;
1102
+ this.stack = [];
1103
+ this.index = 0;
1104
+ this.bufferNode = null;
1105
+ this.mode = mode & ~IterMode.EnterBracketed;
1106
+ if (node instanceof TreeNode) {
1107
+ this.yieldNode(node);
1108
+ } else {
1109
+ this._tree = node.context.parent;
1110
+ this.buffer = node.context;
1111
+ for (let n = node._parent; n; n = n._parent)
1112
+ this.stack.unshift(n.index);
1113
+ this.bufferNode = node;
1114
+ this.yieldBuf(node.index);
1115
+ }
1116
+ }
1117
+ yieldNode(node) {
1118
+ if (!node)
1119
+ return false;
1120
+ this._tree = node;
1121
+ this.type = node.type;
1122
+ this.from = node.from;
1123
+ this.to = node.to;
1124
+ return true;
1125
+ }
1126
+ yieldBuf(index, type) {
1127
+ this.index = index;
1128
+ let { start, buffer } = this.buffer;
1129
+ this.type = type || buffer.set.types[buffer.buffer[index]];
1130
+ this.from = start + buffer.buffer[index + 1];
1131
+ this.to = start + buffer.buffer[index + 2];
1132
+ return true;
1133
+ }
1134
+ /**
1135
+ @internal
1136
+ */
1137
+ yield(node) {
1138
+ if (!node)
1139
+ return false;
1140
+ if (node instanceof TreeNode) {
1141
+ this.buffer = null;
1142
+ return this.yieldNode(node);
1143
+ }
1144
+ this.buffer = node.context;
1145
+ return this.yieldBuf(node.index, node.type);
1146
+ }
1147
+ /**
1148
+ @internal
1149
+ */
1150
+ toString() {
1151
+ return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
1152
+ }
1153
+ /**
1154
+ @internal
1155
+ */
1156
+ enterChild(dir, pos, side) {
1157
+ if (!this.buffer)
1158
+ return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode));
1159
+ let { buffer } = this.buffer;
1160
+ let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);
1161
+ if (index < 0)
1162
+ return false;
1163
+ this.stack.push(this.index);
1164
+ return this.yieldBuf(index);
1165
+ }
1166
+ /**
1167
+ Move the cursor to this node's first child. When this returns
1168
+ false, the node has no child, and the cursor has not been moved.
1169
+ */
1170
+ firstChild() {
1171
+ return this.enterChild(
1172
+ 1,
1173
+ 0,
1174
+ 4
1175
+ /* Side.DontCare */
1176
+ );
1177
+ }
1178
+ /**
1179
+ Move the cursor to this node's last child.
1180
+ */
1181
+ lastChild() {
1182
+ return this.enterChild(
1183
+ -1,
1184
+ 0,
1185
+ 4
1186
+ /* Side.DontCare */
1187
+ );
1188
+ }
1189
+ /**
1190
+ Move the cursor to the first child that ends after `pos`.
1191
+ */
1192
+ childAfter(pos) {
1193
+ return this.enterChild(
1194
+ 1,
1195
+ pos,
1196
+ 2
1197
+ /* Side.After */
1198
+ );
1199
+ }
1200
+ /**
1201
+ Move to the last child that starts before `pos`.
1202
+ */
1203
+ childBefore(pos) {
1204
+ return this.enterChild(
1205
+ -1,
1206
+ pos,
1207
+ -2
1208
+ /* Side.Before */
1209
+ );
1210
+ }
1211
+ /**
1212
+ Move the cursor to the child around `pos`. If side is -1 the
1213
+ child may end at that position, when 1 it may start there. This
1214
+ will also enter [overlaid](#common.MountedTree.overlay)
1215
+ [mounted](#common.NodeProp^mounted) trees unless `overlays` is
1216
+ set to false.
1217
+ */
1218
+ enter(pos, side, mode = this.mode) {
1219
+ if (!this.buffer)
1220
+ return this.yield(this._tree.enter(pos, side, mode));
1221
+ return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side);
1222
+ }
1223
+ /**
1224
+ Move to the node's parent node, if this isn't the top node.
1225
+ */
1226
+ parent() {
1227
+ if (!this.buffer)
1228
+ return this.yieldNode(this.mode & IterMode.IncludeAnonymous ? this._tree._parent : this._tree.parent);
1229
+ if (this.stack.length)
1230
+ return this.yieldBuf(this.stack.pop());
1231
+ let parent = this.mode & IterMode.IncludeAnonymous ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
1232
+ this.buffer = null;
1233
+ return this.yieldNode(parent);
1234
+ }
1235
+ /**
1236
+ @internal
1237
+ */
1238
+ sibling(dir) {
1239
+ if (!this.buffer)
1240
+ return !this._tree._parent ? false : this.yield(this._tree.index < 0 ? null : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4, this.mode));
1241
+ let { buffer } = this.buffer, d = this.stack.length - 1;
1242
+ if (dir < 0) {
1243
+ let parentStart = d < 0 ? 0 : this.stack[d] + 4;
1244
+ if (this.index != parentStart)
1245
+ return this.yieldBuf(buffer.findChild(
1246
+ parentStart,
1247
+ this.index,
1248
+ -1,
1249
+ 0,
1250
+ 4
1251
+ /* Side.DontCare */
1252
+ ));
1253
+ } else {
1254
+ let after = buffer.buffer[this.index + 3];
1255
+ if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3]))
1256
+ return this.yieldBuf(after);
1257
+ }
1258
+ return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4, this.mode)) : false;
1259
+ }
1260
+ /**
1261
+ Move to this node's next sibling, if any.
1262
+ */
1263
+ nextSibling() {
1264
+ return this.sibling(1);
1265
+ }
1266
+ /**
1267
+ Move to this node's previous sibling, if any.
1268
+ */
1269
+ prevSibling() {
1270
+ return this.sibling(-1);
1271
+ }
1272
+ atLastNode(dir) {
1273
+ let index, parent, { buffer } = this;
1274
+ if (buffer) {
1275
+ if (dir > 0) {
1276
+ if (this.index < buffer.buffer.buffer.length)
1277
+ return false;
1278
+ } else {
1279
+ for (let i = 0; i < this.index; i++)
1280
+ if (buffer.buffer.buffer[i + 3] < this.index)
1281
+ return false;
1282
+ }
1283
+ ({ index, parent } = buffer);
1284
+ } else {
1285
+ ({ index, _parent: parent } = this._tree);
1286
+ }
1287
+ for (; parent; { index, _parent: parent } = parent) {
1288
+ if (index > -1)
1289
+ for (let i = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i != e; i += dir) {
1290
+ let child = parent._tree.children[i];
1291
+ if (this.mode & IterMode.IncludeAnonymous || child instanceof TreeBuffer || !child.type.isAnonymous || hasChild(child))
1292
+ return false;
1293
+ }
1294
+ }
1295
+ return true;
1296
+ }
1297
+ move(dir, enter) {
1298
+ if (enter && this.enterChild(
1299
+ dir,
1300
+ 0,
1301
+ 4
1302
+ /* Side.DontCare */
1303
+ ))
1304
+ return true;
1305
+ for (; ; ) {
1306
+ if (this.sibling(dir))
1307
+ return true;
1308
+ if (this.atLastNode(dir) || !this.parent())
1309
+ return false;
1310
+ }
1311
+ }
1312
+ /**
1313
+ Move to the next node in a
1314
+ [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR)
1315
+ traversal, going from a node to its first child or, if the
1316
+ current node is empty or `enter` is false, its next sibling or
1317
+ the next sibling of the first parent node that has one.
1318
+ */
1319
+ next(enter = true) {
1320
+ return this.move(1, enter);
1321
+ }
1322
+ /**
1323
+ Move to the next node in a last-to-first pre-order traversal. A
1324
+ node is followed by its last child or, if it has none, its
1325
+ previous sibling or the previous sibling of the first parent
1326
+ node that has one.
1327
+ */
1328
+ prev(enter = true) {
1329
+ return this.move(-1, enter);
1330
+ }
1331
+ /**
1332
+ Move the cursor to the innermost node that covers `pos`. If
1333
+ `side` is -1, it will enter nodes that end at `pos`. If it is 1,
1334
+ it will enter nodes that start at `pos`.
1335
+ */
1336
+ moveTo(pos, side = 0) {
1337
+ while (this.from == this.to || (side < 1 ? this.from >= pos : this.from > pos) || (side > -1 ? this.to <= pos : this.to < pos))
1338
+ if (!this.parent())
1339
+ break;
1340
+ while (this.enterChild(1, pos, side)) {
1341
+ }
1342
+ return this;
1343
+ }
1344
+ /**
1345
+ Get a [syntax node](#common.SyntaxNode) at the cursor's current
1346
+ position.
1347
+ */
1348
+ get node() {
1349
+ if (!this.buffer)
1350
+ return this._tree;
1351
+ let cache = this.bufferNode, result = null, depth = 0;
1352
+ if (cache && cache.context == this.buffer) {
1353
+ scan: for (let index = this.index, d = this.stack.length; d >= 0; ) {
1354
+ for (let c = cache; c; c = c._parent)
1355
+ if (c.index == index) {
1356
+ if (index == this.index)
1357
+ return c;
1358
+ result = c;
1359
+ depth = d + 1;
1360
+ break scan;
1361
+ }
1362
+ index = this.stack[--d];
1363
+ }
1364
+ }
1365
+ for (let i = depth; i < this.stack.length; i++)
1366
+ result = new BufferNode(this.buffer, result, this.stack[i]);
1367
+ return this.bufferNode = new BufferNode(this.buffer, result, this.index);
1368
+ }
1369
+ /**
1370
+ Get the [tree](#common.Tree) that represents the current node, if
1371
+ any. Will return null when the node is in a [tree
1372
+ buffer](#common.TreeBuffer).
1373
+ */
1374
+ get tree() {
1375
+ return this.buffer ? null : this._tree._tree;
1376
+ }
1377
+ /**
1378
+ Iterate over the current node and all its descendants, calling
1379
+ `enter` when entering a node and `leave`, if given, when leaving
1380
+ one. When `enter` returns `false`, any children of that node are
1381
+ skipped, and `leave` isn't called for it.
1382
+ */
1383
+ iterate(enter, leave) {
1384
+ for (let depth = 0; ; ) {
1385
+ let mustLeave = false;
1386
+ if (this.type.isAnonymous || enter(this) !== false) {
1387
+ if (this.firstChild()) {
1388
+ depth++;
1389
+ continue;
1390
+ }
1391
+ if (!this.type.isAnonymous)
1392
+ mustLeave = true;
1393
+ }
1394
+ for (; ; ) {
1395
+ if (mustLeave && leave)
1396
+ leave(this);
1397
+ mustLeave = this.type.isAnonymous;
1398
+ if (!depth)
1399
+ return;
1400
+ if (this.nextSibling())
1401
+ break;
1402
+ this.parent();
1403
+ depth--;
1404
+ mustLeave = true;
1405
+ }
1406
+ }
1407
+ }
1408
+ /**
1409
+ Test whether the current node matches a given context—a sequence
1410
+ of direct parent node names. Empty strings in the context array
1411
+ are treated as wildcards.
1412
+ */
1413
+ matchContext(context) {
1414
+ if (!this.buffer)
1415
+ return matchNodeContext(this.node.parent, context);
1416
+ let { buffer } = this.buffer, { types } = buffer.set;
1417
+ for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) {
1418
+ if (d < 0)
1419
+ return matchNodeContext(this._tree, context, i);
1420
+ let type = types[buffer.buffer[this.stack[d]]];
1421
+ if (!type.isAnonymous) {
1422
+ if (context[i] && context[i] != type.name)
1423
+ return false;
1424
+ i--;
1425
+ }
1426
+ }
1427
+ return true;
1428
+ }
1429
+ };
1430
+ function hasChild(tree) {
1431
+ return tree.children.some((ch) => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));
1432
+ }
1433
+ function buildTree(data) {
1434
+ var _a;
1435
+ let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data;
1436
+ let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
1437
+ let types = nodeSet.types;
1438
+ let contextHash = 0, lookAhead = 0;
1439
+ function takeNode(parentStart, minPos, children2, positions2, inRepeat, depth) {
1440
+ let { id, start, end, size } = cursor;
1441
+ let lookAheadAtStart = lookAhead, contextAtStart = contextHash;
1442
+ if (size < 0) {
1443
+ cursor.next();
1444
+ if (size == -1) {
1445
+ let node2 = reused[id];
1446
+ children2.push(node2);
1447
+ positions2.push(start - parentStart);
1448
+ return;
1449
+ } else if (size == -3) {
1450
+ contextHash = id;
1451
+ return;
1452
+ } else if (size == -4) {
1453
+ lookAhead = id;
1454
+ return;
1455
+ } else {
1456
+ throw new RangeError(`Unrecognized record size: ${size}`);
1457
+ }
1458
+ }
1459
+ let type = types[id], node, buffer2;
1460
+ let startPos = start - parentStart;
1461
+ if (end - start <= maxBufferLength && (buffer2 = findBufferSize(cursor.pos - minPos, inRepeat))) {
1462
+ let data2 = new Uint16Array(buffer2.size - buffer2.skip);
1463
+ let endPos = cursor.pos - buffer2.size, index = data2.length;
1464
+ while (cursor.pos > endPos)
1465
+ index = copyToBuffer(buffer2.start, data2, index);
1466
+ node = new TreeBuffer(data2, end - buffer2.start, nodeSet);
1467
+ startPos = buffer2.start - parentStart;
1468
+ } else {
1469
+ let endPos = cursor.pos - size;
1470
+ cursor.next();
1471
+ let localChildren = [], localPositions = [];
1472
+ let localInRepeat = id >= minRepeatType ? id : -1;
1473
+ let lastGroup = 0, lastEnd = end;
1474
+ while (cursor.pos > endPos) {
1475
+ if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {
1476
+ if (cursor.end <= lastEnd - maxBufferLength) {
1477
+ makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart, contextAtStart);
1478
+ lastGroup = localChildren.length;
1479
+ lastEnd = cursor.end;
1480
+ }
1481
+ cursor.next();
1482
+ } else if (depth > 2500) {
1483
+ takeFlatNode(start, endPos, localChildren, localPositions);
1484
+ } else {
1485
+ takeNode(start, endPos, localChildren, localPositions, localInRepeat, depth + 1);
1486
+ }
1487
+ }
1488
+ if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)
1489
+ makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart, contextAtStart);
1490
+ localChildren.reverse();
1491
+ localPositions.reverse();
1492
+ if (localInRepeat > -1 && lastGroup > 0) {
1493
+ let make = makeBalanced(type, contextAtStart);
1494
+ node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);
1495
+ } else {
1496
+ node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end, contextAtStart);
1497
+ }
1498
+ }
1499
+ children2.push(node);
1500
+ positions2.push(startPos);
1501
+ }
1502
+ function takeFlatNode(parentStart, minPos, children2, positions2) {
1503
+ let nodes = [];
1504
+ let nodeCount = 0, stopAt = -1;
1505
+ while (cursor.pos > minPos) {
1506
+ let { id, start, end, size } = cursor;
1507
+ if (size > 4) {
1508
+ cursor.next();
1509
+ } else if (stopAt > -1 && start < stopAt) {
1510
+ break;
1511
+ } else {
1512
+ if (stopAt < 0)
1513
+ stopAt = end - maxBufferLength;
1514
+ nodes.push(id, start, end);
1515
+ nodeCount++;
1516
+ cursor.next();
1517
+ }
1518
+ }
1519
+ if (nodeCount) {
1520
+ let buffer2 = new Uint16Array(nodeCount * 4);
1521
+ let start = nodes[nodes.length - 2];
1522
+ for (let i = nodes.length - 3, j = 0; i >= 0; i -= 3) {
1523
+ buffer2[j++] = nodes[i];
1524
+ buffer2[j++] = nodes[i + 1] - start;
1525
+ buffer2[j++] = nodes[i + 2] - start;
1526
+ buffer2[j++] = j;
1527
+ }
1528
+ children2.push(new TreeBuffer(buffer2, nodes[2] - start, nodeSet));
1529
+ positions2.push(start - parentStart);
1530
+ }
1531
+ }
1532
+ function makeBalanced(type, contextHash2) {
1533
+ return (children2, positions2, length2) => {
1534
+ let lookAhead2 = 0, lastI = children2.length - 1, last, lookAheadProp;
1535
+ if (lastI >= 0 && (last = children2[lastI]) instanceof Tree) {
1536
+ if (!lastI && last.type == type && last.length == length2)
1537
+ return last;
1538
+ if (lookAheadProp = last.prop(NodeProp.lookAhead))
1539
+ lookAhead2 = positions2[lastI] + last.length + lookAheadProp;
1540
+ }
1541
+ return makeTree(type, children2, positions2, length2, lookAhead2, contextHash2);
1542
+ };
1543
+ }
1544
+ function makeRepeatLeaf(children2, positions2, base, i, from, to, type, lookAhead2, contextHash2) {
1545
+ let localChildren = [], localPositions = [];
1546
+ while (children2.length > i) {
1547
+ localChildren.push(children2.pop());
1548
+ localPositions.push(positions2.pop() + base - from);
1549
+ }
1550
+ children2.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead2 - to, contextHash2));
1551
+ positions2.push(from - base);
1552
+ }
1553
+ function makeTree(type, children2, positions2, length2, lookAhead2, contextHash2, props) {
1554
+ if (contextHash2) {
1555
+ let pair = [NodeProp.contextHash, contextHash2];
1556
+ props = props ? [pair].concat(props) : [pair];
1557
+ }
1558
+ if (lookAhead2 > 25) {
1559
+ let pair = [NodeProp.lookAhead, lookAhead2];
1560
+ props = props ? [pair].concat(props) : [pair];
1561
+ }
1562
+ return new Tree(type, children2, positions2, length2, props);
1563
+ }
1564
+ function findBufferSize(maxSize, inRepeat) {
1565
+ let fork = cursor.fork();
1566
+ let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength;
1567
+ let result = { size: 0, start: 0, skip: 0 };
1568
+ scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos; ) {
1569
+ let nodeSize2 = fork.size;
1570
+ if (fork.id == inRepeat && nodeSize2 >= 0) {
1571
+ result.size = size;
1572
+ result.start = start;
1573
+ result.skip = skip;
1574
+ skip += 4;
1575
+ size += 4;
1576
+ fork.next();
1577
+ continue;
1578
+ }
1579
+ let startPos = fork.pos - nodeSize2;
1580
+ if (nodeSize2 < 0 || startPos < minPos || fork.start < minStart)
1581
+ break;
1582
+ let localSkipped = fork.id >= minRepeatType ? 4 : 0;
1583
+ let nodeStart = fork.start;
1584
+ fork.next();
1585
+ while (fork.pos > startPos) {
1586
+ if (fork.size < 0) {
1587
+ if (fork.size == -3 || fork.size == -4)
1588
+ localSkipped += 4;
1589
+ else
1590
+ break scan;
1591
+ } else if (fork.id >= minRepeatType) {
1592
+ localSkipped += 4;
1593
+ }
1594
+ fork.next();
1595
+ }
1596
+ start = nodeStart;
1597
+ size += nodeSize2;
1598
+ skip += localSkipped;
1599
+ }
1600
+ if (inRepeat < 0 || size == maxSize) {
1601
+ result.size = size;
1602
+ result.start = start;
1603
+ result.skip = skip;
1604
+ }
1605
+ return result.size > 4 ? result : void 0;
1606
+ }
1607
+ function copyToBuffer(bufferStart, buffer2, index) {
1608
+ let { id, start, end, size } = cursor;
1609
+ cursor.next();
1610
+ if (size >= 0 && id < minRepeatType) {
1611
+ let startIndex = index;
1612
+ if (size > 4) {
1613
+ let endPos = cursor.pos - (size - 4);
1614
+ while (cursor.pos > endPos)
1615
+ index = copyToBuffer(bufferStart, buffer2, index);
1616
+ }
1617
+ buffer2[--index] = startIndex;
1618
+ buffer2[--index] = end - bufferStart;
1619
+ buffer2[--index] = start - bufferStart;
1620
+ buffer2[--index] = id;
1621
+ } else if (size == -3) {
1622
+ contextHash = id;
1623
+ } else if (size == -4) {
1624
+ lookAhead = id;
1625
+ }
1626
+ return index;
1627
+ }
1628
+ let children = [], positions = [];
1629
+ while (cursor.pos > 0)
1630
+ takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1, 0);
1631
+ let length = (_a = data.length) !== null && _a !== void 0 ? _a : children.length ? positions[0] + children[0].length : 0;
1632
+ return new Tree(types[data.topID], children.reverse(), positions.reverse(), length);
1633
+ }
1634
+ var nodeSizeCache = /* @__PURE__ */ new WeakMap();
1635
+ function nodeSize(balanceType, node) {
1636
+ if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType)
1637
+ return 1;
1638
+ let size = nodeSizeCache.get(node);
1639
+ if (size == null) {
1640
+ size = 1;
1641
+ for (let child of node.children) {
1642
+ if (child.type != balanceType || !(child instanceof Tree)) {
1643
+ size = 1;
1644
+ break;
1645
+ }
1646
+ size += nodeSize(balanceType, child);
1647
+ }
1648
+ nodeSizeCache.set(node, size);
1649
+ }
1650
+ return size;
1651
+ }
1652
+ function balanceRange(balanceType, children, positions, from, to, start, length, mkTop, mkTree) {
1653
+ let total = 0;
1654
+ for (let i = from; i < to; i++)
1655
+ total += nodeSize(balanceType, children[i]);
1656
+ let maxChild = Math.ceil(
1657
+ total * 1.5 / 8
1658
+ /* Balance.BranchFactor */
1659
+ );
1660
+ let localChildren = [], localPositions = [];
1661
+ function divide(children2, positions2, from2, to2, offset) {
1662
+ for (let i = from2; i < to2; ) {
1663
+ let groupFrom = i, groupStart = positions2[i], groupSize = nodeSize(balanceType, children2[i]);
1664
+ i++;
1665
+ for (; i < to2; i++) {
1666
+ let nextSize = nodeSize(balanceType, children2[i]);
1667
+ if (groupSize + nextSize >= maxChild)
1668
+ break;
1669
+ groupSize += nextSize;
1670
+ }
1671
+ if (i == groupFrom + 1) {
1672
+ if (groupSize > maxChild) {
1673
+ let only = children2[groupFrom];
1674
+ divide(only.children, only.positions, 0, only.children.length, positions2[groupFrom] + offset);
1675
+ continue;
1676
+ }
1677
+ localChildren.push(children2[groupFrom]);
1678
+ } else {
1679
+ let length2 = positions2[i - 1] + children2[i - 1].length - groupStart;
1680
+ localChildren.push(balanceRange(balanceType, children2, positions2, groupFrom, i, groupStart, length2, null, mkTree));
1681
+ }
1682
+ localPositions.push(groupStart + offset - start);
1683
+ }
1684
+ }
1685
+ divide(children, positions, from, to, 0);
1686
+ return (mkTop || mkTree)(localChildren, localPositions, length);
1687
+ }
1688
+ var stoppedInner = new NodeProp({ perNode: true });
1689
+
1690
+ // node_modules/.pnpm/@codemirror+commands@6.10.3/node_modules/@codemirror/commands/dist/index.js
1691
+ var fromHistory = /* @__PURE__ */ Annotation2.define();
1692
+ var isolateHistory = /* @__PURE__ */ Annotation2.define();
1693
+ var invertedEffects = /* @__PURE__ */ Facet.define();
1694
+ var historyConfig = /* @__PURE__ */ Facet.define({
1695
+ combine(configs) {
1696
+ return combineConfig(configs, {
1697
+ minDepth: 100,
1698
+ newGroupDelay: 500,
1699
+ joinToEvent: (_t, isAdjacent2) => isAdjacent2
1700
+ }, {
1701
+ minDepth: Math.max,
1702
+ newGroupDelay: Math.min,
1703
+ joinToEvent: (a, b) => (tr, adj) => a(tr, adj) || b(tr, adj)
1704
+ });
1705
+ }
1706
+ });
1707
+ var historyField_ = /* @__PURE__ */ StateField2.define({
1708
+ create() {
1709
+ return HistoryState.empty;
1710
+ },
1711
+ update(state, tr) {
1712
+ let config = tr.state.facet(historyConfig);
1713
+ let fromHist = tr.annotation(fromHistory);
1714
+ if (fromHist) {
1715
+ let item = HistEvent.fromTransaction(tr, fromHist.selection), from = fromHist.side;
1716
+ let other = from == 0 ? state.undone : state.done;
1717
+ if (item)
1718
+ other = updateBranch(other, other.length, config.minDepth, item);
1719
+ else
1720
+ other = addSelection(other, tr.startState.selection);
1721
+ return new HistoryState(from == 0 ? fromHist.rest : other, from == 0 ? other : fromHist.rest);
1722
+ }
1723
+ let isolate = tr.annotation(isolateHistory);
1724
+ if (isolate == "full" || isolate == "before")
1725
+ state = state.isolate();
1726
+ if (tr.annotation(Transaction3.addToHistory) === false)
1727
+ return !tr.changes.empty ? state.addMapping(tr.changes.desc) : state;
1728
+ let event = HistEvent.fromTransaction(tr);
1729
+ let time = tr.annotation(Transaction3.time), userEvent = tr.annotation(Transaction3.userEvent);
1730
+ if (event)
1731
+ state = state.addChanges(event, time, userEvent, config, tr);
1732
+ else if (tr.selection)
1733
+ state = state.addSelection(tr.startState.selection, time, userEvent, config.newGroupDelay);
1734
+ if (isolate == "full" || isolate == "after")
1735
+ state = state.isolate();
1736
+ return state;
1737
+ },
1738
+ toJSON(value) {
1739
+ return { done: value.done.map((e) => e.toJSON()), undone: value.undone.map((e) => e.toJSON()) };
1740
+ },
1741
+ fromJSON(json) {
1742
+ return new HistoryState(json.done.map(HistEvent.fromJSON), json.undone.map(HistEvent.fromJSON));
1743
+ }
1744
+ });
1745
+ function history(config = {}) {
1746
+ return [
1747
+ historyField_,
1748
+ historyConfig.of(config),
1749
+ EditorView4.domEventHandlers({
1750
+ beforeinput(e, view) {
1751
+ let command = e.inputType == "historyUndo" ? undo : e.inputType == "historyRedo" ? redo : null;
1752
+ if (!command)
1753
+ return false;
1754
+ e.preventDefault();
1755
+ return command(view);
1756
+ }
1757
+ })
1758
+ ];
1759
+ }
1760
+ var historyField = historyField_;
1761
+ function cmd(side, selection) {
1762
+ return function({ state, dispatch }) {
1763
+ if (!selection && state.readOnly)
1764
+ return false;
1765
+ let historyState = state.field(historyField_, false);
1766
+ if (!historyState)
1767
+ return false;
1768
+ let tr = historyState.pop(side, state, selection);
1769
+ if (!tr)
1770
+ return false;
1771
+ dispatch(tr);
1772
+ return true;
1773
+ };
1774
+ }
1775
+ var undo = /* @__PURE__ */ cmd(0, false);
1776
+ var redo = /* @__PURE__ */ cmd(1, false);
1777
+ var undoSelection = /* @__PURE__ */ cmd(0, true);
1778
+ var redoSelection = /* @__PURE__ */ cmd(1, true);
1779
+ var HistEvent = class _HistEvent {
1780
+ constructor(changes, effects, mapped, startSelection, selectionsAfter) {
1781
+ this.changes = changes;
1782
+ this.effects = effects;
1783
+ this.mapped = mapped;
1784
+ this.startSelection = startSelection;
1785
+ this.selectionsAfter = selectionsAfter;
1786
+ }
1787
+ setSelAfter(after) {
1788
+ return new _HistEvent(this.changes, this.effects, this.mapped, this.startSelection, after);
1789
+ }
1790
+ toJSON() {
1791
+ var _a, _b, _c;
1792
+ return {
1793
+ changes: (_a = this.changes) === null || _a === void 0 ? void 0 : _a.toJSON(),
1794
+ mapped: (_b = this.mapped) === null || _b === void 0 ? void 0 : _b.toJSON(),
1795
+ startSelection: (_c = this.startSelection) === null || _c === void 0 ? void 0 : _c.toJSON(),
1796
+ selectionsAfter: this.selectionsAfter.map((s) => s.toJSON())
1797
+ };
1798
+ }
1799
+ static fromJSON(json) {
1800
+ return new _HistEvent(json.changes && ChangeSet2.fromJSON(json.changes), [], json.mapped && ChangeDesc.fromJSON(json.mapped), json.startSelection && EditorSelection.fromJSON(json.startSelection), json.selectionsAfter.map(EditorSelection.fromJSON));
1801
+ }
1802
+ // This does not check `addToHistory` and such, it assumes the
1803
+ // transaction needs to be converted to an item. Returns null when
1804
+ // there are no changes or effects in the transaction.
1805
+ static fromTransaction(tr, selection) {
1806
+ let effects = none;
1807
+ for (let invert of tr.startState.facet(invertedEffects)) {
1808
+ let result = invert(tr);
1809
+ if (result.length)
1810
+ effects = effects.concat(result);
1811
+ }
1812
+ if (!effects.length && tr.changes.empty)
1813
+ return null;
1814
+ return new _HistEvent(tr.changes.invert(tr.startState.doc), effects, void 0, selection || tr.startState.selection, none);
1815
+ }
1816
+ static selection(selections) {
1817
+ return new _HistEvent(void 0, none, void 0, void 0, selections);
1818
+ }
1819
+ };
1820
+ function updateBranch(branch, to, maxLen, newEvent) {
1821
+ let start = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0;
1822
+ let newBranch = branch.slice(start, to);
1823
+ newBranch.push(newEvent);
1824
+ return newBranch;
1825
+ }
1826
+ function isAdjacent(a, b) {
1827
+ let ranges = [], isAdjacent2 = false;
1828
+ a.iterChangedRanges((f, t) => ranges.push(f, t));
1829
+ b.iterChangedRanges((_f, _t, f, t) => {
1830
+ for (let i = 0; i < ranges.length; ) {
1831
+ let from = ranges[i++], to = ranges[i++];
1832
+ if (t >= from && f <= to)
1833
+ isAdjacent2 = true;
1834
+ }
1835
+ });
1836
+ return isAdjacent2;
1837
+ }
1838
+ function eqSelectionShape(a, b) {
1839
+ return a.ranges.length == b.ranges.length && a.ranges.filter((r, i) => r.empty != b.ranges[i].empty).length === 0;
1840
+ }
1841
+ function conc(a, b) {
1842
+ return !a.length ? b : !b.length ? a : a.concat(b);
1843
+ }
1844
+ var none = [];
1845
+ var MaxSelectionsPerEvent = 200;
1846
+ function addSelection(branch, selection) {
1847
+ if (!branch.length) {
1848
+ return [HistEvent.selection([selection])];
1849
+ } else {
1850
+ let lastEvent = branch[branch.length - 1];
1851
+ let sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent));
1852
+ if (sels.length && sels[sels.length - 1].eq(selection))
1853
+ return branch;
1854
+ sels.push(selection);
1855
+ return updateBranch(branch, branch.length - 1, 1e9, lastEvent.setSelAfter(sels));
1856
+ }
1857
+ }
1858
+ function popSelection(branch) {
1859
+ let last = branch[branch.length - 1];
1860
+ let newBranch = branch.slice();
1861
+ newBranch[branch.length - 1] = last.setSelAfter(last.selectionsAfter.slice(0, last.selectionsAfter.length - 1));
1862
+ return newBranch;
1863
+ }
1864
+ function addMappingToBranch(branch, mapping) {
1865
+ if (!branch.length)
1866
+ return branch;
1867
+ let length = branch.length, selections = none;
1868
+ while (length) {
1869
+ let event = mapEvent(branch[length - 1], mapping, selections);
1870
+ if (event.changes && !event.changes.empty || event.effects.length) {
1871
+ let result = branch.slice(0, length);
1872
+ result[length - 1] = event;
1873
+ return result;
1874
+ } else {
1875
+ mapping = event.mapped;
1876
+ length--;
1877
+ selections = event.selectionsAfter;
1878
+ }
1879
+ }
1880
+ return selections.length ? [HistEvent.selection(selections)] : none;
1881
+ }
1882
+ function mapEvent(event, mapping, extraSelections) {
1883
+ let selections = conc(event.selectionsAfter.length ? event.selectionsAfter.map((s) => s.map(mapping)) : none, extraSelections);
1884
+ if (!event.changes)
1885
+ return HistEvent.selection(selections);
1886
+ let mappedChanges = event.changes.map(mapping), before = mapping.mapDesc(event.changes, true);
1887
+ let fullMapping = event.mapped ? event.mapped.composeDesc(before) : before;
1888
+ return new HistEvent(mappedChanges, StateEffect2.mapEffects(event.effects, mapping), fullMapping, event.startSelection.map(before), selections);
1889
+ }
1890
+ var joinableUserEvent = /^(input\.type|delete)($|\.)/;
1891
+ var HistoryState = class _HistoryState {
1892
+ constructor(done, undone, prevTime = 0, prevUserEvent = void 0) {
1893
+ this.done = done;
1894
+ this.undone = undone;
1895
+ this.prevTime = prevTime;
1896
+ this.prevUserEvent = prevUserEvent;
1897
+ }
1898
+ isolate() {
1899
+ return this.prevTime ? new _HistoryState(this.done, this.undone) : this;
1900
+ }
1901
+ addChanges(event, time, userEvent, config, tr) {
1902
+ let done = this.done, lastEvent = done[done.length - 1];
1903
+ if (lastEvent && lastEvent.changes && !lastEvent.changes.empty && event.changes && (!userEvent || joinableUserEvent.test(userEvent)) && (!lastEvent.selectionsAfter.length && time - this.prevTime < config.newGroupDelay && config.joinToEvent(tr, isAdjacent(lastEvent.changes, event.changes)) || // For compose (but not compose.start) events, always join with previous event
1904
+ userEvent == "input.type.compose")) {
1905
+ done = updateBranch(done, done.length - 1, config.minDepth, new HistEvent(event.changes.compose(lastEvent.changes), conc(StateEffect2.mapEffects(event.effects, lastEvent.changes), lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none));
1906
+ } else {
1907
+ done = updateBranch(done, done.length, config.minDepth, event);
1908
+ }
1909
+ return new _HistoryState(done, none, time, userEvent);
1910
+ }
1911
+ addSelection(selection, time, userEvent, newGroupDelay) {
1912
+ let last = this.done.length ? this.done[this.done.length - 1].selectionsAfter : none;
1913
+ if (last.length > 0 && time - this.prevTime < newGroupDelay && userEvent == this.prevUserEvent && userEvent && /^select($|\.)/.test(userEvent) && eqSelectionShape(last[last.length - 1], selection))
1914
+ return this;
1915
+ return new _HistoryState(addSelection(this.done, selection), this.undone, time, userEvent);
1916
+ }
1917
+ addMapping(mapping) {
1918
+ return new _HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent);
1919
+ }
1920
+ pop(side, state, onlySelection) {
1921
+ let branch = side == 0 ? this.done : this.undone;
1922
+ if (branch.length == 0)
1923
+ return null;
1924
+ let event = branch[branch.length - 1], selection = event.selectionsAfter[0] || (event.startSelection ? event.startSelection.map(event.changes.invertedDesc, 1) : state.selection);
1925
+ if (onlySelection && event.selectionsAfter.length) {
1926
+ return state.update({
1927
+ selection: event.selectionsAfter[event.selectionsAfter.length - 1],
1928
+ annotations: fromHistory.of({ side, rest: popSelection(branch), selection }),
1929
+ userEvent: side == 0 ? "select.undo" : "select.redo",
1930
+ scrollIntoView: true
1931
+ });
1932
+ } else if (!event.changes) {
1933
+ return null;
1934
+ } else {
1935
+ let rest = branch.length == 1 ? none : branch.slice(0, branch.length - 1);
1936
+ if (event.mapped)
1937
+ rest = addMappingToBranch(rest, event.mapped);
1938
+ return state.update({
1939
+ changes: event.changes,
1940
+ selection: event.startSelection,
1941
+ effects: event.effects,
1942
+ annotations: fromHistory.of({ side, rest, selection }),
1943
+ filter: false,
1944
+ userEvent: side == 0 ? "undo" : "redo",
1945
+ scrollIntoView: true
1946
+ });
1947
+ }
1948
+ }
1949
+ };
1950
+ HistoryState.empty = /* @__PURE__ */ new HistoryState(none, none);
1951
+ var historyKeymap = [
1952
+ { key: "Mod-z", run: undo, preventDefault: true },
1953
+ { key: "Mod-y", mac: "Mod-Shift-z", run: redo, preventDefault: true },
1954
+ { linux: "Ctrl-Shift-z", run: redo, preventDefault: true },
1955
+ { key: "Mod-u", run: undoSelection, preventDefault: true },
1956
+ { key: "Alt-u", mac: "Mod-Shift-u", run: redoSelection, preventDefault: true }
1957
+ ];
1958
+ var segmenter = typeof Intl != "undefined" && Intl.Segmenter ? /* @__PURE__ */ new Intl.Segmenter(void 0, { granularity: "word" }) : null;
1959
+
1960
+ // src/vendor/automerge-codemirror/history.ts
1961
+ import { Compartment as Compartment2 } from "@codemirror/state";
1962
+ import { ViewPlugin as ViewPlugin2, keymap } from "@codemirror/view";
1963
+ var automergeHistory = ({
1964
+ handle
1965
+ }) => {
1966
+ const compartment = new Compartment2();
1967
+ const historyExtension = () => [history(), keymap.of(historyKeymap)];
1968
+ const resetPlugin = ViewPlugin2.fromClass(
1969
+ class {
1970
+ warned = false;
1971
+ destroyed = false;
1972
+ view;
1973
+ constructor(view) {
1974
+ this.view = view;
1975
+ this.onChange = this.onChange.bind(this);
1976
+ handle.on("change", this.onChange);
1977
+ queueMicrotask(() => {
1978
+ if (!this.destroyed) this.reset();
1979
+ });
1980
+ }
1981
+ onChange(payload) {
1982
+ if (payload?.scopeReplaced) this.reset();
1983
+ }
1984
+ // CodeMirror has no clear-history API; the sanctioned reset is cycling
1985
+ // the extension out of and back into the configuration, which drops
1986
+ // the history field's state and re-creates it empty.
1987
+ reset() {
1988
+ this.view.dispatch({ effects: compartment.reconfigure([]) });
1989
+ if (!this.warned && this.view.state.field(historyField, false) !== void 0) {
1990
+ this.warned = true;
1991
+ console.warn(
1992
+ "[automerge-codemirror] another history() extension is present in this editor's configuration, so the undo history cannot be reset when the handle's backing is swapped. Remove the other copy \u2014 note that basicSetup includes one."
1993
+ );
1994
+ }
1995
+ this.view.dispatch({
1996
+ effects: compartment.reconfigure(historyExtension())
1997
+ });
1998
+ }
1999
+ destroy() {
2000
+ this.destroyed = true;
2001
+ handle.off("change", this.onChange);
2002
+ }
2003
+ }
2004
+ );
2005
+ return [compartment.of(historyExtension()), resetPlugin];
2006
+ };
2007
+
2008
+ // src/vendor/automerge-codemirror/readOnly.ts
2009
+ import { Compartment as Compartment3, EditorState as EditorState3 } from "@codemirror/state";
2010
+ import { EditorView as EditorView6, ViewPlugin as ViewPlugin3 } from "@codemirror/view";
2011
+ var automergeReadOnly = ({
2012
+ handle
2013
+ }) => {
2014
+ const compartment = new Compartment3();
2015
+ const isReadOnly = () => !!handle.isReadOnly?.();
2016
+ const extensions = () => isReadOnly() ? [EditorState3.readOnly.of(true), EditorView6.editable.of(false)] : [];
2017
+ const trackPlugin = ViewPlugin3.fromClass(
2018
+ class {
2019
+ wasPrevReadOnly = isReadOnly();
2020
+ destroyed = false;
2021
+ view;
2022
+ constructor(view) {
2023
+ this.view = view;
2024
+ this.onChange = this.onChange.bind(this);
2025
+ handle.on("change", this.onChange);
2026
+ queueMicrotask(() => {
2027
+ if (!this.destroyed) this.sync();
2028
+ });
2029
+ }
2030
+ onChange(payload) {
2031
+ if (payload?.scopeReplaced) this.sync();
2032
+ }
2033
+ sync() {
2034
+ const current = isReadOnly();
2035
+ if (current === this.wasPrevReadOnly) return;
2036
+ this.wasPrevReadOnly = current;
2037
+ this.view.dispatch({ effects: compartment.reconfigure(extensions()) });
2038
+ }
2039
+ destroy() {
2040
+ this.destroyed = true;
2041
+ handle.off("change", this.onChange);
2042
+ }
2043
+ }
2044
+ );
2045
+ return [compartment.of(extensions()), trackPlugin];
2046
+ };
2047
+
2048
+ // src/vendor/automerge-codemirror/index.ts
2049
+ var automergePlugin = ({
2050
+ handle,
2051
+ path
2052
+ }) => [
2053
+ automergeSyncPlugin({ handle, path }),
2054
+ automergeHistory({ handle }),
2055
+ automergeReadOnly({ handle })
2056
+ ];
2057
+
2058
+ // src/lib/extensions/automerge.ts
2059
+ function createAutomergeExtension(handle, path, initialDoc) {
2060
+ const compartment = new Compartment4();
2061
+ const extension = () => handle() && path() ? automergePlugin({
2062
+ handle: handle(),
2063
+ // typescript is confused by different version of doc handle
2064
+ path: path()
2065
+ }) : [];
2066
+ const createReconfigureEffect = (view) => createEffect3(() => {
2067
+ view.dispatch({
2068
+ effects: compartment.reconfigure(extension()),
2069
+ changes: {
2070
+ from: 0,
2071
+ to: view.state.doc.length,
2072
+ insert: initialDoc()
2073
+ },
2074
+ annotations: [
2075
+ Transaction4.addToHistory.of(false),
2076
+ Transaction4.remote.of(true)
2077
+ ]
2078
+ });
2079
+ });
2080
+ return [compartment.of(extension()), createReconfigureEffect];
2081
+ }
2082
+
2083
+ // src/lib/extensions/diff.ts
2084
+ import { createEffect as createEffect4 } from "solid-js";
2085
+ import {
2086
+ Decoration as Decoration2,
2087
+ ViewPlugin as ViewPlugin4,
2088
+ WidgetType
2089
+ } from "@codemirror/view";
2090
+ import { RangeSet, StateEffect as StateEffect3 } from "@codemirror/state";
2091
+ import { next as Automerge } from "@automerge/automerge/slim";
2092
+ import {
2093
+ decodeHeads
2094
+ } from "@automerge/automerge-repo/slim";
2095
+ var setBaseline = StateEffect3.define();
2096
+ function createDiffExtension(handle, path, baseline) {
2097
+ const plugin = ViewPlugin4.fromClass(
2098
+ class {
2099
+ baseline = null;
2100
+ decorations = Decoration2.none;
2101
+ update(update) {
2102
+ let baselineChanged = false;
2103
+ for (const tr of update.transactions) {
2104
+ for (const effect of tr.effects) {
2105
+ if (effect.is(setBaseline)) {
2106
+ this.baseline = effect.value;
2107
+ baselineChanged = true;
2108
+ }
2109
+ }
2110
+ }
2111
+ if (update.docChanged || baselineChanged) {
2112
+ this.decorations = this.build();
2113
+ }
2114
+ }
2115
+ build() {
2116
+ const heads = this.baseline;
2117
+ const doc = handle()?.doc();
2118
+ if (!heads || !doc) return Decoration2.none;
2119
+ return RangeSet.of(
2120
+ buildDiffDecorations(
2121
+ diffContent(doc, heads, path()),
2122
+ prefersDarkMode()
2123
+ ),
2124
+ true
2125
+ // sort ranges
2126
+ );
2127
+ }
2128
+ },
2129
+ { decorations: (v) => v.decorations }
2130
+ );
2131
+ const createReconfigureEffect = (view) => createEffect4(() => {
2132
+ view.dispatch({ effects: setBaseline.of(baseline()) });
2133
+ });
2134
+ return [plugin, createReconfigureEffect];
2135
+ }
2136
+ function diffContent(doc, baselineHeads, path) {
2137
+ const before = decodeHeads(baselineHeads);
2138
+ const beforeContent = lookupString(Automerge.view(doc, before), path);
2139
+ const patches = Automerge.diff(doc, before, Automerge.getHeads(doc));
2140
+ const out = [];
2141
+ let offset = 0;
2142
+ for (const patch of patches) {
2143
+ if (!isIndexedChildOf(patch.path, path)) continue;
2144
+ const pos = patch.path[path.length];
2145
+ if (patch.action === "splice") {
2146
+ const len = patch.value.length;
2147
+ out.push({ type: "added", from: pos, to: pos + len });
2148
+ offset -= len;
2149
+ } else if (patch.action === "del") {
2150
+ const len = patch.length ?? 1;
2151
+ const original = pos + offset;
2152
+ out.push({
2153
+ type: "deleted",
2154
+ at: pos,
2155
+ text: beforeContent.substring(original, original + len)
2156
+ });
2157
+ offset += len;
2158
+ }
2159
+ }
2160
+ return out;
2161
+ }
2162
+ function buildDiffDecorations(diffs, dark) {
2163
+ const out = [];
2164
+ for (const diff2 of diffs) {
2165
+ if (diff2.type === "deleted") {
2166
+ out.push(
2167
+ Decoration2.widget({
2168
+ widget: new DeletionMarker(diff2.text, false),
2169
+ side: 1
2170
+ }).range(diff2.at)
2171
+ );
2172
+ continue;
2173
+ }
2174
+ if (diff2.from === diff2.to) continue;
2175
+ out.push(
2176
+ Decoration2.mark({
2177
+ attributes: { style: addedDiffStyle(dark) }
2178
+ }).range(diff2.from, diff2.to)
2179
+ );
2180
+ }
2181
+ return out;
2182
+ }
2183
+ function isIndexedChildOf(patchPath, path) {
2184
+ if (patchPath.length !== path.length + 1) return false;
2185
+ for (let i = 0; i < path.length; i++) {
2186
+ if (patchPath[i] !== path[i]) return false;
2187
+ }
2188
+ return typeof patchPath[path.length] === "number";
2189
+ }
2190
+ function lookupString(doc, path) {
2191
+ let current = doc;
2192
+ for (const key of path) {
2193
+ if (current == null) return "";
2194
+ current = current[key];
2195
+ }
2196
+ return typeof current === "string" ? current : "";
2197
+ }
2198
+ function addedDiffStyle(dark) {
2199
+ return `
2200
+ border-bottom: 2px solid ${dark ? "#4ade80" : "#22c55e"};
2201
+ background-color: ${dark ? "#14532d" : "#dcfce7"};
2202
+ `;
2203
+ }
2204
+ function prefersDarkMode() {
2205
+ return window.matchMedia("(prefers-color-scheme: dark)").matches;
2206
+ }
2207
+ var DeletionMarker = class extends WidgetType {
2208
+ deletedText;
2209
+ isActive;
2210
+ constructor(deletedText, isActive) {
2211
+ super();
2212
+ this.deletedText = deletedText;
2213
+ this.isActive = isActive;
2214
+ }
2215
+ toDOM() {
2216
+ const box = document.createElement("div");
2217
+ box.style.display = "inline-block";
2218
+ box.style.position = "relative";
2219
+ box.style.lineHeight = "1";
2220
+ box.style.verticalAlign = "middle";
2221
+ box.style.boxSizing = "border-box";
2222
+ box.style.padding = "2px 3px";
2223
+ box.style.color = "rgb(239 68 68)";
2224
+ box.style.margin = "0 4px";
2225
+ box.style.fontSize = "1.2em";
2226
+ box.style.whiteSpace = "nowrap";
2227
+ box.style.backgroundColor = this.isActive ? "rgb(239 68 68 / 20%)" : "rgb(239 68 68 / 10%)";
2228
+ box.style.borderRadius = "3px";
2229
+ box.style.cursor = "default";
2230
+ box.innerText = "\u232B";
2231
+ const hoverText = document.createElement("div");
2232
+ hoverText.style.position = "absolute";
2233
+ hoverText.style.top = "100%";
2234
+ hoverText.style.left = "0";
2235
+ hoverText.style.zIndex = "1";
2236
+ hoverText.style.padding = "5px";
2237
+ hoverText.style.backgroundColor = "rgb(254 242 242)";
2238
+ hoverText.style.fontSize = "15px";
2239
+ hoverText.style.color = "rgb(17 24 39)";
2240
+ hoverText.style.border = "1px solid rgb(185 28 28)";
2241
+ hoverText.style.boxShadow = "0px 0px 6px rgba(0, 0, 0, 0.1)";
2242
+ hoverText.style.borderRadius = "3px";
2243
+ hoverText.style.visibility = "hidden";
2244
+ hoverText.innerText = this.deletedText;
2245
+ const isDarkMode = document.documentElement.classList.contains("dark") || window.matchMedia("(prefers-color-scheme: dark)").matches;
2246
+ if (isDarkMode) {
2247
+ box.style.color = "rgb(248 113 113)";
2248
+ box.style.backgroundColor = this.isActive ? "rgb(248 113 113 / 20%)" : "rgb(248 113 113 / 10%)";
2249
+ hoverText.style.backgroundColor = "rgb(69 10 10)";
2250
+ hoverText.style.color = "rgb(254 226 226)";
2251
+ hoverText.style.border = "1px solid rgb(153 27 27)";
2252
+ }
2253
+ box.appendChild(hoverText);
2254
+ box.onmouseover = function() {
2255
+ hoverText.style.visibility = "visible";
2256
+ };
2257
+ box.onmouseout = function() {
2258
+ hoverText.style.visibility = "hidden";
2259
+ };
2260
+ return box;
2261
+ }
2262
+ eq(other) {
2263
+ return other.deletedText === this.deletedText && other.isActive === this.isActive;
2264
+ }
2265
+ ignoreEvent() {
2266
+ return true;
2267
+ }
2268
+ };
2269
+
2270
+ // src/lib/extensions/scrollHighlightIntoView.ts
2271
+ import { createEffect as createEffect5 } from "solid-js";
2272
+ import { EditorView as EditorView8 } from "@codemirror/view";
2273
+ import { EditorSelection as EditorSelection2 } from "@codemirror/state";
2274
+ function createScrollHighlightIntoViewExtension(target) {
2275
+ const extension = [];
2276
+ const createScrollHighlightIntoViewEffect = (view) => createEffect5(() => {
2277
+ const range = target();
2278
+ if (!range) return;
2279
+ const docLength = view.state.doc.length;
2280
+ const from = Math.min(range[0], docLength);
2281
+ const to = Math.min(range[1], docLength);
2282
+ view.dispatch({
2283
+ effects: EditorView8.scrollIntoView(EditorSelection2.range(from, to), {
2284
+ x: "nearest",
2285
+ y: "nearest"
2286
+ })
2287
+ });
2288
+ });
2289
+ return [extension, createScrollHighlightIntoViewEffect];
2290
+ }
2291
+
2292
+ // src/lib/extensions/presence.ts
2293
+ import { createEffect as createEffect6 } from "solid-js";
2294
+ import {
2295
+ Decoration as Decoration3,
2296
+ EditorView as EditorView9,
2297
+ RectangleMarker,
2298
+ ViewPlugin as ViewPlugin5,
2299
+ layer
2300
+ } from "@codemirror/view";
2301
+ import {
2302
+ Compartment as Compartment5,
2303
+ EditorSelection as EditorSelection3,
2304
+ StateEffect as StateEffect4,
2305
+ StateField as StateField3,
2306
+ Transaction as Transaction5
2307
+ } from "@codemirror/state";
2308
+ import {
2309
+ next as A3
2310
+ } from "@automerge/automerge/slim";
2311
+ import {
2312
+ Presence
2313
+ } from "@automerge/automerge-repo/slim";
2314
+ function createPresenceExtension(handle, path, contactUrl) {
2315
+ const compartment = new Compartment5();
2316
+ const extension = () => {
2317
+ const url = contactUrl();
2318
+ return url ? presence(handle(), path(), url) : [];
2319
+ };
2320
+ const createReconfigureEffect = (view) => createEffect6(() => {
2321
+ view.dispatch({ effects: compartment.reconfigure(extension()) });
2322
+ });
2323
+ return [compartment.of(extension()), createReconfigureEffect];
2324
+ }
2325
+ function presence(handle, path, contactUrl) {
2326
+ const setRemoteSelections = StateEffect4.define();
2327
+ const remoteSelectionField = StateField3.define({
2328
+ create() {
2329
+ return [];
2330
+ },
2331
+ update(value, tr) {
2332
+ if (tr.docChanged) {
2333
+ value = value.map((sel) => ({
2334
+ ...sel,
2335
+ from: tr.changes.mapPos(sel.from),
2336
+ to: tr.changes.mapPos(sel.to),
2337
+ head: tr.changes.mapPos(sel.head)
2338
+ }));
2339
+ }
2340
+ for (const e of tr.effects) {
2341
+ if (e.is(setRemoteSelections)) value = e.value;
2342
+ }
2343
+ return value;
2344
+ },
2345
+ // Selection tints are plain mark decorations: they carry no stateful
2346
+ // DOM, so redrawing them is invisible.
2347
+ provide: (f) => EditorView9.decorations.from(f, buildSelectionTints)
2348
+ });
2349
+ const caretLayer = layer({
2350
+ above: true,
2351
+ class: "cm-presence-layer",
2352
+ update: (update) => update.docChanged || update.transactions.some(
2353
+ (tr) => tr.effects.some((e) => e.is(setRemoteSelections))
2354
+ ),
2355
+ markers(view) {
2356
+ const selections = [...view.state.field(remoteSelectionField)].sort(
2357
+ (a, b) => a.peerId < b.peerId ? -1 : a.peerId > b.peerId ? 1 : 0
2358
+ );
2359
+ const markers = [];
2360
+ for (const sel of selections) {
2361
+ const [rect] = RectangleMarker.forRange(
2362
+ view,
2363
+ "cm-presence-caret",
2364
+ EditorSelection3.cursor(sel.head)
2365
+ );
2366
+ if (!rect) continue;
2367
+ markers.push(
2368
+ new PresenceCaretMarker(sel, rect.left, rect.top, rect.height)
2369
+ );
2370
+ }
2371
+ return markers;
2372
+ }
2373
+ });
2374
+ const plugin = ViewPlugin5.fromClass(
2375
+ class {
2376
+ view;
2377
+ presence;
2378
+ destroyed = false;
2379
+ broadcastQueued = false;
2380
+ constructor(view) {
2381
+ this.view = view;
2382
+ this.presence = new Presence({
2383
+ handle,
2384
+ userId: contactUrl
2385
+ });
2386
+ this.presence.start({ initialState: { selection: null } });
2387
+ this.presence.on("update", this.refresh);
2388
+ this.presence.on("snapshot", this.refresh);
2389
+ this.presence.on("goodbye", this.refresh);
2390
+ this.presence.on("pruned", this.refresh);
2391
+ window.addEventListener("pagehide", this.stopPresence);
2392
+ }
2393
+ update(update) {
2394
+ const typed = update.docChanged && update.transactions.some(
2395
+ (tr) => tr.annotation(Transaction5.userEvent) !== void 0
2396
+ );
2397
+ if (update.focusChanged && !update.view.hasFocus) {
2398
+ if (this.presence.running) {
2399
+ this.presence.broadcast("selection", null);
2400
+ }
2401
+ } else if (update.selectionSet || typed || update.focusChanged && update.view.hasFocus) {
2402
+ this.scheduleBroadcast();
2403
+ }
2404
+ if (update.docChanged) {
2405
+ queueMicrotask(this.refresh);
2406
+ }
2407
+ }
2408
+ destroy() {
2409
+ this.destroyed = true;
2410
+ this.stopPresence();
2411
+ window.removeEventListener("pagehide", this.stopPresence);
2412
+ }
2413
+ stopPresence = () => {
2414
+ if (this.presence.running) this.presence.stop();
2415
+ };
2416
+ // rAF-throttled (matching tldraw4) so drag-selections don't flood the
2417
+ // channel. The selection is read fresh at flush time.
2418
+ scheduleBroadcast() {
2419
+ if (this.broadcastQueued) return;
2420
+ this.broadcastQueued = true;
2421
+ requestAnimationFrame(() => {
2422
+ this.broadcastQueued = false;
2423
+ if (this.destroyed || !this.presence.running) return;
2424
+ if (!this.view.hasFocus) return;
2425
+ const doc = handle.doc();
2426
+ const sel = this.view.state.selection.main;
2427
+ this.presence.broadcast("selection", {
2428
+ start: A3.getCursor(doc, path, sel.from),
2429
+ end: A3.getCursor(doc, path, sel.to),
2430
+ headAtStart: sel.to > sel.from && sel.head === sel.from,
2431
+ lastMoved: Date.now()
2432
+ });
2433
+ });
2434
+ }
2435
+ // Re-resolve every peer's cursors against the current doc. A cursor can
2436
+ // briefly fail to resolve when a presence message races ahead of doc
2437
+ // sync -- the peer is skipped and picked up again on the next change.
2438
+ refresh = () => {
2439
+ if (this.destroyed) return;
2440
+ const doc = handle.doc();
2441
+ const resolved = [];
2442
+ for (const peer of this.presence.getPeerStates().peers) {
2443
+ const peerId = String(peer.peerId);
2444
+ const selection = peer.value?.selection ?? null;
2445
+ if (!selection) continue;
2446
+ try {
2447
+ const from = A3.getCursorPosition(doc, path, selection.start);
2448
+ const to = A3.getCursorPosition(doc, path, selection.end);
2449
+ const peerContactUrl = peer.userId ?? null;
2450
+ resolved.push({
2451
+ peerId,
2452
+ contactUrl: peerContactUrl,
2453
+ // Same rule as the contact-cursor token (palette hash of the
2454
+ // contact url), so the tint and the token can't drift apart.
2455
+ color: generateColorFromString(peerContactUrl ?? peerId),
2456
+ from,
2457
+ to,
2458
+ head: selection.headAtStart ? from : to,
2459
+ lastMoved: selection.lastMoved
2460
+ });
2461
+ } catch {
2462
+ continue;
2463
+ }
2464
+ }
2465
+ this.view.dispatch({ effects: setRemoteSelections.of(resolved) });
2466
+ };
2467
+ }
2468
+ );
2469
+ return [remoteSelectionField, caretLayer, plugin, presenceTheme];
2470
+ }
2471
+ function buildSelectionTints(selections) {
2472
+ const ranges = [];
2473
+ for (const sel of selections) {
2474
+ if (sel.from < sel.to) {
2475
+ ranges.push(
2476
+ Decoration3.mark({
2477
+ class: "cm-presence-range",
2478
+ attributes: {
2479
+ style: `background-color: color-mix(in srgb, ${sel.color} 25%, transparent);`
2480
+ }
2481
+ }).range(sel.from, sel.to)
2482
+ );
2483
+ }
2484
+ }
2485
+ return Decoration3.set(ranges, true);
2486
+ }
2487
+ var LABEL_TIMEOUT_MS = 2e3;
2488
+ var PresenceCaretMarker = class {
2489
+ sel;
2490
+ left;
2491
+ top;
2492
+ height;
2493
+ constructor(sel, left, top, height) {
2494
+ this.sel = sel;
2495
+ this.left = left;
2496
+ this.top = top;
2497
+ this.height = height;
2498
+ }
2499
+ eq(other) {
2500
+ return other.sel.peerId === this.sel.peerId && other.sel.contactUrl === this.sel.contactUrl && other.sel.color === this.sel.color && other.sel.lastMoved === this.sel.lastMoved && other.left === this.left && other.top === this.top && other.height === this.height;
2501
+ }
2502
+ draw() {
2503
+ const caret = document.createElement("div");
2504
+ caret.className = "cm-presence-caret";
2505
+ caret.dataset.peerId = this.sel.peerId;
2506
+ if (this.sel.contactUrl) {
2507
+ const label = document.createElement("span");
2508
+ label.className = "cm-presence-caret-label";
2509
+ const token = document.createElement("patchwork-view");
2510
+ token.setAttribute("doc-url", this.sel.contactUrl);
2511
+ token.setAttribute("tool-id", "contact-cursor");
2512
+ token.style.display = "block";
2513
+ label.appendChild(token);
2514
+ caret.appendChild(label);
2515
+ }
2516
+ this.adjust(caret);
2517
+ restartIdleCountdown(caret);
2518
+ return caret;
2519
+ }
2520
+ // Reposition the peer's existing element instead of redrawing it, keeping
2521
+ // the mounted contact token alive (a remount re-renders asynchronously and
2522
+ // flickers -- see the layer comment in `presence`).
2523
+ update(dom, prev) {
2524
+ if (prev.sel.peerId !== this.sel.peerId || prev.sel.contactUrl !== this.sel.contactUrl) {
2525
+ return false;
2526
+ }
2527
+ this.adjust(dom);
2528
+ if (prev.sel.lastMoved !== this.sel.lastMoved) restartIdleCountdown(dom);
2529
+ return true;
2530
+ }
2531
+ adjust(dom) {
2532
+ dom.style.left = `${this.left}px`;
2533
+ dom.style.top = `${this.top}px`;
2534
+ dom.style.height = `${this.height}px`;
2535
+ dom.style.setProperty("--cm-presence-color", this.sel.color);
2536
+ }
2537
+ };
2538
+ var idleTimers = /* @__PURE__ */ new WeakMap();
2539
+ function restartIdleCountdown(caret) {
2540
+ clearTimeout(idleTimers.get(caret));
2541
+ caret.classList.remove("cm-presence-caret--idle");
2542
+ idleTimers.set(
2543
+ caret,
2544
+ setTimeout(
2545
+ () => caret.classList.add("cm-presence-caret--idle"),
2546
+ LABEL_TIMEOUT_MS
2547
+ )
2548
+ );
2549
+ }
2550
+ var presenceTheme = EditorView9.baseTheme({
2551
+ // Positioned absolutely by the layer (document-relative); -1px centers
2552
+ // the 2px bar on the caret position.
2553
+ ".cm-presence-caret": {
2554
+ borderLeft: "2px solid var(--cm-presence-color)",
2555
+ marginLeft: "-1px",
2556
+ pointerEvents: "none"
2557
+ },
2558
+ ".cm-presence-caret-label": {
2559
+ position: "absolute",
2560
+ top: "-1.4em",
2561
+ left: "-2px",
2562
+ zIndex: "150",
2563
+ whiteSpace: "nowrap",
2564
+ pointerEvents: "none",
2565
+ userSelect: "none",
2566
+ opacity: "1",
2567
+ transition: "opacity 200ms ease-in-out"
2568
+ },
2569
+ ".cm-presence-caret--idle .cm-presence-caret-label": {
2570
+ opacity: "0"
2571
+ }
2572
+ });
2573
+ var USER_COLOR_PALETTE = [
2574
+ "hsl(200, 70%, 50%)",
2575
+ "hsl(10, 75%, 58%)",
2576
+ "hsl(145, 70%, 45%)",
2577
+ "hsl(270, 70%, 55%)",
2578
+ "hsl(38, 85%, 50%)",
2579
+ "hsl(350, 70%, 55%)",
2580
+ "hsl(178, 70%, 45%)",
2581
+ "hsl(235, 70%, 58%)",
2582
+ "hsl(85, 70%, 45%)",
2583
+ "hsl(310, 70%, 55%)",
2584
+ "hsl(25, 80%, 52%)",
2585
+ "hsl(188, 75%, 48%)"
2586
+ ];
2587
+ function generateColorFromString(str) {
2588
+ const hash = Math.abs(
2589
+ str.split("").reduce((acc, char) => acc + char.charCodeAt(0), 0)
2590
+ );
2591
+ return USER_COLOR_PALETTE[hash % USER_COLOR_PALETTE.length];
2592
+ }
2593
+
2594
+ // src/lib/codemirror.tsx
2595
+ var lookup = (doc, path) => {
2596
+ let current = doc;
2597
+ for (const key of path) {
2598
+ current = current[key];
2599
+ if (current === void 0) {
2600
+ return void 0;
2601
+ }
2602
+ }
2603
+ return current;
2604
+ };
2605
+ function CodeMirror(props) {
2606
+ const initialDoc = () => props.handle && lookup(props.handle.doc(), props.path) || "";
2607
+ const [automergeExtension, createEffectReconfigureAutomerge] = createAutomergeExtension(() => props.handle, () => props.path, initialDoc);
2608
+ const [readOnlyExtension, createEffectReconfigureReadOnly] = createReadOnlyExtension(() => !!props.readOnly);
2609
+ const [decorationsExtension, createEffectReconfigureDecorations] = createDecorationsExtension(() => props.decorations?.());
2610
+ const [diffExtension, createEffectReconfigureDiff] = createDiffExtension(() => props.handle, () => props.path, () => props.baseline?.() ?? null);
2611
+ const [scrollHighlightIntoViewExtension, createEffectScrollHighlightIntoView] = createScrollHighlightIntoViewExtension(() => props.scrollTarget?.() ?? null);
2612
+ const [presenceExtension, createEffectReconfigurePresence] = createPresenceExtension(() => props.handle, () => props.path, () => props.readOnly || props.handle.isReadOnly() ? null : props.contactUrl?.() ?? null);
2613
+ const userExtensionsCompartment = new Compartment6();
2614
+ const selectionExtension = EditorView10.updateListener.of((update) => {
2615
+ if (!props.onChangeSelection) return;
2616
+ if (update.selectionSet) {
2617
+ const sel = update.state.selection.main;
2618
+ props.onChangeSelection(sel.from, sel.to);
2619
+ }
2620
+ });
2621
+ const extensions = [
2622
+ selectionExtension,
2623
+ decorationsExtension,
2624
+ // automergeExtension must come before diffExtension so diff stays in sync with edits.
2625
+ automergeExtension,
2626
+ diffExtension,
2627
+ scrollHighlightIntoViewExtension,
2628
+ presenceExtension,
2629
+ userExtensionsCompartment.of(props.extensions || []),
2630
+ readOnlyExtension
2631
+ ].filter(Boolean);
2632
+ const state = EditorState4.create({
2633
+ doc: initialDoc(),
2634
+ extensions
2635
+ });
2636
+ const view = new EditorView10({
2637
+ state
2638
+ });
2639
+ props.withView?.(view);
2640
+ createEffectReconfigureAutomerge(view);
2641
+ createEffectReconfigureReadOnly(view);
2642
+ createEffectReconfigureDecorations?.(view);
2643
+ createEffectReconfigureDiff(view);
2644
+ createEffectScrollHighlightIntoView(view);
2645
+ createEffectReconfigurePresence(view);
2646
+ createEffect7(() => {
2647
+ view.dispatch({
2648
+ effects: userExtensionsCompartment.reconfigure(props.extensions || [])
2649
+ });
2650
+ });
2651
+ onCleanup(() => view.destroy());
2652
+ return view.dom;
2653
+ }
2654
+
2655
+ export {
2656
+ CodeMirror
2657
+ };
2658
+ //# sourceMappingURL=chunk-H5POLO74.js.map