@kuzuma/colwork 0.0.0-stage → 0.2.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.
@@ -0,0 +1,1928 @@
1
+ var ve = Object.defineProperty;
2
+ var xe = (o, e, t) => e in o ? ve(o, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : o[e] = t;
3
+ var u = (o, e, t) => xe(o, typeof e != "symbol" ? e + "" : e, t);
4
+ import { WebsocketProvider as me } from "y-websocket";
5
+ import * as D from "yjs";
6
+ import { Awareness as ze } from "y-protocols/awareness";
7
+ import { WebrtcProvider as Me } from "y-webrtc";
8
+ function Le(o, e) {
9
+ return {
10
+ start: {
11
+ row: Math.min(o.row, e.row),
12
+ column: Math.min(o.column, e.column)
13
+ },
14
+ end: {
15
+ row: Math.max(o.row, e.row),
16
+ column: Math.max(o.column, e.column)
17
+ }
18
+ };
19
+ }
20
+ function P(o, e) {
21
+ return e.row >= o.start.row && e.row <= o.end.row && e.column >= o.start.column && e.column <= o.end.column;
22
+ }
23
+ function yt(o) {
24
+ return {
25
+ rows: o.end.row - o.start.row + 1,
26
+ columns: o.end.column - o.start.column + 1
27
+ };
28
+ }
29
+ function H(o) {
30
+ return `${o.row}:${o.column}`;
31
+ }
32
+ function $(o, e) {
33
+ const t = o ?? e ?? { row: 0, column: 0 };
34
+ return Le(t, e ?? t);
35
+ }
36
+ function fe(o, e, t, s) {
37
+ return {
38
+ row: o === "column" || o === "all" ? t - 1 : e.row,
39
+ column: o === "row" || o === "all" ? s - 1 : e.column
40
+ };
41
+ }
42
+ function Ae(o, e, t) {
43
+ if (!(!o.anchor || !o.focus))
44
+ return $(o.anchor, fe(o.mode, o.focus, e, t));
45
+ }
46
+ class Re {
47
+ constructor(e) {
48
+ u(this, "rows");
49
+ u(this, "columns");
50
+ var s;
51
+ for (const n of [e.rowCount, e.columnCount])
52
+ if (n !== void 0 && (!Number.isSafeInteger(n) || n < 1)) throw new RangeError("Table dimensions must be positive safe integers");
53
+ const t = e.transport === "external";
54
+ this.rows = Math.max(e.rowCount ?? 100, t ? 1 : ((s = e.rows) == null ? void 0 : s.length) ?? 10), this.columns = Math.max(e.columnCount ?? 10, t ? 1 : 6);
55
+ }
56
+ expandDocument(e) {
57
+ const t = e.getContentSize(), s = t.rows > this.rows || t.columns > this.columns;
58
+ return this.rows = Math.max(this.rows, t.rows), this.columns = Math.max(this.columns, t.columns), s;
59
+ }
60
+ expandRemote(e) {
61
+ const t = this.rows, s = this.columns;
62
+ return e.getStates().forEach((n, r) => {
63
+ if (r === e.clientID) return;
64
+ const i = n.selection;
65
+ !(i != null && i.anchor) || !i.focus || (this.rows = Math.max(this.rows, i.anchor.row + 1, i.focus.row + 1), this.columns = Math.max(this.columns, i.anchor.column + 1, i.focus.column + 1));
66
+ }), t !== this.rows || s !== this.columns;
67
+ }
68
+ expandViewport(e, t) {
69
+ const s = e.scrollTop + e.clientHeight >= e.scrollHeight - 280, n = e.scrollLeft + e.clientWidth >= e.scrollWidth - 280;
70
+ s && (this.rows += 100), n && (this.columns += 5), t.mode && (s || n) && (t.focus = fe(t.mode, t.focus ?? { row: 0, column: 0 }, this.rows, this.columns), t.publishSelection());
71
+ }
72
+ }
73
+ const ge = [
74
+ ["设计协作表格", "小林", "进行中", "高", "2026-08-07", "欢迎测试"],
75
+ ["整理组件 API", "阿南", "已完成", "中", "2026-08-08", "已补充示例"],
76
+ ["补充单元测试", "小周", "未开始", "高", "2026-08-09", "覆盖边界输入"],
77
+ ["实现虚拟滚动", "小林", "进行中", "高", "2026-08-10", "先支持行虚拟化"],
78
+ ["接入 WebSocket", "阿南", "已完成", "中", "2026-08-11", "等待联调"],
79
+ ["增加复制粘贴", "小周", "进行中", "中", "2026-08-12", "支持 TSV 格式"],
80
+ ["检查 Safari 兼容性", "小雨", "阻塞", "高", "2026-08-13", "需要补充 ICE 日志"],
81
+ ["编写使用文档", "阿南", "未开始", "低", "2026-08-14", "准备 API 清单"],
82
+ ["优化移动端布局", "小雨", "未开始", "中", "2026-08-15", "检查横向滚动"],
83
+ ["发布 v0.1.0", "小林", "未开始", "低", "2026-08-18", "等待最终验收"]
84
+ ];
85
+ function pe(o) {
86
+ o.doc.transact(() => {
87
+ o.cells.set("0:0", `设计协作表格
88
+ 多人协作工作区`), o.cells.delete("0:1"), o.cells.delete("0:2"), o.merges.set("0:0-0:2", "1"), o.styles.set("0:0", JSON.stringify({ bold: !0, fontSize: 16, color: "#0f172a", background: "#bae6fd", align: "center", wrap: !0, border: { top: !0, right: !0, bottom: !0, left: !0 } })), o.styles.set("1:0", JSON.stringify({ bold: !0, underline: !0, background: "#fef3c7", border: { bottom: !0 } })), o.styles.set("1:1", JSON.stringify({ italic: !0, color: "#7c3aed" })), o.styles.set("1:2", JSON.stringify({ strike: !0, color: "#b91c1c" })), o.cells.set("2:0", "125000"), o.styles.set("2:0", JSON.stringify({ format: "number", fontSize: 14, border: { top: !0, bottom: !0 } })), o.cells.set("2:1", "0.72"), o.styles.set("2:1", JSON.stringify({ format: "percent", color: "#047857", align: "right" })), o.cells.set("2:2", "2026-08-09"), o.styles.set("2:2", JSON.stringify({ format: "date", background: "#dcfce7" })), o.cells.set("3:0", `这是一段较长的演示内容
89
+ 可使用自动换行工具查看`), o.styles.set("3:0", JSON.stringify({ wrap: !0, background: "#f1f5f9", border: { top: !0, right: !0, bottom: !0, left: !0 } })), o.cells.set("4:0", "删除线示例"), o.styles.set("4:0", JSON.stringify({ strike: !0, color: "#64748b" })), o.cells.set("5:0", "合并区域示例"), o.cells.delete("5:1"), o.cells.delete("5:2"), o.merges.set("5:0-5:2", "1"), o.styles.set("5:0", JSON.stringify({ bold: !0, align: "center", background: "#ede9fe", border: { top: !0, right: !0, bottom: !0, left: !0 } })), o.rowHeights.set("0", 72), o.rowHeights.set("3", 72), o.rowHeights.set("5", 44), o.columnWidths.set("0", 220), o.columnWidths.set("1", 130), o.columnWidths.set("2", 130);
90
+ });
91
+ }
92
+ function $e(o, e, t, s, n) {
93
+ const r = o.provider;
94
+ if (!(!r || e.transport === "external")) {
95
+ if (r instanceof me) {
96
+ r.on("status", ({ status: i }) => n.log(i === "connected" ? "signaling:connected" : "signaling:disconnected")), r.on("sync", (i) => {
97
+ if (n.log(i ? "synced" : "syncing"), !i || !e.initializeAfterSync) return;
98
+ const c = t.doc.getMap("colwork-metadata");
99
+ n.canEdit() && !c.get("initialized") && (t.doc.transact(() => {
100
+ s && t.cells.size === 0 && t.locks.size === 0 && (t.seed(e.rows ?? ge), pe(t)), c.set("initialized", !0);
101
+ }), n.clearHistory()), n.render();
102
+ }), e.initializeAfterSync && r.connect();
103
+ return;
104
+ }
105
+ r.on("status", ({ connected: i }) => {
106
+ n.log(i ? "signaling:connected" : "signaling:disconnected"), n.inspect();
107
+ }), r.on("synced", ({ synced: i }) => n.log(i ? "synced" : "syncing")), r.on("peers", ({ added: i, removed: c, webrtcPeers: h }) => {
108
+ i.length && n.log(`peer:+${i.length}`), c.length && n.log(`peer:-${c.length}`), n.log(`webrtc:${h.length}`), n.inspect();
109
+ });
110
+ }
111
+ }
112
+ function _e(o, e) {
113
+ const t = o.trim().replace("#", "");
114
+ if (/^[\da-f]{3}$/i.test(t)) {
115
+ const [n, r, i] = t.split("").map((c) => Number.parseInt(c + c, 16));
116
+ return `rgba(${n}, ${r}, ${i}, ${e})`;
117
+ }
118
+ if (/^[\da-f]{6}$/i.test(t)) {
119
+ const n = Number.parseInt(t, 16);
120
+ return `rgba(${n >> 16}, ${n >> 8 & 255}, ${n & 255}, ${e})`;
121
+ }
122
+ const s = o.match(/^rgba?\(\s*([\d.]+)[, ]+\s*([\d.]+)[, ]+\s*([\d.]+)/i);
123
+ return s ? `rgba(${s[1]}, ${s[2]}, ${s[3]}, ${e})` : `color-mix(in srgb, ${o} 12%, transparent)`;
124
+ }
125
+ function W(o, e) {
126
+ let t = 0;
127
+ for (let s = 0; s < o; s += 1) t += e(s);
128
+ return t;
129
+ }
130
+ function j(o, e) {
131
+ return W(o, e);
132
+ }
133
+ function He(o) {
134
+ const e = (h, m, a, l) => {
135
+ let d = 0, f = 0;
136
+ for (; f < a && d + l(f) <= h; )
137
+ d += l(f), f += 1;
138
+ const S = Math.max(0, f - o.overscan);
139
+ let x = f, b = d;
140
+ for (; x < a && b < h + m; )
141
+ b += l(x), x += 1;
142
+ return { start: S, end: Math.min(a - 1, x + o.overscan - 1) };
143
+ }, t = e(o.scrollTop, o.clientHeight, o.rowCount, o.rowSize), s = e(o.scrollLeft, o.clientWidth, o.columnCount, o.columnSize), n = t.start, r = t.end, i = s.start, c = s.end;
144
+ return { top: n, bottom: r, left: i, right: c };
145
+ }
146
+ function we(o, e, t, s, n) {
147
+ o.querySelectorAll("td[data-key]").forEach((r) => {
148
+ const [i, c] = r.dataset.key.split(":").map(Number), h = Number(r.dataset.renderRow ?? i), m = Number(r.dataset.renderColumn ?? c), a = Number(r.dataset.renderBottom ?? h + r.rowSpan - 1), l = Number(r.dataset.renderRight ?? m + r.colSpan - 1);
149
+ if (h > e.end.row || a < e.start.row || m > e.end.column || l < e.start.column) return;
150
+ const d = getComputedStyle(r), f = parseFloat(d.borderTopWidth), S = parseFloat(d.borderRightWidth), x = parseFloat(d.borderBottomWidth), b = parseFloat(d.borderLeftWidth), M = (E, z, A, C, B, N, g) => {
151
+ if (E >= A && z <= C) return [`${-N}px`, `${-g}px`];
152
+ let v = 0, y = 0, k = 0;
153
+ for (let O = E; O <= z; O++) {
154
+ const I = o.querySelector(`th[data-selection-axis="${B}"][data-selection-index="${O}"]`), V = I == null ? void 0 : I.getBoundingClientRect(), Y = B === "row" ? (V == null ? void 0 : V.height) ?? n("row", O) : (V == null ? void 0 : V.width) ?? n("column", O);
155
+ v += Y, O < A && (y += Y), O > C && (k += Y);
156
+ }
157
+ const L = (O, I) => O === 0 ? `${-I}px` : `calc(${O / v * 100}% + ${(N + g) * O / v - I}px)`;
158
+ return [L(y, N), L(k, g)];
159
+ }, [R, _] = M(h, a, e.start.row, e.end.row, "row", f, x), [T, w] = M(m, l, e.start.column, e.end.column, "column", b, S), p = document.createElement("span");
160
+ p.className = t, p.setAttribute("aria-hidden", "true"), Object.assign(p.style, {
161
+ top: R,
162
+ right: w,
163
+ bottom: _,
164
+ left: T,
165
+ borderTopWidth: h <= e.start.row ? "2px" : "0",
166
+ borderRightWidth: l >= e.end.column ? "2px" : "0",
167
+ borderBottomWidth: a >= e.end.row ? "2px" : "0",
168
+ borderLeftWidth: m <= e.start.column ? "2px" : "0",
169
+ borderColor: s,
170
+ backgroundColor: _e(s, 0.1)
171
+ }), r.append(p);
172
+ });
173
+ }
174
+ function ne(o, e, t) {
175
+ var n, r;
176
+ const s = document.createElement("span");
177
+ s.className = "colwork-table__remote-cursor", s.style.backgroundColor = ((n = e.user) == null ? void 0 : n.color) ?? "#64748b", s.textContent = ((r = e.user) == null ? void 0 : r.name) ?? String(t).slice(0, 6), o.append(s);
178
+ }
179
+ function re(o, e, t, s, n, r, i) {
180
+ o.replaceChildren(), o.style.width = `${e.clientWidth}px`, o.style.height = `${e.clientHeight}px`;
181
+ const c = (h, m, a, l) => {
182
+ if (!m || a >= l) return;
183
+ const d = document.createElement("span");
184
+ d.className = `colwork-table__frozen-boundary colwork-table__frozen-boundary--${h}`, d.setAttribute("aria-hidden", "true"), d.style.left = `${h === "column" ? a - 1 : 0}px`, d.style.top = `${h === "row" ? a - 1 : 0}px`, h === "column" ? d.style.height = `${e.clientHeight}px` : d.style.width = `${e.clientWidth}px`, o.append(d);
185
+ };
186
+ c("row", t, r + W(t, (h) => i("row", h)), e.clientHeight), c("column", s, n + W(s, (h) => i("column", h)), e.clientWidth);
187
+ }
188
+ function Ne(o) {
189
+ const e = document.activeElement;
190
+ o.table.querySelectorAll("td[data-key]").forEach((t) => {
191
+ const s = t.dataset.key;
192
+ if (s && t !== e && s !== o.editingKey) {
193
+ const n = t.querySelector(".colwork-table__cell-value");
194
+ n ? n.textContent = o.formatting.displayValue(s) : t.textContent = o.formatting.displayValue(s);
195
+ }
196
+ });
197
+ }
198
+ function ye(o) {
199
+ if (o.viewport.querySelectorAll(".colwork-table__selection").forEach((t) => t.remove()), !o.selection.focus) return;
200
+ const e = o.selection.getSelectionBounds();
201
+ o.table.querySelectorAll("th[data-selection-axis]").forEach((t) => {
202
+ const s = t.dataset.selectionAxis, n = Number(t.dataset.selectionIndex), r = o.selection.mode === "all" || o.selection.mode === s && (s === "row" ? n >= e.top && n <= e.bottom : n >= e.left && n <= e.right);
203
+ t.classList.toggle("is-selected-header", r);
204
+ }), we(o.table, $({ row: e.top, column: e.left }, { row: e.bottom, column: e.right }), "colwork-table__selection", o.userColor ?? "#3b82f6", (t, s) => t === "row" ? o.size("row", s) : o.size("column", s));
205
+ }
206
+ function be(o) {
207
+ o.table && (o.table.querySelectorAll("td[data-key]").forEach((e) => {
208
+ e.querySelectorAll(".colwork-table__remote-cursor").forEach((t) => t.remove());
209
+ }), o.viewport.querySelectorAll(".colwork-table__remote-selection").forEach((e) => e.remove()), o.awareness.getStates().forEach((e, t) => {
210
+ var n;
211
+ if (t === o.awareness.clientID) return;
212
+ const s = e.selection;
213
+ if (s != null && s.anchor && s.focus) {
214
+ const r = Ae(s, o.rowCount, o.columnCount);
215
+ r && we(o.table, r, "colwork-table__remote-selection", ((n = e.user) == null ? void 0 : n.color) ?? "#94a3b8", (m, a) => m === "row" ? o.size("row", a) : o.size("column", a));
216
+ const i = Math.min(s.anchor.row, s.focus.row), c = Math.min(s.anchor.column, s.focus.column), h = o.table.querySelector(`td[data-key="${i}:${c}"]`);
217
+ h && ne(h, e, t);
218
+ } else {
219
+ const r = e.cursor, i = r && o.table.querySelector(`td[data-key="${r.row}:${r.column}"]`);
220
+ i && ne(i, e, t);
221
+ }
222
+ }));
223
+ }
224
+ function De(o) {
225
+ o.table.querySelectorAll("td[data-key]").forEach((e) => {
226
+ if (e.dataset.key) {
227
+ o.formatting.applyStyle(e, e.dataset.key);
228
+ const t = e.querySelector(".colwork-table__cell-value");
229
+ t && (o.formatting.applyStyle(t, e.dataset.key), t.textContent = o.formatting.displayValue(e.dataset.key));
230
+ }
231
+ }), ye(o), be(o);
232
+ }
233
+ class Oe {
234
+ constructor(e) {
235
+ u(this, "selecting", !1);
236
+ u(this, "headerSelecting");
237
+ u(this, "pendingCellContext");
238
+ u(this, "rightButtonReleased", !1);
239
+ u(this, "rightMouseUpPoint");
240
+ u(this, "rightDrag");
241
+ this.host = e;
242
+ }
243
+ cancel() {
244
+ this.selecting = !1, this.headerSelecting = void 0, this.pendingCellContext = void 0, this.rightDrag = void 0;
245
+ }
246
+ release(e) {
247
+ this.selecting = !1, this.headerSelecting = void 0, e.button === 2 && (this.rightButtonReleased = !0, this.rightMouseUpPoint = { x: e.clientX, y: e.clientY }, this.pendingCellContext && (this.pendingCellContext = void 0, this.showCellContextMenu(e.clientX, e.clientY))), this.host.selection.pendingCursor && this.host.selection.sendAwareness(this.host.selection.pendingCursor);
248
+ }
249
+ blur() {
250
+ this.headerSelecting && (this.selecting = !1, this.headerSelecting = void 0, this.host.selection.pendingCursor && this.host.selection.sendAwareness(this.host.selection.pendingCursor));
251
+ }
252
+ protectionActions() {
253
+ return [
254
+ ["锁定选区", () => this.host.dialogs.requestSelectionLock(!0)],
255
+ ["密码锁定选区", () => this.host.dialogs.requestSelectionLock(!0, !0)],
256
+ ["解锁选区", () => this.host.dialogs.requestSelectionLock(!1)]
257
+ ];
258
+ }
259
+ hasHeaderSelection(e, t) {
260
+ const s = $(this.host.selection.anchor, this.host.selection.focus);
261
+ return this.host.selection.mode === e && (e === "row" ? t >= s.start.row && t <= s.end.row : t >= s.start.column && t <= s.end.column);
262
+ }
263
+ openRowContextMenu(e, t) {
264
+ if (!this.host.canEdit()) return;
265
+ e.preventDefault(), e.stopPropagation(), this.hasHeaderSelection("row", t) || this.host.selection.selectHeaderRange("row", t, !1);
266
+ const s = $(this.host.selection.anchor, this.host.selection.focus), n = s.end.row - s.start.row + 1;
267
+ this.host.menu.show(e.clientX, e.clientY, [
268
+ { label: "行操作", actions: [
269
+ [`在上方插入 ${n} 行`, () => this.host.modifyAxis("row", s.start.row, n)],
270
+ [`在下方插入 ${n} 行`, () => this.host.modifyAxis("row", s.end.row + 1, n)],
271
+ [`删除 ${n} 行`, () => this.host.deleteRows()]
272
+ ] },
273
+ { label: "固定", actions: [
274
+ ["固定至此行", () => this.host.freezeSelection("row")],
275
+ ["取消固定", () => this.host.setFrozenPanes(0, 0)]
276
+ ] },
277
+ { label: "保护", actions: this.protectionActions() }
278
+ ]);
279
+ }
280
+ openColumnContextMenu(e, t) {
281
+ if (!this.host.canEdit()) return;
282
+ e.preventDefault(), e.stopPropagation(), this.hasHeaderSelection("column", t) || this.host.selection.selectHeaderRange("column", t, !1);
283
+ const s = $(this.host.selection.anchor, this.host.selection.focus), n = s.end.column - s.start.column + 1;
284
+ this.host.menu.show(e.clientX, e.clientY, [
285
+ { label: "列操作", actions: [
286
+ [`在左侧插入 ${n} 列`, () => this.host.modifyAxis("column", s.start.column, n)],
287
+ [`在右侧插入 ${n} 列`, () => this.host.modifyAxis("column", s.end.column + 1, n)],
288
+ [`删除 ${n} 列`, () => this.host.deleteColumns()]
289
+ ] },
290
+ { label: "固定", actions: [
291
+ ["固定至此列", () => this.host.freezeSelection("column")],
292
+ ["取消固定", () => this.host.setFrozenPanes(0, 0)]
293
+ ] },
294
+ { label: "保护", actions: this.protectionActions() }
295
+ ]);
296
+ }
297
+ addHeaderSelection(e, t, s) {
298
+ e.dataset.selectionAxis = t, e.dataset.selectionIndex = String(s), e.addEventListener("mousedown", (n) => {
299
+ n.button === 0 && (n.preventDefault(), n.stopPropagation(), this.host.editing.finish(!0), this.host.viewport.focus({ preventScroll: !0 }), this.host.menu.hide(), this.host.selection.selectHeaderRange(t, s, n.shiftKey), this.headerSelecting = { axis: t, anchor: this.host.selection.anchor[t] }, this.selecting = !0);
300
+ }), e.addEventListener("mouseenter", (n) => {
301
+ if (!(!this.selecting || !this.headerSelecting || this.headerSelecting.axis !== t)) {
302
+ if (!(n.buttons & 1)) {
303
+ this.blur();
304
+ return;
305
+ }
306
+ this.host.selection.selectHeaderSpan(t, this.headerSelecting.anchor, s);
307
+ }
308
+ }), e.addEventListener("contextmenu", (n) => t === "row" ? this.openRowContextMenu(n, s) : this.openColumnContextMenu(n, s));
309
+ }
310
+ showCellContextMenu(e, t) {
311
+ this.host.canEdit() && this.host.menu.show(e, t, [
312
+ { label: "编辑", actions: [
313
+ ["复制", () => this.host.clipboard.copySelection()],
314
+ ["清空内容", () => this.host.clearSelectionContents()]
315
+ ] },
316
+ { label: "单元格", actions: [
317
+ ["合并单元格", () => this.host.mergeSelection()],
318
+ ["取消合并单元格", () => this.host.unmergeSelection()]
319
+ ] },
320
+ { label: "固定", actions: [
321
+ ["固定至选中行", () => this.host.freezeSelection("row")],
322
+ ["固定至选中列", () => this.host.freezeSelection("column")],
323
+ ["取消固定", () => this.host.setFrozenPanes(0, 0)]
324
+ ] },
325
+ { label: "保护", actions: this.protectionActions() }
326
+ ]);
327
+ }
328
+ openCellContextMenu(e) {
329
+ if (this.host.canEdit() && (e.preventDefault(), e.stopPropagation(), this.pendingCellContext = { x: e.clientX, y: e.clientY }, this.rightButtonReleased)) {
330
+ this.pendingCellContext = void 0;
331
+ const t = this.rightMouseUpPoint ?? { x: e.clientX, y: e.clientY };
332
+ this.showCellContextMenu(t.x, t.y);
333
+ }
334
+ }
335
+ attachCellListeners(e, t, s, n) {
336
+ e.addEventListener("mousedown", (r) => {
337
+ r.target instanceof HTMLTextAreaElement || r.button !== 0 && r.button !== 2 || (r.button === 2 ? (this.rightButtonReleased = !1, this.rightDrag = { start: { row: s, column: n }, moved: !1 }) : this.rightDrag = void 0, r.preventDefault(), this.host.viewport.focus({ preventScroll: !0 }), this.selecting = !0, (r.button === 0 || !this.host.selection.isPositionSelected({ row: s, column: n })) && this.host.selection.selectCell(s, n, r.shiftKey), this.host.refreshSelection());
338
+ }), e.addEventListener("mouseenter", () => {
339
+ if (!(!this.selecting || this.headerSelecting)) {
340
+ if (this.rightDrag) {
341
+ if (this.rightDrag.start.row === s && this.rightDrag.start.column === n) return;
342
+ this.rightDrag.moved || (this.rightDrag.moved = !0, this.host.selection.mode = void 0, this.host.selection.anchor = this.rightDrag.start, this.host.selection.selectedKey = H(this.rightDrag.start));
343
+ }
344
+ this.host.selection.selectCell(s, n, !0), this.host.refreshSelection();
345
+ }
346
+ }), this.host.canEdit() && e.addEventListener("dblclick", () => this.host.editing.start(e, t, !1)), e.addEventListener("contextmenu", (r) => this.openCellContextMenu(r));
347
+ }
348
+ }
349
+ class We {
350
+ constructor(e) {
351
+ u(this, "anchor");
352
+ u(this, "focus");
353
+ u(this, "mode");
354
+ u(this, "selectedKey");
355
+ u(this, "pendingCursor");
356
+ this.host = e;
357
+ }
358
+ selectRange(e, t, s) {
359
+ this.anchor = e, this.focus = t, this.mode = s, this.selectedKey = H(e), this.pendingCursor = t, this.host.refresh();
360
+ }
361
+ selectHeaderRange(e, t, s) {
362
+ var r, i;
363
+ let n = t;
364
+ s && this.mode === e && (n = e === "row" ? ((r = this.anchor) == null ? void 0 : r.row) ?? t : ((i = this.anchor) == null ? void 0 : i.column) ?? t), this.selectHeaderSpan(e, n, t);
365
+ }
366
+ selectHeaderSpan(e, t, s) {
367
+ e === "row" ? this.selectRange({ row: t, column: 0 }, { row: s, column: this.host.dimensions().columns - 1 }, "row") : this.selectRange({ row: 0, column: t }, { row: this.host.dimensions().rows - 1, column: s }, "column");
368
+ }
369
+ publishSelection() {
370
+ this.updateAwareness();
371
+ }
372
+ updateAwareness(e = {}) {
373
+ this.host.session.publish({
374
+ ...e,
375
+ selection: { anchor: this.anchor, focus: this.focus, mode: this.mode }
376
+ });
377
+ }
378
+ getSelectionBounds() {
379
+ const e = this.anchor ?? this.focus ?? { row: 0, column: 0 }, t = this.focus ?? e, s = $(e, t);
380
+ return { top: s.start.row, bottom: s.end.row, left: s.start.column, right: s.end.column };
381
+ }
382
+ selectCell(e, t, s = !1) {
383
+ const n = { row: e, column: t };
384
+ this.mode = void 0, (!s || !this.anchor) && (this.anchor = n);
385
+ const r = this.host.sheet.expandSelectionToMerges(this.anchor, n);
386
+ this.anchor = r.anchor, this.focus = r.focus, this.selectedKey = `${e}:${t}`, this.pendingCursor = n;
387
+ }
388
+ isPositionSelected(e) {
389
+ return P($(this.anchor, this.focus), e);
390
+ }
391
+ sendAwareness(e) {
392
+ this.pendingCursor = void 0, this.updateAwareness({ cursor: e, editing: this.host.editingKey() ?? null });
393
+ }
394
+ }
395
+ function Se(o) {
396
+ for (const e of o) {
397
+ const t = e.codePointAt(0);
398
+ if (t >= 55296 && t <= 57343) return !1;
399
+ }
400
+ return !0;
401
+ }
402
+ function ke(o) {
403
+ return Array.from(o, (e) => {
404
+ const t = e.codePointAt(0);
405
+ return t >= 55296 && t <= 57343 ? "�" : e;
406
+ }).join("");
407
+ }
408
+ const ee = 1, F = Object.freeze({
409
+ cells: "cells",
410
+ styles: "styles",
411
+ rowHeights: "rowHeights",
412
+ columnWidths: "columnWidths",
413
+ merges: "merges",
414
+ locks: "locks",
415
+ metadata: "colwork-metadata"
416
+ });
417
+ function q(o) {
418
+ if (!/^(0|[1-9]\d*):(0|[1-9]\d*)$/.test(o)) return;
419
+ const [e, t] = o.split(":").map(Number);
420
+ return Number.isSafeInteger(e) && Number.isSafeInteger(t) ? { row: e, column: t } : void 0;
421
+ }
422
+ function bt(o) {
423
+ return `${o.start.row}:${o.start.column}-${o.end.row}:${o.end.column}`;
424
+ }
425
+ function te(o) {
426
+ const e = o.split("-");
427
+ if (e.length !== 2) return;
428
+ const t = q(e[0]), s = q(e[1]);
429
+ if (!(!t || !s || t.row > s.row || t.column > s.column))
430
+ return { start: t, end: s };
431
+ }
432
+ function Be(o) {
433
+ if (o.length < 2) return !1;
434
+ const e = [...new Set(o.flatMap((c) => [c.start.column, c.end.column + 1]))].sort((c, h) => c - h), t = new Map(e.map((c, h) => [c, h])), s = o.flatMap((c) => [
435
+ { row: c.start.row, left: t.get(c.start.column), right: t.get(c.end.column + 1) - 1, delta: 1 },
436
+ { row: c.end.row + 1, left: t.get(c.start.column), right: t.get(c.end.column + 1) - 1, delta: -1 }
437
+ ]).sort((c, h) => c.row - h.row || c.delta - h.delta), n = new Int32Array(e.length * 4), r = new Int32Array(e.length * 4), i = (c, h, m, a, l, d) => {
438
+ if (a <= h && m <= l) {
439
+ n[c] += d, r[c] += d;
440
+ return;
441
+ }
442
+ const f = Math.floor((h + m) / 2);
443
+ a <= f && i(c * 2, h, f, a, l, d), l > f && i(c * 2 + 1, f + 1, m, a, l, d), n[c] = r[c] + Math.max(n[c * 2], n[c * 2 + 1]);
444
+ };
445
+ for (const c of s)
446
+ if (i(1, 0, e.length - 2, c.left, c.right, c.delta), n[1] > 1) return !0;
447
+ return !1;
448
+ }
449
+ const X = (o) => !!o && typeof o == "object" && !Array.isArray(o) && Object.getPrototypeOf(o) === Object.prototype, Z = (o, e) => Object.keys(o).every((t) => e.includes(t));
450
+ function Fe(o) {
451
+ return X(o) && Z(o, ["version", "algorithm", "iterations", "salt", "verifier"]) && o.version === 1 && o.algorithm === "PBKDF2-SHA-256" && o.iterations === 6e5 && typeof o.salt == "string" && /^[0-9a-f]{32}$/.test(o.salt) && typeof o.verifier == "string" && /^[0-9a-f]{64}$/.test(o.verifier);
452
+ }
453
+ function se(o) {
454
+ if (!X(o) || !Z(o, ["bold", "italic", "underline", "strike", "wrap", "border", "fontSize", "color", "background", "align", "format"])) return !1;
455
+ for (const e of ["bold", "italic", "underline", "strike", "wrap"]) if (e in o && typeof o[e] != "boolean") return !1;
456
+ for (const e of ["color", "background"]) if (e in o && (typeof o[e] != "string" || !Se(o[e]))) return !1;
457
+ if ("fontSize" in o && (typeof o.fontSize != "number" || !Number.isFinite(o.fontSize) || o.fontSize <= 0) || "align" in o && (typeof o.align != "string" || !["left", "center", "right"].includes(o.align)) || "format" in o && (typeof o.format != "string" || !["general", "number", "date", "percent"].includes(o.format))) return !1;
458
+ if ("border" in o) {
459
+ if (!X(o.border) || !Z(o.border, ["top", "right", "bottom", "left"])) return !1;
460
+ for (const e of Object.keys(o.border)) if (typeof o.border[e] != "boolean") return !1;
461
+ }
462
+ return !0;
463
+ }
464
+ function G(o) {
465
+ return {
466
+ cells: o.getMap(F.cells),
467
+ styles: o.getMap(F.styles),
468
+ rowHeights: o.getMap(F.rowHeights),
469
+ columnWidths: o.getMap(F.columnWidths),
470
+ merges: o.getMap(F.merges),
471
+ locks: o.getMap(F.locks)
472
+ };
473
+ }
474
+ function Ce(o, e = {}) {
475
+ for (const l of ["maxRows", "maxColumns", "maxEntries", "maxStringLength", "maxMergeArea", "maxMerges"]) {
476
+ const d = e[l];
477
+ if (d !== void 0 && (!Number.isSafeInteger(d) || d < 0)) throw new RangeError(`${l} must be a non-negative safe integer`);
478
+ }
479
+ const t = [];
480
+ (o.store.pendingStructs !== null || o.store.pendingDs !== null) && t.push({ path: "$", message: "Document contains unresolved Yjs update dependencies" });
481
+ const s = (l, d) => {
482
+ t.push({ path: l, message: d });
483
+ };
484
+ if (!e.allowUnknownRoots)
485
+ for (const l of o.share.keys())
486
+ Object.values(F).includes(l) || s(l, "Unknown document root");
487
+ let n, r;
488
+ try {
489
+ n = G(o), r = o.getMap(F.metadata);
490
+ } catch {
491
+ return [...t, { path: "$", message: "Sheet roots must be Y.Map values" }];
492
+ }
493
+ for (const [l, d] of [...Object.entries(n), ["metadata", r]])
494
+ (!(d instanceof D.Map) || d._start !== null) && s(l, "Expected map entries without sequence content");
495
+ const i = Object.values(n).reduce((l, d) => l + d.size, r.size);
496
+ e.maxEntries !== void 0 && i > e.maxEntries && s("$", "Document exceeds maxEntries");
497
+ const c = (l, d) => l < Number.MAX_SAFE_INTEGER && d < Number.MAX_SAFE_INTEGER && (e.maxRows === void 0 || l < e.maxRows) && (e.maxColumns === void 0 || d < e.maxColumns), h = (l, d) => {
498
+ if (typeof l != "string") return !1;
499
+ try {
500
+ return d(JSON.parse(l));
501
+ } catch {
502
+ return !1;
503
+ }
504
+ }, m = (l, d, f) => {
505
+ typeof f == "string" && e.maxStringLength !== void 0 && f.length > e.maxStringLength && s(`${l}.${d}`, "String exceeds maxStringLength");
506
+ };
507
+ for (const l of ["cells", "styles", "locks"])
508
+ n[l].forEach((d, f) => {
509
+ const S = q(f);
510
+ (!S || !c(S.row, S.column)) && s(`${l}.${f}`, "Invalid or out-of-bounds row:column key"), m(l, f, d), l === "cells" && (typeof d != "string" || !Se(d)) && s(`${l}.${f}`, "Cell values must be strings"), l === "styles" && !h(d, se) && s(`${l}.${f}`, "Expected a JSON CellStyle object"), l === "locks" && d !== "1" && !h(d, Fe) && s(`${l}.${f}`, "Expected a plain lock or version-one password verifier");
511
+ });
512
+ for (const l of ["rowHeights", "columnWidths"])
513
+ n[l].forEach((d, f) => {
514
+ const S = Number(f), x = l === "rowHeights" ? e.maxRows : e.maxColumns;
515
+ (!/^(0|[1-9]\d*)$/.test(f) || !Number.isSafeInteger(S) || S >= Number.MAX_SAFE_INTEGER || x !== void 0 && S >= x) && s(`${l}.${f}`, "Invalid or out-of-bounds index"), (typeof d != "number" || !Number.isFinite(d) || d <= 0) && s(`${l}.${f}`, "Sizes must be finite positive numbers");
516
+ });
517
+ e.maxMerges !== void 0 && n.merges.size > e.maxMerges && s("merges", "Document exceeds maxMerges");
518
+ const a = [];
519
+ return n.merges.forEach((l, d) => {
520
+ const f = te(d);
521
+ !f || l !== "1" || !c(f.end.row, f.end.column) ? s(`merges.${d}`, "Invalid or out-of-bounds merge range") : (e.maxMergeArea !== void 0 && f.end.row - f.start.row + 1 > e.maxMergeArea / (f.end.column - f.start.column + 1) && s(`merges.${d}`, "Merge exceeds maxMergeArea"), a.push(f));
522
+ }), Be(a) && s("merges", "Merge ranges must not overlap"), r.forEach((l, d) => {
523
+ d === "schemaVersion" ? l !== ee && s("metadata.schemaVersion", "Unsupported schema version") : d === "initialized" ? typeof l != "boolean" && s("metadata.initialized", "Expected a boolean") : s(`metadata.${d}`, "Unknown metadata field");
524
+ }), t;
525
+ }
526
+ const ie = "application/x-colwork-cells";
527
+ function Pe(o) {
528
+ if (!o || typeof o != "object") return !1;
529
+ const e = o;
530
+ return Array.isArray(e.values) && e.values.length > 0 && e.values.every((t) => Array.isArray(t) && t.every((s) => typeof s == "string")) && Array.isArray(e.styles) && e.styles.every((t) => Array.isArray(t) && t.every((s) => s === null || se(s)));
531
+ }
532
+ class Te {
533
+ constructor(e) {
534
+ u(this, "onCopy", (e) => {
535
+ if (e.target instanceof HTMLTextAreaElement) return;
536
+ const t = this.payload();
537
+ !t || !e.clipboardData || (e.clipboardData.setData("text/plain", t.values.map((s) => s.join(" ")).join(`
538
+ `)), e.clipboardData.setData(ie, JSON.stringify(t)), e.preventDefault());
539
+ });
540
+ u(this, "onPaste", (e) => {
541
+ var a, l, d;
542
+ if (e.target instanceof HTMLTextAreaElement) return;
543
+ e.preventDefault(), e.stopPropagation();
544
+ const { selection: t, sheet: s, editing: n } = this.host;
545
+ if (!this.host.canEdit() || !t.focus) return;
546
+ const r = (l = (a = e.clipboardData) == null ? void 0 : a.getData("text/plain")) == null ? void 0 : l.replace(/^\uFEFF/, "");
547
+ if (!r) return;
548
+ n.finish(!1);
549
+ let i = r.replace(/\r\n?/g, `
550
+ `).split(`
551
+ `).filter((f, S, x) => !(S === x.length - 1 && f === "")).map((f) => f.split(" ")), c;
552
+ try {
553
+ const f = JSON.parse(((d = e.clipboardData) == null ? void 0 : d.getData(ie)) ?? "");
554
+ Pe(f) && (i = f.values, c = f.styles);
555
+ } catch {
556
+ }
557
+ const h = t.focus;
558
+ if (i.some((f, S) => f.some((x, b) => s.isCellLocked(H({ row: h.row + S, column: h.column + b }))))) return;
559
+ const m = this.host.dimensions();
560
+ s.doc.transact(() => i.forEach((f, S) => f.forEach((x, b) => {
561
+ var _;
562
+ const M = { row: h.row + S, column: h.column + b };
563
+ if (M.row >= m.rows || M.column >= m.columns) return;
564
+ const R = H(M);
565
+ if (s.cells.set(R, ke(x)), c) {
566
+ const T = (_ = c[S]) == null ? void 0 : _[b];
567
+ T ? s.styles.set(R, JSON.stringify(T)) : s.styles.delete(R);
568
+ }
569
+ })), this.host.origin), t.anchor = h, t.focus = { row: Math.min(m.rows - 1, h.row + i.length - 1), column: Math.min(m.columns - 1, h.column + Math.max(...i.map((f) => f.length)) - 1) }, this.host.render();
570
+ });
571
+ this.host = e;
572
+ }
573
+ payload() {
574
+ const { sheet: e, selection: t, formatting: s } = this.host;
575
+ if (!t.focus) return;
576
+ const n = $(t.anchor, t.focus), r = [], i = [];
577
+ for (let c = n.start.row; c <= n.end.row; c++) {
578
+ const h = [], m = [];
579
+ for (let a = n.start.column; a <= n.end.column; a++) {
580
+ const l = H({ row: c, column: a });
581
+ h.push(e.cells.get(l) ?? "");
582
+ const d = s.readStyle(l);
583
+ m.push(Object.keys(d).length ? d : null);
584
+ }
585
+ r.push(h), i.push(m);
586
+ }
587
+ return { values: r, styles: i };
588
+ }
589
+ copySelection() {
590
+ var t, s;
591
+ const e = (t = this.payload()) == null ? void 0 : t.values.map((n) => n.join(" ")).join(`
592
+ `);
593
+ e && ((s = navigator.clipboard) == null || s.writeText(e));
594
+ }
595
+ }
596
+ function U(o) {
597
+ let e = "";
598
+ for (let s = 0; s < o.length; s += 32768)
599
+ e += String.fromCharCode(...o.subarray(s, s + 32768));
600
+ return btoa(e);
601
+ }
602
+ function ae(o) {
603
+ const e = atob(o);
604
+ return Uint8Array.from(e, (t) => t.charCodeAt(0));
605
+ }
606
+ function le(o) {
607
+ if (o != null && o.trim())
608
+ return JSON.parse(o);
609
+ }
610
+ function qe(o) {
611
+ if (!(!o || o.format === "colwork.update-log"))
612
+ return o.format === "colwork.archive" ? o.snapshot : o;
613
+ }
614
+ function ce(o) {
615
+ return !o || o.format === "colwork.snapshot" ? [] : o.updates ?? [];
616
+ }
617
+ function St(o, e) {
618
+ const t = le(o), s = le(e), n = qe(t), r = [...ce(t), ...ce(s)], i = new D.Doc();
619
+ try {
620
+ n != null && n.snapshot && D.applyUpdate(i, ae(n.snapshot));
621
+ const c = Number((n == null ? void 0 : n.sequence) ?? 0), h = /* @__PURE__ */ new Set(), m = /* @__PURE__ */ new Set();
622
+ let a = c;
623
+ for (const l of r.sort((d, f) => Number(d.seq) - Number(f.seq))) {
624
+ const d = Number(l.seq);
625
+ !Number.isInteger(d) || typeof l.update != "string" || d <= c || h.has(d) || m.has(l.update) || (D.applyUpdate(i, ae(l.update)), h.add(d), m.add(l.update), a = Math.max(a, d));
626
+ }
627
+ return {
628
+ format: "colwork.snapshot",
629
+ version: 1,
630
+ room: n == null ? void 0 : n.room,
631
+ sequence: a,
632
+ snapshot: U(D.encodeStateAsUpdate(i)),
633
+ stateVector: U(D.encodeStateVector(i))
634
+ };
635
+ } finally {
636
+ i.destroy();
637
+ }
638
+ }
639
+ function Ie(o, e) {
640
+ const t = o.split(":").map(Number), s = e.split(":").map(Number);
641
+ return t[0] - s[0] || (t[1] ?? 0) - (s[1] ?? 0);
642
+ }
643
+ function K(o) {
644
+ return [...o].sort(([e], [t]) => Ie(e, t));
645
+ }
646
+ function Ve(o) {
647
+ const e = {};
648
+ for (const t of ["bold", "italic", "underline", "strike", "wrap", "fontSize", "color", "background", "align", "format"])
649
+ o[t] !== void 0 && (e[t] = o[t]);
650
+ if (o.border !== void 0) {
651
+ const t = {};
652
+ for (const s of ["top", "right", "bottom", "left"]) o.border[s] !== void 0 && (t[s] = o.border[s]);
653
+ e.border = t;
654
+ }
655
+ return e;
656
+ }
657
+ function Ke(o, e) {
658
+ const t = Ce(o, e);
659
+ if (t.length) throw new TypeError(`Invalid Colwork document at ${t[0].path}: ${t[0].message}`);
660
+ const s = G(o), n = Object.fromEntries(K(s.styles).map(([m, a]) => [m, Ve(JSON.parse(a))])), r = Object.fromEntries(K(s.locks).map(([m, a]) => {
661
+ if (a === "1") return [m, "1"];
662
+ const l = JSON.parse(a);
663
+ return [m, { version: l.version, algorithm: l.algorithm, iterations: l.iterations, salt: l.salt, verifier: l.verifier }];
664
+ })), i = [...s.merges.keys()].map((m) => te(m)).sort((m, a) => m.start.row - a.start.row || m.start.column - a.start.column || m.end.row - a.end.row || m.end.column - a.end.column);
665
+ let c = 1, h = 1;
666
+ for (const m of [...s.cells.keys(), ...s.styles.keys(), ...s.locks.keys()]) {
667
+ const a = q(m);
668
+ c = Math.max(c, a.row + 1), h = Math.max(h, a.column + 1);
669
+ }
670
+ for (const m of i)
671
+ c = Math.max(c, m.end.row + 1), h = Math.max(h, m.end.column + 1);
672
+ for (const m of s.rowHeights.keys()) c = Math.max(c, Number(m) + 1);
673
+ for (const m of s.columnWidths.keys()) h = Math.max(h, Number(m) + 1);
674
+ return {
675
+ schemaVersion: ee,
676
+ rowCount: c,
677
+ columnCount: h,
678
+ cells: Object.fromEntries(K(s.cells)),
679
+ styles: n,
680
+ rowHeights: Object.fromEntries(K(s.rowHeights)),
681
+ columnWidths: Object.fromEntries(K(s.columnWidths)),
682
+ merges: i,
683
+ locks: r
684
+ };
685
+ }
686
+ function kt(o) {
687
+ const e = Ce(o);
688
+ if (e.length) throw new TypeError(`Invalid Colwork document at ${e[0].path}: ${e[0].message}`);
689
+ if (Object.values(G(o)).some((s) => s.size > 0)) throw new Error("Blank initialization requires an empty sheet");
690
+ const t = o.getMap(F.metadata);
691
+ o.transact(() => {
692
+ t.set("schemaVersion", ee), t.set("initialized", !0);
693
+ });
694
+ }
695
+ function Ue(o, e = {}) {
696
+ const t = e.sequence ?? 0;
697
+ if (!Number.isSafeInteger(t) || t < 0) throw new RangeError("sequence must be a non-negative safe integer");
698
+ return {
699
+ format: "colwork.snapshot",
700
+ version: 1,
701
+ room: e.room,
702
+ sequence: t,
703
+ snapshot: U(D.encodeStateAsUpdate(o)),
704
+ stateVector: U(D.encodeStateVector(o))
705
+ };
706
+ }
707
+ function Ct(o, e) {
708
+ const t = new D.Doc();
709
+ try {
710
+ return D.applyUpdate(t, o), Ke(t, e);
711
+ } finally {
712
+ t.destroy();
713
+ }
714
+ }
715
+ class je {
716
+ constructor(e, t, s, n, r, i) {
717
+ u(this, "revision", 0);
718
+ u(this, "sequence", 0);
719
+ u(this, "updates", []);
720
+ u(this, "loggedPeers", /* @__PURE__ */ new Set());
721
+ u(this, "loggedSignals", /* @__PURE__ */ new Set());
722
+ u(this, "onUpdate", (e, t) => {
723
+ if (this.revision++, this.updates.push({ seq: ++this.sequence, update: U(e), timestamp: Date.now() }), !this.logging) return;
724
+ const s = this.provider;
725
+ this.logChunk(`yjs:${t === (s == null ? void 0 : s.room) ? "recv" : "send"}`, e);
726
+ const { cells: n, rowHeights: r, columnWidths: i, merges: c } = this.sheet;
727
+ this.log(`yjs:state ${JSON.stringify({ cells: [...n], rowHeights: [...r], columnWidths: [...i], merges: [...c] })}`);
728
+ });
729
+ u(this, "onAwarenessUpdate", ({ added: e, updated: t, removed: s }, n) => {
730
+ if (!this.logging) return;
731
+ const r = this.provider;
732
+ this.log(`awareness:${n === (r == null ? void 0 : r.room) ? "recv" : "send"} added=${e.join(",")} updated=${t.join(",")} removed=${s.join(",")}`), this.log(`awareness:state ${JSON.stringify([...this.awareness.getStates()])}`);
733
+ });
734
+ this.sheet = e, this.awareness = t, this.provider = s, this.room = n, this.log = r, this.logging = i, e.doc.on("update", this.onUpdate), t.on("update", this.onAwarenessUpdate);
735
+ }
736
+ snapshot() {
737
+ return Ue(this.sheet.doc, { room: this.room, sequence: this.sequence });
738
+ }
739
+ updateLog() {
740
+ return { format: "colwork.update-log", version: 1, room: this.room, updates: this.updates.map((e) => ({ ...e })) };
741
+ }
742
+ destroy() {
743
+ this.sheet.doc.off("update", this.onUpdate), this.awareness.off("update", this.onAwarenessUpdate);
744
+ }
745
+ logChunk(e, t) {
746
+ const s = Array.from(t, (n) => n.toString(16).padStart(2, "0")).join(" ");
747
+ this.log(`${e} bytes=${t.byteLength} hex=${s}`);
748
+ }
749
+ inspectConnections() {
750
+ var t, s;
751
+ if (!this.logging) return;
752
+ const e = this.provider;
753
+ (t = e.signalingConns) == null || t.forEach((n) => {
754
+ if (this.loggedSignals.has(n)) return;
755
+ this.loggedSignals.add(n);
756
+ const r = n.send.bind(n);
757
+ n.send = (i) => {
758
+ this.log(`signal:send ${JSON.stringify(i)}`), r(i);
759
+ }, n.on("message", (i) => this.log(`signal:recv ${JSON.stringify(i)}`)), n.on("connect", () => this.log("signal:connect")), n.on("disconnect", () => this.log("signal:disconnect")), n.on("error", (i) => this.log(`signal:error ${String(i)}`));
760
+ }), (s = e.room) == null || s.webrtcConns.forEach((n, r) => {
761
+ const i = n.peer;
762
+ if (this.loggedPeers.has(i)) return;
763
+ this.loggedPeers.add(i);
764
+ const c = i.send.bind(i);
765
+ i.send = (h) => {
766
+ this.logChunk(`webrtc:send peer=${r}`, h), c(h);
767
+ }, i.on("data", (h) => this.logChunk(`webrtc:recv peer=${r}`, h)), i.on("connect", () => this.log(`webrtc:connect peer=${r}`)), i.on("close", () => this.log(`webrtc:close peer=${r}`)), i.on("error", (h) => this.log(`webrtc:error peer=${r} ${String(h)}`));
768
+ });
769
+ }
770
+ }
771
+ const J = /* @__PURE__ */ new WeakMap(), Je = ["stun:stun.qq.com:3478", "stun:stun.miwifi.com:3478", "stun:stun.chat.bilibili.com:3478", "stun:stun.l.google.com:19302", "stun:stun1.l.google.com:19302"].map((o) => ({ urls: o }));
772
+ class Ge {
773
+ constructor(e) {
774
+ u(this, "document");
775
+ u(this, "awareness");
776
+ u(this, "provider");
777
+ u(this, "external");
778
+ u(this, "destroyed", !1);
779
+ u(this, "published", {});
780
+ var s, n, r;
781
+ if (this.external = e.transport === "external", e.transport === "external") {
782
+ if (!((s = e.collaboration) != null && s.document) || !e.collaboration.awareness) throw new TypeError("External collaboration requires a document and awareness");
783
+ if (e.collaboration.awareness.doc !== e.collaboration.document) throw new TypeError("Awareness must belong to the supplied document");
784
+ if (e.rows !== void 0 || e.snapshot !== void 0 || e.updates !== void 0 || e.initializeAfterSync === !0)
785
+ throw new TypeError("Initialize external documents through the model API before creating a table");
786
+ this.document = e.collaboration.document, this.awareness = e.collaboration.awareness;
787
+ } else {
788
+ if (typeof e.room != "string") throw new TypeError("Built-in collaboration requires a room");
789
+ this.document = new D.Doc();
790
+ try {
791
+ if (e.readOnly) this.awareness = new ze(this.document);
792
+ else if (e.transport === "webrtc")
793
+ this.provider = new Me(e.room, this.document, {
794
+ signaling: [e.signalingUrl ?? "ws://127.0.0.1:4444"],
795
+ filterBcConns: !1,
796
+ peerOpts: e.peerOpts ?? { config: { iceServers: Je } }
797
+ }), this.awareness = this.provider.awareness;
798
+ else {
799
+ const i = new URL(e.websocketUrl ?? "ws://127.0.0.1:1234"), c = Object.fromEntries(i.searchParams);
800
+ i.search = "", this.provider = new me(i.toString().replace(/\/$/, ""), encodeURIComponent(e.room), this.document, { params: c, connect: !e.initializeAfterSync }), this.awareness = this.provider.awareness;
801
+ }
802
+ e.snapshot && D.applyUpdate(this.document, e.snapshot), (n = e.updates) == null || n.forEach((i) => D.applyUpdate(this.document, i));
803
+ } catch (i) {
804
+ throw (r = this.provider) == null || r.destroy(), this.document.destroy(), i;
805
+ }
806
+ }
807
+ const t = this.awareness.getLocalState();
808
+ t !== null && t.user === void 0 && this.awareness.setLocalStateField("user", { name: e.user, color: e.userColor });
809
+ }
810
+ publish(e) {
811
+ if (this.destroyed) return;
812
+ const t = this.awareness.getLocalState();
813
+ t !== null && (this.published = { ...this.published, ...e }, J.set(this.awareness, this), this.awareness.setLocalState({ ...t, ...e }));
814
+ }
815
+ finishEditing() {
816
+ var e;
817
+ J.get(this.awareness) === this && ((e = this.awareness.getLocalState()) == null ? void 0 : e.editing) === this.published.editing && this.publish({ editing: null });
818
+ }
819
+ destroy() {
820
+ var n;
821
+ if (this.destroyed) return;
822
+ if (this.destroyed = !0, !this.external) {
823
+ (n = this.provider) == null || n.destroy(), this.awareness.destroy(), this.document.destroy();
824
+ return;
825
+ }
826
+ if (J.get(this.awareness) !== this) return;
827
+ J.delete(this.awareness);
828
+ const e = this.awareness.getLocalState();
829
+ if (e === null) return;
830
+ const t = { ...e };
831
+ let s = !1;
832
+ for (const r of ["selection", "cursor", "editing"])
833
+ r in this.published && t[r] === this.published[r] && (delete t[r], s = !0);
834
+ s && this.awareness.setLocalState(t);
835
+ }
836
+ }
837
+ class Ye {
838
+ constructor(e) {
839
+ u(this, "messageDialog");
840
+ u(this, "passwordDialog");
841
+ this.host = e;
842
+ }
843
+ close() {
844
+ var e, t;
845
+ this.closeLockMessage(), (e = this.passwordDialog) == null || e.close(), (t = this.passwordDialog) == null || t.remove(), this.passwordDialog = void 0;
846
+ }
847
+ requestSelectionLock(e, t = !1) {
848
+ if (this.host.readOnly() || this.host.destroyed() || !this.host.selectionFocus() || this.passwordDialog) return;
849
+ this.closeLockMessage();
850
+ const s = $(this.host.selectionAnchor(), this.host.selectionFocus());
851
+ if (!(t || !e && Array.from(this.host.locks.entries()).some(([b, M]) => {
852
+ const [R, _] = b.split(":").map(Number);
853
+ return M !== "1" && P(s, { row: R, column: _ });
854
+ }))) {
855
+ this.host.setSelectionLocked(e).catch((b) => this.showLockMessage(b instanceof Error ? b.message : "操作失败"));
856
+ return;
857
+ }
858
+ const r = document.createElement("dialog");
859
+ this.passwordDialog = r, r.className = "colwork-table__password-dialog", r.setAttribute("aria-label", e ? "密码锁定" : "密码解锁");
860
+ const i = document.createElement("form"), c = document.createElement("h3");
861
+ c.textContent = e ? "设置锁定密码" : "输入解锁密码";
862
+ const h = document.createElement("input");
863
+ h.type = "password", h.required = !0, h.placeholder = e ? "设置密码" : "输入密码", h.autocomplete = e ? "new-password" : "current-password", h.setAttribute("aria-label", "密码");
864
+ const m = document.createElement("input");
865
+ m.type = "password", m.required = e, m.placeholder = "再次输入密码", m.autocomplete = "new-password", m.setAttribute("aria-label", "确认密码");
866
+ const a = document.createElement("p");
867
+ a.setAttribute("role", "alert");
868
+ const l = document.createElement("button");
869
+ l.type = "submit", l.textContent = e ? "确认锁定" : "确认解锁";
870
+ const d = document.createElement("button");
871
+ d.type = "button", d.textContent = "取消", d.addEventListener("click", () => r.close()), r.addEventListener("close", () => {
872
+ h.value = "", m.value = "", r.remove(), this.passwordDialog === r && (this.passwordDialog = void 0);
873
+ });
874
+ const f = this.host.selectionAnchor(), S = f && { ...f }, x = { ...this.host.selectionFocus() };
875
+ i.addEventListener("submit", async (b) => {
876
+ if (b.preventDefault(), !l.disabled) {
877
+ if (e && h.value !== m.value) {
878
+ a.textContent = "两次输入的密码不一致";
879
+ return;
880
+ }
881
+ l.disabled = !0, d.disabled = !0, r.oncancel = (M) => M.preventDefault(), a.textContent = "正在处理…";
882
+ try {
883
+ this.host.restoreSelection(S, x), await this.host.setSelectionLocked(e, h.value), r.close();
884
+ } catch (M) {
885
+ a.textContent = M instanceof Error ? M.message : "操作失败,请重试", h.value = "", m.value = "", h.focus();
886
+ } finally {
887
+ l.disabled = !1, d.disabled = !1, r.oncancel = null;
888
+ }
889
+ }
890
+ }), i.append(c, h), e && i.append(m), i.append(a, l, d), r.append(i), this.host.root().append(r), r.showModal(), h.focus();
891
+ }
892
+ closeLockMessage() {
893
+ const e = this.messageDialog;
894
+ this.messageDialog = void 0, e == null || e.close(), e == null || e.remove();
895
+ }
896
+ showLockMessage(e) {
897
+ if (this.host.destroyed()) return;
898
+ this.closeLockMessage(), this.host.hideMenu();
899
+ const t = document.createElement("dialog");
900
+ this.messageDialog = t, t.className = "colwork-table__message-dialog", t.setAttribute("role", "alertdialog"), t.setAttribute("aria-label", "操作提示"), t.setAttribute("aria-description", e);
901
+ const s = document.createElement("h3");
902
+ s.textContent = "操作提示";
903
+ const n = document.createElement("p");
904
+ n.className = "colwork-table__lock-status", n.setAttribute("role", "status"), n.textContent = e;
905
+ const r = document.createElement("button");
906
+ r.type = "button", r.textContent = "确定", r.addEventListener("click", () => t.close()), t.addEventListener("close", () => {
907
+ t.remove(), this.messageDialog === t && (this.messageDialog = void 0);
908
+ }), t.append(s, n, r), this.host.root().append(t), t.showModal(), r.focus();
909
+ }
910
+ }
911
+ class Xe {
912
+ constructor(e) {
913
+ u(this, "input");
914
+ u(this, "key");
915
+ u(this, "original", "");
916
+ this.host = e;
917
+ }
918
+ start(e, t, s = !0) {
919
+ if (!this.host.canEdit(t) || this.key === t) return;
920
+ this.finish(!0), e = this.host.table.querySelector(`td[data-key="${t}"]`) ?? e, this.key = t, this.original = this.host.read(t) ?? "";
921
+ const n = document.createElement("textarea");
922
+ n.className = "colwork-table__editor", n.value = this.original, this.host.applyStyle(n, t), this.input = n, e.classList.add("is-editing"), e.append(n), s && this.host.announce({ ...this.host.focus() ?? { row: 0, column: 0 }, offset: 0 }), n.addEventListener("input", () => this.host.changed({ editing: !0, dirty: n.value !== this.original })), this.host.changed({ editing: !0, dirty: !1 }), n.addEventListener("blur", () => this.finish(!0), { once: !0 }), n.addEventListener("keydown", (r) => {
923
+ r.key === "Enter" && !r.ctrlKey && !r.shiftKey && n.blur(), r.key === "Escape" && this.finish(!1);
924
+ }), n.focus(), n.select();
925
+ }
926
+ finish(e) {
927
+ if (!this.input || !this.key) return;
928
+ const t = this.key, s = this.input;
929
+ this.input = void 0, this.key = void 0, e && this.host.canEdit(t) && s.value !== this.host.read(t) && this.host.write(t, ke(s.value)), this.original = "", this.host.clearEditingPresence(), s.remove();
930
+ const n = this.host.table.querySelector(`td[data-key="${t}"]`);
931
+ if (!n) {
932
+ this.host.render(), this.host.changed({ editing: !1, dirty: !1 });
933
+ return;
934
+ }
935
+ this.host.table.querySelectorAll("td.is-editing").forEach((i) => i.classList.remove("is-editing"));
936
+ const r = n.querySelector(".colwork-table__cell-value") ?? document.createElement("span");
937
+ r.className = "colwork-table__cell-value", r.textContent = this.host.displayValue(t), r.parentElement || n.append(r), Array.from(n.childNodes).forEach((i) => {
938
+ i !== r && i.nodeType === Node.TEXT_NODE && i.remove();
939
+ }), this.host.applyStyle(n, t), this.host.applyStyle(r, t), this.host.refresh(), this.host.changed({ editing: !1, dirty: !1 });
940
+ }
941
+ }
942
+ class Ze {
943
+ constructor(e, t = null) {
944
+ u(this, "cells");
945
+ u(this, "styles");
946
+ u(this, "rowHeights");
947
+ u(this, "columnWidths");
948
+ u(this, "merges");
949
+ u(this, "locks");
950
+ u(this, "mergeCache");
951
+ u(this, "onMergesChange", () => {
952
+ this.mergeCache = void 0;
953
+ });
954
+ this.doc = e, this.origin = t;
955
+ const s = G(e);
956
+ this.cells = s.cells, this.styles = s.styles, this.rowHeights = s.rowHeights, this.columnWidths = s.columnWidths, this.merges = s.merges, this.locks = s.locks, this.merges.observe(this.onMergesChange);
957
+ }
958
+ getContentSize() {
959
+ let e = 1, t = 1;
960
+ for (const s of [...this.cells.keys(), ...this.styles.keys(), ...this.locks.keys()]) {
961
+ const n = q(s);
962
+ n && (e = Math.max(e, n.row + 1), t = Math.max(t, n.column + 1));
963
+ }
964
+ for (const s of this.getMergeRanges())
965
+ e = Math.max(e, s.end.row + 1), t = Math.max(t, s.end.column + 1);
966
+ for (const s of this.rowHeights.keys()) e = Math.max(e, Number(s) + 1 || 1);
967
+ for (const s of this.columnWidths.keys()) t = Math.max(t, Number(s) + 1 || 1);
968
+ return { rows: e, columns: t };
969
+ }
970
+ hasPartialMerge(e, t, s) {
971
+ return t > s ? !1 : this.getMergeRanges().some((n) => {
972
+ const r = n.start[e], i = n.end[e];
973
+ return r <= s && i >= t && (r < t || i > s);
974
+ });
975
+ }
976
+ rangeHasLocks(e, t = !1) {
977
+ const s = (r) => this.locks.has(r) && (!t || this.locks.get(r) !== "1");
978
+ if ((e.end.row - e.start.row + 1) * (e.end.column - e.start.column + 1) <= this.locks.size) {
979
+ for (let r = e.start.row; r <= e.end.row; r++)
980
+ for (let i = e.start.column; i <= e.end.column; i++) if (s(H({ row: r, column: i }))) return !0;
981
+ return !1;
982
+ }
983
+ for (const r of this.locks.keys()) {
984
+ const i = q(r);
985
+ if (i && s(r) && P(e, i)) return !0;
986
+ }
987
+ return !1;
988
+ }
989
+ isCellLocked(e, t) {
990
+ if (this.locks.has(e)) return !0;
991
+ const s = q(e);
992
+ return t === void 0 && s && (t = this.getMergeRanges().find((n) => P(n, s))), !!t && this.rangeHasLocks(t);
993
+ }
994
+ isCellPasswordLocked(e, t) {
995
+ if (this.locks.has(e) && this.locks.get(e) !== "1") return !0;
996
+ const s = q(e);
997
+ return t === void 0 && s && (t = this.getMergeRanges().find((n) => P(n, s))), !!t && this.rangeHasLocks(t, !0);
998
+ }
999
+ isAxisLocked(e, t, s = !1) {
1000
+ return Array.from(this.locks.keys()).some((n) => {
1001
+ const r = Number(n.split(":")[e === "row" ? 0 : 1]);
1002
+ return s ? r >= t : r === t;
1003
+ });
1004
+ }
1005
+ /** Passwords are optional for legacy/plain locks; protected locks require verification. */
1006
+ mergeKey(e) {
1007
+ return `${e.start.row}:${e.start.column}-${e.end.row}:${e.end.column}`;
1008
+ }
1009
+ getMergeRanges() {
1010
+ if (this.mergeCache) return this.mergeCache;
1011
+ const e = Array.from(this.merges.keys()).flatMap((t) => {
1012
+ const s = te(t);
1013
+ return s ? [s] : [];
1014
+ });
1015
+ return this.doc._transaction === null && (this.mergeCache = e), e;
1016
+ }
1017
+ destroy() {
1018
+ this.merges.unobserve(this.onMergesChange);
1019
+ }
1020
+ expandSelectionToMerges(e, t) {
1021
+ let s = $(e, t);
1022
+ for (const i of this.getMergeRanges())
1023
+ i.start.row <= s.end.row && i.end.row >= s.start.row && i.start.column <= s.end.column && i.end.column >= s.start.column && (s = {
1024
+ start: { row: Math.min(s.start.row, i.start.row), column: Math.min(s.start.column, i.start.column) },
1025
+ end: { row: Math.max(s.end.row, i.end.row), column: Math.max(s.end.column, i.end.column) }
1026
+ });
1027
+ const n = t.row >= e.row, r = t.column >= e.column;
1028
+ return {
1029
+ anchor: {
1030
+ row: n ? s.start.row : s.end.row,
1031
+ column: r ? s.start.column : s.end.column
1032
+ },
1033
+ focus: {
1034
+ row: n ? s.end.row : s.start.row,
1035
+ column: r ? s.end.column : s.start.column
1036
+ }
1037
+ };
1038
+ }
1039
+ seed(e) {
1040
+ e.forEach((t, s) => t.forEach((n, r) => {
1041
+ const i = `${s}:${r}`;
1042
+ !this.cells.has(i) && !this.isCellLocked(i) && this.cells.set(i, n);
1043
+ }));
1044
+ }
1045
+ modifyAxis(e, t, s, n = 0) {
1046
+ const r = [this.cells, this.styles];
1047
+ this.doc.transact(() => {
1048
+ r.forEach((c) => {
1049
+ const h = Array.from(c.entries());
1050
+ c.clear(), h.forEach(([m, a]) => {
1051
+ const [l, d] = m.split(":").map(Number), f = e === "row" ? l : d;
1052
+ if (n && f >= t && f < t + n) return;
1053
+ const S = f >= t + n ? f + s : f, x = H(e === "row" ? { row: S, column: d } : { row: l, column: S });
1054
+ c.set(x, a);
1055
+ });
1056
+ });
1057
+ const i = this.getMergeRanges();
1058
+ this.merges.clear(), i.forEach((c) => {
1059
+ const h = e === "row" ? c.start.row : c.start.column, m = e === "row" ? c.end.row : c.end.column;
1060
+ if (n && h < t + n && m >= t) return;
1061
+ const a = h >= t + n ? s : 0, l = e === "row" ? { start: { row: c.start.row + a, column: c.start.column }, end: { row: c.end.row + a, column: c.end.column } } : { start: { row: c.start.row, column: c.start.column + a }, end: { row: c.end.row, column: c.end.column + a } };
1062
+ this.merges.set(this.mergeKey(l), "1");
1063
+ });
1064
+ }, this.origin);
1065
+ }
1066
+ }
1067
+ class Qe {
1068
+ constructor(e, t) {
1069
+ u(this, "menu");
1070
+ this.viewport = e, this.onHide = t;
1071
+ }
1072
+ contains(e) {
1073
+ var t;
1074
+ return ((t = this.menu) == null ? void 0 : t.contains(e)) ?? !1;
1075
+ }
1076
+ hide() {
1077
+ var e;
1078
+ this.onHide(), (e = this.menu) == null || e.remove(), this.menu = void 0;
1079
+ }
1080
+ show(e, t, s) {
1081
+ var i;
1082
+ this.hide();
1083
+ const n = document.createElement("div");
1084
+ n.className = "colwork-table__context-menu", n.setAttribute("aria-label", "表格操作"), s.forEach(({ label: c, actions: h }) => {
1085
+ const m = document.createElement("div");
1086
+ m.className = "colwork-table__context-group", m.setAttribute("role", "group"), m.setAttribute("aria-label", c);
1087
+ const a = document.createElement("div");
1088
+ a.className = "colwork-table__context-label", a.textContent = c, m.append(a), h.forEach(([l, d]) => {
1089
+ const f = document.createElement("button");
1090
+ f.type = "button", f.textContent = l, (l.startsWith("删除") || l === "清空内容") && (f.className = "is-destructive"), f.addEventListener("click", () => {
1091
+ this.hide(), d();
1092
+ }), m.append(f);
1093
+ }), n.append(m);
1094
+ }), n.addEventListener("keydown", (c) => {
1095
+ var l;
1096
+ if (c.key === "Escape") {
1097
+ c.preventDefault(), this.hide(), this.viewport.focus({ preventScroll: !0 });
1098
+ return;
1099
+ }
1100
+ const h = Array.from(n.querySelectorAll("button")), m = h.indexOf(document.activeElement);
1101
+ let a;
1102
+ if (c.key === "ArrowDown") a = (m + 1) % h.length;
1103
+ else if (c.key === "ArrowUp") a = (m - 1 + h.length) % h.length;
1104
+ else if (c.key === "Home") a = 0;
1105
+ else if (c.key === "End") a = h.length - 1;
1106
+ else return;
1107
+ c.preventDefault(), (l = h[a]) == null || l.focus();
1108
+ }), n.style.left = `${e}px`, n.style.top = `${t}px`, document.body.append(n);
1109
+ const r = n.getBoundingClientRect();
1110
+ n.style.left = `${Math.max(8, Math.min(e, window.innerWidth - r.width - 8))}px`, n.style.top = `${Math.max(8, Math.min(t, window.innerHeight - r.height - 8))}px`, this.menu = n, (i = n.querySelector("button")) == null || i.focus({ preventScroll: !0 });
1111
+ }
1112
+ }
1113
+ function et(o) {
1114
+ var N;
1115
+ let e, t;
1116
+ const s = document.createElement("div");
1117
+ s.className = "colwork-table__toolbar", o.readOnly && (s.hidden = !0), s.setAttribute("aria-label", "表格工具栏");
1118
+ const n = document.createElement("div");
1119
+ n.className = "colwork-table__toolbar-row";
1120
+ const r = document.createElement("div");
1121
+ r.className = "colwork-table__toolbar-row", s.append(n, r);
1122
+ const i = (g, v) => {
1123
+ const y = document.createElement("div");
1124
+ y.className = "colwork-table__toolbar-group", y.setAttribute("role", "group"), y.setAttribute("aria-label", v);
1125
+ const k = document.createElement("span");
1126
+ return k.className = "colwork-table__group-label", k.textContent = v, y.append(k), g.append(y), y;
1127
+ }, c = i(n, "历史"), h = i(n, "单元格"), m = i(n, "保护"), a = i(n, "显示"), l = i(r, "文字"), d = i(r, "对齐"), f = i(r, "格式");
1128
+ [
1129
+ ["撤销", "↶", () => o.undo()],
1130
+ ["重做", "↷", () => o.redo()]
1131
+ ].forEach(([g, v, y], k) => {
1132
+ const L = document.createElement("button");
1133
+ L.type = "button", L.className = `colwork-table__history colwork-table__history--${k === 0 ? "undo" : "redo"}`, L.title = g, L.textContent = v, L.addEventListener("mousedown", (O) => O.preventDefault()), L.addEventListener("click", y), k === 0 ? e = L : t = L, c.append(L);
1134
+ }), [
1135
+ ["合并单元格", "合并", () => o.mergeSelection()],
1136
+ ["拆分单元格", "拆分", () => o.unmergeSelection()]
1137
+ ].forEach(([g, v, y]) => {
1138
+ const k = document.createElement("button");
1139
+ k.type = "button", k.className = "colwork-table__format colwork-table__grid-action", k.title = g, k.textContent = v, k.addEventListener("mousedown", (L) => L.preventDefault()), k.addEventListener("click", y), h.append(k);
1140
+ }), (N = m.querySelector(".colwork-table__group-label")) == null || N.remove();
1141
+ const b = document.createElement("button");
1142
+ b.type = "button", b.className = "colwork-table__format colwork-table__dropdown-trigger", b.textContent = "保护", b.title = "锁定、密码锁定与解锁", b.setAttribute("aria-label", "保护"), b.setAttribute("aria-expanded", "false"), b.addEventListener("mousedown", (g) => g.preventDefault()), b.addEventListener("click", () => {
1143
+ if (b.getAttribute("aria-expanded") === "true") {
1144
+ o.hideContextMenu();
1145
+ return;
1146
+ }
1147
+ const g = b.getBoundingClientRect();
1148
+ o.showContextMenu(g.left, g.bottom + 4, [{ label: "锁定与解锁", actions: o.protectionActions() }]), b.setAttribute("aria-expanded", "true");
1149
+ }), b.addEventListener("keydown", (g) => {
1150
+ g.key === "ArrowDown" && (g.preventDefault(), b.click());
1151
+ }), m.append(b);
1152
+ const M = document.createElement("div");
1153
+ M.className = "colwork-table__view-control";
1154
+ const R = document.createElement("button");
1155
+ R.type = "button", R.className = "colwork-table__format", R.textContent = "视图", R.setAttribute("aria-label", "视图"), R.classList.add("colwork-table__dropdown-trigger"), R.title = "本地视图选项";
1156
+ const _ = document.createElement("div");
1157
+ _.className = "colwork-table__view-menu", [
1158
+ ["隔行异色", () => o.view.bandedRows, (g) => {
1159
+ o.view.bandedRows = g;
1160
+ }],
1161
+ ["显示网格线", () => o.view.showGridLines, (g) => {
1162
+ o.view.showGridLines = g;
1163
+ }]
1164
+ ].forEach(([g, v, y]) => {
1165
+ const k = document.createElement("label"), L = document.createElement("input");
1166
+ L.type = "checkbox", L.checked = v(), L.addEventListener("change", () => {
1167
+ y(L.checked), o.render();
1168
+ }), k.append(L, document.createTextNode(g)), _.append(k);
1169
+ }), [
1170
+ ["固定至选中行", () => o.freezeSelection("row")],
1171
+ ["固定至选中列", () => o.freezeSelection("column")],
1172
+ ["取消固定", () => o.setFrozenPanes(0, 0)]
1173
+ ].forEach(([g, v]) => {
1174
+ const y = document.createElement("button");
1175
+ y.type = "button", y.textContent = g, y.addEventListener("mousedown", (k) => k.preventDefault()), y.addEventListener("click", v), _.append(y);
1176
+ }), M.append(R, _), a.append(M), [
1177
+ ["bold", "B", "加粗"],
1178
+ ["italic", "I", "斜体"],
1179
+ ["underline", "U", "下划线"],
1180
+ ["strike", "S", "删除线"],
1181
+ ["wrap", "换行", "自动换行"],
1182
+ ["align-left", "左", "左对齐"],
1183
+ ["align-center", "中", "居中"],
1184
+ ["align-right", "右", "右对齐"]
1185
+ ].forEach(([g, v, y]) => {
1186
+ const k = document.createElement("button");
1187
+ k.type = "button", k.className = `colwork-table__format colwork-table__format--${g}`, k.textContent = v, k.title = y, k.addEventListener("mousedown", (L) => L.preventDefault()), k.addEventListener("click", () => g.startsWith("align-") ? o.setStyle("align", g.slice(6)) : o.toggleFormat(g)), (g.startsWith("align-") || g === "wrap" ? d : l).append(k);
1188
+ });
1189
+ const p = document.createElement("select");
1190
+ p.className = "colwork-table__select", p.title = "字体大小", [10, 12, 14, 16, 18, 24].forEach((g) => {
1191
+ const v = document.createElement("option");
1192
+ v.value = String(g), v.textContent = `${g}px`, p.append(v);
1193
+ }), p.addEventListener("change", () => o.setStyle("fontSize", Number(p.value))), l.append(p);
1194
+ const E = document.createElement("select");
1195
+ E.className = "colwork-table__select", E.title = "单元格格式", [
1196
+ ["general", "常规"],
1197
+ ["number", "数字"],
1198
+ ["date", "日期"],
1199
+ ["percent", "百分比"]
1200
+ ].forEach(([g, v]) => {
1201
+ const y = document.createElement("option");
1202
+ y.value = g, y.textContent = v, E.append(y);
1203
+ }), E.addEventListener("change", () => o.setStyle("format", E.value)), f.append(E);
1204
+ const z = document.createElement("button");
1205
+ z.type = "button", z.className = "colwork-table__format", z.title = "清除格式", z.textContent = "清除", z.addEventListener("mousedown", (g) => g.preventDefault()), z.addEventListener("click", () => o.clearFormatting()), f.append(z);
1206
+ const A = document.createElement("div");
1207
+ A.className = "colwork-table__border-control";
1208
+ const C = document.createElement("button");
1209
+ C.type = "button", C.className = "colwork-table__format", C.title = "边框选项", C.textContent = "边框", C.setAttribute("aria-label", "边框"), C.classList.add("colwork-table__dropdown-trigger");
1210
+ const B = document.createElement("div");
1211
+ return B.className = "colwork-table__border-menu", [
1212
+ ["外围", "outer"],
1213
+ ["中间", "inner"],
1214
+ ["横线", "horizontal"],
1215
+ ["竖线", "vertical"]
1216
+ ].forEach(([g, v]) => {
1217
+ const y = document.createElement("button");
1218
+ y.type = "button", y.textContent = g, y.addEventListener("click", () => o.toggleBorder(v)), B.append(y);
1219
+ }), A.append(C, B), f.insertBefore(A, z), [
1220
+ ["color", "文字颜色"],
1221
+ ["background", "背景颜色"]
1222
+ ].forEach(([g, v]) => {
1223
+ const y = document.createElement("input");
1224
+ y.type = "color", y.className = `colwork-table__color colwork-table__color--${g}`, y.title = v, y.addEventListener("input", () => o.setStyle(g, y.value)), (g === "color" ? l : f).append(y);
1225
+ }), { toolbar: s, undoButton: e, redoButton: t, protectionButton: b };
1226
+ }
1227
+ function tt(o, e, t, s) {
1228
+ const n = /* @__PURE__ */ new Map(), r = (i, c, h, m, a) => {
1229
+ const l = [];
1230
+ h > 0 && i < h && l.push([i, Math.min(c, h - 1)]);
1231
+ const d = Math.max(i, h, m), f = Math.min(c, a);
1232
+ return d <= f && l.push([d, f]), l;
1233
+ };
1234
+ for (const i of o) {
1235
+ const c = r(i.start.row, i.end.row, t, e.top, e.bottom), h = r(i.start.column, i.end.column, s, e.left, e.right);
1236
+ for (const [m, a] of c)
1237
+ for (const [l, d] of h) {
1238
+ const f = { source: i, start: { row: m, column: l }, end: { row: a, column: d } };
1239
+ for (let S = m; S <= a; S++)
1240
+ for (let x = l; x <= d; x++) n.set(H({ row: S, column: x }), f);
1241
+ }
1242
+ }
1243
+ return n;
1244
+ }
1245
+ function st(o, e) {
1246
+ return o.start.row === e.row && o.start.column === e.column;
1247
+ }
1248
+ const ot = 54, nt = 42, he = 12, rt = 56, it = 150, de = 28, ue = 64, at = 0.25, lt = 2;
1249
+ function ct(o) {
1250
+ let e = o + 1, t = "";
1251
+ for (; e > 0; )
1252
+ e -= 1, t = String.fromCharCode(65 + e % 26) + t, e = Math.floor(e / 26);
1253
+ return t;
1254
+ }
1255
+ function ht(o) {
1256
+ const { rowCount: e, columnCount: t } = o, s = (w) => o.getRowHeight(w), n = (w) => o.getColumnWidth(w), r = He({
1257
+ scrollTop: o.viewport.scrollTop,
1258
+ scrollLeft: o.viewport.scrollLeft,
1259
+ clientHeight: o.viewport.clientHeight || 560,
1260
+ clientWidth: o.viewport.clientWidth || 900,
1261
+ rowCount: e,
1262
+ columnCount: t,
1263
+ rowSize: s,
1264
+ columnSize: n,
1265
+ overscan: 4
1266
+ }), i = tt(o.getMergeRanges(), r, o.frozenRows, o.frozenColumns);
1267
+ r.bottom = Math.max(r.bottom, o.frozenRows - 1), r.right = Math.max(r.right, o.frozenColumns - 1);
1268
+ const c = Math.max(o.frozenRows, r.top), h = Math.max(o.frozenColumns, r.left), m = (w, p, E) => [
1269
+ ...Array.from({ length: w }, (z, A) => A),
1270
+ -1,
1271
+ // spacer between the frozen prefix and the virtual window
1272
+ ...Array.from({ length: Math.max(0, E - p + 1) }, (z, A) => p + A)
1273
+ ], a = m(o.frozenRows, c, r.bottom), l = m(o.frozenColumns, h, r.right), d = W(h, n) - W(o.frozenColumns, n), f = W(c, s) - W(o.frozenRows, s), S = (w, p, E) => {
1274
+ const z = p >= 0 && p < o.frozenRows, A = E >= 0 && E < o.frozenColumns;
1275
+ !z && !A || (w.classList.add("is-frozen"), w.style.position = "sticky", z && (w.style.top = `${o.columnHeaderHeight + W(p, s)}px`), A && (w.style.left = `${o.rowHeaderWidth + W(E, n)}px`), w.style.zIndex = String(p < 0 ? 10 : E < 0 ? 8 : z && A ? 5 : z ? 4 : 3));
1276
+ }, x = document.createElement("thead"), b = document.createElement("tr"), M = document.createElement("th");
1277
+ M.style.width = `${o.rowHeaderWidth}px`, M.style.height = `${o.columnHeaderHeight}px`, M.addEventListener("mousedown", (w) => {
1278
+ w.preventDefault(), w.stopPropagation(), o.selectRange({ row: 0, column: 0 }, { row: e - 1, column: t - 1 }, "all");
1279
+ }), b.append(M);
1280
+ const R = (w) => {
1281
+ const p = document.createElement("th");
1282
+ return p.style.width = `${w}px`, p.style.padding = "0", p.style.border = "0", p;
1283
+ };
1284
+ for (const w of l) {
1285
+ if (w === -1) {
1286
+ b.append(R(d));
1287
+ continue;
1288
+ }
1289
+ const p = document.createElement("th");
1290
+ p.style.width = `${n(w)}px`, p.style.height = `${o.columnHeaderHeight}px`, p.style.fontSize = `${he * o.zoomRatio}px`;
1291
+ const E = document.createElement("b");
1292
+ E.className = "colwork-table__column-letter", E.textContent = ct(w), p.append(E), o.addResizeHandle(p, "column", w), o.addHeaderSelection(p, "column", w), S(p, -1, w), b.append(p);
1293
+ }
1294
+ b.append(R(j(t, n) - W(r.right + 1, n))), x.append(b);
1295
+ const _ = document.createElement("tbody"), T = (w) => {
1296
+ const p = document.createElement("tr");
1297
+ p.className = "colwork-table__spacer", p.style.height = `${w}px`;
1298
+ const E = document.createElement("td");
1299
+ return E.colSpan = l.length + 2, E.style.height = `${w}px`, p.append(E), p;
1300
+ };
1301
+ for (const w of a) {
1302
+ if (w === -1) {
1303
+ _.append(T(f));
1304
+ continue;
1305
+ }
1306
+ const p = document.createElement("tr");
1307
+ o.bandedRows && w % 2 === 1 && (p.className = "is-banded-row"), p.style.height = `${s(w)}px`;
1308
+ const E = document.createElement("th");
1309
+ E.style.width = `${o.rowHeaderWidth}px`, E.style.height = `${s(w)}px`, E.style.fontSize = `${he * o.zoomRatio}px`, E.textContent = String(w + 1), o.addResizeHandle(E, "row", w), o.addHeaderSelection(E, "row", w), p.append(E), S(E, w, -1);
1310
+ for (const A of l) {
1311
+ if (A === -1) {
1312
+ const k = document.createElement("td");
1313
+ k.style.width = `${d}px`, k.style.padding = "0", k.style.border = "0", p.append(k);
1314
+ continue;
1315
+ }
1316
+ const C = i.get(H({ row: w, column: A }));
1317
+ if (C && !st(C, { row: w, column: A })) continue;
1318
+ const B = (C == null ? void 0 : C.source.start) ?? { row: w, column: A }, N = H(B), g = document.createElement("td");
1319
+ g.style.width = `${n(A)}px`, g.style.height = `${s(w)}px`, g.dataset.key = N, C && (g.rowSpan = C.end.row - C.start.row + 1, g.colSpan = C.end.column - C.start.column + 1, g.dataset.renderRow = String(C.start.row), g.dataset.renderColumn = String(C.start.column), g.dataset.renderBottom = String(C.end.row), g.dataset.renderRight = String(C.end.column));
1320
+ const v = document.createElement("span");
1321
+ v.className = "colwork-table__cell-value", v.style.height = `${Math.max(0, s(w) - 4)}px`, v.style.maxHeight = `${Math.max(0, s(w) - 4)}px`, v.textContent = o.displayValue(N), o.applyStyle(v, N), g.append(v), o.applyStyle(g, N), S(g, w, A);
1322
+ const y = o.isCellLocked(N, (C == null ? void 0 : C.source) ?? null);
1323
+ g.classList.toggle("is-locked", y), g.classList.toggle("is-password-locked", o.isCellPasswordLocked(N, (C == null ? void 0 : C.source) ?? null)), g.setAttribute("aria-readonly", String(o.readOnly || y)), y && (g.title = o.isCellPasswordLocked(N, (C == null ? void 0 : C.source) ?? null) ? "密码锁定:验证密码后可编辑" : "已锁定:解锁后可编辑"), o.attachCellListeners(g, N, B.row, B.column), p.append(g);
1324
+ }
1325
+ const z = document.createElement("td");
1326
+ z.style.width = `${j(t, n) - W(r.right + 1, n)}px`, z.style.padding = "0", z.style.border = "0", p.append(z), _.append(p);
1327
+ }
1328
+ _.append(T(j(e, s) - W(r.bottom + 1, s))), o.table.style.setProperty("--colwork-zoom", String(o.zoomRatio)), o.table.style.width = `${o.rowHeaderWidth + j(t, n)}px`, o.table.classList.toggle("is-grid-hidden", !o.showGridLines), o.table.classList.toggle("is-banded-rows", o.bandedRows), o.table.style.fontSize = `${o.zoomRatio}em`, o.table.replaceChildren(x, _);
1329
+ }
1330
+ class dt {
1331
+ constructor(e, t, s, n) {
1332
+ this.doc = e, this.cells = t, this.styles = s, this.host = n;
1333
+ }
1334
+ readStyle(e) {
1335
+ try {
1336
+ const t = JSON.parse(this.styles.get(e) ?? "{}");
1337
+ return se(t) ? t : {};
1338
+ } catch {
1339
+ return {};
1340
+ }
1341
+ }
1342
+ applyStyle(e, t) {
1343
+ var n, r, i, c;
1344
+ const s = this.readStyle(t);
1345
+ e.style.fontWeight = s.bold ? "700" : "", e.style.fontStyle = s.italic ? "oblique" : "", e.style.textDecoration = [s.underline ? "underline" : "", s.strike ? "line-through" : ""].filter(Boolean).join(" "), e.style.transform = e.classList.contains("colwork-table__cell-value") && s.italic ? "skewX(-8deg)" : "", e.style.fontSize = s.fontSize ? `${s.fontSize * this.host.zoom()}px` : "", e.style.color = s.color ?? "", e.style.backgroundColor = s.background ?? "", e.style.textAlign = s.align ?? "", e.classList.contains("colwork-table__cell-value") && (e.style.whiteSpace = s.wrap ? "pre-wrap" : "pre"), !e.classList.contains("colwork-table__cell-value") && !e.classList.contains("colwork-table__editor") && (e.style.borderTop = (n = s.border) != null && n.top ? "2px solid #64748b" : "", e.style.borderRight = (r = s.border) != null && r.right ? "2px solid #64748b" : "", e.style.borderBottom = (i = s.border) != null && i.bottom ? "2px solid #64748b" : "", e.style.borderLeft = (c = s.border) != null && c.left ? "2px solid #64748b" : "");
1346
+ }
1347
+ displayValue(e) {
1348
+ const t = this.cells.get(e) ?? "", s = this.readStyle(e).format ?? "general";
1349
+ if (!t || s === "general") return t;
1350
+ if (s === "number") {
1351
+ const r = Number(t);
1352
+ return Number.isFinite(r) ? r.toLocaleString() : t;
1353
+ }
1354
+ if (s === "percent") {
1355
+ const r = Number(t.replace(/%$/, ""));
1356
+ return Number.isFinite(r) ? `${t.endsWith("%") ? r : r * 100}%` : t;
1357
+ }
1358
+ const n = new Date(t);
1359
+ return Number.isNaN(n.getTime()) ? t : n.toISOString().slice(0, 10);
1360
+ }
1361
+ toggleFormat(e) {
1362
+ if (!this.host.canEdit() || !this.host.selectedKey()) return;
1363
+ const { top: t, bottom: s, left: n, right: r } = this.host.bounds(), i = this.readStyle(this.host.selectedKey())[e];
1364
+ this.doc.transact(() => {
1365
+ for (let c = t; c <= s; c += 1)
1366
+ for (let h = n; h <= r; h += 1) {
1367
+ const m = `${c}:${h}`, a = this.readStyle(m);
1368
+ a[e] = !i, this.styles.set(m, JSON.stringify(a));
1369
+ }
1370
+ }, this.host.origin), this.host.render();
1371
+ }
1372
+ clearFormatting() {
1373
+ if (!this.host.canEdit() || !this.host.selectedKey()) return;
1374
+ const { top: e, bottom: t, left: s, right: n } = this.host.bounds();
1375
+ this.doc.transact(() => {
1376
+ for (let r = e; r <= t; r += 1)
1377
+ for (let i = s; i <= n; i += 1) this.styles.delete(H({ row: r, column: i }));
1378
+ }, this.host.origin), this.host.render();
1379
+ }
1380
+ toggleBorder(e) {
1381
+ if (!this.host.canEdit() || !this.host.selectedKey()) return;
1382
+ const { top: t, bottom: s, left: n, right: r } = this.host.bounds(), i = (a, l) => {
1383
+ const d = [];
1384
+ return e === "outer" && (a === t && d.push("top"), a === s && d.push("bottom"), l === n && d.push("left"), l === r && d.push("right")), (e === "inner" || e === "horizontal") && a < s && d.push("bottom"), (e === "inner" || e === "vertical") && l < r && d.push("right"), d;
1385
+ }, c = Array.from({ length: s - t + 1 }, (a, l) => Array.from({ length: r - n + 1 }, (d, f) => ({
1386
+ row: t + l,
1387
+ column: n + f
1388
+ }))).flat();
1389
+ if (!c.flatMap(({ row: a, column: l }) => i(a, l)).length) return;
1390
+ const m = !c.every(({ row: a, column: l }) => i(a, l).every((d) => {
1391
+ var f;
1392
+ return (f = this.readStyle(H({ row: a, column: l })).border) == null ? void 0 : f[d];
1393
+ }));
1394
+ this.doc.transact(() => {
1395
+ for (let a = t; a <= s; a += 1)
1396
+ for (let l = n; l <= r; l += 1) {
1397
+ const d = H({ row: a, column: l }), f = this.readStyle(d), S = { ...f.border ?? {} };
1398
+ i(a, l).forEach((x) => {
1399
+ m ? S[x] = !0 : delete S[x];
1400
+ }), Object.keys(S).length ? f.border = S : delete f.border, this.styles.set(d, JSON.stringify(f));
1401
+ }
1402
+ }, this.host.origin), this.host.render();
1403
+ }
1404
+ setStyle(e, t) {
1405
+ if (!this.host.canEdit() || !this.host.selectedKey()) return;
1406
+ const { top: s, bottom: n, left: r, right: i } = this.host.bounds();
1407
+ this.doc.transact(() => {
1408
+ for (let c = s; c <= n; c += 1)
1409
+ for (let h = r; h <= i; h += 1) {
1410
+ const m = `${c}:${h}`, a = this.readStyle(m);
1411
+ e === "align" ? a.align = t : e === "color" ? a.color = t : e === "background" ? a.background = t : e === "fontSize" ? a.fontSize = t : a.format = t, this.styles.set(m, JSON.stringify(a));
1412
+ }
1413
+ }, this.host.origin), this.host.render();
1414
+ }
1415
+ }
1416
+ const oe = 6e5, Q = (o) => Array.from(o, (e) => e.toString(16).padStart(2, "0")).join("");
1417
+ async function Ee(o, e) {
1418
+ var s;
1419
+ if (!((s = globalThis.crypto) != null && s.subtle)) throw new Error("密码锁定需要 HTTPS 或 localhost 环境");
1420
+ const t = await crypto.subtle.importKey("raw", new TextEncoder().encode(o), "PBKDF2", !1, ["deriveBits"]);
1421
+ return new Uint8Array(await crypto.subtle.deriveBits({ name: "PBKDF2", hash: "SHA-256", salt: e, iterations: oe }, t, 256));
1422
+ }
1423
+ async function ut(o) {
1424
+ var s;
1425
+ if (!o.length) throw new Error("密码不能为空");
1426
+ if (!((s = globalThis.crypto) != null && s.subtle)) throw new Error("密码锁定需要 HTTPS 或 localhost 环境");
1427
+ const e = crypto.getRandomValues(new Uint8Array(16)), t = {
1428
+ version: 1,
1429
+ algorithm: "PBKDF2-SHA-256",
1430
+ iterations: oe,
1431
+ salt: Q(e),
1432
+ verifier: Q(await Ee(o, e))
1433
+ };
1434
+ return JSON.stringify(t);
1435
+ }
1436
+ async function mt(o, e) {
1437
+ let t;
1438
+ try {
1439
+ t = JSON.parse(o);
1440
+ } catch {
1441
+ throw new Error("锁定数据无效,无法解锁");
1442
+ }
1443
+ if (!t || t.version !== 1 || t.algorithm !== "PBKDF2-SHA-256" || t.iterations !== oe || typeof t.salt != "string" || !/^[0-9a-f]{32}$/.test(t.salt) || typeof t.verifier != "string" || !/^[0-9a-f]{64}$/.test(t.verifier))
1444
+ throw new Error("锁定数据无效或版本不受支持,无法解锁");
1445
+ const s = Uint8Array.from(t.salt.match(/../g), (i) => parseInt(i, 16)), n = Q(await Ee(e, s));
1446
+ let r = 0;
1447
+ for (let i = 0; i < n.length; i += 1) r |= n.charCodeAt(i) ^ t.verifier.charCodeAt(i);
1448
+ return r === 0;
1449
+ }
1450
+ class Et {
1451
+ constructor(e, t) {
1452
+ u(this, "session");
1453
+ u(this, "doc");
1454
+ u(this, "sheet");
1455
+ u(this, "cells");
1456
+ u(this, "styles");
1457
+ u(this, "rowHeights");
1458
+ u(this, "columnWidths");
1459
+ u(this, "locks");
1460
+ u(this, "pointer");
1461
+ u(this, "clipboard");
1462
+ u(this, "selection");
1463
+ u(this, "formatting");
1464
+ u(this, "dialogs");
1465
+ u(this, "destroyed", !1);
1466
+ u(this, "editEpoch", 0);
1467
+ u(this, "frozenRows", 0);
1468
+ u(this, "frozenColumns", 0);
1469
+ u(this, "merges");
1470
+ u(this, "undoManager");
1471
+ u(this, "provider");
1472
+ u(this, "awareness");
1473
+ u(this, "root");
1474
+ u(this, "options");
1475
+ u(this, "toolbar");
1476
+ u(this, "table");
1477
+ u(this, "viewportResizeObserver");
1478
+ u(this, "viewport");
1479
+ u(this, "frozenBoundaryLayer");
1480
+ u(this, "protectionMenuButton");
1481
+ u(this, "menu");
1482
+ u(this, "undoButton");
1483
+ u(this, "redoButton");
1484
+ u(this, "dimensions");
1485
+ u(this, "zoomRatio", 1);
1486
+ u(this, "showGridLines", !0);
1487
+ u(this, "bandedRows", !1);
1488
+ u(this, "readOnly");
1489
+ u(this, "archive");
1490
+ u(this, "resizing");
1491
+ u(this, "onCellsChange", () => {
1492
+ this.expandLogicalSizeFromDocument() ? this.render() : this.refreshValues();
1493
+ });
1494
+ u(this, "onStylesChange", () => {
1495
+ this.expandLogicalSizeFromDocument() ? this.render() : this.refreshStyles();
1496
+ });
1497
+ u(this, "onSizesChange", () => this.render());
1498
+ u(this, "onMergesChange", () => this.render());
1499
+ u(this, "onLocksChange", () => {
1500
+ this.undoManager.clear(), this.editing.key && this.sheet.isCellLocked(this.editing.key) && this.editing.finish(!1), this.resizing && this.sheet.isAxisLocked(this.resizing.axis, this.resizing.index) && (this.resizing = void 0, this.viewport.classList.remove("is-resizing")), this.render();
1501
+ });
1502
+ u(this, "onAwarenessChange", () => {
1503
+ this.table && (this.expandForRemoteSelections() ? this.render() : this.refreshCursors());
1504
+ });
1505
+ u(this, "renderFrame");
1506
+ u(this, "onViewportScroll", () => {
1507
+ this.renderFrame === void 0 && (this.renderFrame = requestAnimationFrame(() => {
1508
+ this.renderFrame = void 0, this.expandLogicalSpace(), this.render();
1509
+ }));
1510
+ });
1511
+ u(this, "onViewportWheel", (e) => {
1512
+ if (!e.ctrlKey) return;
1513
+ e.preventDefault();
1514
+ const t = e.deltaY < 0 ? 1.1 : 0.9;
1515
+ this.zoomRatio = Math.max(at, Math.min(lt, this.zoomRatio * t)), this.expandLogicalSpace(), this.render();
1516
+ });
1517
+ u(this, "onViewportKeyDown", (e) => {
1518
+ if (this.readOnly || this.editing.input) return;
1519
+ const t = e.ctrlKey || e.metaKey;
1520
+ if (t && e.key.toLowerCase() === "z") {
1521
+ e.preventDefault(), e.shiftKey ? this.redo() : this.undo();
1522
+ return;
1523
+ }
1524
+ if (t && e.key.toLowerCase() === "y") {
1525
+ e.preventDefault(), this.redo();
1526
+ return;
1527
+ }
1528
+ if (e.key !== " " || !this.selection.focus) return;
1529
+ const s = `${this.selection.focus.row}:${this.selection.focus.column}`, n = this.table.querySelector(`td[data-key="${s}"]`);
1530
+ n && (e.preventDefault(), this.editing.start(n, s));
1531
+ });
1532
+ u(this, "onTableMouseDown", (e) => {
1533
+ e.target.closest("th") && e.preventDefault();
1534
+ });
1535
+ u(this, "onDocumentMouseDown", (e) => {
1536
+ var t;
1537
+ !this.menu.contains(e.target) && !((t = this.protectionMenuButton) != null && t.contains(e.target)) && this.menu.hide();
1538
+ });
1539
+ u(this, "onWindowMouseUp", (e) => {
1540
+ if (this.resizing) {
1541
+ const t = this.resizing;
1542
+ this.doc.transact(() => {
1543
+ (t.axis === "row" ? this.rowHeights : this.columnWidths).set(String(t.index), t.currentSize / this.zoomRatio);
1544
+ }, this), this.resizing = void 0, this.viewport.classList.remove("is-resizing");
1545
+ return;
1546
+ }
1547
+ this.pointer.release(e);
1548
+ });
1549
+ u(this, "onWindowBlur", () => this.pointer.blur());
1550
+ u(this, "onWindowMouseMove", (e) => {
1551
+ if (this.pointer.headerSelecting && !(e.buttons & 1) && this.onWindowBlur(), !this.resizing) return;
1552
+ const t = this.resizing.axis === "row" ? e.clientY - this.resizing.start : e.clientX - this.resizing.start, s = (this.resizing.axis === "row" ? de : ue) * this.zoomRatio, n = Math.max(s, this.resizing.size + t);
1553
+ this.resizing.currentSize = n, this.render();
1554
+ });
1555
+ u(this, "onHistoryChange", () => this.refreshHistoryButtons());
1556
+ u(this, "editing");
1557
+ var m;
1558
+ this.root = e, this.options = t, this.readOnly = t.readOnly === !0, this.dimensions = new Re(t), this.session = new Ge(t), this.doc = this.session.document, this.awareness = this.session.awareness, this.provider = this.session.provider, this.sheet = new Ze(this.doc, this), this.cells = this.sheet.cells, this.styles = this.sheet.styles, this.rowHeights = this.sheet.rowHeights, this.columnWidths = this.sheet.columnWidths, this.merges = this.sheet.merges, this.locks = this.sheet.locks, this.selection = new We({
1559
+ sheet: this.sheet,
1560
+ session: this.session,
1561
+ dimensions: () => ({ rows: this.rowCount, columns: this.columnCount }),
1562
+ editingKey: () => {
1563
+ var a;
1564
+ return (a = this.editing) == null ? void 0 : a.key;
1565
+ },
1566
+ refresh: () => this.refreshSelection()
1567
+ }), this.formatting = new dt(this.doc, this.cells, this.styles, {
1568
+ origin: this,
1569
+ zoom: () => this.zoomRatio,
1570
+ canEdit: () => !this.readOnly && !this.destroyed && !this.selectionHasLocks(),
1571
+ selectedKey: () => this.selection.selectedKey,
1572
+ bounds: () => this.selection.getSelectionBounds(),
1573
+ render: () => this.render()
1574
+ }), this.dialogs = new Ye({
1575
+ readOnly: () => this.readOnly,
1576
+ destroyed: () => this.destroyed,
1577
+ selectionFocus: () => this.selection.focus,
1578
+ selectionAnchor: () => this.selection.anchor,
1579
+ restoreSelection: (a, l) => {
1580
+ this.selection.anchor = a, this.selection.focus = l;
1581
+ },
1582
+ root: () => this.root,
1583
+ locks: this.locks,
1584
+ hideMenu: () => this.menu.hide(),
1585
+ setSelectionLocked: (a, l) => this.setSelectionLocked(a, l)
1586
+ });
1587
+ const s = t.transport === "webrtc";
1588
+ this.log(`room:${t.room}`), this.archive = new je(this.sheet, this.awareness, this.provider, t.room, (a) => this.log(a), !!t.onLog), this.awareness.on("change", this.onAwarenessChange), s && this.provider && this.archive.inspectConnections();
1589
+ const n = document.createElement("section");
1590
+ n.className = "colwork-table", this.viewport = document.createElement("div"), this.viewport.className = "colwork-table__viewport", this.menu = new Qe(this.viewport, () => {
1591
+ var a;
1592
+ return (a = this.protectionMenuButton) == null ? void 0 : a.setAttribute("aria-expanded", "false");
1593
+ }), this.viewport.addEventListener("scroll", this.onViewportScroll), this.viewport.addEventListener("wheel", this.onViewportWheel, { passive: !1 }), this.viewport.tabIndex = 0, this.viewport.addEventListener("keydown", this.onViewportKeyDown), window.addEventListener("mouseup", this.onWindowMouseUp), window.addEventListener("mousemove", this.onWindowMouseMove), window.addEventListener("blur", this.onWindowBlur), document.addEventListener("mousedown", this.onDocumentMouseDown), this.table = document.createElement("table"), this.editing = new Xe({
1594
+ table: this.table,
1595
+ canEdit: (a) => !this.readOnly && !this.destroyed && !this.sheet.isCellLocked(a),
1596
+ read: (a) => this.cells.get(a),
1597
+ write: (a, l) => this.doc.transact(() => this.cells.set(a, l), this),
1598
+ applyStyle: (a, l) => this.formatting.applyStyle(a, l),
1599
+ displayValue: (a) => this.formatting.displayValue(a),
1600
+ announce: (a) => this.selection.sendAwareness(a),
1601
+ focus: () => this.selection.focus,
1602
+ clearEditingPresence: () => {
1603
+ this.destroyed || this.session.finishEditing();
1604
+ },
1605
+ changed: (a) => {
1606
+ var l, d;
1607
+ return (d = (l = this.options).onEditingChange) == null ? void 0 : d.call(l, a);
1608
+ },
1609
+ refresh: () => {
1610
+ this.refreshSelection(), this.refreshCursors();
1611
+ },
1612
+ render: () => {
1613
+ this.destroyed || this.render();
1614
+ }
1615
+ }), this.clipboard = new Te({
1616
+ sheet: this.sheet,
1617
+ selection: this.selection,
1618
+ editing: this.editing,
1619
+ formatting: this.formatting,
1620
+ canEdit: () => !this.readOnly && !this.destroyed,
1621
+ dimensions: () => ({ rows: this.rowCount, columns: this.columnCount }),
1622
+ render: () => this.render(),
1623
+ origin: this
1624
+ }), this.pointer = new Oe({
1625
+ selection: this.selection,
1626
+ menu: this.menu,
1627
+ viewport: this.viewport,
1628
+ editing: this.editing,
1629
+ dialogs: this.dialogs,
1630
+ clipboard: this.clipboard,
1631
+ canEdit: () => !this.readOnly && !this.destroyed,
1632
+ freezeSelection: (a) => this.freezeSelection(a),
1633
+ setFrozenPanes: (a, l) => this.setFrozenPanes(a, l),
1634
+ modifyAxis: (a, l, d) => this.modifyAxis(a, l, d),
1635
+ deleteRows: () => this.deleteRows(),
1636
+ deleteColumns: () => this.deleteColumns(),
1637
+ mergeSelection: () => this.mergeSelection(),
1638
+ unmergeSelection: () => this.unmergeSelection(),
1639
+ clearSelectionContents: () => this.clearSelectionContents(),
1640
+ refreshSelection: () => this.refreshSelection()
1641
+ }), this.table.addEventListener("mousedown", this.onTableMouseDown), this.viewport.addEventListener("copy", this.clipboard.onCopy, !0), this.viewport.addEventListener("paste", this.clipboard.onPaste, !0), this.viewport.append(this.table), this.frozenBoundaryLayer = document.createElement("div"), this.frozenBoundaryLayer.className = "colwork-table__frozen-boundaries", this.frozenBoundaryLayer.setAttribute("aria-hidden", "true");
1642
+ const r = this, i = et({
1643
+ readOnly: this.readOnly,
1644
+ view: {
1645
+ get bandedRows() {
1646
+ return r.bandedRows;
1647
+ },
1648
+ set bandedRows(a) {
1649
+ r.bandedRows = a;
1650
+ },
1651
+ get showGridLines() {
1652
+ return r.showGridLines;
1653
+ },
1654
+ set showGridLines(a) {
1655
+ r.showGridLines = a;
1656
+ }
1657
+ },
1658
+ undo: () => this.undo(),
1659
+ redo: () => this.redo(),
1660
+ mergeSelection: () => this.mergeSelection(),
1661
+ unmergeSelection: () => this.unmergeSelection(),
1662
+ hideContextMenu: () => this.menu.hide(),
1663
+ showContextMenu: (a, l, d) => this.menu.show(a, l, d),
1664
+ protectionActions: () => this.pointer.protectionActions(),
1665
+ freezeSelection: (a) => this.freezeSelection(a),
1666
+ setFrozenPanes: (a, l) => this.setFrozenPanes(a, l),
1667
+ render: () => this.render(),
1668
+ setStyle: (a, l) => this.formatting.setStyle(a, l),
1669
+ toggleFormat: (a) => this.formatting.toggleFormat(a),
1670
+ clearFormatting: () => this.formatting.clearFormatting(),
1671
+ toggleBorder: (a) => this.formatting.toggleBorder(a)
1672
+ });
1673
+ this.toolbar = i.toolbar, this.undoButton = i.undoButton, this.redoButton = i.redoButton, this.protectionMenuButton = i.protectionButton, n.append(this.toolbar, this.viewport, this.frozenBoundaryLayer), e.replaceChildren(n);
1674
+ const c = !this.session.external && !this.readOnly && !t.snapshot && !((m = t.updates) != null && m.length), h = c && this.cells.size === 0 && this.locks.size === 0;
1675
+ c && !t.initializeAfterSync && this.sheet.seed(t.rows ?? ge), h && !t.initializeAfterSync && pe(this.sheet), this.expandLogicalSizeFromDocument(), this.undoManager = new D.UndoManager([this.cells, this.styles, this.rowHeights, this.columnWidths, this.merges], { captureTimeout: 500, trackedOrigins: this.session.external ? /* @__PURE__ */ new Set([this]) : /* @__PURE__ */ new Set([null, this]) }), this.undoManager.on("stack-item-added", this.onHistoryChange), this.undoManager.on("stack-item-popped", this.onHistoryChange), this.undoManager.on("stack-cleared", this.onHistoryChange), this.render(), this.refreshHistoryButtons(), this.cells.observe(this.onCellsChange), this.styles.observe(this.onStylesChange), this.rowHeights.observe(this.onSizesChange), this.columnWidths.observe(this.onSizesChange), this.merges.observe(this.onMergesChange), this.locks.observe(this.onLocksChange), this.viewportResizeObserver = new ResizeObserver(() => re(this.frozenBoundaryLayer, this.viewport, this.frozenRows, this.frozenColumns, this.rowHeaderWidth, this.columnHeaderHeight, (a, l) => a === "row" ? this.getRowHeight(l) : this.getColumnWidth(l))), this.viewportResizeObserver.observe(this.viewport), $e(this.session, t, this.sheet, c, {
1676
+ canEdit: () => !this.readOnly && !this.destroyed,
1677
+ log: (a) => this.log(a),
1678
+ inspect: () => this.archive.inspectConnections(),
1679
+ clearHistory: () => this.undoManager.clear(),
1680
+ render: () => this.render()
1681
+ });
1682
+ }
1683
+ log(e) {
1684
+ var t, s;
1685
+ (s = (t = this.options).onLog) == null || s.call(t, `${(/* @__PURE__ */ new Date()).toLocaleTimeString()} ${e}`);
1686
+ }
1687
+ undo() {
1688
+ this.readOnly || !this.undoManager.canUndo() || (this.editing.input && this.editing.finish(!0), this.undoManager.undo());
1689
+ }
1690
+ redo() {
1691
+ this.readOnly || !this.undoManager.canRedo() || (this.editing.input && this.editing.finish(!0), this.undoManager.redo());
1692
+ }
1693
+ refreshHistoryButtons() {
1694
+ this.undoButton && (this.undoButton.disabled = this.readOnly || !this.undoManager.canUndo()), this.redoButton && (this.redoButton.disabled = this.readOnly || !this.undoManager.canRedo());
1695
+ }
1696
+ /** Changes local editing affordances. Hosts enforce actual document permissions. */
1697
+ setReadOnly(e) {
1698
+ this.destroyed || this.readOnly === e || (this.readOnly = e, this.editEpoch++, this.editing.finish(!1), this.resizing = void 0, this.viewport.classList.remove("is-resizing"), this.pointer.cancel(), this.dialogs.close(), this.menu.hide(), this.toolbar.hidden = e, this.undoManager.clear(), this.refreshHistoryButtons(), this.render());
1699
+ }
1700
+ /** Explicitly commits the active cell draft before a host publishes or exports. */
1701
+ commitEditing() {
1702
+ this.destroyed || this.editing.finish(!0);
1703
+ }
1704
+ /** Discards an active draft while preserving the current shared document value. */
1705
+ cancelEditing() {
1706
+ this.destroyed || this.editing.finish(!1);
1707
+ }
1708
+ getYjsSnapshot() {
1709
+ return this.archive.snapshot();
1710
+ }
1711
+ getYjsUpdateLog() {
1712
+ return this.archive.updateLog();
1713
+ }
1714
+ /** Freeze a leading prefix in this local view. */
1715
+ setFrozenPanes(e, t) {
1716
+ if (this.destroyed) return !1;
1717
+ if (![e, t].every((r) => Number.isInteger(r) && r >= 0))
1718
+ throw new RangeError("Frozen row and column counts must be non-negative integers");
1719
+ const s = Math.min(e, this.rowCount - 1), n = Math.min(t, this.columnCount - 1);
1720
+ return this.sheet.hasPartialMerge("row", 0, s - 1) || this.sheet.hasPartialMerge("column", 0, n - 1) ? (this.dialogs.showLockMessage("当前选择包含不完整的合并块,无法固定,请选择完整的合并块"), !1) : (this.editing.finish(!0), this.frozenRows = s, this.frozenColumns = n, this.dialogs.closeLockMessage(), this.render(), !0);
1721
+ }
1722
+ crossesFrozenBoundary(e) {
1723
+ return e.start.row < this.frozenRows && e.end.row >= this.frozenRows || e.start.column < this.frozenColumns && e.end.column >= this.frozenColumns;
1724
+ }
1725
+ freezeSelection(e) {
1726
+ if (!this.selection.focus) return;
1727
+ const t = $(this.selection.anchor, this.selection.focus);
1728
+ if (this.sheet.hasPartialMerge(e, t.start[e], t.end[e])) {
1729
+ this.dialogs.showLockMessage("当前选择包含不完整的合并块,无法固定,请选择完整的合并块");
1730
+ return;
1731
+ }
1732
+ this.setFrozenPanes(
1733
+ e === "row" ? t.end.row + 1 : this.frozenRows,
1734
+ e === "column" ? t.end.column + 1 : this.frozenColumns
1735
+ );
1736
+ }
1737
+ selectionHasLocks() {
1738
+ return this.sheet.rangeHasLocks($(this.selection.anchor, this.selection.focus));
1739
+ }
1740
+ async setSelectionLocked(e, t) {
1741
+ if (this.readOnly || this.destroyed || !this.selection.focus) return;
1742
+ this.editing.finish(!0);
1743
+ const s = this.sheet.expandSelectionToMerges(
1744
+ this.selection.anchor ?? this.selection.focus,
1745
+ this.selection.focus
1746
+ ), n = $(s.anchor, s.focus), r = [];
1747
+ for (let a = n.start.row; a <= n.end.row; a += 1)
1748
+ for (let l = n.start.column; l <= n.end.column; l += 1) r.push(H({ row: a, column: l }));
1749
+ const i = [...new Set(r.map((a) => this.locks.get(a)).filter((a) => a !== void 0 && a !== "1"))];
1750
+ if (e && i.length) throw new Error("选区包含密码锁定单元格,请先用原密码解锁");
1751
+ const c = this.archive.revision, h = this.editEpoch;
1752
+ let m = "1";
1753
+ if (e && t !== void 0 && (m = await ut(t)), !e && i.length) {
1754
+ if (!t) throw new Error("请输入解锁密码");
1755
+ for (const a of i)
1756
+ if (!await mt(a, t)) throw new Error("密码不正确,选区未解锁");
1757
+ }
1758
+ if (!(this.destroyed || this.readOnly || h !== this.editEpoch)) {
1759
+ if (c !== this.archive.revision) throw new Error("表格内容或锁定状态已变化,请重试");
1760
+ this.doc.transact(() => {
1761
+ r.forEach((a) => {
1762
+ e ? this.locks.set(a, m) : this.locks.delete(a);
1763
+ });
1764
+ }, this);
1765
+ }
1766
+ }
1767
+ get rowCount() {
1768
+ return this.dimensions.rows;
1769
+ }
1770
+ get columnCount() {
1771
+ return this.dimensions.columns;
1772
+ }
1773
+ get rowHeaderWidth() {
1774
+ return ot * this.zoomRatio;
1775
+ }
1776
+ get columnHeaderHeight() {
1777
+ return nt * this.zoomRatio;
1778
+ }
1779
+ getRowHeight(e) {
1780
+ var t;
1781
+ return ((t = this.resizing) == null ? void 0 : t.axis) === "row" && this.resizing.index === e ? this.resizing.currentSize : Math.max(de, this.rowHeights.get(String(e)) ?? rt) * this.zoomRatio;
1782
+ }
1783
+ getColumnWidth(e) {
1784
+ var t;
1785
+ return ((t = this.resizing) == null ? void 0 : t.axis) === "column" && this.resizing.index === e ? this.resizing.currentSize : Math.max(ue, this.columnWidths.get(String(e)) ?? it) * this.zoomRatio;
1786
+ }
1787
+ beginResize(e, t, s) {
1788
+ s.preventDefault(), s.stopPropagation(), !(s.button !== 0 || this.readOnly || this.sheet.isAxisLocked(e, t)) && (this.editing.finish(!0), this.pointer.selecting = !1, this.pointer.headerSelecting = void 0, this.resizing = {
1789
+ axis: e,
1790
+ index: t,
1791
+ start: e === "row" ? s.clientY : s.clientX,
1792
+ size: e === "row" ? this.getRowHeight(t) : this.getColumnWidth(t),
1793
+ currentSize: e === "row" ? this.getRowHeight(t) : this.getColumnWidth(t)
1794
+ }, this.viewport.classList.add("is-resizing"));
1795
+ }
1796
+ addResizeHandle(e, t, s) {
1797
+ const n = document.createElement("span");
1798
+ n.className = `colwork-table__resize-handle colwork-table__resize-handle--${t}`, n.addEventListener("mousedown", (r) => this.beginResize(t, s, r)), e.append(n);
1799
+ }
1800
+ mergeSelection() {
1801
+ if (this.readOnly || this.selectionHasLocks()) return;
1802
+ const e = $(this.selection.anchor, this.selection.focus);
1803
+ if (!(e.start.row === e.end.row && e.start.column === e.end.column)) {
1804
+ if (this.crossesFrozenBoundary(e)) {
1805
+ this.dialogs.showLockMessage("合并范围同时包含固定和非固定区域,无法合并,请调整选区或取消固定");
1806
+ return;
1807
+ }
1808
+ this.dialogs.closeLockMessage(), this.doc.transact(() => {
1809
+ this.sheet.getMergeRanges().forEach((t) => {
1810
+ (P(e, t.start) || P(t, e.start)) && this.merges.delete(this.sheet.mergeKey(t));
1811
+ }), this.merges.set(this.sheet.mergeKey(e), "1");
1812
+ }, this);
1813
+ }
1814
+ }
1815
+ unmergeSelection() {
1816
+ if (this.readOnly || this.selectionHasLocks()) return;
1817
+ const e = $(this.selection.anchor, this.selection.focus);
1818
+ this.doc.transact(() => this.sheet.getMergeRanges().forEach((t) => {
1819
+ (P(e, t.start) || P(t, e.start)) && this.merges.delete(this.sheet.mergeKey(t));
1820
+ }), this);
1821
+ }
1822
+ modifyAxis(e, t, s, n = 0) {
1823
+ this.readOnly || s === 0 || this.sheet.isAxisLocked(e, t, !0) || (this.sheet.modifyAxis(e, t, s, n), e === "row" ? this.dimensions.rows = Math.max(1, this.dimensions.rows + s) : this.dimensions.columns = Math.max(1, this.dimensions.columns + s), this.render());
1824
+ }
1825
+ deleteRows() {
1826
+ const e = $(this.selection.anchor, this.selection.focus), t = Math.min(e.end.row - e.start.row + 1, this.rowCount - 1);
1827
+ this.modifyAxis("row", e.start.row, -t, t);
1828
+ }
1829
+ deleteColumns() {
1830
+ const e = $(this.selection.anchor, this.selection.focus), t = Math.min(e.end.column - e.start.column + 1, this.columnCount - 1);
1831
+ this.modifyAxis("column", e.start.column, -t, t);
1832
+ }
1833
+ expandLogicalSpace() {
1834
+ return this.dimensions.expandViewport(this.viewport, this.selection);
1835
+ }
1836
+ expandForRemoteSelections() {
1837
+ return this.dimensions.expandRemote(this.awareness);
1838
+ }
1839
+ clearSelectionContents() {
1840
+ if (this.readOnly || this.selectionHasLocks()) return;
1841
+ const e = $(this.selection.anchor, this.selection.focus);
1842
+ this.doc.transact(() => {
1843
+ for (let t = e.start.row; t <= e.end.row; t += 1)
1844
+ for (let s = e.start.column; s <= e.end.column; s += 1) this.cells.delete(H({ row: t, column: s }));
1845
+ }, this);
1846
+ }
1847
+ expandLogicalSizeFromDocument() {
1848
+ return this.dimensions.expandDocument(this.sheet);
1849
+ }
1850
+ render() {
1851
+ this.editing.input && this.editing.finish(!0), this.expandLogicalSizeFromDocument(), this.frozenRows = Math.min(this.frozenRows, this.rowCount - 1), this.frozenColumns = Math.min(this.frozenColumns, this.columnCount - 1);
1852
+ const e = this.sheet.hasPartialMerge("row", 0, this.frozenRows - 1), t = this.sheet.hasPartialMerge("column", 0, this.frozenColumns - 1);
1853
+ (e || t) && (e && (this.frozenRows = 0), t && (this.frozenColumns = 0), this.dialogs.showLockMessage("合并区域已变化,已取消与合并块冲突的固定行列")), ht({
1854
+ table: this.table,
1855
+ viewport: this.viewport,
1856
+ rowCount: this.rowCount,
1857
+ columnCount: this.columnCount,
1858
+ frozenRows: this.frozenRows,
1859
+ frozenColumns: this.frozenColumns,
1860
+ zoomRatio: this.zoomRatio,
1861
+ rowHeaderWidth: this.rowHeaderWidth,
1862
+ columnHeaderHeight: this.columnHeaderHeight,
1863
+ bandedRows: this.bandedRows,
1864
+ showGridLines: this.showGridLines,
1865
+ readOnly: this.readOnly,
1866
+ getRowHeight: (s) => this.getRowHeight(s),
1867
+ getColumnWidth: (s) => this.getColumnWidth(s),
1868
+ getMergeRanges: () => this.sheet.getMergeRanges(),
1869
+ isCellLocked: (s, n) => this.sheet.isCellLocked(s, n),
1870
+ isCellPasswordLocked: (s, n) => this.sheet.isCellPasswordLocked(s, n),
1871
+ displayValue: (s) => this.formatting.displayValue(s),
1872
+ applyStyle: (s, n) => this.formatting.applyStyle(s, n),
1873
+ addResizeHandle: (s, n, r) => this.addResizeHandle(s, n, r),
1874
+ addHeaderSelection: (s, n, r) => this.pointer.addHeaderSelection(s, n, r),
1875
+ selectRange: (s, n, r) => this.selection.selectRange(s, n, r),
1876
+ attachCellListeners: (s, n, r, i) => this.pointer.attachCellListeners(s, n, r, i)
1877
+ }), re(this.frozenBoundaryLayer, this.viewport, this.frozenRows, this.frozenColumns, this.rowHeaderWidth, this.columnHeaderHeight, (s, n) => s === "row" ? this.getRowHeight(n) : this.getColumnWidth(n)), this.refreshSelection(), this.refreshCursors();
1878
+ }
1879
+ refreshValues() {
1880
+ Ne(this.refreshView());
1881
+ }
1882
+ refreshSelection() {
1883
+ ye(this.refreshView());
1884
+ }
1885
+ refreshCursors() {
1886
+ be(this.refreshView());
1887
+ }
1888
+ refreshStyles() {
1889
+ De(this.refreshView());
1890
+ }
1891
+ refreshView() {
1892
+ var e;
1893
+ return {
1894
+ table: this.table,
1895
+ viewport: this.viewport,
1896
+ editingKey: (e = this.editing) == null ? void 0 : e.key,
1897
+ formatting: this.formatting,
1898
+ selection: this.selection,
1899
+ awareness: this.awareness,
1900
+ userColor: this.options.userColor,
1901
+ rowCount: this.rowCount,
1902
+ columnCount: this.columnCount,
1903
+ size: (t, s) => t === "row" ? this.getRowHeight(s) : this.getColumnWidth(s)
1904
+ };
1905
+ }
1906
+ destroy() {
1907
+ this.destroyed || (this.session.external || this.editing.finish(!0), this.destroyed = !0, this.viewportResizeObserver.disconnect(), this.dialogs.close(), this.editing.finish(!1), this.archive.destroy(), this.awareness.off("change", this.onAwarenessChange), this.cells.unobserve(this.onCellsChange), this.styles.unobserve(this.onStylesChange), this.rowHeights.unobserve(this.onSizesChange), this.columnWidths.unobserve(this.onSizesChange), this.merges.unobserve(this.onMergesChange), this.locks.unobserve(this.onLocksChange), this.undoManager.off("stack-item-added", this.onHistoryChange), this.undoManager.off("stack-item-popped", this.onHistoryChange), this.undoManager.off("stack-cleared", this.onHistoryChange), this.viewport.removeEventListener("scroll", this.onViewportScroll), this.viewport.removeEventListener("wheel", this.onViewportWheel), this.viewport.removeEventListener("keydown", this.onViewportKeyDown), this.viewport.removeEventListener("copy", this.clipboard.onCopy, !0), this.viewport.removeEventListener("paste", this.clipboard.onPaste, !0), this.table.removeEventListener("mousedown", this.onTableMouseDown), window.removeEventListener("mouseup", this.onWindowMouseUp), window.removeEventListener("mousemove", this.onWindowMouseMove), window.removeEventListener("blur", this.onWindowBlur), document.removeEventListener("mousedown", this.onDocumentMouseDown), this.menu.hide(), this.renderFrame !== void 0 && cancelAnimationFrame(this.renderFrame), this.undoManager.destroy(), this.sheet.destroy(), this.session.destroy(), this.root.replaceChildren());
1908
+ }
1909
+ }
1910
+ export {
1911
+ F as COLWORK_MAP_NAMES,
1912
+ ee as COLWORK_SCHEMA_VERSION,
1913
+ Et as ColworkTable,
1914
+ H as cellKey,
1915
+ P as containsPosition,
1916
+ Ue as exportYjsSnapshot,
1917
+ G as getSheetMaps,
1918
+ kt as initializeBlankSheet,
1919
+ bt as mergeKey,
1920
+ Le as normalizeRange,
1921
+ q as parseCellKey,
1922
+ te as parseMergeKey,
1923
+ yt as rangeSize,
1924
+ Ke as readSheetSnapshot,
1925
+ Ct as readSheetSnapshotUpdate,
1926
+ St as rebuildYjsSnapshot,
1927
+ Ce as validateSheetDocument
1928
+ };