plitejs 0.0.1 → 54.0.0-beta.3

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 (61) hide show
  1. package/LICENSE +4 -1
  2. package/README.md +83 -0
  3. package/dist/annotation-store-metrics-Ccjkef45.js +12 -0
  4. package/dist/annotations/index.d.ts +2 -0
  5. package/dist/annotations/index.js +2 -0
  6. package/dist/authored/index.d.ts +596 -0
  7. package/dist/authored/index.js +18558 -0
  8. package/dist/authored-veto-DSnQcHGR.js +6 -0
  9. package/dist/browser-protocol-pvt4HFF7.js +5 -0
  10. package/dist/comparison-plan-CEQL0ooW.js +1338 -0
  11. package/dist/comparison-types-Dt-unJZY.d.ts +179 -0
  12. package/dist/create-editor-CkHtPWXV.js +1107 -0
  13. package/dist/diff/index.d.ts +32 -0
  14. package/dist/diff/index.js +1748 -0
  15. package/dist/dom/index.d.ts +2 -0
  16. package/dist/dom/index.js +2 -0
  17. package/dist/dom-Cgfscvnm.js +9220 -0
  18. package/dist/editor-owner-IUmkTeXz.js +171 -0
  19. package/dist/editor-view-lifetime-GJKa_QGh.js +23 -0
  20. package/dist/history/index.d.ts +170 -0
  21. package/dist/history/index.js +6718 -0
  22. package/dist/hyperscript/index.d.ts +2 -0
  23. package/dist/hyperscript/index.js +2 -0
  24. package/dist/hyperscript-FPuoArEi.js +299 -0
  25. package/dist/index-BpQx2UG4.d.ts +1093 -0
  26. package/dist/index-Cw-oC2ps.d.ts +190 -0
  27. package/dist/index-DPWyk3lG.d.ts +65 -0
  28. package/dist/index-DpltOCot.d.ts +9753 -0
  29. package/dist/index-HPYawTae.d.ts +119 -0
  30. package/dist/index-K0Za9YXc.d.ts +1246 -0
  31. package/dist/index.d.ts +2 -0
  32. package/dist/index.js +5 -0
  33. package/dist/internal/index.d.ts +2 -0
  34. package/dist/internal/index.js +156 -0
  35. package/dist/mapped-view-store-ld-6uxEU.js +120 -0
  36. package/dist/native-grouping-input-DMNcsIaW.js +8 -0
  37. package/dist/pagination/index.d.ts +169 -0
  38. package/dist/pagination/index.js +2 -0
  39. package/dist/pagination/react.d.ts +33 -0
  40. package/dist/pagination/react.js +1509 -0
  41. package/dist/pagination-D_A8iPJP.js +1021 -0
  42. package/dist/plugin-DWzkJbnJ.js +50999 -0
  43. package/dist/range-geometry-BLAHRE11.d.ts +38 -0
  44. package/dist/range-geometry-BjeLHOnl.js +486 -0
  45. package/dist/react/index.d.ts +5 -0
  46. package/dist/react/index.js +7 -0
  47. package/dist/react/virtualized.d.ts +13 -0
  48. package/dist/react/virtualized.js +209 -0
  49. package/dist/react-DZ15gmz2.js +1018 -0
  50. package/dist/retraction-BMem8Rfk.js +109 -0
  51. package/dist/src-cT1OTKP_.js +1386 -0
  52. package/dist/store-Cz2mXyDe.js +704 -0
  53. package/dist/testing/index.d.ts +183 -0
  54. package/dist/testing/index.js +96 -0
  55. package/dist/use-editor-dom-scope-BbMDSCpW.js +28354 -0
  56. package/dist/yjs/index.d.ts +2 -0
  57. package/dist/yjs/index.js +2 -0
  58. package/dist/yjs/react/index.d.ts +26 -0
  59. package/dist/yjs/react/index.js +85 -0
  60. package/dist/yjs-DOK-m7kl.js +13413 -0
  61. package/package.json +191 -43
@@ -0,0 +1,704 @@
1
+ import { Ic as readAuthoredView, eu as failInvariant, il as notifyObservers, ip as getDefined, mu as RangeApi, pi as subscribeEditorViewState } from "./plugin-DWzkJbnJ.js";
2
+ import { p as projectRange } from "./create-editor-CkHtPWXV.js";
3
+ import { n as registerAnnotationStoreMetrics } from "./annotation-store-metrics-Ccjkef45.js";
4
+ import { n as createMappedViewStoreKernel, r as createViewSourceFaultBoundary, t as areMappedViewDataEqual } from "./mapped-view-store-ld-6uxEU.js";
5
+ //#region src/internal/view/stable-id-mapped-source.ts
6
+ const EMPTY_OUTPUTS = Object.freeze([]);
7
+ const createPersistentReadonlyRecord = (initial, onNodeCopy, onChildEntriesCopy) => {
8
+ const EMPTY_NODE = Object.freeze({ children: /* @__PURE__ */ new Map() });
9
+ const createNode = (children, value, key) => {
10
+ onNodeCopy();
11
+ return Object.freeze({
12
+ children,
13
+ ...value === void 0 ? {} : {
14
+ key,
15
+ value
16
+ }
17
+ });
18
+ };
19
+ const createUpdate = () => ({
20
+ assigned: false,
21
+ children: /* @__PURE__ */ new Map()
22
+ });
23
+ const keyBytes = (key) => {
24
+ let bytes = "";
25
+ for (let index = 0; index < key.length; index += 1) {
26
+ const unit = key.charCodeAt(index);
27
+ bytes += String.fromCharCode(unit >>> 8, unit & 255);
28
+ }
29
+ return bytes;
30
+ };
31
+ const setValues = (base, changes) => {
32
+ const updates = createUpdate();
33
+ for (const [key, value] of changes) {
34
+ let update = updates;
35
+ for (const part of keyBytes(key)) {
36
+ let child = update.children.get(part);
37
+ if (!child) {
38
+ child = createUpdate();
39
+ update.children.set(part, child);
40
+ }
41
+ update = child;
42
+ }
43
+ update.assigned = true;
44
+ update.key = key;
45
+ update.value = value;
46
+ }
47
+ const stack = [{
48
+ iterator: updates.children.entries(),
49
+ node: base,
50
+ part: "",
51
+ update: updates
52
+ }];
53
+ while (stack.length > 0) {
54
+ const frame = getDefined(stack.at(-1));
55
+ const entry = frame.iterator.next();
56
+ if (!entry.done) {
57
+ const [part, update] = entry.value;
58
+ stack.push({
59
+ iterator: update.children.entries(),
60
+ node: frame.node.children.get(part) ?? EMPTY_NODE,
61
+ part,
62
+ update
63
+ });
64
+ continue;
65
+ }
66
+ const { children, node, update } = frame;
67
+ const value = update.assigned ? update.value : node.value;
68
+ const next = !children && value === node.value ? node : createNode(children ?? node.children, value, update.assigned ? update.key : node.key);
69
+ stack.pop();
70
+ const parent = stack.at(-1);
71
+ if (!parent) return next;
72
+ if (node === next) continue;
73
+ if (!parent.children) {
74
+ parent.children = new Map(parent.node.children);
75
+ onChildEntriesCopy(parent.node.children.size);
76
+ }
77
+ if (next.value === void 0 && next.children.size === 0) parent.children.delete(frame.part);
78
+ else parent.children.set(frame.part, next);
79
+ }
80
+ return base;
81
+ };
82
+ const readValue = (root, key) => {
83
+ let node = root;
84
+ for (const part of keyBytes(key)) {
85
+ const child = node.children.get(part);
86
+ if (!child) return void 0;
87
+ node = child;
88
+ }
89
+ return node.value;
90
+ };
91
+ const readKeys = (root) => {
92
+ const keys = [];
93
+ const stack = [root.children.values()];
94
+ if (root.value !== void 0) keys.push(getDefined(root.key));
95
+ while (stack.length > 0) {
96
+ const entry = getDefined(stack.at(-1)).next();
97
+ if (entry.done) {
98
+ stack.pop();
99
+ continue;
100
+ }
101
+ const node = entry.value;
102
+ if (node.value !== void 0) keys.push(getDefined(node.key));
103
+ if (node.children.size > 0) stack.push(node.children.values());
104
+ }
105
+ return keys;
106
+ };
107
+ let root = setValues(EMPTY_NODE, Object.entries(initial));
108
+ let snapshot;
109
+ const createSnapshot = (snapshotRoot) => new Proxy(Object.create(null), {
110
+ defineProperty: () => false,
111
+ deleteProperty: () => false,
112
+ get: (_target, key) => typeof key === "string" ? readValue(snapshotRoot, key) : void 0,
113
+ getOwnPropertyDescriptor: (_target, key) => {
114
+ if (typeof key !== "string") return void 0;
115
+ const value = readValue(snapshotRoot, key);
116
+ return value === void 0 ? void 0 : {
117
+ configurable: true,
118
+ enumerable: true,
119
+ value,
120
+ writable: false
121
+ };
122
+ },
123
+ has: (_target, key) => typeof key === "string" && readValue(snapshotRoot, key) !== void 0,
124
+ ownKeys: () => readKeys(snapshotRoot),
125
+ set: () => false
126
+ });
127
+ snapshot = createSnapshot(root);
128
+ return {
129
+ getSnapshot: () => snapshot,
130
+ publish(changes) {
131
+ if (changes.size === 0) return snapshot;
132
+ root = setValues(root, changes);
133
+ snapshot = createSnapshot(root);
134
+ return snapshot;
135
+ }
136
+ };
137
+ };
138
+ const createReadonlyEntityMap = (values, allIds, size) => {
139
+ function* entries() {
140
+ for (const id of allIds) {
141
+ const value = values[id];
142
+ if (value !== void 0) yield [id, value];
143
+ }
144
+ }
145
+ const snapshot = {
146
+ entries,
147
+ forEach(callback, thisArg) {
148
+ for (const [id, value] of entries()) callback.call(thisArg, value, id, snapshot);
149
+ },
150
+ get: (id) => values[id],
151
+ has: (id) => values[id] !== void 0,
152
+ *keys() {
153
+ for (const [id] of entries()) yield id;
154
+ },
155
+ size,
156
+ *values() {
157
+ for (const [, value] of entries()) yield value;
158
+ },
159
+ [Symbol.iterator]: entries,
160
+ [Symbol.toStringTag]: "Map"
161
+ };
162
+ return Object.freeze(snapshot);
163
+ };
164
+ const hasEntity = (value) => value.entity !== void 0;
165
+ const unique = (values) => [...new Set(values)];
166
+ const areArraysEqual = (left, right, isEqual) => left.length === right.length && left.every((value, index) => {
167
+ const other = right[index];
168
+ return other !== void 0 && isEqual(value, other);
169
+ });
170
+ const getChangedMapIds = (left, right, isEqual) => {
171
+ const changedIds = [];
172
+ for (const id of /* @__PURE__ */ new Set([...left.keys(), ...right.keys()])) {
173
+ const leftValue = left.get(id);
174
+ const rightValue = right.get(id);
175
+ if (leftValue === void 0 || rightValue === void 0 || !isEqual(leftValue, rightValue)) changedIds.push(id);
176
+ }
177
+ return changedIds;
178
+ };
179
+ const getChangedOutputKeys = (left, right, isEqual) => {
180
+ const changedKeys = [];
181
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(left), ...Object.keys(right)])) if (!areArraysEqual(left[key] ?? EMPTY_OUTPUTS, right[key] ?? EMPTY_OUTPUTS, isEqual)) changedKeys.push(key);
182
+ return changedKeys;
183
+ };
184
+ const getMappedMetadata = (id, mapped) => ({
185
+ id,
186
+ ...mapped.metadata === void 0 ? {} : { metadata: mapped.metadata }
187
+ });
188
+ /**
189
+ * Private stable-ID mapping kernel shared by decoration, annotation, and
190
+ * keyed derived stores. It keeps their public models separate while making a
191
+ * same-order source refresh pay one semantic scan plus changed-item mapping.
192
+ */
193
+ const createStableIdMappedSource = (initialItems, options) => {
194
+ const isEntityEqual = options.isEntityEqual ?? Object.is;
195
+ const work = {
196
+ entityCopies: 0,
197
+ inputVisits: 0,
198
+ outputCandidateVisits: 0,
199
+ outputVisits: 0,
200
+ snapshotChildEntryCopies: 0,
201
+ snapshotNodeCopies: 0,
202
+ unprojectedVisits: 0
203
+ };
204
+ const mapItem = (item) => {
205
+ const mapped = options.map(item);
206
+ const outputsByKey = /* @__PURE__ */ new Map();
207
+ for (const output of mapped.outputs) {
208
+ work.outputVisits += 1;
209
+ const values = outputsByKey.get(output.key) ?? [];
210
+ values.push(output.value);
211
+ outputsByKey.set(output.key, values);
212
+ }
213
+ return {
214
+ ...mapped,
215
+ outputsByKey
216
+ };
217
+ };
218
+ const buildState = (items) => {
219
+ work.inputVisits += items.length;
220
+ const ids = items.map(options.getId);
221
+ if (new Set(ids).size !== ids.length) throw new Error("Stable mapped view source IDs must be unique.");
222
+ const allIds = Object.freeze(ids);
223
+ const entities = Object.create(null);
224
+ const byOutputKey = Object.create(null);
225
+ const idsByOutputKey = /* @__PURE__ */ new Map();
226
+ const mappedById = /* @__PURE__ */ new Map();
227
+ const unprojectedIds = /* @__PURE__ */ new Set();
228
+ items.forEach((item, index) => {
229
+ const id = allIds[index];
230
+ const mapped = mapItem(item);
231
+ mappedById.set(id, mapped);
232
+ if (hasEntity(mapped)) entities[id] = mapped.entity;
233
+ if (mapped.outputs.length === 0) unprojectedIds.add(id);
234
+ const outputKeys = /* @__PURE__ */ new Set();
235
+ for (const output of mapped.outputs) {
236
+ const outputValues = byOutputKey[output.key] ?? [];
237
+ outputValues.push(output.value);
238
+ byOutputKey[output.key] = outputValues;
239
+ const outputIds = idsByOutputKey.get(output.key) ?? [];
240
+ if (!outputKeys.has(output.key)) {
241
+ outputIds.push(id);
242
+ outputKeys.add(output.key);
243
+ }
244
+ idsByOutputKey.set(output.key, outputIds);
245
+ }
246
+ });
247
+ const frozenOutputs = Object.create(null);
248
+ Object.entries(byOutputKey).forEach(([key, values]) => {
249
+ frozenOutputs[key] = Object.freeze(values);
250
+ });
251
+ const outputRecord = createPersistentReadonlyRecord(Object.freeze(frozenOutputs), () => {
252
+ work.snapshotNodeCopies += 1;
253
+ }, (count) => {
254
+ work.snapshotChildEntryCopies += count;
255
+ });
256
+ const entityRecord = createPersistentReadonlyRecord(entities, () => {
257
+ work.snapshotNodeCopies += 1;
258
+ }, (count) => {
259
+ work.snapshotChildEntryCopies += count;
260
+ });
261
+ return {
262
+ allIds,
263
+ byId: createReadonlyEntityMap(entityRecord.getSnapshot(), allIds, Object.keys(entities).length),
264
+ byOutputKey: outputRecord.getSnapshot(),
265
+ entityRecord,
266
+ idsByOutputKey,
267
+ indexById: new Map(allIds.map((id, index) => [id, index])),
268
+ inputs: [...items],
269
+ mappedById,
270
+ outputRecord,
271
+ unprojectedIds
272
+ };
273
+ };
274
+ let state = buildState(initialItems);
275
+ const replaceAll = (items) => {
276
+ const previousState = state;
277
+ const nextState = buildState(items);
278
+ const orderChanged = !areArraysEqual(state.allIds, nextState.allIds, Object.is);
279
+ const changedEntityIds = getChangedMapIds(state.byId, nextState.byId, isEntityEqual);
280
+ const changedOutputKeys = getChangedOutputKeys(state.byOutputKey, nextState.byOutputKey, options.isOutputEqual);
281
+ const changedEntityIdSet = new Set(changedEntityIds);
282
+ const affectedOutputKeys = new Set(changedOutputKeys);
283
+ for (const key of /* @__PURE__ */ new Set([...previousState.idsByOutputKey.keys(), ...nextState.idsByOutputKey.keys()])) {
284
+ const previousIds = previousState.idsByOutputKey.get(key) ?? [];
285
+ const nextIds = nextState.idsByOutputKey.get(key) ?? [];
286
+ if (!areArraysEqual(previousIds, nextIds, Object.is) || previousIds.some((id) => changedEntityIdSet.has(id)) || nextIds.some((id) => changedEntityIdSet.has(id))) affectedOutputKeys.add(key);
287
+ }
288
+ const mapped = nextState.allIds.map((id) => getMappedMetadata(id, nextState.mappedById.get(id) ?? failInvariant("Expected value to be defined")));
289
+ state = nextState;
290
+ return {
291
+ affectedOutputKeys: Object.freeze([...affectedOutputKeys]),
292
+ changedEntityIds: Object.freeze(changedEntityIds),
293
+ changedOutputKeys: Object.freeze(changedOutputKeys),
294
+ fullFallback: true,
295
+ mapped: Object.freeze(mapped),
296
+ orderChanged
297
+ };
298
+ };
299
+ return Object.freeze({
300
+ getIdsForOutputKeys(keys) {
301
+ return Object.freeze(unique(keys.flatMap((key) => state.idsByOutputKey.get(key) ?? [])));
302
+ },
303
+ getIdsWithoutOutputs() {
304
+ work.unprojectedVisits += state.unprojectedIds.size;
305
+ return Object.freeze([...state.unprojectedIds].sort((left, right) => getDefined(state.indexById.get(left)) - getDefined(state.indexById.get(right))));
306
+ },
307
+ getWork: () => Object.freeze({ ...work }),
308
+ getSnapshot() {
309
+ return Object.freeze({
310
+ allIds: state.allIds,
311
+ byId: state.byId,
312
+ byOutputKey: state.byOutputKey
313
+ });
314
+ },
315
+ refresh(items, refreshOptions = {}) {
316
+ const { changedIds } = refreshOptions;
317
+ if (changedIds) {
318
+ if (items.length !== state.allIds.length) return replaceAll(items);
319
+ for (const id of changedIds) {
320
+ work.inputVisits += 1;
321
+ const index = state.indexById.get(id);
322
+ if (index === void 0 || options.getId(items[index]) !== id) return replaceAll(items);
323
+ }
324
+ } else {
325
+ work.inputVisits += items.length;
326
+ const nextIds = items.map(options.getId);
327
+ if (nextIds.length !== state.allIds.length || nextIds.some((id, index) => id !== state.allIds[index])) return replaceAll(items);
328
+ }
329
+ const candidateIndexes = /* @__PURE__ */ new Set();
330
+ if (changedIds) changedIds.forEach((id) => {
331
+ candidateIndexes.add(state.indexById.get(id) ?? failInvariant("Expected value to be defined"));
332
+ });
333
+ else if (refreshOptions.forceAll) items.forEach((_, index) => {
334
+ candidateIndexes.add(index);
335
+ });
336
+ else refreshOptions.forceIds?.forEach((id) => {
337
+ const index = state.indexById.get(id);
338
+ if (index !== void 0) candidateIndexes.add(index);
339
+ });
340
+ if (!changedIds) items.forEach((item, index) => {
341
+ work.inputVisits += 1;
342
+ if (!options.isItemEqual(state.inputs[index], item)) candidateIndexes.add(index);
343
+ });
344
+ if (candidateIndexes.size === 0) {
345
+ if (!changedIds) state.inputs = [...items];
346
+ return {
347
+ affectedOutputKeys: Object.freeze([]),
348
+ changedEntityIds: Object.freeze([]),
349
+ changedOutputKeys: Object.freeze([]),
350
+ fullFallback: false,
351
+ mapped: Object.freeze([]),
352
+ orderChanged: false
353
+ };
354
+ }
355
+ const candidates = [...candidateIndexes].sort((left, right) => left - right).map((index) => {
356
+ const id = state.allIds[index];
357
+ return {
358
+ id,
359
+ index,
360
+ next: mapItem(items[index]),
361
+ previous: state.mappedById.get(id) ?? failInvariant("Expected value to be defined")
362
+ };
363
+ });
364
+ const changedCandidates = candidates.filter(({ next, previous }) => {
365
+ const previousHasEntity = hasEntity(previous);
366
+ const nextHasEntity = hasEntity(next);
367
+ if (previousHasEntity !== nextHasEntity) return true;
368
+ if (previousHasEntity && nextHasEntity && !isEntityEqual(previous.entity, next.entity)) return true;
369
+ return !areArraysEqual(previous.outputs, next.outputs, (left, right) => left.key === right.key && options.isOutputEqual(left.value, right.value));
370
+ });
371
+ const mapped = Object.freeze(candidates.map(({ id, next }) => getMappedMetadata(id, next)));
372
+ if (changedCandidates.length === 0) {
373
+ if (changedIds) candidates.forEach(({ index }) => {
374
+ state.inputs[index] = items[index];
375
+ });
376
+ else state.inputs = [...items];
377
+ return {
378
+ affectedOutputKeys: Object.freeze([]),
379
+ changedEntityIds: Object.freeze([]),
380
+ changedOutputKeys: Object.freeze([]),
381
+ fullFallback: false,
382
+ mapped,
383
+ orderChanged: false
384
+ };
385
+ }
386
+ const changedEntityIds = [];
387
+ const dirtyOutputKeys = /* @__PURE__ */ new Set();
388
+ const entityChanges = /* @__PURE__ */ new Map();
389
+ let entityCount = state.byId.size;
390
+ const membershipChanges = /* @__PURE__ */ new Map();
391
+ const nextMappedById = new Map(changedCandidates.map(({ id, next }) => [id, next]));
392
+ for (const { id, next, previous } of changedCandidates) {
393
+ const previousHasEntity = hasEntity(previous);
394
+ const nextHasEntity = hasEntity(next);
395
+ if (previousHasEntity !== nextHasEntity || previousHasEntity && nextHasEntity && !isEntityEqual(previous.entity, next.entity)) {
396
+ changedEntityIds.push(id);
397
+ work.entityCopies += 1;
398
+ entityChanges.set(id, nextHasEntity ? next.entity : void 0);
399
+ entityCount += Number(nextHasEntity) - Number(previousHasEntity);
400
+ }
401
+ for (const key of previous.outputsByKey.keys()) {
402
+ work.outputCandidateVisits += 1;
403
+ dirtyOutputKeys.add(key);
404
+ if (next.outputsByKey.has(key)) continue;
405
+ const changes = membershipChanges.get(key) ?? /* @__PURE__ */ new Map();
406
+ changes.set(id, false);
407
+ membershipChanges.set(key, changes);
408
+ }
409
+ for (const key of next.outputsByKey.keys()) {
410
+ if (previous.outputsByKey.has(key)) continue;
411
+ work.outputCandidateVisits += 1;
412
+ dirtyOutputKeys.add(key);
413
+ const changes = membershipChanges.get(key) ?? /* @__PURE__ */ new Map();
414
+ changes.set(id, true);
415
+ membershipChanges.set(key, changes);
416
+ }
417
+ }
418
+ const nextIdsByOutputKey = /* @__PURE__ */ new Map();
419
+ const nextOutputValuesByKey = /* @__PURE__ */ new Map();
420
+ const changedOutputKeys = [];
421
+ dirtyOutputKeys.forEach((key) => {
422
+ const changes = membershipChanges.get(key);
423
+ let ids = state.idsByOutputKey.get(key) ?? [];
424
+ if (changes) {
425
+ ids = ids.filter((id) => changes.get(id) !== false);
426
+ changes.forEach((included, id) => {
427
+ if (included) ids.push(id);
428
+ });
429
+ ids.sort((left, right) => (state.indexById.get(left) ?? failInvariant("Expected value to be defined")) - (state.indexById.get(right) ?? failInvariant("Expected value to be defined")));
430
+ }
431
+ nextIdsByOutputKey.set(key, ids);
432
+ const nextValues = ids.flatMap((id) => {
433
+ const values = (nextMappedById.get(id) ?? state.mappedById.get(id) ?? failInvariant("Expected value to be defined")).outputsByKey.get(key) ?? EMPTY_OUTPUTS;
434
+ work.outputVisits += values.length;
435
+ return values;
436
+ });
437
+ const previousValues = state.byOutputKey[key] ?? EMPTY_OUTPUTS;
438
+ if (areArraysEqual(previousValues, nextValues, options.isOutputEqual)) return;
439
+ changedOutputKeys.push(key);
440
+ nextOutputValuesByKey.set(key, nextValues.length > 0 ? Object.freeze(nextValues) : void 0);
441
+ });
442
+ if (changedIds) candidates.forEach(({ index }) => {
443
+ state.inputs[index] = items[index];
444
+ });
445
+ else state.inputs = [...items];
446
+ if (entityChanges.size > 0) state.byId = createReadonlyEntityMap(state.entityRecord.publish(entityChanges), state.allIds, entityCount);
447
+ nextIdsByOutputKey.forEach((ids, key) => {
448
+ if (ids.length === 0) state.idsByOutputKey.delete(key);
449
+ else state.idsByOutputKey.set(key, ids);
450
+ });
451
+ changedCandidates.forEach(({ id, next }) => {
452
+ state.mappedById.set(id, next);
453
+ if (next.outputs.length === 0) state.unprojectedIds.add(id);
454
+ else state.unprojectedIds.delete(id);
455
+ });
456
+ state.byOutputKey = state.outputRecord.publish(nextOutputValuesByKey);
457
+ return {
458
+ affectedOutputKeys: Object.freeze([...dirtyOutputKeys]),
459
+ changedEntityIds: Object.freeze(changedEntityIds),
460
+ changedOutputKeys: Object.freeze(changedOutputKeys),
461
+ fullFallback: false,
462
+ mapped,
463
+ orderChanged: false
464
+ };
465
+ }
466
+ });
467
+ };
468
+ //#endregion
469
+ //#region src/annotations/store.ts
470
+ const authoredPreview = (editor) => {
471
+ const view = readAuthoredView(editor);
472
+ return view && "preview" in view ? view.preview : null;
473
+ };
474
+ const EMPTY_METRICS = Object.freeze({
475
+ annotationResolveCount: 0,
476
+ annotationSubscriberWakeCount: 0,
477
+ changedAnnotationCount: 0,
478
+ fullFallbackCount: 0,
479
+ recomputeCount: 0
480
+ });
481
+ const assertUniqueAnnotationIds = (annotations) => {
482
+ const ids = /* @__PURE__ */ new Set();
483
+ for (const annotation of annotations) {
484
+ if (ids.has(annotation.id)) throw new Error(`Annotation IDs must be unique: "${annotation.id}".`);
485
+ ids.add(annotation.id);
486
+ }
487
+ };
488
+ const INVALID_ANNOTATION_RANGE_ERROR = /Cannot project a range outside the committed snapshot|Point offset .* is outside text bounds/;
489
+ const projectAnnotationRange = (editor, range) => {
490
+ try {
491
+ return projectRange(editor, range);
492
+ } catch (error) {
493
+ if (error instanceof Error && INVALID_ANNOTATION_RANGE_ERROR.test(error.message)) return null;
494
+ throw error;
495
+ }
496
+ };
497
+ const shouldRefreshForEditorChange = (change) => !change || change.changed.hasAny("document") || change.changed.hasAny("marks");
498
+ const areAnnotationInputsEqual = (left, right) => left.id === right.id && left.anchor === right.anchor && areMappedViewDataEqual(left.data, right.data);
499
+ const areResolvedAnnotationsEqual = (left, right) => left.id === right.id && RangeApi.equals(left.range, right.range) && areMappedViewDataEqual(left.data, right.data);
500
+ const createPliteAnnotationStoreInternal = (editorInput, source, options, dormant) => {
501
+ const editor = editorInput;
502
+ const getAnnotations = typeof source === "function" ? source : () => source;
503
+ const faultBoundary = createViewSourceFaultBoundary({
504
+ id: options.id ?? "annotations",
505
+ onError: options.onError
506
+ });
507
+ let mappedResolveCount = 0;
508
+ const createMappedSource = (annotations) => createStableIdMappedSource(annotations, {
509
+ getId: (annotation) => annotation.id,
510
+ isEntityEqual: areResolvedAnnotationsEqual,
511
+ isItemEqual: areAnnotationInputsEqual,
512
+ isOutputEqual: Object.is,
513
+ map: (annotation) => {
514
+ mappedResolveCount += 1;
515
+ const resolvedRange = annotation.anchor.resolve(editor);
516
+ const mappedRange = resolvedRange ? projectAnnotationRange(editor, resolvedRange) : null;
517
+ const range = mappedRange ? resolvedRange : null;
518
+ return {
519
+ entity: Object.freeze({
520
+ data: annotation.data,
521
+ id: annotation.id,
522
+ range
523
+ }),
524
+ outputs: mappedRange?.map((segment) => ({
525
+ key: segment.key,
526
+ value: true
527
+ })) ?? []
528
+ };
529
+ }
530
+ });
531
+ const initialAnnotationsResult = dormant ? {
532
+ ok: true,
533
+ value: []
534
+ } : faultBoundary.run("read", getAnnotations);
535
+ if (initialAnnotationsResult.ok) assertUniqueAnnotationIds(initialAnnotationsResult.value);
536
+ const initialMappedResult = initialAnnotationsResult.ok ? faultBoundary.run("resolve", () => createMappedSource(initialAnnotationsResult.value)) : { ok: false };
537
+ if (!initialMappedResult.ok) mappedResolveCount = 0;
538
+ const mappedSource = initialMappedResult.ok ? initialMappedResult.value : createMappedSource([]);
539
+ let currentAnnotations = initialMappedResult.ok && initialAnnotationsResult.ok ? initialAnnotationsResult.value : null;
540
+ const toSnapshot = () => {
541
+ const snapshot = mappedSource.getSnapshot();
542
+ return Object.freeze({
543
+ allIds: snapshot.allIds,
544
+ byId: snapshot.byId
545
+ });
546
+ };
547
+ const annotationsStore = createMappedViewStoreKernel(toSnapshot(), editor);
548
+ const changeListeners = /* @__PURE__ */ new Set();
549
+ let metrics = Object.freeze({
550
+ ...EMPTY_METRICS,
551
+ annotationResolveCount: mappedResolveCount
552
+ });
553
+ let activated = !dormant;
554
+ let destroyed = false;
555
+ let subscriberCount = 0;
556
+ let lastSnapshot = dormant ? null : editor.read.runtime.snapshot();
557
+ let lastProjection = dormant ? void 0 : authoredPreview(editor);
558
+ const refreshCandidates = (candidateIds = null, forceAll = candidateIds === null, reason = "refresh") => {
559
+ const annotationsResult = faultBoundary.run("read", getAnnotations);
560
+ if (!annotationsResult.ok) return;
561
+ if (reason !== "editor" || annotationsResult.value !== currentAnnotations) assertUniqueAnnotationIds(annotationsResult.value);
562
+ const previousResolveCount = mappedResolveCount;
563
+ const mappedResult = faultBoundary.run("resolve", () => mappedSource.refresh(annotationsResult.value, { ...reason === "editor" && candidateIds && annotationsResult.value === currentAnnotations ? { changedIds: candidateIds } : {
564
+ forceAll,
565
+ forceIds: candidateIds ?? void 0
566
+ } }));
567
+ if (!mappedResult.ok) return;
568
+ currentAnnotations = annotationsResult.value;
569
+ lastSnapshot = editor.read.runtime.snapshot();
570
+ lastProjection = authoredPreview(editor);
571
+ const changedIds = mappedResult.value.changedEntityIds;
572
+ const changed = changedIds.length > 0 || mappedResult.value.orderChanged || mappedResult.value.affectedOutputKeys.length > 0;
573
+ const subscriberWakeCount = changed ? annotationsStore.subscriberCount() + changeListeners.size + annotationsStore.countKeySubscribers(changedIds) : 0;
574
+ metrics = Object.freeze({
575
+ ...metrics,
576
+ annotationResolveCount: metrics.annotationResolveCount + (mappedResolveCount - previousResolveCount),
577
+ annotationSubscriberWakeCount: metrics.annotationSubscriberWakeCount + subscriberWakeCount,
578
+ changedAnnotationCount: metrics.changedAnnotationCount + changedIds.length,
579
+ fullFallbackCount: metrics.fullFallbackCount + (mappedResult.value.fullFallback || forceAll ? 1 : 0),
580
+ recomputeCount: metrics.recomputeCount + (changed ? 1 : 0)
581
+ });
582
+ if (changed) {
583
+ const change = Object.freeze({
584
+ ids: Object.freeze([...changedIds]),
585
+ nodeKeys: Object.freeze(mappedResult.value.affectedOutputKeys.map((key) => key)),
586
+ reason
587
+ });
588
+ annotationsStore.publish(toSnapshot(), changedIds);
589
+ notifyObservers(editor, changeListeners, "commit-listener", (listener) => listener(change));
590
+ }
591
+ };
592
+ const ensureFresh = () => {
593
+ if (!activated || destroyed) return;
594
+ const snapshot = editor.read.runtime.snapshot();
595
+ if (snapshot.children !== lastSnapshot?.children || snapshot.index !== lastSnapshot?.index || authoredPreview(editor) !== lastProjection) refreshCandidates(null, true, "editor");
596
+ };
597
+ const subscribeToEditor = () => {
598
+ const unsubscribeCommit = editor.subscribeCommit((change) => {
599
+ if (destroyed || !shouldRefreshForEditorChange(change)) return;
600
+ if (authoredPreview(editor) !== lastProjection) {
601
+ refreshCandidates(null, true, "editor");
602
+ return;
603
+ }
604
+ const candidateIds = change ? Array.from(/* @__PURE__ */ new Set([...mappedSource.getIdsForOutputKeys(change.changed.nodeKeysAll("decoration")), ...change.changed.hasAny("document") ? mappedSource.getIdsWithoutOutputs() : []])) : null;
605
+ if (candidateIds && candidateIds.length === 0) {
606
+ lastSnapshot = editor.read.runtime.snapshot();
607
+ lastProjection = authoredPreview(editor);
608
+ return;
609
+ }
610
+ refreshCandidates(candidateIds, candidateIds === null, "editor");
611
+ });
612
+ const unsubscribeView = subscribeEditorViewState(editor, (change) => {
613
+ if (destroyed || change !== "authored") return;
614
+ ensureFresh();
615
+ });
616
+ return () => {
617
+ unsubscribeCommit();
618
+ unsubscribeView();
619
+ };
620
+ };
621
+ let unsubscribeEditor = null;
622
+ const observe = (subscribe) => {
623
+ if (destroyed) return () => {};
624
+ ensureFresh();
625
+ const unsubscribe = subscribe();
626
+ subscriberCount += 1;
627
+ if (activated && subscriberCount === 1) unsubscribeEditor = subscribeToEditor();
628
+ let subscribed = true;
629
+ return () => {
630
+ if (!subscribed) return;
631
+ subscribed = false;
632
+ unsubscribe();
633
+ subscriberCount -= 1;
634
+ if (subscriberCount === 0) {
635
+ unsubscribeEditor?.();
636
+ unsubscribeEditor = null;
637
+ }
638
+ };
639
+ };
640
+ const refresh = (refreshOptions = {}) => {
641
+ if (!activated || destroyed || refreshOptions.ids?.length === 0) return;
642
+ faultBoundary.activate();
643
+ ensureFresh();
644
+ refreshCandidates(refreshOptions.ids ?? null, refreshOptions.ids === void 0, refreshOptions.reason ?? "refresh");
645
+ };
646
+ const store = {
647
+ getAnnotation: (id) => {
648
+ ensureFresh();
649
+ return annotationsStore.getSnapshot().byId.get(id) ?? null;
650
+ },
651
+ getAnnotationsAt: (nodeKey) => {
652
+ ensureFresh();
653
+ return Object.freeze(mappedSource.getIdsForOutputKeys([nodeKey]).flatMap((id) => annotationsStore.getSnapshot().byId.get(id) ?? []));
654
+ },
655
+ getSnapshot: () => {
656
+ ensureFresh();
657
+ return annotationsStore.getSnapshot();
658
+ },
659
+ refresh,
660
+ subscribe: (listener) => observe(() => annotationsStore.subscribe(listener)),
661
+ subscribeAnnotation: (id, listener) => observe(() => annotationsStore.subscribeKey(id, listener)),
662
+ subscribeChanges: (listener) => observe(() => {
663
+ changeListeners.add(listener);
664
+ return () => {
665
+ changeListeners.delete(listener);
666
+ };
667
+ })
668
+ };
669
+ const owner = {
670
+ activate() {
671
+ if (activated || destroyed) return;
672
+ activated = true;
673
+ refreshCandidates(null, true);
674
+ if (subscriberCount > 0) unsubscribeEditor = subscribeToEditor();
675
+ },
676
+ destroy() {
677
+ if (destroyed) return;
678
+ destroyed = true;
679
+ unsubscribeEditor?.();
680
+ unsubscribeEditor = null;
681
+ changeListeners.clear();
682
+ annotationsStore.destroy();
683
+ },
684
+ getMetrics: () => metrics,
685
+ store
686
+ };
687
+ Object.freeze(store);
688
+ Object.freeze(owner);
689
+ registerAnnotationStoreMetrics(store, owner.getMetrics);
690
+ return owner;
691
+ };
692
+ /** Read a lazy view index; editor observation lasts only while subscribed. */
693
+ const createAnnotationStore = (editor, source, options = {}) => {
694
+ const owner = createPliteAnnotationStoreInternal(editor, source, options, false);
695
+ const store = Object.freeze({
696
+ ...owner.store,
697
+ destroy: owner.destroy
698
+ });
699
+ registerAnnotationStoreMetrics(store, owner.getMetrics);
700
+ return store;
701
+ };
702
+ const createDormantPliteAnnotationStoreOwner = (editor, source, options = {}) => createPliteAnnotationStoreInternal(editor, source, options, true);
703
+ //#endregion
704
+ export { createDormantPliteAnnotationStoreOwner as n, createAnnotationStore as t };