@w100n/documents 0.18.1 → 0.19.1

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.
@@ -40,10 +40,10 @@ import {
40
40
  import { getSchema } from "@tiptap/core";
41
41
  import { Transform } from "@tiptap/pm/transform";
42
42
  import { prosemirrorJSONToYXmlFragment, updateYFragment, yXmlFragmentToProseMirrorRootNode } from "@tiptap/y-tiptap";
43
- import * as Y2 from "yjs";
43
+ import * as Y3 from "yjs";
44
44
 
45
45
  // package.json
46
- var version = "0.18.1";
46
+ var version = "0.19.1";
47
47
 
48
48
  // src/sheets/model.ts
49
49
  var SheetRefusal = class extends Error {
@@ -56,8 +56,8 @@ var SheetRefusal = class extends Error {
56
56
  var counter = 0;
57
57
  var fresh = (prefix) => `${prefix}${Date.now().toString(36)}${(counter++).toString(36)}${Math.random().toString(36).slice(2, 6)}`;
58
58
  var numbered = (prefix, count) => Array.from({ length: count }, (_, i) => `${prefix}${i}`);
59
- function insert(list, at, count, prefix) {
60
- list.splice(at, 0, ...Array.from({ length: count }, () => fresh(prefix)));
59
+ function insert(list, at2, count, prefix) {
60
+ list.splice(at2, 0, ...Array.from({ length: count }, () => fresh(prefix)));
61
61
  }
62
62
  function move(list, from, count, to) {
63
63
  const taken = list.splice(from, count);
@@ -107,12 +107,12 @@ function encode(text, encoding, bom) {
107
107
  if (encoding === "utf-16le" || encoding === "utf-16be") {
108
108
  const out2 = new Uint8Array(text.length * 2 + (bom ? 2 : 0));
109
109
  const view = new DataView(out2.buffer);
110
- let at = 0;
110
+ let at2 = 0;
111
111
  if (bom) {
112
112
  view.setUint16(0, 65279, encoding === "utf-16le");
113
- at = 2;
113
+ at2 = 2;
114
114
  }
115
- for (let i = 0; i < text.length; i++) view.setUint16(at + i * 2, text.charCodeAt(i), encoding === "utf-16le");
115
+ for (let i = 0; i < text.length; i++) view.setUint16(at2 + i * 2, text.charCodeAt(i), encoding === "utf-16le");
116
116
  return out2;
117
117
  }
118
118
  const table = /* @__PURE__ */ new Map();
@@ -248,8 +248,8 @@ function writeCsv(original, model) {
248
248
  const r0 = rowFrom.get(lines2.rows[r]) ?? -1;
249
249
  const was = r0 >= 0 ? old[r0] : void 0;
250
250
  const line = cells[r] ?? {};
251
- const filled2 = Object.keys(line).map(Number).filter((c) => show(value(line[c])) !== "");
252
- let count = filled2.length ? Math.max(...filled2) + 1 : 0;
251
+ const filled3 = Object.keys(line).map(Number).filter((c) => show(value(line[c])) !== "");
252
+ let count = filled3.length ? Math.max(...filled3) + 1 : 0;
253
253
  if (was) for (let c0 = 0; c0 < was.length; c0++) count = Math.max(count, lines2.cols.indexOf(origin.cols[c0]) + 1);
254
254
  const fields = [];
255
255
  for (let c = 0; c < count; c++) {
@@ -685,8 +685,8 @@ var Styles = class {
685
685
  return index;
686
686
  }
687
687
  add(list, xml) {
688
- const at = this[list].indexOf(xml);
689
- if (at >= 0) return at;
688
+ const at2 = this[list].indexOf(xml);
689
+ if (at2 >= 0) return at2;
690
690
  this[list].push(xml);
691
691
  this.added = true;
692
692
  return this[list].length - 1;
@@ -765,8 +765,8 @@ var Styles = class {
765
765
  edits2.push([el.start, el.end, `${open} count="${lists[name].length}">${lists[name].join("")}</${el.name}>`]);
766
766
  } else {
767
767
  const after = root.kids.find((k) => order2.indexOf(this.bare(k.name)) > order2.indexOf(name));
768
- const at = after ? after.start : root.close;
769
- edits2.push([at, at, `<${p}${name} count="${lists[name].length}">${lists[name].join("")}</${p}${name}>`]);
768
+ const at2 = after ? after.start : root.close;
769
+ edits2.push([at2, at2, `<${p}${name} count="${lists[name].length}">${lists[name].join("")}</${p}${name}>`]);
770
770
  }
771
771
  }
772
772
  edits2.sort((x, y) => y[0] - x[0]);
@@ -868,7 +868,7 @@ function load(bytes) {
868
868
  if (state === "hidden") sheet.hidden = 1;
869
869
  if (state === "veryHidden") sheet.hidden = 2;
870
870
  const open = element(sxml, `${p}sheetData`);
871
- const bounds = open ? [open.start, open.open, open.close, open.end] : [sxml.length, sxml.length, sxml.length, sxml.length];
871
+ const bounds2 = open ? [open.start, open.open, open.close, open.end] : [sxml.length, sxml.length, sxml.length, sxml.length];
872
872
  const head = open ? sxml.slice(0, open.start) : sxml;
873
873
  const tail = open ? sxml.slice(open.end) : "";
874
874
  const format = /<(?:\w+:)?sheetFormatPr\b[^>]*>/.exec(head)?.[0];
@@ -908,13 +908,13 @@ function load(bytes) {
908
908
  let maxRow = -1, maxCol = -1;
909
909
  if (open && open.close > open.open) {
910
910
  const end = open.close;
911
- let at = open.open, row = -1, col = -1;
912
- while (at < end) {
913
- const lt = sxml.indexOf("<", at);
911
+ let at2 = open.open, row = -1, col = -1;
912
+ while (at2 < end) {
913
+ const lt = sxml.indexOf("<", at2);
914
914
  if (lt < 0 || lt >= end) break;
915
915
  const gt = sxml.indexOf(">", lt);
916
916
  if (sxml.charCodeAt(lt + 1) === 47) {
917
- at = gt + 1;
917
+ at2 = gt + 1;
918
918
  continue;
919
919
  }
920
920
  let j = lt + 1;
@@ -942,11 +942,11 @@ function load(bytes) {
942
942
  }
943
943
  if (Object.keys(rd).length) rowData[row] = rd;
944
944
  if (rd.h !== void 0 || rd.hd || rd.s) maxRow = Math.max(maxRow, row);
945
- at = gt + 1;
945
+ at2 = gt + 1;
946
946
  continue;
947
947
  }
948
948
  if (name !== "c") {
949
- at = gt + 1;
949
+ at2 = gt + 1;
950
950
  continue;
951
951
  }
952
952
  const ref = attr2(tag, "r");
@@ -1010,7 +1010,7 @@ function load(bytes) {
1010
1010
  }
1011
1011
  }
1012
1012
  cells.set(key(row, col), { start: lt, end: stop, shared });
1013
- at = stop;
1013
+ at2 = stop;
1014
1014
  }
1015
1015
  }
1016
1016
  for (const [r, c, si] of children) {
@@ -1091,7 +1091,7 @@ function load(bytes) {
1091
1091
  xml: sxml,
1092
1092
  p,
1093
1093
  rels: srels,
1094
- bounds,
1094
+ bounds: bounds2,
1095
1095
  rows,
1096
1096
  cells,
1097
1097
  cols,
@@ -1118,8 +1118,8 @@ function load(bytes) {
1118
1118
  if (Object.keys(notes).length) resources.push({ name: "SHEET_NOTE_PLUGIN", data: JSON.stringify(notes) });
1119
1119
  if (Object.keys(validations).length) resources.push({ name: "SHEET_DATA_VALIDATION_PLUGIN", data: JSON.stringify(validations) });
1120
1120
  if (Object.keys(filters).length) resources.push({ name: "SHEET_FILTER_PLUGIN", data: JSON.stringify(filters) });
1121
- const shown = entries[active];
1122
- if (shown?.sheet && book.sheetOrder.includes(`s${shown.sheetId}`)) model.active = `s${shown.sheetId}`;
1121
+ const shown2 = entries[active];
1122
+ if (shown2?.sheet && book.sheetOrder.includes(`s${shown2.sheetId}`)) model.active = `s${shown2.sheetId}`;
1123
1123
  return { model, book: { pack, part, xml, rels, styles, stylesPart: stylesPart ?? null, sheets, entries } };
1124
1124
  }
1125
1125
  var kinds = { whole: "whole", decimal: "decimal", list: "list", textLength: "textLength", custom: "custom" };
@@ -1287,14 +1287,14 @@ function place(xml, name, value2) {
1287
1287
  if (found) return xml.slice(0, found.start) + (value2 ?? "") + xml.slice(found.end);
1288
1288
  if (value2 === null) return xml;
1289
1289
  const rank = order.indexOf(name);
1290
- let at = -1;
1290
+ let at2 = -1;
1291
1291
  for (const later of order.slice(rank + 1)) {
1292
1292
  const f = find(xml, later);
1293
- if (f && (at < 0 || f.start < at)) at = f.start;
1293
+ if (f && (at2 < 0 || f.start < at2)) at2 = f.start;
1294
1294
  }
1295
- if (at < 0) at = xml.search(/<\/(?:\w+:)?worksheet>\s*$/);
1296
- if (at < 0) at = xml.length;
1297
- return xml.slice(0, at) + value2 + xml.slice(at);
1295
+ if (at2 < 0) at2 = xml.search(/<\/(?:\w+:)?worksheet>\s*$/);
1296
+ if (at2 < 0) at2 = xml.length;
1297
+ return xml.slice(0, at2) + value2 + xml.slice(at2);
1298
1298
  }
1299
1299
  function remapZone(xml, mine, rows, cols) {
1300
1300
  const ranges = (sqref) => boxes(sqref).map((b) => squeeze(b, rows.map, cols.map)).filter((b) => b !== null).map(span).join(" ");
@@ -1528,8 +1528,8 @@ function writeXlsx(original, model) {
1528
1528
  if (curRules && !same(rules.map(canonRule), oldRules.map(canonRule))) {
1529
1529
  changed = true;
1530
1530
  const known = new Map((rec?.validations ?? []).map((v, i) => [`dv${i}`, v]));
1531
- const shown = new Set(rules.map((r) => r.uid));
1532
- const hiddenRules = [...known].filter(([uid, v]) => !shown.has(uid) && !(rec && baseRules[rec.sid]?.some((r) => r.uid === uid)) && v).map(([, v]) => rows.moved || cols.moved ? remapZone(v, mine, rows, cols) : v);
1531
+ const shown2 = new Set(rules.map((r) => r.uid));
1532
+ const hiddenRules = [...known].filter(([uid, v]) => !shown2.has(uid) && !(rec && baseRules[rec.sid]?.some((r) => r.uid === uid)) && v).map(([, v]) => rows.moved || cols.moved ? remapZone(v, mine, rows, cols) : v);
1533
1533
  const list = [...hiddenRules, ...rules.map((r) => validationXml(p, r, known.get(r.uid)))].filter(Boolean);
1534
1534
  tail = place(tail, "dataValidations", list.length ? `<${p}dataValidations count="${list.length}">${list.join("")}</${p}dataValidations>` : null);
1535
1535
  }
@@ -1640,9 +1640,9 @@ function writeXlsx(original, model) {
1640
1640
  listed.push({ xml: tag, sheetId: s.sheetId, oldIndex: s.rec ? indexOf.get(s.sheetId) : -1 });
1641
1641
  }
1642
1642
  for (const { e, i } of nonSheets) {
1643
- let at = listed.findIndex((x) => x.oldIndex > i);
1644
- if (at < 0) at = listed.length;
1645
- listed.splice(at, 0, { xml: e.xml, sheetId: e.sheetId, oldIndex: i });
1643
+ let at2 = listed.findIndex((x) => x.oldIndex > i);
1644
+ if (at2 < 0) at2 = listed.length;
1645
+ listed.splice(at2, 0, { xml: e.xml, sheetId: e.sheetId, oldIndex: i });
1646
1646
  }
1647
1647
  wb = wb.replace(/(<(?:\w+:)?sheets\b[^>]*>)[\s\S]*?(<\/(?:\w+:)?sheets>)/, (_, a, b) => a + listed.map((x) => x.xml).join("") + b);
1648
1648
  const newIndex = new Map(listed.map((x, i) => [x.oldIndex, i]));
@@ -1668,9 +1668,9 @@ function writeXlsx(original, model) {
1668
1668
  for (const [from, to] of names) f = renamed(f, from, to);
1669
1669
  return `${tag}${escape(f)}</${p}definedName>`;
1670
1670
  });
1671
- for (const [sheetId, f] of filterNames) {
1671
+ for (const [sheetId2, f] of filterNames) {
1672
1672
  if (!f) continue;
1673
- const def = `<${wp}definedName name="_xlnm._FilterDatabase" localSheetId="${sheetIndex.get(sheetId)}" hidden="1">${escape(f)}</${wp}definedName>`;
1673
+ const def = `<${wp}definedName name="_xlnm._FilterDatabase" localSheetId="${sheetIndex.get(sheetId2)}" hidden="1">${escape(f)}</${wp}definedName>`;
1674
1674
  wb = /<(?:\w+:)?definedNames\b/.test(wb) ? wb.replace(/<\/(?:\w+:)?definedNames>/, (end) => def + end) : wb.replace(/<\/(?:\w+:)?sheets>/, (end) => `${end}<${wp}definedNames>${def}</${wp}definedNames>`);
1675
1675
  }
1676
1676
  wb = wb.replace(/<((?:\w+:)?)definedNames>\s*<\/\1definedNames>/, "");
@@ -1987,18 +1987,18 @@ function fill(doc, model) {
1987
1987
  const { cells, rowData, colData, merges, notes: kept } = pieces(sheets.get(sid));
1988
1988
  for (const [r, line] of Object.entries(sheet.cellData ?? {})) for (const [c, x] of Object.entries(line ?? {})) {
1989
1989
  if (!x) continue;
1990
- const at = spot(l.rows[+r], l.cols[+c]);
1990
+ const at2 = spot(l.rows[+r], l.cols[+c]);
1991
1991
  const out = {};
1992
1992
  if (x.f) {
1993
1993
  out.f = x.f;
1994
- values.set(`${sid}:${at}`, { v: x.v ?? null, t: x.t ?? null });
1994
+ values.set(`${sid}:${at2}`, { v: x.v ?? null, t: x.t ?? null });
1995
1995
  } else {
1996
1996
  if (x.v !== void 0 && x.v !== null) out.v = x.v;
1997
1997
  if (x.t) out.t = x.t;
1998
1998
  }
1999
1999
  if (x.p) out.p = x.p;
2000
2000
  if (typeof x.s === "string") out.s = x.s;
2001
- cells.set(at, out);
2001
+ cells.set(at2, out);
2002
2002
  }
2003
2003
  for (const [r, rd] of Object.entries(sheet.rowData ?? {})) if (rd) rowData.set(l.rows[+r], strip({ h: rd.h, hd: rd.hd, ia: rd.ia, s: typeof rd.s === "string" ? rd.s : void 0 }));
2004
2004
  for (const [c, cd] of Object.entries(sheet.columnData ?? {})) if (cd) colData.set(l.cols[+c], strip({ w: cd.w, hd: cd.hd, s: typeof cd.s === "string" ? cd.s : void 0 }));
@@ -2013,11 +2013,11 @@ function sheetOf(doc, sid, l) {
2013
2013
  const { cells, rowData, colData, merges } = pieces(m);
2014
2014
  const rows = new Map(l.rows.map((id, i) => [id, i])), cols = new Map(l.cols.map((id, i) => [id, i]));
2015
2015
  const cellData = {};
2016
- for (const [at, x] of cells) {
2017
- const [row, col] = at.split(":");
2016
+ for (const [at2, x] of cells) {
2017
+ const [row, col] = at2.split(":");
2018
2018
  const r = rows.get(row), c = cols.get(col);
2019
2019
  if (r === void 0 || c === void 0) continue;
2020
- const kept = x.f ? values.get(`${sid}:${at}`) : void 0;
2020
+ const kept = x.f ? values.get(`${sid}:${at2}`) : void 0;
2021
2021
  (cellData[r] ?? (cellData[r] = {}))[c] = kept ? { ...x, v: kept.v, t: kept.t } : { ...x };
2022
2022
  }
2023
2023
  const rowsOut = {}, colsOut = {};
@@ -2030,7 +2030,7 @@ function sheetOf(doc, sid, l) {
2030
2030
  }
2031
2031
  var notesOf = (m, l) => {
2032
2032
  const rows = new Map(l.rows.map((id, i) => [id, i])), cols = new Map(l.cols.map((id, i) => [id, i]));
2033
- return [...pieces(m).notes].map(([at, n]) => ({ ...n, row: rows.get(at.split(":")[0]), col: cols.get(at.split(":")[1]) })).filter((n) => n.row !== void 0 && n.col !== void 0);
2033
+ return [...pieces(m).notes].map(([at2, n]) => ({ ...n, row: rows.get(at2.split(":")[0]), col: cols.get(at2.split(":")[1]) })).filter((n) => n.row !== void 0 && n.col !== void 0);
2034
2034
  };
2035
2035
  function build(doc) {
2036
2036
  const { book, order: order2, sheets, styles, origin } = parts(doc);
@@ -2114,17 +2114,19 @@ function applyCells(doc, list, origin) {
2114
2114
  const [r, c] = cell(x.ref);
2115
2115
  if (!sid || r < 0) continue;
2116
2116
  const { rows, cols, cells } = pieces(sheets.get(sid));
2117
- if (r >= rows.length || c >= cols.length) continue;
2118
- const at = spot(rows.get(r), cols.get(c));
2117
+ if (r >= rows.length + 1e4 || c >= cols.length + 1e3) continue;
2118
+ if (r >= rows.length) rows.push(Array.from({ length: r + 1 - rows.length }, () => fresh("n")));
2119
+ if (c >= cols.length) cols.push(Array.from({ length: c + 1 - cols.length }, () => fresh("n")));
2120
+ const at2 = spot(rows.get(r), cols.get(c));
2119
2121
  const next = {};
2120
2122
  if (x.formula !== void 0) next.f = x.formula.startsWith("=") ? x.formula : `=${x.formula}`;
2121
2123
  else if (typeof x.value === "boolean") Object.assign(next, { v: x.value ? 1 : 0, t: 3 });
2122
2124
  else if (x.value !== void 0 && x.value !== null && x.value !== "") Object.assign(next, { v: x.value, t: typeof x.value === "number" ? 2 : 1 });
2123
- const s = cells.get(at)?.s;
2125
+ const s = cells.get(at2)?.s;
2124
2126
  if (s) next.s = s;
2125
- values.delete(`${sid}:${at}`);
2126
- if (Object.keys(next).length) cells.set(at, next);
2127
- else cells.delete(at);
2127
+ values.delete(`${sid}:${at2}`);
2128
+ if (Object.keys(next).length) cells.set(at2, next);
2129
+ else cells.delete(at2);
2128
2130
  done++;
2129
2131
  }
2130
2132
  }, origin);
@@ -2142,6 +2144,9 @@ var en = {
2142
2144
  loading: "Opening the sheet",
2143
2145
  failed: "This sheet could not be opened",
2144
2146
  retry: "Try again",
2147
+ fontSize: "Font size",
2148
+ smaller: "Smaller text",
2149
+ bigger: "Bigger text",
2145
2150
  undo: "Undo",
2146
2151
  redo: "Redo",
2147
2152
  bold: "Bold",
@@ -2215,6 +2220,9 @@ var pl = {
2215
2220
  loading: "Otwieranie arkusza",
2216
2221
  failed: "Nie uda\u0142o si\u0119 otworzy\u0107 tego arkusza",
2217
2222
  retry: "Spr\xF3buj ponownie",
2223
+ fontSize: "Rozmiar czcionki",
2224
+ smaller: "Mniejszy tekst",
2225
+ bigger: "Wi\u0119kszy tekst",
2218
2226
  undo: "Cofnij",
2219
2227
  redo: "Pon\xF3w",
2220
2228
  bold: "Pogrubienie",
@@ -2288,6 +2296,9 @@ var uk = {
2288
2296
  loading: "\u0412\u0456\u0434\u043A\u0440\u0438\u0432\u0430\u0454\u043C\u043E \u0442\u0430\u0431\u043B\u0438\u0446\u044E",
2289
2297
  failed: "\u041D\u0435 \u0432\u0434\u0430\u043B\u043E\u0441\u044F \u0432\u0456\u0434\u043A\u0440\u0438\u0442\u0438 \u0446\u044E \u0442\u0430\u0431\u043B\u0438\u0446\u044E",
2290
2298
  retry: "\u0421\u043F\u0440\u043E\u0431\u0443\u0432\u0430\u0442\u0438 \u0449\u0435",
2299
+ fontSize: "\u0420\u043E\u0437\u043C\u0456\u0440 \u0448\u0440\u0438\u0444\u0442\u0443",
2300
+ smaller: "\u041C\u0435\u043D\u0448\u0438\u0439 \u0442\u0435\u043A\u0441\u0442",
2301
+ bigger: "\u0411\u0456\u043B\u044C\u0448\u0438\u0439 \u0442\u0435\u043A\u0441\u0442",
2291
2302
  undo: "\u0412\u0456\u0434\u043C\u0456\u043D\u0438\u0442\u0438",
2292
2303
  redo: "\u041F\u043E\u0432\u0442\u043E\u0440\u0438\u0442\u0438",
2293
2304
  bold: "\u0416\u0438\u0440\u043D\u0438\u0439",
@@ -2353,25 +2364,107 @@ var uk = {
2353
2364
  };
2354
2365
  var sheetTexts = { en, pl, uk };
2355
2366
 
2367
+ // src/sheets/agent.ts
2368
+ import * as Y2 from "yjs";
2369
+ var sheetId = (doc, name) => {
2370
+ const { order: order2, sheets } = parts(doc);
2371
+ return order2.toArray().find((id) => sheets.get(id)?.get("name") === name);
2372
+ };
2373
+ function at(doc, x) {
2374
+ const sid = sheetId(doc, x.sheet);
2375
+ const [r, c] = cell(x.ref);
2376
+ if (!sid || r < 0) return void 0;
2377
+ const { rows, cols, cells } = pieces(parts(doc).sheets.get(sid));
2378
+ return r < rows.length && c < cols.length ? cells.get(spot(rows.get(r), cols.get(c))) : void 0;
2379
+ }
2380
+ var filled = (x) => !!x?.f || x?.v !== void 0 && x.v !== null && x.v !== "";
2381
+ var bare = (x) => x?.f ? `=${x.f}` : filled(x) ? canon([x.v, x.t ?? null]) : "";
2382
+ var shown = (x) => x?.f ?? (filled(x) ? String(x.v) : "");
2383
+ function clashes(doc, kind, seen, list) {
2384
+ const old = new Y2.Doc();
2385
+ fill(old, readSheet(seen, kind));
2386
+ const out = list.filter((x) => sheetId(old, x.sheet) && bare(at(old, x)) !== bare(at(doc, x))).map((x) => ({ sheet: x.sheet, ref: x.ref, now: shown(at(doc, x)) }));
2387
+ old.destroy();
2388
+ return out;
2389
+ }
2390
+ function appendRows(doc, sheet, lines2, origin) {
2391
+ const sid = sheetId(doc, sheet);
2392
+ if (!sid || !lines2.length) return null;
2393
+ const { rows, cells } = pieces(parts(doc).sheets.get(sid));
2394
+ const index = new Map(rows.toArray().map((id, i) => [id, i]));
2395
+ let last = -1;
2396
+ for (const [key2, x] of cells) if (filled(x)) last = Math.max(last, index.get(key2.split(":")[0]) ?? -1);
2397
+ const writes = lines2.flatMap((line, i) => line.map((x, c) => ({ sheet, ref: a1(last + 1 + i, c), ...typeof x === "string" && x.startsWith("=") ? { formula: x } : { value: x } })));
2398
+ applyCells(doc, writes.filter((w) => "formula" in w || w.value !== null && w.value !== ""), origin);
2399
+ return `${a1(last + 1, 0)}:${a1(last + lines2.length, Math.max(1, ...lines2.map((l) => l.length)) - 1)}`;
2400
+ }
2401
+ async function compute(doc, origin) {
2402
+ const { sheets, values } = parts(doc);
2403
+ const model = build(doc);
2404
+ const formulas2 = [];
2405
+ for (const sid of model.book.sheetOrder) {
2406
+ const l = model.lines[sid];
2407
+ const rows = new Map(l.rows.map((id, i) => [id, i])), cols = new Map(l.cols.map((id, i) => [id, i]));
2408
+ for (const [key2, x] of pieces(sheets.get(sid)).cells) {
2409
+ const [r, c] = key2.split(":");
2410
+ if (x.f && rows.has(r) && cols.has(c)) formulas2.push([sid, key2, rows.get(r), cols.get(c)]);
2411
+ }
2412
+ }
2413
+ if (!formulas2.length) return 0;
2414
+ const [{ LocaleType, LogLevel, Univer }, { FUniver }, { UniverFormulaEnginePlugin }, { UniverSheetsPlugin }, { UniverSheetsFormulaPlugin }] = await Promise.all([
2415
+ import("@univerjs/core"),
2416
+ import("@univerjs/core/facade"),
2417
+ import("@univerjs/engine-formula"),
2418
+ import("@univerjs/sheets"),
2419
+ import("@univerjs/sheets-formula"),
2420
+ import("@univerjs/engine-formula/facade"),
2421
+ import("@univerjs/sheets/facade")
2422
+ ]);
2423
+ const univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: {} }, logLevel: LogLevel.ERROR });
2424
+ univer.registerPlugin(UniverFormulaEnginePlugin);
2425
+ univer.registerPlugin(UniverSheetsPlugin);
2426
+ univer.registerPlugin(UniverSheetsFormulaPlugin);
2427
+ try {
2428
+ const api = FUniver.newAPI(univer);
2429
+ const wb = api.createWorkbook(structuredClone(model.book));
2430
+ const applied = api.getFormula().onCalculationResultApplied(1e4);
2431
+ api.getFormula().executeCalculation();
2432
+ await applied;
2433
+ let changed = 0;
2434
+ doc.transact(() => {
2435
+ for (const [sid, key2, r, c] of formulas2) {
2436
+ const got = wb.getSheetBySheetId(sid)?.getRange(r, c).getCellData();
2437
+ const next = { v: got?.v ?? null, t: got?.t ?? null };
2438
+ if (canon(values.get(`${sid}:${key2}`)) === canon(next)) continue;
2439
+ values.set(`${sid}:${key2}`, next);
2440
+ changed++;
2441
+ }
2442
+ }, origin);
2443
+ return changed;
2444
+ } finally {
2445
+ univer.dispose();
2446
+ }
2447
+ }
2448
+
2356
2449
  // src/collab.ts
2357
2450
  var ours = "w100n-collab";
2358
2451
  var schemas = /* @__PURE__ */ new Map();
2359
2452
  var schemaOf = (kind) => schemas.get(kind) ?? schemas.set(kind, getSchema(kit(kind, texts.en))).get(kind);
2360
2453
  var parse2 = async (kind, bytes) => kind === "docx" ? (await readDocx(bytes)).doc : fromMarkdown(new TextDecoder().decode(bytes)).doc;
2361
2454
  var edits = (tr) => tr.changedParentTypes.has(tr.doc.get("default")) || tr.changedParentTypes.has(tr.doc.get("book")) || tr.changedParentTypes.has(tr.doc.get("setup"));
2362
- var filled = (doc) => doc.getXmlFragment("default").length > 0 || doc.getMap("book").size > 0;
2455
+ var filled2 = (doc) => doc.getXmlFragment("default").length > 0 || doc.getMap("book").size > 0;
2363
2456
  function seed(doc, kind, bytes, json) {
2364
- if (filled(doc)) return false;
2365
- const fixed = new Y2.Doc();
2457
+ if (filled2(doc)) return false;
2458
+ const fixed = new Y3.Doc();
2366
2459
  fixed.clientID = fnv(new Uint8Array(bytes), fnv(new TextEncoder().encode(`${version}:${kind}`)));
2367
2460
  if (kind === "xlsx" || kind === "csv") fill(fixed, readSheet(bytes, kind));
2368
2461
  else prosemirrorJSONToYXmlFragment(schemaOf(kind), json, fixed.getXmlFragment("default"));
2369
- Y2.applyUpdate(doc, Y2.encodeStateAsUpdate(fixed), ours);
2462
+ Y3.applyUpdate(doc, Y3.encodeStateAsUpdate(fixed), ours);
2370
2463
  return true;
2371
2464
  }
2372
2465
  function follow(doc, author) {
2373
2466
  const editors = doc.getMap("editors");
2374
- const before = (tr) => tr.meta.set("fresh", !filled(doc));
2467
+ const before = (tr) => tr.meta.set("fresh", !filled2(doc));
2375
2468
  const after = (tr) => {
2376
2469
  const who = !tr.meta.get("fresh") && edits(tr) ? author(tr.origin) : null;
2377
2470
  if (who && !editors.has(who.id)) doc.transact(() => editors.set(who.id, who), ours);
@@ -2399,13 +2492,57 @@ function applyText(doc, kind, changes, origin) {
2399
2492
  return false;
2400
2493
  });
2401
2494
  if (hits.length !== 1) throw new Refusal(`${hits.length ? "more than once" : "not"} in the document: ${c.find.slice(0, 80)}`);
2402
- const [at] = hits;
2403
- if (c.replace) step.replaceWith(at, at + c.find.length, schema.text(c.replace, step.doc.resolve(at + 1).marks()));
2404
- else step.delete(at, at + c.find.length);
2495
+ const [at2] = hits;
2496
+ if (c.replace) step.replaceWith(at2, at2 + c.find.length, schema.text(c.replace, step.doc.resolve(at2 + 1).marks()));
2497
+ else step.delete(at2, at2 + c.find.length);
2405
2498
  }
2406
2499
  updateYFragment({ transact: (run) => doc.transact(run, origin) }, fragment, step.doc, { mapping: /* @__PURE__ */ new Map(), isOMark: /* @__PURE__ */ new Map() });
2407
2500
  return changes.length;
2408
2501
  }
2502
+ var bounds = (doc, heading) => {
2503
+ const want = heading.trim().replace(/^#+\s*/, "").toLowerCase();
2504
+ let at2 = -1, level = 0, end = doc.content.size, pos = 0;
2505
+ doc.forEach((node, offset) => {
2506
+ if (end !== doc.content.size) return;
2507
+ if (at2 < 0 && node.type.name === "heading" && node.textContent.trim().toLowerCase() === want) [at2, level, pos] = [offset, node.attrs.level, offset + node.nodeSize];
2508
+ else if (at2 >= 0 && node.type.name === "heading" && node.attrs.level <= level) end = offset;
2509
+ });
2510
+ if (at2 < 0) throw new Refusal(`no heading ${heading.slice(0, 80)} in the document`);
2511
+ return { from: pos, to: end };
2512
+ };
2513
+ function applySteps(doc, kind, steps, seen, origin) {
2514
+ const schema = schemaOf(kind);
2515
+ const fragment = doc.getXmlFragment("default");
2516
+ const step = new Transform(yXmlFragmentToProseMirrorRootNode(fragment, schema));
2517
+ const old = seen && schema.nodeFromJSON(seen);
2518
+ const clashes2 = [];
2519
+ let done = 0, span2 = null;
2520
+ for (const s of steps) {
2521
+ const blocks2 = schema.nodeFromJSON(fromMarkdown(s.text).doc).content;
2522
+ const range = s.op === "append" ? { from: step.doc.content.size, to: step.doc.content.size } : s.op === "all" ? { from: 0, to: step.doc.content.size } : bounds(step.doc, s.heading ?? "");
2523
+ const was = !old || s.op === "append" ? null : s.op === "all" ? { from: 0, to: old.content.size } : (() => {
2524
+ try {
2525
+ return bounds(old, s.heading ?? "");
2526
+ } catch {
2527
+ return null;
2528
+ }
2529
+ })();
2530
+ if (old && was) {
2531
+ const now = step.doc.textBetween(range.from, range.to, "\n\n");
2532
+ if (old.textBetween(was.from, was.to, "\n\n") !== now) {
2533
+ clashes2.push({ section: s.op === "all" ? "" : s.heading ?? "", now });
2534
+ continue;
2535
+ }
2536
+ }
2537
+ const from = s.op === "after" ? range.to : range.from;
2538
+ if (s.op === "after") step.insert(range.to, blocks2);
2539
+ else step.replaceWith(range.from, range.to, blocks2);
2540
+ span2 = [step.doc.resolve(from).index(0), step.doc.resolve(Math.min(from + blocks2.size, step.doc.content.size)).index(0)];
2541
+ done++;
2542
+ }
2543
+ if (done) updateYFragment({ transact: (run) => doc.transact(run, origin) }, fragment, step.doc, { mapping: /* @__PURE__ */ new Map(), isOMark: /* @__PURE__ */ new Map() });
2544
+ return { done, clashes: clashes2, span: span2 };
2545
+ }
2409
2546
  async function write(kind, base, node, load2, setup) {
2410
2547
  if (kind === "docx") return writeDocx(base, node.toJSON(), load2, setup);
2411
2548
  const parsed = fromMarkdown(new TextDecoder().decode(base));
@@ -2414,7 +2551,7 @@ async function write(kind, base, node, load2, setup) {
2414
2551
  var blocks = (fragment, schema) => {
2415
2552
  const out = [];
2416
2553
  const walk = (parent) => parent.toArray().forEach((child) => {
2417
- if (!(child instanceof Y2.XmlElement) || !schema.nodes[child.nodeName]?.isBlock) return;
2554
+ if (!(child instanceof Y3.XmlElement) || !schema.nodes[child.nodeName]?.isBlock) return;
2418
2555
  out.push(child);
2419
2556
  walk(child);
2420
2557
  });
@@ -2513,15 +2650,19 @@ export {
2513
2650
  extras,
2514
2651
  applyCells,
2515
2652
  sheetTexts,
2653
+ clashes,
2654
+ appendRows,
2655
+ compute,
2516
2656
  ours,
2517
2657
  parse2 as parse,
2518
2658
  edits,
2519
- filled,
2659
+ filled2 as filled,
2520
2660
  seed,
2521
2661
  follow,
2522
2662
  pending,
2523
2663
  Refusal,
2524
2664
  applyText,
2665
+ applySteps,
2525
2666
  save
2526
2667
  };
2527
- //# sourceMappingURL=chunk-2G34AIPU.js.map
2668
+ //# sourceMappingURL=chunk-VG7UW2CQ.js.map