@rowsncolumns/y-spreadsheet 16.1.0 → 17.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/Readme.md +21 -6
  2. package/dist/cjs/helpers-v5.d.ts +11 -11
  3. package/dist/cjs/helpers-v5.d.ts.map +1 -1
  4. package/dist/cjs/helpers-v5.js +46 -33
  5. package/dist/cjs/helpers.d.ts +17 -19
  6. package/dist/cjs/helpers.d.ts.map +1 -1
  7. package/dist/cjs/helpers.js +89 -86
  8. package/dist/cjs/observables.d.ts +7 -7
  9. package/dist/cjs/observables.d.ts.map +1 -1
  10. package/dist/cjs/observables.js +34 -46
  11. package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -1
  12. package/dist/cjs/types.d.ts +96 -19
  13. package/dist/cjs/types.d.ts.map +1 -1
  14. package/dist/cjs/use-yspreadsheet-v2.d.ts +11 -10
  15. package/dist/cjs/use-yspreadsheet-v2.d.ts.map +1 -1
  16. package/dist/cjs/use-yspreadsheet-v2.js +79 -90
  17. package/dist/cjs/use-yspreadsheet.d.ts +6 -6
  18. package/dist/cjs/use-yspreadsheet.d.ts.map +1 -1
  19. package/dist/cjs/use-yspreadsheet.js +38 -74
  20. package/dist/cjs/yjs-runtime.js +5 -5
  21. package/dist/cjs/ynodes.d.ts +61 -0
  22. package/dist/cjs/ynodes.d.ts.map +1 -0
  23. package/dist/cjs/ynodes.js +224 -0
  24. package/dist/esm/helpers-v5.d.ts +11 -11
  25. package/dist/esm/helpers-v5.d.ts.map +1 -1
  26. package/dist/esm/helpers-v5.js +46 -33
  27. package/dist/esm/helpers.d.ts +17 -19
  28. package/dist/esm/helpers.d.ts.map +1 -1
  29. package/dist/esm/helpers.js +90 -87
  30. package/dist/esm/observables.d.ts +7 -7
  31. package/dist/esm/observables.d.ts.map +1 -1
  32. package/dist/esm/observables.js +21 -25
  33. package/dist/esm/tsconfig.esm.tsbuildinfo +1 -1
  34. package/dist/esm/types.d.ts +96 -19
  35. package/dist/esm/types.d.ts.map +1 -1
  36. package/dist/esm/use-yspreadsheet-v2.d.ts +11 -10
  37. package/dist/esm/use-yspreadsheet-v2.d.ts.map +1 -1
  38. package/dist/esm/use-yspreadsheet-v2.js +76 -88
  39. package/dist/esm/use-yspreadsheet.d.ts +6 -6
  40. package/dist/esm/use-yspreadsheet.d.ts.map +1 -1
  41. package/dist/esm/use-yspreadsheet.js +17 -43
  42. package/dist/esm/yjs-runtime.js +5 -5
  43. package/dist/esm/ynodes.d.ts +61 -0
  44. package/dist/esm/ynodes.d.ts.map +1 -0
  45. package/dist/esm/ynodes.js +146 -0
  46. package/package.json +9 -8
@@ -5,17 +5,17 @@ import { useCallback, useMemo, useRef, useState } from "react";
5
5
  import { flushSync } from "react-dom";
6
6
  import { addSheetDataPatches, addSheetDataPatchesV5, addSheetDataPatchesV3, applyMapPatches, createCellReaderV5, createCellKeyV3, filterErrorCellPatches, getCellDataFromYSheetData, mergeErrorEffectiveValueIntoCellData, processSheetDataEvents, shouldPersistErrorCellPatch, processSheetDataEventsV3, processSheetDataChangesV5, readStyleOverlayV5, sheetDataV2ToV3, sheetDataV3ToV2, sheetDataV5ToV2, updateArrayType, validateSheets, } from "./helpers";
7
7
  import { resolveYjsRuntime } from "./yjs-runtime";
8
+ import { arrayJson, changedKeys as changedKeysOf, childDelta, listDelete, mapJson, } from "./ynodes";
8
9
  /**
9
10
  * Convert Y.js events to SheetDataEvent format for incremental processing
11
+ * (read inside the observer: a delta is computed from its transaction)
10
12
  */
11
13
  const convertToSheetDataEvents = (events, yjs) => {
12
- return events.map((event) => {
13
- const isYArrayEvent = event instanceof yjs.YArrayEvent;
14
+ return events.map(({ event, path }) => {
15
+ const isYArrayEvent = yjs.isArray(event.target);
14
16
  return {
15
- path: event.path,
16
- delta: isYArrayEvent
17
- ? event.changes.delta
18
- : undefined,
17
+ path,
18
+ delta: isYArrayEvent ? childDelta(event) : undefined,
19
19
  isYArrayEvent,
20
20
  };
21
21
  });
@@ -26,13 +26,13 @@ const convertToSheetDataEvents = (events, yjs) => {
26
26
  * before sheetData observer has updated React state.
27
27
  */
28
28
  const getUserEnteredValueFromYDoc = (ySheetData, sheetId, rowIndex, columnIndex) => {
29
- const sheet = ySheetData.get(String(sheetId));
29
+ const sheet = ySheetData.getAttr(String(sheetId));
30
30
  if (!sheet || rowIndex >= sheet.length)
31
31
  return undefined;
32
32
  const row = sheet.get(rowIndex);
33
33
  if (!row)
34
34
  return undefined;
35
- const values = row.get("values");
35
+ const values = row.getAttr("values");
36
36
  if (!values || columnIndex >= values.length)
37
37
  return undefined;
38
38
  const cell = values.get(columnIndex);
@@ -46,7 +46,7 @@ const getUserEnteredValueFromYDoc = (ySheetData, sheetId, rowIndex, columnIndex)
46
46
  */
47
47
  const getUserEnteredValueFromYDocV3 = (ySheetDataV3, sheetId, rowIndex, columnIndex) => {
48
48
  const cellKey = createCellKeyV3(sheetId, rowIndex, columnIndex);
49
- const cellDataV3 = ySheetDataV3.get(cellKey);
49
+ const cellDataV3 = ySheetDataV3.getAttr(cellKey);
50
50
  return getExtendedValueFormula(getCellUserEnteredValue(cellDataV3?.value));
51
51
  };
52
52
  import { createDeepObservable, createObservable, createSheetDataObservable, getPatchDeltasFromEvent, } from "./observables";
@@ -90,14 +90,14 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
90
90
  useIsomorphicLayoutEffect(() => {
91
91
  isLeaderRef.current = isLeader;
92
92
  }, [isLeader]);
93
- const ySheetDataV2 = useMemo(() => doc.getMap("sheetDataV2"), [doc]);
93
+ const ySheetDataV2 = useMemo(() => doc.get("sheetDataV2"), [doc]);
94
94
  // V3: Flat map structure - Map<cellKey, CellDataV3>
95
95
  // cellKey format: `${sheetId}!${A1Address}` (e.g., "1!A1", "2!B5")
96
- const ySheetDataV3 = useMemo(() => doc.getMap("sheetDataV3"), [doc]);
96
+ const ySheetDataV3 = useMemo(() => doc.get("sheetDataV3"), [doc]);
97
97
  // Doc metadata - used as fallback for version when prop is undefined
98
- const yDocMeta = useMemo(() => doc.getMap("docMeta"), [doc]);
98
+ const yDocMeta = useMemo(() => doc.get("docMeta"), [doc]);
99
99
  // V5: the engine marks the doc in `docMeta`; read live (the marker may arrive with a sync)
100
- const isV5Doc = useCallback(() => sheetDataVersion === "v5" || yDocMeta.get("sheetDataVersion") === "v5", [sheetDataVersion, yDocMeta]);
100
+ const isV5Doc = useCallback(() => sheetDataVersion === "v5" || yDocMeta.getAttr("sheetDataVersion") === "v5", [sheetDataVersion, yDocMeta]);
101
101
  // V5: the composed style plane, folded on a full read and on a remote style
102
102
  // change, updated in place by this hook's own writes
103
103
  const stylesV5Ref = useRef(null);
@@ -106,9 +106,9 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
106
106
  stylesV5Ref.current = readStyleOverlayV5(doc);
107
107
  return sheetDataV5ToV2(doc, stylesV5Ref.current);
108
108
  }, [doc]);
109
- const yDisableRecalc = useMemo(() => doc.getMap("disableRecalc"), [doc]);
109
+ const yDisableRecalc = useMemo(() => doc.get("disableRecalc"), [doc]);
110
110
  // Recalc cells
111
- const yRecalcCells = useMemo(() => doc.getArray("recalcCells"), [doc]);
111
+ const yRecalcCells = useMemo(() => doc.get("recalcCells"), [doc]);
112
112
  // Make sure initialSheets is always filled
113
113
  const getInitialSheets = useCallback(() => {
114
114
  if (initialSheets.length) {
@@ -117,10 +117,10 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
117
117
  return [createNewSheet(1, "Sheet1")];
118
118
  }, [initialSheets]);
119
119
  // cellxfs
120
- const yCellXfs = useMemo(() => doc.getMap("cellXfs"), [doc]);
120
+ const yCellXfs = useMemo(() => doc.get("cellXfs"), [doc]);
121
121
  // Shared strings - always use Map for new storage, Array kept for migration
122
- const ySharedStringsArray = useMemo(() => doc.getArray("sharedStrings"), [doc]);
123
- const ySharedStringsMap = useMemo(() => doc.getMap("sharedStringsMap"), [doc]);
122
+ const ySharedStringsArray = useMemo(() => doc.get("sharedStrings"), [doc]);
123
+ const ySharedStringsMap = useMemo(() => doc.get("sharedStringsMap"), [doc]);
124
124
  // Track if initial sync has changed active sheet
125
125
  const isActiveSheetChanged = useRef(false);
126
126
  /**
@@ -151,60 +151,51 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
151
151
  return newMap;
152
152
  });
153
153
  }, [onChangeSharedStrings]);
154
+ // Each root with the kind it is read as (a root carries no type on the wire)
154
155
  const documentMap = useMemo(() => {
155
156
  const entries = [
156
- ["sheets", [doc.getArray("sheets"), onChangeSheets]],
157
- ["tables", [doc.getArray("tables"), onChangeTables]],
158
- [
159
- "embeds",
160
- [doc.getArray("embeds"), onChangeEmbeds],
161
- ],
162
- [
163
- "charts",
164
- [doc.getArray("charts"), onChangeCharts],
165
- ],
157
+ ["sheets", [doc.get("sheets"), onChangeSheets, "array"]],
158
+ ["tables", [doc.get("tables"), onChangeTables, "array"]],
159
+ ["embeds", [doc.get("embeds"), onChangeEmbeds, "array"]],
160
+ ["charts", [doc.get("charts"), onChangeCharts, "array"]],
166
161
  [
167
162
  "conditionalFormats",
168
163
  [
169
- doc.getArray("conditionalFormats"),
164
+ doc.get("conditionalFormats"),
170
165
  onChangeConditionalFormats,
166
+ "array",
171
167
  ],
172
168
  ],
173
169
  [
174
170
  "dataValidations",
175
- [
176
- doc.getArray("dataValidations"),
177
- onChangeDataValidations,
178
- ],
171
+ [doc.get("dataValidations"), onChangeDataValidations, "array"],
179
172
  ],
180
173
  [
181
174
  "pivotTables",
182
- [doc.getArray("pivotTables"), onChangePivotTables],
175
+ [doc.get("pivotTables"), onChangePivotTables, "array"],
183
176
  ],
184
177
  [
185
178
  "namedRanges",
186
- [doc.getArray("namedRanges"), onChangeNamedRanges],
179
+ [doc.get("namedRanges"), onChangeNamedRanges, "array"],
187
180
  ],
188
181
  [
189
182
  "protectedRanges",
190
- [
191
- doc.getArray("protectedRanges"),
192
- onChangeProtectedRanges,
193
- ],
194
- ],
195
- [
196
- "citations",
197
- [doc.getArray("citations"), onChangeCitations],
183
+ [doc.get("protectedRanges"), onChangeProtectedRanges, "array"],
198
184
  ],
185
+ ["citations", [doc.get("citations"), onChangeCitations, "array"]],
199
186
  [
200
187
  "sharedStrings",
201
- [ySharedStringsMap, handleSharedStringsMapChange],
188
+ [ySharedStringsMap, handleSharedStringsMapChange, "map"],
202
189
  ],
203
190
  ...(supportLegacySharedStringsArray
204
191
  ? [
205
192
  [
206
193
  "sharedStringsArray",
207
- [ySharedStringsArray, handleSharedStringsArrayChange],
194
+ [
195
+ ySharedStringsArray,
196
+ handleSharedStringsArrayChange,
197
+ "array",
198
+ ],
208
199
  ],
209
200
  ]
210
201
  : []),
@@ -230,8 +221,7 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
230
221
  ]);
231
222
  // Get backlog of recalc cells from backend
232
223
  const getBacklog = useCallback(() => {
233
- return yRecalcCells
234
- .toArray()
224
+ return yRecalcCells.toArray()
235
225
  .flatMap((entry) => entry.patches)
236
226
  .filter(([, , source]) => source === "backend" || source === "agent");
237
227
  }, [yRecalcCells]);
@@ -320,7 +310,7 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
320
310
  // Both formats are now supported simultaneously via handleSharedStringsMapChange
321
311
  // and handleSharedStringsArrayChange callbacks.
322
312
  const arrayData = ySharedStringsArray.toArray();
323
- const mapData = ySharedStringsMap.toJSON();
313
+ const mapData = mapJson(ySharedStringsMap, yjs);
324
314
  const hasArrayData = arrayData.length > 0;
325
315
  const isMapEmpty = Object.keys(mapData).length === 0;
326
316
  // Migrate if array has data and map is empty
@@ -328,15 +318,15 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
328
318
  doc.transact(() => {
329
319
  // Convert array to map with string keys
330
320
  arrayData.forEach((value, index) => {
331
- ySharedStringsMap.set(String(index), value);
321
+ ySharedStringsMap.setAttr(String(index), value);
332
322
  });
333
323
  // Optional: Clear the old array to save space
334
324
  // Uncomment if you want to remove old data after migration
335
325
  // ySharedStringsArray.delete(0, ySharedStringsArray.length);
336
326
  }, "migration");
337
327
  }
338
- for (const [mappingKey, [ydoc, callback]] of documentMap.entries()) {
339
- let value = ydoc.toJSON();
328
+ for (const [mappingKey, [ydoc, callback, kind]] of documentMap.entries()) {
329
+ let value = kind === "map" ? mapJson(ydoc, yjs) : arrayJson(ydoc, yjs);
340
330
  if (mappingKey === "sheets") {
341
331
  const sheets = (Array.isArray(value) && value.length
342
332
  ? validateSheets(value)
@@ -365,9 +355,9 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
365
355
  else if (useV3) {
366
356
  // Check if we need to migrate from V2 to V3
367
357
  // Use prop if provided, otherwise fall back to yDocMeta for backwards compatibility
368
- const resolvedVersion = sheetDataVersion ?? yDocMeta.get("sheetDataVersion");
358
+ const resolvedVersion = sheetDataVersion ?? yDocMeta.getAttr("sheetDataVersion");
369
359
  if (resolvedVersion !== "v3") {
370
- const v2Data = ySheetDataV2.toJSON();
360
+ const v2Data = mapJson(ySheetDataV2, yjs);
371
361
  const hasV2Data = Object.keys(v2Data).length > 0;
372
362
  if (hasV2Data) {
373
363
  // Migrate V2 data to V3
@@ -375,12 +365,12 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
375
365
  const v3Data = sheetDataV2ToV3(v2Data);
376
366
  // Add all V3 entries to the Y.Map
377
367
  for (const [key, cellData] of v3Data.entries()) {
378
- ySheetDataV3.set(key, cellData);
368
+ ySheetDataV3.setAttr(key, cellData);
379
369
  }
380
370
  // Optionally clear V2 data after migration
381
371
  if (deleteV2AfterMigration) {
382
- for (const sheetId of ySheetDataV2.keys()) {
383
- ySheetDataV2.delete(sheetId);
372
+ for (const sheetId of ySheetDataV2.attrKeys()) {
373
+ ySheetDataV2.deleteAttr(sheetId);
384
374
  }
385
375
  }
386
376
  }, "migrate-v2-to-v3");
@@ -393,15 +383,15 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
393
383
  }
394
384
  }
395
385
  // V3: Convert flat map to V2 format for React state
396
- const v3Data = ySheetDataV3.toJSON();
386
+ const v3Data = mapJson(ySheetDataV3, yjs);
397
387
  const v3Map = new Map(Object.entries(v3Data));
398
388
  onChangeSheetData?.(sheetDataV3ToV2(v3Map));
399
389
  }
400
390
  else {
401
- onChangeSheetData?.(ySheetDataV2.toJSON());
391
+ onChangeSheetData?.(mapJson(ySheetDataV2, yjs));
402
392
  }
403
393
  // Cellxfs
404
- const cellXfs = new Map(Object.entries(yCellXfs.toJSON() ?? {}));
394
+ const cellXfs = new Map(Object.entries(mapJson(yCellXfs, yjs) ?? {}));
405
395
  onChangeCellXfs?.(cellXfs);
406
396
  }, [
407
397
  documentMap,
@@ -422,6 +412,7 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
422
412
  deleteV2AfterMigration,
423
413
  isV5Doc,
424
414
  readSheetDataV5,
415
+ yjs,
425
416
  ]);
426
417
  /**
427
418
  * Replay the backend/agent recalc backlog into the local graph — and, on
@@ -437,7 +428,7 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
437
428
  syncRecalcCells(backlog, "backend");
438
429
  if (isLeaderRef.current) {
439
430
  doc.transact(() => {
440
- yRecalcCells.delete(0, yRecalcCells.length);
431
+ listDelete(yRecalcCells, 0, yRecalcCells.length);
441
432
  }, origin);
442
433
  }
443
434
  }, [getBacklog, syncRecalcCells, doc, yRecalcCells]);
@@ -499,7 +490,7 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
499
490
  if (useV3)
500
491
  return; // Skip V2 observer in V3 mode
501
492
  // Subscribe to sheet data
502
- const subscription = createSheetDataObservable(ySheetDataV2).subscribe((events) => {
493
+ const subscription = createSheetDataObservable(ySheetDataV2, yjs).subscribe((events) => {
503
494
  /**
504
495
  * Disable recalc is a flag that is set ONLY locally
505
496
  * when a calculation completes
@@ -508,14 +499,14 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
508
499
  * and updating it, which is not necessary
509
500
  */
510
501
  if (events.length) {
511
- const origin = events?.[0]?.transaction?.origin;
502
+ const origin = events?.[0]?.event.transaction?.origin;
512
503
  if (origin !== "local") {
513
504
  // Convert Y.js events to SheetDataEvent format and apply incremental updates
514
505
  const sheetDataEvents = convertToSheetDataEvents(events, yjs);
515
506
  onChangeSheetData((prevSheetData) => {
516
- const result = processSheetDataEvents(sheetDataEvents, prevSheetData, ySheetDataV2);
507
+ const result = processSheetDataEvents(sheetDataEvents, prevSheetData, ySheetDataV2, yjs);
517
508
  // Fall back to full serialization only if incremental update fails
518
- return result ?? ySheetDataV2.toJSON();
509
+ return result ?? mapJson(ySheetDataV2, yjs);
519
510
  });
520
511
  }
521
512
  }
@@ -523,7 +514,7 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
523
514
  return () => {
524
515
  subscription.unsubscribe();
525
516
  };
526
- }, [onChangeSheetData, ySheetDataV2, useV3]);
517
+ }, [onChangeSheetData, ySheetDataV2, useV3, yjs]);
527
518
  // Only for sheet Data (V3 mode)
528
519
  useIsomorphicLayoutEffect(() => {
529
520
  if (!useV3)
@@ -531,12 +522,9 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
531
522
  // Subscribe to V3 sheet data (flat Map)
532
523
  const callback = (event) => {
533
524
  if (event.transaction.origin !== "local") {
534
- // Extract changes synchronously - Yjs requires accessing event.changes
535
- // within the event handler, not in a deferred callback like setState
536
- const changedKeys = new Map();
537
- event.changes.keys.forEach((change, key) => {
538
- changedKeys.set(key, { action: change.action });
539
- });
525
+ // Extract changes synchronously - they are read from the document as
526
+ // the event leaves it, not in a deferred callback like setState
527
+ const changedKeys = changedKeysOf(event);
540
528
  // Now we can safely use the extracted data in the async setState callback
541
529
  onChangeSheetData((prevSheetData) => {
542
530
  const result = processSheetDataEventsV3(changedKeys, prevSheetData, ySheetDataV3);
@@ -544,7 +532,7 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
544
532
  return result;
545
533
  }
546
534
  // Fall back to full conversion
547
- const v3Data = ySheetDataV3.toJSON();
535
+ const v3Data = mapJson(ySheetDataV3, yjs);
548
536
  const v3Map = new Map(Object.entries(v3Data));
549
537
  return sheetDataV3ToV2(v3Map);
550
538
  });
@@ -554,7 +542,7 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
554
542
  return () => {
555
543
  ySheetDataV3.unobserve(callback);
556
544
  };
557
- }, [onChangeSheetData, ySheetDataV3, useV3]);
545
+ }, [onChangeSheetData, ySheetDataV3, useV3, yjs]);
558
546
  // Only for sheet Data (V5 docs): `rncCells`, `rncNotes`, the style planes and
559
547
  // every sheet's id arrays. A change of an id array, a style plane (or of
560
548
  // `docMeta`): full re-read; a cell or note change alone is applied
@@ -598,7 +586,7 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
598
586
  // Subscribe to sheet data
599
587
  const callback = (event) => {
600
588
  if (event.transaction.origin !== "local") {
601
- const cellXfs = new Map(Object.entries(yCellXfs.toJSON() ?? {}));
589
+ const cellXfs = new Map(Object.entries(mapJson(yCellXfs, yjs) ?? {}));
602
590
  onChangeCellXfs?.(cellXfs);
603
591
  }
604
592
  };
@@ -606,17 +594,17 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
606
594
  return () => {
607
595
  yCellXfs.unobserve(callback);
608
596
  };
609
- }, [onChangeCellXfs, yCellXfs]);
597
+ }, [onChangeCellXfs, yCellXfs, yjs]);
610
598
  // All others
611
599
  useIsomorphicLayoutEffect(() => {
612
600
  const subs = [];
613
- for (const [mappingKey, [ydoc, callback]] of documentMap.entries()) {
601
+ for (const [mappingKey, [ydoc, callback, kind]] of documentMap.entries()) {
614
602
  // Only observe Arrays (shared strings Map is handled separately if needed)
615
- if (ydoc instanceof yjs.Array) {
616
- const subscription = createDeepObservable(ydoc).subscribe((events) => {
617
- for (const event of events) {
603
+ if (kind === "array") {
604
+ const subscription = createDeepObservable(ydoc, yjs).subscribe((events) => {
605
+ for (const { event } of events) {
618
606
  if (event.transaction.origin !== "local") {
619
- let json = ydoc.toJSON();
607
+ let json = arrayJson(ydoc, yjs);
620
608
  if (Array.isArray(json) &&
621
609
  json.length &&
622
610
  json[0]?.userId) {
@@ -628,11 +616,11 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
628
616
  });
629
617
  subs.push(subscription);
630
618
  }
631
- else if (ydoc instanceof yjs.Map && mappingKey === "sharedStrings") {
619
+ else if (kind === "map" && mappingKey === "sharedStrings") {
632
620
  // Handle shared strings Map observation
633
621
  const callback_map = (event) => {
634
622
  if (event.transaction.origin !== "local") {
635
- const json = ydoc.toJSON();
623
+ const json = mapJson(ydoc, yjs);
636
624
  const sharedStringsMap = new Map(Object.entries(json ?? {}));
637
625
  callback?.(sharedStringsMap);
638
626
  }
@@ -646,7 +634,7 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
646
634
  return () => {
647
635
  subs.forEach((sub) => sub.unsubscribe());
648
636
  };
649
- }, [documentMap]);
637
+ }, [documentMap, yjs]);
650
638
  // Only for recalc cells
651
639
  useIsomorphicLayoutEffect(() => {
652
640
  if (!synced) {
@@ -721,7 +709,7 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
721
709
  const currentCellData = readV5
722
710
  ? readV5(Number(patchSheetId), Number(rowIndex), Number(columnIndex))
723
711
  : useV3
724
- ? ySheetDataV3.get(createCellKeyV3(Number(patchSheetId), Number(rowIndex), Number(columnIndex)))?.value
712
+ ? ySheetDataV3.getAttr(createCellKeyV3(Number(patchSheetId), Number(rowIndex), Number(columnIndex)))?.value
725
713
  : getCellDataFromYSheetData(ySheetDataV2, patchSheetId, Number(rowIndex), Number(columnIndex));
726
714
  const incomingCellData = errorPatch.value;
727
715
  if (!shouldPersistErrorCellPatch(currentCellData, incomingCellData)) {
@@ -774,14 +762,14 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
774
762
  const patches = patch.cellXfs?.[patchKey];
775
763
  applyMapPatches(yCellXfs, patches);
776
764
  }
777
- for (const [mappingKey, [ydoc]] of documentMap.entries()) {
765
+ for (const [mappingKey, [ydoc, , kind]] of documentMap.entries()) {
778
766
  if (patch?.[mappingKey]) {
779
767
  const patches = patch[mappingKey]?.[patchKey];
780
768
  // Handle shared strings Map (always use Map now)
781
- if (mappingKey === "sharedStrings" && ydoc instanceof yjs.Map) {
769
+ if (mappingKey === "sharedStrings" && kind === "map") {
782
770
  applyMapPatches(ydoc, patches);
783
771
  }
784
- else if (ydoc instanceof yjs.Array) {
772
+ else if (kind === "array") {
785
773
  // Check if we are updating sheets
786
774
  if (mappingKey === "sheets" && ydoc.length === 0) {
787
775
  // Add initial sheets
@@ -795,7 +783,7 @@ export const useYSpreadsheetV2 = ({ onChangeSheetData, onChangeSheets, onChangeT
795
783
  if (patch.recalcCells?.[type]) {
796
784
  if (isLeader) {
797
785
  // Remove old cells
798
- yRecalcCells.delete(0, yRecalcCells.length);
786
+ listDelete(yRecalcCells, 0, yRecalcCells.length);
799
787
  }
800
788
  yRecalcCells.push([
801
789
  {
@@ -3,19 +3,19 @@ import type { CellInterface } from "@rowsncolumns/grid";
3
3
  import type { CellData, Collaborator, ConditionalFormatRule, DataValidationRuleRecord, EmbeddedChart, EmbeddedObject, NamedRange, ProtectedRange, Sheet, TableView } from "@rowsncolumns/spreadsheet";
4
4
  import type { CalculateNowOptions, CalculationOperation, HistoryType, SheetData, SpreadsheetPatch } from "@rowsncolumns/spreadsheet-state";
5
5
  import type { Patch } from "immer";
6
- import type * as Y from "yjs";
7
- import type { CollabProviderLike, YjsRuntime } from "./types";
6
+ import type { CollabProviderLike, YDoc, YjsRuntime } from "./types";
8
7
  export type useYSpreadsheetProps<T extends CellData, S extends Sheet, C extends EmbeddedChart, O extends EmbeddedObject> = {
9
8
  userId: string | number;
10
9
  title: string;
11
10
  sheetId: number;
12
11
  activeCell?: CellInterface;
13
12
  provider?: HocuspocusProvider | CollabProviderLike | any;
14
- doc: Y.Doc;
13
+ /** The `@y/y` 14 document (its roots are read with `doc.get(name)`). */
14
+ doc: YDoc;
15
15
  /**
16
- * The Yjs implementation `doc` belongs to, e.g. `import * as Y from "yjs"`.
17
- * Falls back to the runtime registered with `setDefaultYjsRuntime`; with
18
- * neither, the hook throws (see `YjsRuntime`).
16
+ * The host's node operations and update functions for `doc` (see
17
+ * `YjsRuntime`). Falls back to the runtime registered with
18
+ * `setDefaultYjsRuntime`; with neither, the hook throws.
19
19
  */
20
20
  yjs?: YjsRuntime;
21
21
  calculateNow(options?: CalculateNowOptions): void;
@@ -1 +1 @@
1
- {"version":3,"file":"use-yspreadsheet.d.ts","sourceRoot":"","sources":["../../use-yspreadsheet.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC/D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EACV,QAAQ,EACR,YAAY,EACZ,qBAAqB,EACrB,wBAAwB,EACxB,aAAa,EACb,cAAc,EACd,UAAU,EACV,cAAc,EACd,KAAK,EACL,SAAS,EACV,MAAM,2BAA2B,CAAC;AAKnC,OAAO,KAAK,EACV,mBAAmB,EACnB,oBAAoB,EACpB,WAAW,EAEX,SAAS,EACT,gBAAgB,EACjB,MAAM,iCAAiC,CAAC;AACzC,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,OAAO,CAAC;AAInC,OAAO,KAAK,KAAK,CAAC,MAAM,KAAK,CAAC;AAE9B,OAAO,KAAK,EACV,kBAAkB,EAIlB,UAAU,EACX,MAAM,S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AAuB,CAAC,EAAE,KAAK,CAAC,QAAQ,CACtC,KAAK,CAAC,cAAc,CAAC,cAAc,EAAE,CAAC,CACvC,CAAC;IACF,0BAA0B,CAAC,EAAE,KAAK,CAAC,QAAQ,CACzC,KAAK,CAAC,cAAc,CAAC,qBAAqB,EAAE,CAAC,CAC9C,CAAC;IACF,uBAAuB,CAAC,EAAE,KAAK,CAAC,QAAQ,CACtC,KAAK,CAAC,cAAc,CAAC,wBAAwB,EAAE,CAAC,CACjD,CAAC;IACF,kBAAkB,EAAE,CAAC,SAAS,EAAE,oBAAoB,KAAK,IAAI,CAAC;IAC9D,OAAO,CAAC,CAAC,GAAG,EAAE,OAAO,GAAG,IAAI,CAAC;IAC7B,mBAAmB,CAAC,IAAI,IAAI,CAAC;CAC9B,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,eAAe,GAC1B,CAAC,SAAS,QAAQ,EAClB,CAAC,SAAS,KAAK,EACf,CAAC,SAAS,aAAa,EACvB,CAAC,SAAS,cAAc,EACxB,0SAoBC,oBAAoB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;gCA0QpB,CACP,KAAK,EAAE,gBAAgB,CAAC,KAAK,CAAC,EAC9B,IAAI,CAAC,EAAE,WAAW,GAAG,SAAS,CAC/B,EAAE;;;CAwDR,CAAC"}
@@ -3,6 +3,7 @@ import { applyPatches } from "immer";
3
3
  import uniqBy from "lodash/uniqBy";
4
4
  import { useCallback, useMemo, useRef, useState } from "react";
5
5
  import { resolveYjsRuntime } from "./yjs-runtime";
6
+ import { insertedValues } from "./ynodes";
6
7
  const getStateVector = (doc, yjs) => yjs.encodeStateVector(doc);
7
8
  // Function to get updates between two state vectors
8
9
  const getUpdatesBetween = (doc, stateVector1, stateVector2, yjs) => {
@@ -22,52 +23,31 @@ export const useYSpreadsheet = ({ onChangeSheetData, onChangeSheets, onChangeTab
22
23
  const previousStateVectorRef = useRef(undefined);
23
24
  const currentStateVectorRef = useRef(undefined);
24
25
  // Recalc cells
25
- const yRecalcCells = useMemo(() => doc.getArray("recalcCells"), [doc]);
26
- const yDisableRecalc = doc.getMap("disableRecalc");
26
+ const yRecalcCells = useMemo(() => doc.get("recalcCells"), [doc]);
27
+ const yDisableRecalc = doc.get("disableRecalc");
27
28
  // Counter
28
29
  // Create a counter to keep track of when the last sync was done
29
30
  const docSyncCounterRef = useRef(new Map());
30
31
  // Create a doc map
31
32
  const docMap = useMemo(() => {
32
33
  const docMap = new Map([
33
- [
34
- "sheets",
35
- [doc.getArray("sheets"), onChangeSheets, "sheetId"],
36
- ],
37
- [
38
- "sheetData",
39
- [doc.getArray("sheetData"), onChangeSheetData],
40
- ],
41
- ["tables", [doc.getArray("tables"), onChangeTables, "id"]],
42
- ["embeds", [doc.getArray("embeds"), onChangeEmbeds, "id"]],
43
- ["charts", [doc.getArray("charts"), onChangeCharts, "id"]],
34
+ ["sheets", [doc.get("sheets"), onChangeSheets, "sheetId"]],
35
+ ["sheetData", [doc.get("sheetData"), onChangeSheetData]],
36
+ ["tables", [doc.get("tables"), onChangeTables, "id"]],
37
+ ["embeds", [doc.get("embeds"), onChangeEmbeds, "id"]],
38
+ ["charts", [doc.get("charts"), onChangeCharts, "id"]],
44
39
  [
45
40
  "conditionalFormats",
46
- [
47
- doc.getArray("conditionalFormats"),
48
- onChangeConditionalFormats,
49
- "id",
50
- ],
41
+ [doc.get("conditionalFormats"), onChangeConditionalFormats, "id"],
51
42
  ],
52
43
  [
53
44
  "dataValidations",
54
- [
55
- doc.getArray("dataValidations"),
56
- onChangeDataValidations,
57
- "id",
58
- ],
59
- ],
60
- [
61
- "namedRanges",
62
- [doc.getArray("namedRanges"), onChangeNamedRanges, "id"],
45
+ [doc.get("dataValidations"), onChangeDataValidations, "id"],
63
46
  ],
47
+ ["namedRanges", [doc.get("namedRanges"), onChangeNamedRanges, "id"]],
64
48
  [
65
49
  "protectedRanges",
66
- [
67
- doc.getArray("protectedRanges"),
68
- onChangeProtectedRanges,
69
- "id",
70
- ],
50
+ [doc.get("protectedRanges"), onChangeProtectedRanges, "id"],
71
51
  ],
72
52
  ]);
73
53
  return docMap;
@@ -111,7 +91,7 @@ export const useYSpreadsheet = ({ onChangeSheetData, onChangeSheets, onChangeTab
111
91
  };
112
92
  for (const [mappingKey, [_, setStateFn, idKey]] of docMap) {
113
93
  const startCounter = docSyncCounterRef.current.get(mappingKey) ?? 0;
114
- const [patches, endCounter] = getInitialPatches(syncedDoc.getArray(mappingKey), startCounter);
94
+ const [patches, endCounter] = getInitialPatches(syncedDoc.get(mappingKey), startCounter);
115
95
  if (patches.length) {
116
96
  docSyncCounterRef.current.set(mappingKey, endCounter);
117
97
  setStateFn?.((prev) => {
@@ -194,15 +174,9 @@ export const useYSpreadsheet = ({ onChangeSheetData, onChangeSheets, onChangeTab
194
174
  const getPatchDeltasFromEvent = (event) => {
195
175
  const patches = [];
196
176
  if (event.transaction.origin !== "locale") {
197
- for (const changes of event.changes.delta) {
198
- for (const type in changes) {
199
- if (type === "insert" && changes[type] !== undefined) {
200
- for (const { patches: userPatches } of changes[type]) {
201
- for (const patch of userPatches) {
202
- patches.push(patch);
203
- }
204
- }
205
- }
177
+ for (const { patches: userPatches } of insertedValues(event)) {
178
+ for (const patch of userPatches) {
179
+ patches.push(patch);
206
180
  }
207
181
  }
208
182
  }
@@ -229,7 +203,7 @@ export const useYSpreadsheet = ({ onChangeSheetData, onChangeSheets, onChangeTab
229
203
  for (const [_, [doc, setStateFn]] of docMap) {
230
204
  const callback = (event) => {
231
205
  const patches = getPatchDeltasFromEvent(event);
232
- const disableRecalc = yDisableRecalc.get("disableRecalc");
206
+ const disableRecalc = yDisableRecalc.getAttr("disableRecalc");
233
207
  if (event.transaction.origin !== "local" && disableRecalc !== true) {
234
208
  if (patches.length) {
235
209
  setStateFn?.((prev) => {
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * y-spreadsheet does not import a Yjs implementation: every helper and hook
3
- * takes the namespace of the implementation the document belongs to (`yjs`,
4
- * or a yjs-13-compatible layer over `@y/y` 14). A host that always works with
5
- * one implementation can register it once here instead of passing it on every
6
- * call; a runtime passed to a call wins over the registered one.
3
+ * takes the host's node operations for the `@y/y` 14 document it works on
4
+ * (`YjsRuntime`). A host that always works with one runtime can register it
5
+ * once here instead of passing it on every call; a runtime passed to a call
6
+ * wins over the registered one.
7
7
  */
8
8
  let defaultYjsRuntime;
9
9
  /** Registers (or, with `undefined`, clears) the runtime used when a call passes none. */
@@ -14,7 +14,7 @@ export const setDefaultYjsRuntime = (runtime) => {
14
14
  export const resolveYjsRuntime = (runtime) => {
15
15
  const resolved = runtime ?? defaultYjsRuntime;
16
16
  if (!resolved) {
17
- throw new Error("@rowsncolumns/y-spreadsheet: no Yjs runtime. Pass `yjs` (the namespace of the Yjs implementation the document belongs to, e.g. `import * as Y from \"yjs\"`) or register one with setDefaultYjsRuntime(Y). The package does not import yjs itself.");
17
+ throw new Error("@rowsncolumns/y-spreadsheet: no Yjs runtime. Pass `yjs` (the host's YjsRuntime for its @y/y 14 documents: createMap / createArray / isMap / isArray, getPathTo, Doc and the update functions) or register one with setDefaultYjsRuntime(runtime). The package does not import a Yjs implementation itself.");
18
18
  }
19
19
  return resolved;
20
20
  };