@kuzuma/colwork 0.1.0 → 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.
package/dist/colwork.js CHANGED
@@ -1,134 +1,76 @@
1
- var ct = Object.defineProperty;
2
- var ht = (a, t, e) => t in a ? ct(a, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : a[t] = e;
3
- var h = (a, t, e) => ht(a, typeof t != "symbol" ? t + "" : t, e);
4
- import * as K from "yjs";
5
- import { Awareness as dt } from "y-protocols/awareness";
6
- import { WebrtcProvider as ut } from "y-webrtc";
7
- import { WebsocketProvider as tt } from "y-websocket";
8
- const Y = 6e5, G = (a) => Array.from(a, (t) => t.toString(16).padStart(2, "0")).join("");
9
- async function it(a, t) {
10
- var s;
11
- if (!((s = globalThis.crypto) != null && s.subtle)) throw new Error("密码锁定需要 HTTPS 或 localhost 环境");
12
- const e = await crypto.subtle.importKey("raw", new TextEncoder().encode(a), "PBKDF2", !1, ["deriveBits"]);
13
- return new Uint8Array(await crypto.subtle.deriveBits({ name: "PBKDF2", hash: "SHA-256", salt: t, iterations: Y }, e, 256));
14
- }
15
- async function mt(a) {
16
- var s;
17
- if (!a.length) throw new Error("密码不能为空");
18
- if (!((s = globalThis.crypto) != null && s.subtle)) throw new Error("密码锁定需要 HTTPS 或 localhost 环境");
19
- const t = crypto.getRandomValues(new Uint8Array(16)), e = {
20
- version: 1,
21
- algorithm: "PBKDF2-SHA-256",
22
- iterations: Y,
23
- salt: G(t),
24
- verifier: G(await it(a, t))
25
- };
26
- return JSON.stringify(e);
27
- }
28
- async function gt(a, t) {
29
- let e;
30
- try {
31
- e = JSON.parse(a);
32
- } catch {
33
- throw new Error("锁定数据无效,无法解锁");
34
- }
35
- if (!e || e.version !== 1 || e.algorithm !== "PBKDF2-SHA-256" || e.iterations !== Y || typeof e.salt != "string" || !/^[0-9a-f]{32}$/.test(e.salt) || typeof e.verifier != "string" || !/^[0-9a-f]{64}$/.test(e.verifier))
36
- throw new Error("锁定数据无效或版本不受支持,无法解锁");
37
- const s = Uint8Array.from(e.salt.match(/../g), (n) => parseInt(n, 16)), o = G(await it(t, s));
38
- let r = 0;
39
- for (let n = 0; n < o.length; n += 1) r |= o.charCodeAt(n) ^ e.verifier.charCodeAt(n);
40
- return r === 0;
41
- }
42
- function ft(a, t) {
43
- const e = a.trim().replace("#", "");
44
- if (/^[\da-f]{3}$/i.test(e)) {
45
- const [o, r, n] = e.split("").map((i) => Number.parseInt(i + i, 16));
46
- return `rgba(${o}, ${r}, ${n}, ${t})`;
47
- }
48
- if (/^[\da-f]{6}$/i.test(e)) {
49
- const o = Number.parseInt(e, 16);
50
- return `rgba(${o >> 16}, ${o >> 8 & 255}, ${o & 255}, ${t})`;
51
- }
52
- const s = a.match(/^rgba?\(\s*([\d.]+)[, ]+\s*([\d.]+)[, ]+\s*([\d.]+)/i);
53
- return s ? `rgba(${s[1]}, ${s[2]}, ${s[3]}, ${t})` : `color-mix(in srgb, ${a} 12%, transparent)`;
54
- }
55
- function pt(a, t) {
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) {
56
9
  return {
57
10
  start: {
58
- row: Math.min(a.row, t.row),
59
- column: Math.min(a.column, t.column)
11
+ row: Math.min(o.row, e.row),
12
+ column: Math.min(o.column, e.column)
60
13
  },
61
14
  end: {
62
- row: Math.max(a.row, t.row),
63
- column: Math.max(a.column, t.column)
15
+ row: Math.max(o.row, e.row),
16
+ column: Math.max(o.column, e.column)
64
17
  }
65
18
  };
66
19
  }
67
- function T(a, t) {
68
- return t.row >= a.start.row && t.row <= a.end.row && t.column >= a.start.column && t.column <= a.end.column;
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;
69
22
  }
70
- function Dt(a) {
23
+ function yt(o) {
71
24
  return {
72
- rows: a.end.row - a.start.row + 1,
73
- columns: a.end.column - a.start.column + 1
25
+ rows: o.end.row - o.start.row + 1,
26
+ columns: o.end.column - o.start.column + 1
74
27
  };
75
28
  }
76
- function W(a) {
77
- return `${a.row}:${a.column}`;
29
+ function H(o) {
30
+ return `${o.row}:${o.column}`;
78
31
  }
79
- function $(a, t) {
80
- const e = a ?? t ?? { row: 0, column: 0 };
81
- return pt(e, t ?? e);
32
+ function $(o, e) {
33
+ const t = o ?? e ?? { row: 0, column: 0 };
34
+ return Le(t, e ?? t);
82
35
  }
83
- function at(a, t, e, s) {
36
+ function fe(o, e, t, s) {
84
37
  return {
85
- row: a === "column" || a === "all" ? e - 1 : t.row,
86
- column: a === "row" || a === "all" ? s - 1 : t.column
38
+ row: o === "column" || o === "all" ? t - 1 : e.row,
39
+ column: o === "row" || o === "all" ? s - 1 : e.column
87
40
  };
88
41
  }
89
- function wt(a, t, e) {
90
- if (!(!a.anchor || !a.focus))
91
- return $(a.anchor, at(a.mode, a.focus, t, e));
42
+ function Ae(o, e, t) {
43
+ if (!(!o.anchor || !o.focus))
44
+ return $(o.anchor, fe(o.mode, o.focus, e, t));
92
45
  }
93
- const yt = 54, bt = 42, et = 12, St = 56, Ct = 150, vt = 28, kt = 64, Et = 0.25, Mt = 2;
94
- function P(a, t) {
95
- let e = 0;
96
- for (let s = 0; s < a; s += 1) e += t(s);
97
- return e;
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
+ }
98
72
  }
99
- function J(a, t) {
100
- return P(a, t);
101
- }
102
- function zt(a) {
103
- const t = (l, d, c, m) => {
104
- let g = 0, p = 0;
105
- for (; p < c && g + m(p) <= l; )
106
- g += m(p), p += 1;
107
- const M = Math.max(0, p - a.overscan);
108
- let E = p, R = g;
109
- for (; E < c && R < l + d; )
110
- R += m(E), E += 1;
111
- return { start: M, end: Math.min(c - 1, E + a.overscan - 1) };
112
- }, e = t(a.scrollTop, a.clientHeight, a.rowCount, a.rowSize), s = t(a.scrollLeft, a.clientWidth, a.columnCount, a.columnSize), o = e.start, r = e.end, n = s.start, i = s.end;
113
- return { top: o, bottom: r, left: n, right: i };
114
- }
115
- function I(a) {
116
- let t = "";
117
- for (let s = 0; s < a.length; s += 32768)
118
- t += String.fromCharCode(...a.subarray(s, s + 32768));
119
- return btoa(t);
120
- }
121
- function st(a) {
122
- const t = atob(a);
123
- return Uint8Array.from(t, (e) => e.charCodeAt(0));
124
- }
125
- const ot = "application/x-colwork-cells", Lt = ["任务", "负责人", "状态", "优先级", "开始日期", "备注"], xt = [
126
- { urls: "stun:stun.qq.com:3478" },
127
- { urls: "stun:stun.miwifi.com:3478" },
128
- { urls: "stun:stun.chat.bilibili.com:3478" },
129
- { urls: "stun:stun.l.google.com:19302" },
130
- { urls: "stun:stun1.l.google.com:19302" }
131
- ], j = [
73
+ const ge = [
132
74
  ["设计协作表格", "小林", "进行中", "高", "2026-08-07", "欢迎测试"],
133
75
  ["整理组件 API", "阿南", "已完成", "中", "2026-08-08", "已补充示例"],
134
76
  ["补充单元测试", "小周", "未开始", "高", "2026-08-09", "覆盖边界输入"],
@@ -140,1202 +82,1847 @@ const ot = "application/x-colwork-cells", Lt = ["任务", "负责人", "状态",
140
82
  ["优化移动端布局", "小雨", "未开始", "中", "2026-08-15", "检查横向滚动"],
141
83
  ["发布 v0.1.0", "小林", "未开始", "低", "2026-08-18", "等待最终验收"]
142
84
  ];
143
- function At(a) {
144
- let t = a + 1, e = "";
145
- for (; t > 0; )
146
- t -= 1, e = String.fromCharCode(65 + t % 26) + e, t = Math.floor(t / 26);
147
- return e;
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
+ });
148
91
  }
149
- class Ft {
150
- constructor(t, e) {
151
- h(this, "doc");
152
- h(this, "cells");
153
- h(this, "styles");
154
- h(this, "rowHeights");
155
- h(this, "columnWidths");
156
- h(this, "locks");
157
- h(this, "messageDialog");
158
- h(this, "passwordDialog");
159
- h(this, "destroyed", !1);
160
- h(this, "frozenRows", 0);
161
- h(this, "frozenColumns", 0);
162
- h(this, "merges");
163
- h(this, "undoManager");
164
- h(this, "provider");
165
- h(this, "awareness");
166
- h(this, "root");
167
- h(this, "options");
168
- h(this, "table");
169
- h(this, "viewportResizeObserver");
170
- h(this, "viewport");
171
- h(this, "frozenBoundaryLayer");
172
- h(this, "protectionMenuButton");
173
- h(this, "contextMenu");
174
- h(this, "pendingCellContext");
175
- h(this, "rightButtonReleased", !1);
176
- h(this, "rightMouseUpPoint");
177
- h(this, "rightDrag");
178
- h(this, "undoButton");
179
- h(this, "redoButton");
180
- h(this, "rowCountValue");
181
- h(this, "columnCountValue");
182
- h(this, "zoomRatio", 1);
183
- h(this, "showGridLines", !0);
184
- h(this, "bandedRows", !1);
185
- h(this, "readOnly");
186
- h(this, "documentRevision", 0);
187
- h(this, "updateSequence", 0);
188
- h(this, "updateLog", []);
189
- h(this, "resizing");
190
- h(this, "onCellsChange", () => this.refreshValues());
191
- h(this, "onStylesChange", () => this.refreshStyles());
192
- h(this, "onSizesChange", () => this.render());
193
- h(this, "onMergesChange", () => this.render());
194
- h(this, "onLocksChange", () => {
195
- this.undoManager.clear(), this.editingKey && this.isCellLocked(this.editingKey) && this.finishEdit(!1), this.resizing && this.isAxisLocked(this.resizing.axis, this.resizing.index) && (this.resizing = void 0, this.viewport.classList.remove("is-resizing")), this.render();
196
- });
197
- h(this, "onAwarenessChange", () => {
198
- this.table && (this.expandForRemoteSelections() ? this.render() : this.refreshCursors());
199
- });
200
- h(this, "renderFrame");
201
- h(this, "onViewportScroll", () => {
202
- this.renderFrame === void 0 && (this.renderFrame = requestAnimationFrame(() => {
203
- this.renderFrame = void 0, this.expandLogicalSpace(), this.render();
204
- }));
205
- });
206
- h(this, "onViewportWheel", (t) => {
207
- if (!t.ctrlKey) return;
208
- t.preventDefault();
209
- const e = t.deltaY < 0 ? 1.1 : 0.9;
210
- this.zoomRatio = Math.max(Et, Math.min(Mt, this.zoomRatio * e)), this.expandLogicalSpace(), this.render();
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();
211
109
  });
212
- h(this, "onViewportKeyDown", (t) => {
213
- if (this.readOnly || this.editor) return;
214
- const e = t.ctrlKey || t.metaKey;
215
- if (e && t.key.toLowerCase() === "z") {
216
- t.preventDefault(), t.shiftKey ? this.redo() : this.undo();
217
- return;
218
- }
219
- if (e && t.key.toLowerCase() === "y") {
220
- t.preventDefault(), this.redo();
221
- return;
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);
222
156
  }
223
- if (t.key !== " " || !this.selectionFocus) return;
224
- const s = `${this.selectionFocus.row}:${this.selectionFocus.column}`, o = this.table.querySelector(`td[data-key="${s}"]`);
225
- o && (t.preventDefault(), this.startEdit(o, s));
226
- });
227
- h(this, "onTableMouseDown", (t) => {
228
- t.target.closest("th") && t.preventDefault();
229
- });
230
- h(this, "onDocumentMouseDown", (t) => {
231
- var e;
232
- this.contextMenu && !this.contextMenu.contains(t.target) && !((e = this.protectionMenuButton) != null && e.contains(t.target)) && this.hideContextMenu();
233
- });
234
- h(this, "onWindowMouseUp", (t) => {
235
- if (this.resizing) {
236
- this.resizing.axis === "row" ? this.rowHeights.set(String(this.resizing.index), this.resizing.currentSize / this.zoomRatio) : this.columnWidths.set(String(this.resizing.index), this.resizing.currentSize / this.zoomRatio), this.resizing = void 0, this.viewport.classList.remove("is-resizing");
237
- return;
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);
238
307
  }
239
- if (this.selecting = !1, this.headerSelecting = void 0, t.button === 2 && (this.rightButtonReleased = !0, this.rightMouseUpPoint = { x: t.clientX, y: t.clientY }, this.pendingCellContext)) {
240
- const e = this.rightMouseUpPoint;
241
- this.pendingCellContext = void 0, this.showCellContextMenu(e.x, e.y);
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();
242
345
  }
243
- this.pendingAwarenessCursor && this.sendAwareness(this.pendingAwarenessCursor);
244
- });
245
- h(this, "onWindowBlur", () => {
246
- this.headerSelecting && (this.selecting = !1, this.headerSelecting = void 0, this.pendingAwarenessCursor && this.sendAwareness(this.pendingAwarenessCursor));
247
- });
248
- h(this, "onWindowMouseMove", (t) => {
249
- if (this.headerSelecting && !(t.buttons & 1) && this.onWindowBlur(), !this.resizing) return;
250
- const e = this.resizing.axis === "row" ? t.clientY - this.resizing.start : t.clientX - this.resizing.start, s = (this.resizing.axis === "row" ? vt : kt) * this.zoomRatio, o = Math.max(s, this.resizing.size + e);
251
- this.resizing.currentSize = o, this.render();
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 }
252
376
  });
253
- h(this, "onHistoryChange", () => this.refreshHistoryButtons());
254
- h(this, "editor");
255
- h(this, "editingKey");
256
- h(this, "editingOriginal", "");
257
- h(this, "selectedKey");
258
- h(this, "selectionAnchor");
259
- h(this, "selectionFocus");
260
- h(this, "selectionMode");
261
- h(this, "selecting", !1);
262
- h(this, "headerSelecting");
263
- h(this, "pendingAwarenessCursor");
264
- h(this, "loggedPeers", /* @__PURE__ */ new Set());
265
- h(this, "loggedSignals", /* @__PURE__ */ new Set());
266
- h(this, "onDocUpdate", (t, e) => {
267
- this.documentRevision += 1;
268
- const s = this.provider, o = { seq: ++this.updateSequence, update: I(t), timestamp: Date.now() };
269
- this.updateLog.push(o), this.logChunk(`yjs:${e === (s == null ? void 0 : s.room) ? "recv" : "send"}`, t), this.log(`yjs:state ${JSON.stringify({ cells: Array.from(this.cells.entries()), rowHeights: Array.from(this.rowHeights.entries()), columnWidths: Array.from(this.columnWidths.entries()), merges: Array.from(this.merges.entries()) })}`);
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");
270
511
  });
271
- h(this, "onAwarenessUpdate", ({ added: t, updated: e, removed: s }, o) => {
272
- const r = this.provider;
273
- this.log(`awareness:${o === (r == null ? void 0 : r.room) ? "recv" : "send"} added=${t.join(",")} updated=${e.join(",")} removed=${s.join(",")}`), this.log(`awareness:state ${JSON.stringify(Array.from(this.awareness.getStates().entries()))}`);
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");
274
516
  });
275
- h(this, "onCopy", (t) => {
276
- const e = this.selectionToClipboard();
277
- if (!e || !t.clipboardData) return;
278
- const s = e.values.map((o) => o.join(" ")).join(`
279
- `);
280
- t.clipboardData.setData("text/plain", s), t.clipboardData.setData(ot, JSON.stringify(e)), t.preventDefault();
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());
281
539
  });
282
- h(this, "onPaste", (t) => {
283
- var l, d, c;
284
- if (t.preventDefault(), t.stopPropagation(), this.readOnly) return;
285
- const e = (d = (l = t.clipboardData) == null ? void 0 : l.getData("text/plain")) == null ? void 0 : d.replace(/^\uFEFF/, "");
286
- if (!e || !this.selectionFocus) return;
287
- this.editor && this.finishEdit(!1);
288
- let s = e.replace(/\r\n/g, `
289
- `).replace(/\r/g, `
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, `
290
550
  `).split(`
291
- `).filter((m, g, p) => !(g === p.length - 1 && m === "")).map((m) => m.split(" ")), o;
292
- const r = (c = t.clipboardData) == null ? void 0 : c.getData(ot);
293
- if (r)
294
- try {
295
- const m = JSON.parse(r);
296
- Array.isArray(m.values) && Array.isArray(m.styles) && (s = m.values, o = m.styles);
297
- } catch {
298
- o = void 0;
299
- }
300
- const n = this.selectionFocus, i = Math.max(...s.map((m) => m.length));
301
- s.some((m, g) => m.some((p, M) => this.isCellLocked(W({ row: n.row + g, column: n.column + M })))) || (this.doc.transact(() => s.forEach((m, g) => m.forEach((p, M) => {
302
- var q;
303
- const E = n.row + g, R = n.column + M;
304
- if (E >= this.rowCount || R >= this.columnCount) return;
305
- const H = W({ row: E, column: R });
306
- if (this.cells.set(H, p), o) {
307
- const O = (q = o[g]) == null ? void 0 : q[M];
308
- O ? this.styles.set(H, JSON.stringify(O)) : this.styles.delete(H);
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);
309
568
  }
310
- }))), this.selectionAnchor = n, this.selectionFocus = { row: Math.min(this.rowCount - 1, n.row + s.length - 1), column: Math.min(this.columnCount - 1, n.column + i - 1) }, this.render());
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();
311
570
  });
312
- var A, X, Z, Q;
313
- this.root = t, this.options = e, this.readOnly = e.readOnly === !0, this.doc = new K.Doc(), this.cells = this.doc.getMap("cells"), this.styles = this.doc.getMap("styles"), this.rowHeights = this.doc.getMap("rowHeights"), this.columnWidths = this.doc.getMap("columnWidths"), this.merges = this.doc.getMap("merges"), this.locks = this.doc.getMap("locks"), this.rowCountValue = Math.max(e.rowCount ?? 100, ((A = e.rows) == null ? void 0 : A.length) ?? j.length), this.columnCountValue = Math.max(e.columnCount ?? 10, Lt.length);
314
- const s = e.transport === "webrtc", o = new URL(e.websocketUrl ?? "ws://127.0.0.1:1234"), r = Object.fromEntries(o.searchParams);
315
- o.search = "", this.readOnly ? this.awareness = new dt(this.doc) : (this.provider = s ? new ut(e.room, this.doc, {
316
- signaling: [e.signalingUrl ?? "ws://127.0.0.1:4444"],
317
- filterBcConns: !1,
318
- peerOpts: e.peerOpts ?? {
319
- config: {
320
- iceServers: xt
321
- }
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);
322
584
  }
323
- }) : new tt(o.toString().replace(/\/$/, ""), encodeURIComponent(e.room), this.doc, { params: r, connect: !e.initializeAfterSync }), this.awareness = this.provider.awareness), e.snapshot && K.applyUpdate(this.doc, e.snapshot), (X = e.updates) == null || X.forEach((f) => K.applyUpdate(this.doc, f)), this.log(`room:${e.room}`), this.doc.on("update", this.onDocUpdate), this.awareness.on("update", this.onAwarenessUpdate), this.awareness.on("change", this.onAwarenessChange), this.awareness.setLocalStateField("user", { name: e.user, color: e.userColor }), s && this.provider && this.inspectConnections();
324
- const n = document.createElement("section");
325
- n.className = "colwork-table";
326
- const i = document.createElement("div");
327
- i.className = "colwork-table__toolbar", this.readOnly && (i.hidden = !0), i.setAttribute("aria-label", "表格工具栏");
328
- const l = document.createElement("div");
329
- l.className = "colwork-table__toolbar-row";
330
- const d = document.createElement("div");
331
- d.className = "colwork-table__toolbar-row", i.append(l, d);
332
- const c = (f, S) => {
333
- const w = document.createElement("div");
334
- w.className = "colwork-table__toolbar-group", w.setAttribute("role", "group"), w.setAttribute("aria-label", S);
335
- const k = document.createElement("span");
336
- return k.className = "colwork-table__group-label", k.textContent = S, w.append(k), f.append(w), w;
337
- }, m = c(l, "历史"), g = c(l, "单元格"), p = c(l, "保护"), M = c(l, "显示"), E = c(d, "文字"), R = c(d, "对齐"), H = c(d, "格式");
338
- [
339
- ["撤销", "↶", () => this.undo()],
340
- ["重做", "↷", () => this.redo()]
341
- ].forEach(([f, S, w], k) => {
342
- const _ = document.createElement("button");
343
- _.type = "button", _.className = `colwork-table__history colwork-table__history--${k === 0 ? "undo" : "redo"}`, _.title = f, _.textContent = S, _.addEventListener("mousedown", (lt) => lt.preventDefault()), _.addEventListener("click", w), k === 0 ? this.undoButton = _ : this.redoButton = _, m.append(_);
344
- }), [
345
- ["合并单元格", "合并", () => this.mergeSelection()],
346
- ["拆分单元格", "拆分", () => this.unmergeSelection()]
347
- ].forEach(([f, S, w]) => {
348
- const k = document.createElement("button");
349
- k.type = "button", k.className = "colwork-table__format colwork-table__grid-action", k.title = f, k.textContent = S, k.addEventListener("mousedown", (_) => _.preventDefault()), k.addEventListener("click", w), g.append(k);
350
- }), (Z = p.querySelector(".colwork-table__group-label")) == null || Z.remove();
351
- const z = document.createElement("button");
352
- this.protectionMenuButton = z, z.type = "button", z.className = "colwork-table__format colwork-table__dropdown-trigger", z.textContent = "保护", z.title = "锁定、密码锁定与解锁", z.setAttribute("aria-label", "保护"), z.setAttribute("aria-expanded", "false"), z.addEventListener("mousedown", (f) => f.preventDefault()), z.addEventListener("click", () => {
353
- if (z.getAttribute("aria-expanded") === "true") {
354
- this.hideContextMenu();
355
- return;
356
- }
357
- const f = z.getBoundingClientRect();
358
- this.showContextMenu(f.left, f.bottom + 4, [{ label: "锁定与解锁", actions: this.protectionActions() }]), z.setAttribute("aria-expanded", "true");
359
- }), z.addEventListener("keydown", (f) => {
360
- f.key === "ArrowDown" && (f.preventDefault(), z.click());
361
- }), p.append(z);
362
- const U = document.createElement("div");
363
- U.className = "colwork-table__view-control";
364
- const D = document.createElement("button");
365
- D.type = "button", D.className = "colwork-table__format", D.textContent = "视图", D.setAttribute("aria-label", "视图"), D.classList.add("colwork-table__dropdown-trigger"), D.title = "本地视图选项";
366
- const V = document.createElement("div");
367
- V.className = "colwork-table__view-menu", [
368
- ["隔行异色", () => this.bandedRows, (f) => {
369
- this.bandedRows = f;
370
- }],
371
- ["显示网格线", () => this.showGridLines, (f) => {
372
- this.showGridLines = f;
373
- }]
374
- ].forEach(([f, S, w]) => {
375
- const k = document.createElement("label"), _ = document.createElement("input");
376
- _.type = "checkbox", _.checked = S(), _.addEventListener("change", () => {
377
- w(_.checked), this.render();
378
- }), k.append(_, document.createTextNode(f)), V.append(k);
379
- }), [
380
- ["固定至选中行", () => this.freezeSelection("row")],
381
- ["固定至选中列", () => this.freezeSelection("column")],
382
- ["取消固定", () => this.setFrozenPanes(0, 0)]
383
- ].forEach(([f, S]) => {
384
- const w = document.createElement("button");
385
- w.type = "button", w.textContent = f, w.addEventListener("mousedown", (k) => k.preventDefault()), w.addEventListener("click", S), V.append(w);
386
- }), U.append(D, V), M.append(U), [
387
- ["bold", "B", "加粗"],
388
- ["italic", "I", "斜体"],
389
- ["underline", "U", "下划线"],
390
- ["strike", "S", "删除线"],
391
- ["wrap", "换行", "自动换行"],
392
- ["align-left", "左", "左对齐"],
393
- ["align-center", "中", "居中"],
394
- ["align-right", "右", "右对齐"]
395
- ].forEach(([f, S, w]) => {
396
- const k = document.createElement("button");
397
- k.type = "button", k.className = `colwork-table__format colwork-table__format--${f}`, k.textContent = S, k.title = w, k.addEventListener("mousedown", (_) => _.preventDefault()), k.addEventListener("click", () => f.startsWith("align-") ? this.setStyle("align", f.slice(6)) : this.toggleFormat(f)), (f.startsWith("align-") || f === "wrap" ? R : E).append(k);
398
- });
399
- const b = document.createElement("select");
400
- b.className = "colwork-table__select", b.title = "字体大小", [10, 12, 14, 16, 18, 24].forEach((f) => {
401
- const S = document.createElement("option");
402
- S.value = String(f), S.textContent = `${f}px`, b.append(S);
403
- }), b.addEventListener("change", () => this.setStyle("fontSize", Number(b.value))), E.append(b);
404
- const L = document.createElement("select");
405
- L.className = "colwork-table__select", L.title = "单元格格式", [
406
- ["general", "常规"],
407
- ["number", "数字"],
408
- ["date", "日期"],
409
- ["percent", "百分比"]
410
- ].forEach(([f, S]) => {
411
- const w = document.createElement("option");
412
- w.value = f, w.textContent = S, L.append(w);
413
- }), L.addEventListener("change", () => this.setStyle("format", L.value)), H.append(L);
414
- const C = document.createElement("button");
415
- C.type = "button", C.className = "colwork-table__format", C.title = "清除格式", C.textContent = "清除", C.addEventListener("mousedown", (f) => f.preventDefault()), C.addEventListener("click", () => this.clearFormatting()), H.append(C);
416
- const F = document.createElement("div");
417
- F.className = "colwork-table__border-control";
418
- const v = document.createElement("button");
419
- v.type = "button", v.className = "colwork-table__format", v.title = "边框选项", v.textContent = "边框", v.setAttribute("aria-label", "边框"), v.classList.add("colwork-table__dropdown-trigger");
420
- const x = document.createElement("div");
421
- x.className = "colwork-table__border-menu", [
422
- ["外围", "outer"],
423
- ["中间", "inner"],
424
- ["横线", "horizontal"],
425
- ["竖线", "vertical"]
426
- ].forEach(([f, S]) => {
427
- const w = document.createElement("button");
428
- w.type = "button", w.textContent = f, w.addEventListener("click", () => this.toggleBorder(S)), x.append(w);
429
- }), F.append(v, x), H.insertBefore(F, C), [
430
- ["color", "文字颜色"],
431
- ["background", "背景颜色"]
432
- ].forEach(([f, S]) => {
433
- const w = document.createElement("input");
434
- w.type = "color", w.className = `colwork-table__color colwork-table__color--${f}`, w.title = S, w.addEventListener("input", () => this.setStyle(f, w.value)), (f === "color" ? E : H).append(w);
435
- }), this.viewport = document.createElement("div"), this.viewport.className = "colwork-table__viewport", this.viewport.addEventListener("scroll", this.onViewportScroll), this.viewport.addEventListener("wheel", this.onViewportWheel, { passive: !1 }), this.viewport.tabIndex = 0, this.viewport.addEventListener("keydown", this.onViewportKeyDown), this.viewport.addEventListener("copy", this.onCopy, !0), this.viewport.addEventListener("paste", this.onPaste, !0), 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.table.addEventListener("mousedown", this.onTableMouseDown), this.viewport.append(this.table), this.frozenBoundaryLayer = document.createElement("div"), this.frozenBoundaryLayer.className = "colwork-table__frozen-boundaries", this.frozenBoundaryLayer.setAttribute("aria-hidden", "true"), n.append(i, this.viewport, this.frozenBoundaryLayer), t.replaceChildren(n);
436
- const N = !this.readOnly && !e.snapshot && !((Q = e.updates) != null && Q.length), B = N && this.cells.size === 0 && this.locks.size === 0;
437
- if (N && !e.initializeAfterSync && this.seed(e.rows ?? j), B && !e.initializeAfterSync && this.seedDemoFormatting(), this.expandLogicalSizeFromDocument(), this.undoManager = new K.UndoManager([this.cells, this.styles, this.rowHeights, this.columnWidths, this.merges], { captureTimeout: 500 }), 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(() => this.refreshFrozenBoundaries()), this.viewportResizeObserver.observe(this.viewport), this.provider) {
438
- const f = this.provider;
439
- f.on("status", ({ connected: S, status: w }) => {
440
- this.log(S === !0 || w === "connected" ? "signaling:connected" : "signaling:disconnected"), s && this.inspectConnections();
441
- }), s ? f.on("synced", ({ synced: S }) => this.log(S ? "synced" : "syncing")) : f.on("sync", (S) => {
442
- if (this.log(S ? "synced" : "syncing"), !S || !e.initializeAfterSync) return;
443
- const w = this.doc.getMap("colwork-metadata");
444
- w.get("initialized") || (this.doc.transact(() => {
445
- N && this.cells.size === 0 && this.locks.size === 0 && (this.seed(e.rows ?? j), this.seedDemoFormatting()), w.set("initialized", !0);
446
- }), this.undoManager.clear()), this.expandLogicalSizeFromDocument(), this.render();
447
- }), e.initializeAfterSync && this.provider instanceof tt && this.provider.connect(), s && f.on("peers", ({ added: S, removed: w, webrtcPeers: k }) => {
448
- S.length && this.log(`peer:+${S.length}`), w.length && this.log(`peer:-${w.length}`), this.log(`webrtc:${k.length}`), this.inspectConnections();
449
- });
585
+ r.push(h), i.push(m);
450
586
  }
587
+ return { values: r, styles: i };
451
588
  }
452
- log(t) {
453
- var e, s;
454
- (s = (e = this.options).onLog) == null || s.call(e, `${(/* @__PURE__ */ new Date()).toLocaleTimeString()} ${t}`);
455
- }
456
- undo() {
457
- this.readOnly || !this.undoManager.canUndo() || (this.editor && this.finishEdit(!0), this.undoManager.undo());
458
- }
459
- redo() {
460
- this.readOnly || !this.undoManager.canRedo() || (this.editor && this.finishEdit(!0), this.undoManager.redo());
461
- }
462
- refreshHistoryButtons() {
463
- this.undoButton && (this.undoButton.disabled = this.readOnly || !this.undoManager.canUndo()), this.redoButton && (this.redoButton.disabled = this.readOnly || !this.undoManager.canRedo());
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));
464
594
  }
465
- getYjsSnapshot() {
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
+ }
466
627
  return {
467
628
  format: "colwork.snapshot",
468
629
  version: 1,
469
- room: this.options.room,
470
- sequence: this.updateSequence,
471
- snapshot: I(K.encodeStateAsUpdate(this.doc)),
472
- stateVector: I(K.encodeStateVector(this.doc))
630
+ room: n == null ? void 0 : n.room,
631
+ sequence: a,
632
+ snapshot: U(D.encodeStateAsUpdate(i)),
633
+ stateVector: U(D.encodeStateVector(i))
473
634
  };
635
+ } finally {
636
+ i.destroy();
474
637
  }
475
- getYjsUpdateLog() {
476
- return {
477
- format: "colwork.update-log",
478
- version: 1,
479
- room: this.options.room,
480
- updates: this.updateLog.map((t) => ({ ...t }))
481
- };
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;
482
654
  }
483
- /** Freeze a leading prefix of rows/columns in this client only. */
484
- setFrozenPanes(t, e) {
485
- if (![t, e].every((r) => Number.isInteger(r) && r >= 0))
486
- throw new RangeError("Frozen row and column counts must be non-negative integers");
487
- const s = Math.min(t, this.rowCount - 1), o = Math.min(e, this.columnCount - 1);
488
- return this.hasPartialMerge("row", 0, s - 1) || this.hasPartialMerge("column", 0, o - 1) ? (this.showLockMessage("当前选择包含不完整的合并块,无法固定,请选择完整的合并块"), !1) : (this.finishEdit(!0), this.frozenRows = s, this.frozenColumns = o, this.closeLockMessage(), this.render(), !0);
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();
489
713
  }
490
- hasPartialMerge(t, e, s) {
491
- return e > s ? !1 : this.getMergeRanges().some((o) => {
492
- const r = o.start[t], n = o.end[t];
493
- return r <= s && n >= e && (r < e || n > s);
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] })}`);
494
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);
495
735
  }
496
- crossesFrozenBoundary(t) {
497
- return t.start.row < this.frozenRows && t.end.row >= this.frozenRows || t.start.column < this.frozenColumns && t.end.column >= this.frozenColumns;
498
- }
499
- freezeSelection(t) {
500
- if (!this.selectionFocus) return;
501
- const e = $(this.selectionAnchor, this.selectionFocus);
502
- if (this.hasPartialMerge(t, e.start[t], e.end[t])) {
503
- this.showLockMessage("当前选择包含不完整的合并块,无法固定,请选择完整的合并块");
504
- return;
505
- }
506
- this.setFrozenPanes(
507
- t === "row" ? e.end.row + 1 : this.frozenRows,
508
- t === "column" ? e.end.column + 1 : this.frozenColumns
509
- );
736
+ snapshot() {
737
+ return Ue(this.sheet.doc, { room: this.room, sequence: this.sequence });
510
738
  }
511
- rangeHasLocks(t) {
512
- return Array.from(this.locks.keys()).some((e) => {
513
- const [s, o] = e.split(":").map(Number);
514
- return T(t, { row: s, column: o });
515
- });
739
+ updateLog() {
740
+ return { format: "colwork.update-log", version: 1, room: this.room, updates: this.updates.map((e) => ({ ...e })) };
516
741
  }
517
- isCellLocked(t) {
518
- if (this.locks.has(t)) return !0;
519
- const [e, s] = t.split(":").map(Number), o = this.getMergeRanges().find((r) => T(r, { row: e, column: s }));
520
- return !!o && this.rangeHasLocks(o);
521
- }
522
- isCellPasswordLocked(t) {
523
- const e = (n) => this.locks.has(n) && this.locks.get(n) !== "1";
524
- if (e(t)) return !0;
525
- const [s, o] = t.split(":").map(Number), r = this.getMergeRanges().find((n) => T(n, { row: s, column: o }));
526
- return !!r && Array.from(this.locks.keys()).some((n) => {
527
- const [i, l] = n.split(":").map(Number);
528
- return e(n) && T(r, { row: i, column: l });
529
- });
742
+ destroy() {
743
+ this.sheet.doc.off("update", this.onUpdate), this.awareness.off("update", this.onAwarenessUpdate);
530
744
  }
531
- selectionHasLocks() {
532
- return this.rangeHasLocks($(this.selectionAnchor, this.selectionFocus));
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}`);
533
748
  }
534
- isAxisLocked(t, e, s = !1) {
535
- return Array.from(this.locks.keys()).some((o) => {
536
- const r = Number(o.split(":")[t === "row" ? 0 : 1]);
537
- return s ? r >= e : r === e;
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)}`));
538
768
  });
539
769
  }
540
- /** Passwords are optional for legacy/plain locks; protected locks require verification. */
541
- async setSelectionLocked(t, e) {
542
- if (this.readOnly || this.destroyed || !this.selectionFocus) return;
543
- this.finishEdit(!0);
544
- const s = this.expandSelectionToMerges(
545
- this.selectionAnchor ?? this.selectionFocus,
546
- this.selectionFocus
547
- ), o = $(s.anchor, s.focus), r = [];
548
- for (let d = o.start.row; d <= o.end.row; d += 1)
549
- for (let c = o.start.column; c <= o.end.column; c += 1) r.push(W({ row: d, column: c }));
550
- const n = [...new Set(r.map((d) => this.locks.get(d)).filter((d) => d !== void 0 && d !== "1"))];
551
- if (t && n.length) throw new Error("选区包含密码锁定单元格,请先用原密码解锁");
552
- const i = this.documentRevision;
553
- let l = "1";
554
- if (t && e !== void 0 && (l = await mt(e)), !t && n.length) {
555
- if (!e) throw new Error("请输入解锁密码");
556
- for (const d of n)
557
- if (!await gt(d, e)) throw new Error("密码不正确,选区未解锁");
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
+ }
558
806
  }
559
- if (!this.destroyed) {
560
- if (i !== this.documentRevision) throw new Error("表格内容或锁定状态已变化,请重试");
561
- this.doc.transact(() => {
562
- r.forEach((d) => {
563
- t ? this.locks.set(d, l) : this.locks.delete(d);
564
- });
565
- });
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;
566
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);
567
835
  }
568
- requestSelectionLock(t, e = !1) {
569
- if (this.readOnly || this.destroyed || !this.selectionFocus || this.passwordDialog) return;
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;
570
849
  this.closeLockMessage();
571
- const s = $(this.selectionAnchor, this.selectionFocus);
572
- if (!(e || !t && Array.from(this.locks.entries()).some(([E, R]) => {
573
- const [H, q] = E.split(":").map(Number);
574
- return R !== "1" && T(s, { row: H, column: q });
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: _ });
575
854
  }))) {
576
- this.setSelectionLocked(t).catch((E) => this.showLockMessage(E instanceof Error ? E.message : "操作失败"));
855
+ this.host.setSelectionLocked(e).catch((b) => this.showLockMessage(b instanceof Error ? b.message : "操作失败"));
577
856
  return;
578
857
  }
579
858
  const r = document.createElement("dialog");
580
- this.passwordDialog = r, r.className = "colwork-table__password-dialog", r.setAttribute("aria-label", t ? "密码锁定" : "密码解锁");
581
- const n = document.createElement("form"), i = document.createElement("h3");
582
- i.textContent = t ? "设置锁定密码" : "输入解锁密码";
583
- const l = document.createElement("input");
584
- l.type = "password", l.required = !0, l.placeholder = t ? "设置密码" : "输入密码", l.autocomplete = t ? "new-password" : "current-password", l.setAttribute("aria-label", "密码");
585
- const d = document.createElement("input");
586
- d.type = "password", d.required = t, d.placeholder = "再次输入密码", d.autocomplete = "new-password", d.setAttribute("aria-label", "确认密码");
587
- const c = document.createElement("p");
588
- c.setAttribute("role", "alert");
589
- const m = document.createElement("button");
590
- m.type = "submit", m.textContent = t ? "确认锁定" : "确认解锁";
591
- const g = document.createElement("button");
592
- g.type = "button", g.textContent = "取消", g.addEventListener("click", () => r.close()), r.addEventListener("close", () => {
593
- l.value = "", d.value = "", r.remove(), this.passwordDialog === r && (this.passwordDialog = void 0);
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);
594
873
  });
595
- const p = this.selectionAnchor && { ...this.selectionAnchor }, M = { ...this.selectionFocus };
596
- n.addEventListener("submit", async (E) => {
597
- if (E.preventDefault(), !m.disabled) {
598
- if (t && l.value !== d.value) {
599
- c.textContent = "两次输入的密码不一致";
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 = "两次输入的密码不一致";
600
879
  return;
601
880
  }
602
- m.disabled = !0, g.disabled = !0, r.oncancel = (R) => R.preventDefault(), c.textContent = "正在处理…";
881
+ l.disabled = !0, d.disabled = !0, r.oncancel = (M) => M.preventDefault(), a.textContent = "正在处理…";
603
882
  try {
604
- this.selectionAnchor = p, this.selectionFocus = M, await this.setSelectionLocked(t, l.value), r.close();
605
- } catch (R) {
606
- c.textContent = R instanceof Error ? R.message : "操作失败,请重试", l.value = "", d.value = "", l.focus();
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();
607
886
  } finally {
608
- m.disabled = !1, g.disabled = !1, r.oncancel = null;
887
+ l.disabled = !1, d.disabled = !1, r.oncancel = null;
609
888
  }
610
889
  }
611
- }), n.append(i, l), t && n.append(d), n.append(c, m, g), r.append(n), this.root.append(r), r.showModal(), l.focus();
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();
612
891
  }
613
892
  closeLockMessage() {
614
- const t = this.messageDialog;
615
- this.messageDialog = void 0, t == null || t.close(), t == null || t.remove();
616
- }
617
- showLockMessage(t) {
618
- if (this.destroyed) return;
619
- this.closeLockMessage(), this.hideContextMenu();
620
- const e = document.createElement("dialog");
621
- this.messageDialog = e, e.className = "colwork-table__message-dialog", e.setAttribute("role", "alertdialog"), e.setAttribute("aria-label", "操作提示"), e.setAttribute("aria-description", t);
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);
622
901
  const s = document.createElement("h3");
623
902
  s.textContent = "操作提示";
624
- const o = document.createElement("p");
625
- o.className = "colwork-table__lock-status", o.setAttribute("role", "status"), o.textContent = t;
903
+ const n = document.createElement("p");
904
+ n.className = "colwork-table__lock-status", n.setAttribute("role", "status"), n.textContent = e;
626
905
  const r = document.createElement("button");
627
- r.type = "button", r.textContent = "确定", r.addEventListener("click", () => e.close()), e.addEventListener("close", () => {
628
- e.remove(), this.messageDialog === e && (this.messageDialog = void 0);
629
- }), e.append(s, o, r), this.root.append(e), e.showModal(), r.focus();
630
- }
631
- get rowCount() {
632
- return this.rowCountValue;
633
- }
634
- get columnCount() {
635
- return this.columnCountValue;
636
- }
637
- get rowHeaderWidth() {
638
- return yt * this.zoomRatio;
639
- }
640
- get columnHeaderHeight() {
641
- return bt * this.zoomRatio;
642
- }
643
- getRowHeight(t) {
644
- var e;
645
- return ((e = this.resizing) == null ? void 0 : e.axis) === "row" && this.resizing.index === t ? this.resizing.currentSize : (this.rowHeights.get(String(t)) ?? St) * this.zoomRatio;
646
- }
647
- getColumnWidth(t) {
648
- var e;
649
- return ((e = this.resizing) == null ? void 0 : e.axis) === "column" && this.resizing.index === t ? this.resizing.currentSize : (this.columnWidths.get(String(t)) ?? Ct) * this.zoomRatio;
650
- }
651
- beginResize(t, e, s) {
652
- s.preventDefault(), s.stopPropagation(), !(s.button !== 0 || this.readOnly || this.isAxisLocked(t, e)) && (this.finishEdit(!0), this.selecting = !1, this.headerSelecting = void 0, this.resizing = {
653
- axis: t,
654
- index: e,
655
- start: t === "row" ? s.clientY : s.clientX,
656
- size: t === "row" ? this.getRowHeight(e) : this.getColumnWidth(e),
657
- currentSize: t === "row" ? this.getRowHeight(e) : this.getColumnWidth(e)
658
- }, this.viewport.classList.add("is-resizing"));
659
- }
660
- addResizeHandle(t, e, s) {
661
- const o = document.createElement("span");
662
- o.className = `colwork-table__resize-handle colwork-table__resize-handle--${e}`, o.addEventListener("mousedown", (r) => this.beginResize(e, s, r)), t.append(o);
663
- }
664
- selectRange(t, e, s) {
665
- this.selectionAnchor = t, this.selectionFocus = e, this.selectionMode = s, this.selectedKey = W(t), this.pendingAwarenessCursor = e, this.refreshSelection();
666
- }
667
- hideContextMenu() {
668
- var t, e;
669
- (t = this.protectionMenuButton) == null || t.setAttribute("aria-expanded", "false"), (e = this.contextMenu) == null || e.remove(), this.contextMenu = void 0;
670
- }
671
- showContextMenu(t, e, s) {
672
- var n;
673
- this.hideContextMenu();
674
- const o = document.createElement("div");
675
- o.className = "colwork-table__context-menu", o.setAttribute("aria-label", "表格操作"), s.forEach(({ label: i, actions: l }) => {
676
- const d = document.createElement("div");
677
- d.className = "colwork-table__context-group", d.setAttribute("role", "group"), d.setAttribute("aria-label", i);
678
- const c = document.createElement("div");
679
- c.className = "colwork-table__context-label", c.textContent = i, d.append(c), l.forEach(([m, g]) => {
680
- const p = document.createElement("button");
681
- p.type = "button", p.textContent = m, (m.startsWith("删除") || m === "清空内容") && (p.className = "is-destructive"), p.addEventListener("click", () => {
682
- this.hideContextMenu(), g();
683
- }), d.append(p);
684
- }), o.append(d);
685
- }), o.addEventListener("keydown", (i) => {
686
- var m;
687
- if (i.key === "Escape") {
688
- i.preventDefault(), this.hideContextMenu(), this.viewport.focus({ preventScroll: !0 });
689
- return;
690
- }
691
- const l = Array.from(o.querySelectorAll("button")), d = l.indexOf(document.activeElement);
692
- let c;
693
- if (i.key === "ArrowDown") c = (d + 1) % l.length;
694
- else if (i.key === "ArrowUp") c = (d - 1 + l.length) % l.length;
695
- else if (i.key === "Home") c = 0;
696
- else if (i.key === "End") c = l.length - 1;
697
- else return;
698
- i.preventDefault(), (m = l[c]) == null || m.focus();
699
- }), o.style.left = `${t}px`, o.style.top = `${e}px`, document.body.append(o);
700
- const r = o.getBoundingClientRect();
701
- o.style.left = `${Math.max(8, Math.min(t, window.innerWidth - r.width - 8))}px`, o.style.top = `${Math.max(8, Math.min(e, window.innerHeight - r.height - 8))}px`, this.contextMenu = o, (n = o.querySelector("button")) == null || n.focus({ preventScroll: !0 });
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();
702
909
  }
703
- protectionActions() {
704
- return [
705
- ["锁定选区", () => this.requestSelectionLock(!0)],
706
- ["密码锁定选区", () => this.requestSelectionLock(!0, !0)],
707
- ["解锁选区", () => this.requestSelectionLock(!1)]
708
- ];
709
- }
710
- hasHeaderSelection(t, e) {
711
- const s = $(this.selectionAnchor, this.selectionFocus);
712
- return this.selectionMode === t && (t === "row" ? e >= s.start.row && e <= s.end.row : e >= s.start.column && e <= s.end.column);
713
- }
714
- openRowContextMenu(t, e) {
715
- if (this.readOnly) return;
716
- t.preventDefault(), t.stopPropagation(), this.hasHeaderSelection("row", e) || this.selectHeaderRange("row", e, !1);
717
- const s = $(this.selectionAnchor, this.selectionFocus), o = s.end.row - s.start.row + 1;
718
- this.showContextMenu(t.clientX, t.clientY, [
719
- { label: "行操作", actions: [
720
- [`在上方插入 ${o} 行`, () => this.modifyAxis("row", s.start.row, o)],
721
- [`在下方插入 ${o} 行`, () => this.modifyAxis("row", s.end.row + 1, o)],
722
- [`删除 ${o} 行`, () => this.deleteRows()]
723
- ] },
724
- { label: "固定", actions: [
725
- ["固定至此行", () => this.freezeSelection("row")],
726
- ["取消固定", () => this.setFrozenPanes(0, 0)]
727
- ] },
728
- { label: "保护", actions: this.protectionActions() }
729
- ]);
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 });
730
940
  }
731
- openColumnContextMenu(t, e) {
732
- if (this.readOnly) return;
733
- t.preventDefault(), t.stopPropagation(), this.hasHeaderSelection("column", e) || this.selectHeaderRange("column", e, !1);
734
- const s = $(this.selectionAnchor, this.selectionFocus), o = s.end.column - s.start.column + 1;
735
- this.showContextMenu(t.clientX, t.clientY, [
736
- { label: "列操作", actions: [
737
- [`在左侧插入 ${o} 列`, () => this.modifyAxis("column", s.start.column, o)],
738
- [`在右侧插入 ${o} 列`, () => this.modifyAxis("column", s.end.column + 1, o)],
739
- [`删除 ${o} 列`, () => this.deleteColumns()]
740
- ] },
741
- { label: "固定", actions: [
742
- ["固定至此列", () => this.freezeSelection("column")],
743
- ["取消固定", () => this.setFrozenPanes(0, 0)]
744
- ] },
745
- { label: "保护", actions: this.protectionActions() }
746
- ]);
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
+ });
747
975
  }
748
- mergeKey(t) {
749
- return `${t.start.row}:${t.start.column}-${t.end.row}:${t.end.column}`;
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
+ });
750
1004
  }
751
- parseMergeKey(t) {
752
- const e = t.match(/^(\d+):(\d+)-(\d+):(\d+)$/);
753
- if (e)
754
- return {
755
- start: { row: Number(e[1]), column: Number(e[2]) },
756
- end: { row: Number(e[3]), column: Number(e[4]) }
757
- };
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}`;
758
1008
  }
759
1009
  getMergeRanges() {
760
- return Array.from(this.merges.keys()).flatMap((t) => {
761
- const e = this.parseMergeKey(t);
762
- return e ? [e] : [];
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] : [];
763
1014
  });
1015
+ return this.doc._transaction === null && (this.mergeCache = e), e;
764
1016
  }
765
- expandSelectionToMerges(t, e) {
766
- let s = $(t, e);
767
- for (const n of this.getMergeRanges())
768
- n.start.row <= s.end.row && n.end.row >= s.start.row && n.start.column <= s.end.column && n.end.column >= s.start.column && (s = {
769
- start: { row: Math.min(s.start.row, n.start.row), column: Math.min(s.start.column, n.start.column) },
770
- end: { row: Math.max(s.end.row, n.end.row), column: Math.max(s.end.column, n.end.column) }
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) }
771
1026
  });
772
- const o = e.row >= t.row, r = e.column >= t.column;
1027
+ const n = t.row >= e.row, r = t.column >= e.column;
773
1028
  return {
774
1029
  anchor: {
775
- row: o ? s.start.row : s.end.row,
1030
+ row: n ? s.start.row : s.end.row,
776
1031
  column: r ? s.start.column : s.end.column
777
1032
  },
778
1033
  focus: {
779
- row: o ? s.end.row : s.start.row,
1034
+ row: n ? s.end.row : s.start.row,
780
1035
  column: r ? s.end.column : s.start.column
781
1036
  }
782
1037
  };
783
1038
  }
784
- getMergeStartingAt(t, e) {
785
- return this.getMergeRanges().find((s) => s.start.row === t && s.start.column === e);
786
- }
787
- isMergeCovered(t, e) {
788
- return this.getMergeRanges().some((s) => T(s, { row: t, column: e }) && (s.start.row !== t || s.start.column !== e));
789
- }
790
- mergeSelection() {
791
- if (this.readOnly || this.selectionHasLocks()) return;
792
- const t = $(this.selectionAnchor, this.selectionFocus);
793
- if (!(t.start.row === t.end.row && t.start.column === t.end.column)) {
794
- if (this.crossesFrozenBoundary(t)) {
795
- this.showLockMessage("合并范围同时包含固定和非固定区域,无法合并,请调整选区或取消固定");
796
- return;
797
- }
798
- this.closeLockMessage(), this.doc.transact(() => {
799
- this.getMergeRanges().forEach((e) => {
800
- (T(t, e.start) || T(e, t.start)) && this.merges.delete(this.mergeKey(e));
801
- }), this.merges.set(this.mergeKey(t), "1");
802
- });
803
- }
804
- }
805
- unmergeSelection() {
806
- if (this.readOnly || this.selectionHasLocks()) return;
807
- const t = $(this.selectionAnchor, this.selectionFocus);
808
- this.doc.transact(() => this.getMergeRanges().forEach((e) => {
809
- (T(t, e.start) || T(e, t.start)) && this.merges.delete(this.mergeKey(e));
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);
810
1043
  }));
811
1044
  }
812
- modifyAxis(t, e, s, o = 0) {
813
- if (this.readOnly || s === 0 || this.isAxisLocked(t, e, !0)) return;
1045
+ modifyAxis(e, t, s, n = 0) {
814
1046
  const r = [this.cells, this.styles];
815
1047
  this.doc.transact(() => {
816
- r.forEach((i) => {
817
- const l = Array.from(i.entries());
818
- i.clear(), l.forEach(([d, c]) => {
819
- const [m, g] = d.split(":").map(Number), p = t === "row" ? m : g;
820
- if (o && p >= e && p < e + o) return;
821
- const M = p >= e + o ? p + s : p, E = W(t === "row" ? { row: M, column: g } : { row: m, column: M });
822
- i.set(E, c);
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);
823
1055
  });
824
1056
  });
825
- const n = this.getMergeRanges();
826
- this.merges.clear(), n.forEach((i) => {
827
- const l = t === "row" ? i.start.row : i.start.column, d = t === "row" ? i.end.row : i.end.column;
828
- if (o && l < e + o && d >= e) return;
829
- const c = l >= e + o ? s : 0, m = t === "row" ? { start: { row: i.start.row + c, column: i.start.column }, end: { row: i.end.row + c, column: i.end.column } } : { start: { row: i.start.row, column: i.start.column + c }, end: { row: i.end.row, column: i.end.column + c } };
830
- this.merges.set(this.mergeKey(m), "1");
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");
831
1063
  });
832
- }), t === "row" ? this.rowCountValue = Math.max(1, this.rowCountValue + s) : this.columnCountValue = Math.max(1, this.columnCountValue + s), this.render();
833
- }
834
- deleteRows() {
835
- const t = $(this.selectionAnchor, this.selectionFocus), e = Math.min(t.end.row - t.start.row + 1, this.rowCount - 1);
836
- this.modifyAxis("row", t.start.row, -e, e);
837
- }
838
- deleteColumns() {
839
- const t = $(this.selectionAnchor, this.selectionFocus), e = Math.min(t.end.column - t.start.column + 1, this.columnCount - 1);
840
- this.modifyAxis("column", t.start.column, -e, e);
841
- }
842
- selectHeaderRange(t, e, s) {
843
- var r, n;
844
- let o = e;
845
- s && this.selectionMode === t && (o = t === "row" ? ((r = this.selectionAnchor) == null ? void 0 : r.row) ?? e : ((n = this.selectionAnchor) == null ? void 0 : n.column) ?? e), this.selectHeaderSpan(t, o, e);
846
- }
847
- selectHeaderSpan(t, e, s) {
848
- t === "row" ? this.selectRange({ row: e, column: 0 }, { row: s, column: this.columnCount - 1 }, "row") : this.selectRange({ row: 0, column: e }, { row: this.rowCount - 1, column: s }, "column");
849
- }
850
- addHeaderSelection(t, e, s) {
851
- t.dataset.selectionAxis = e, t.dataset.selectionIndex = String(s), t.addEventListener("mousedown", (o) => {
852
- o.button === 0 && (o.preventDefault(), o.stopPropagation(), this.finishEdit(!0), this.viewport.focus({ preventScroll: !0 }), this.hideContextMenu(), this.selectHeaderRange(e, s, o.shiftKey), this.headerSelecting = { axis: e, anchor: this.selectionAnchor[e] }, this.selecting = !0);
853
- }), t.addEventListener("mouseenter", (o) => {
854
- if (!(!this.selecting || !this.headerSelecting || this.headerSelecting.axis !== e)) {
855
- if (!(o.buttons & 1)) {
856
- this.onWindowBlur();
857
- return;
858
- }
859
- this.selectHeaderSpan(e, this.headerSelecting.anchor, s);
860
- }
861
- }), t.addEventListener("contextmenu", (o) => e === "row" ? this.openRowContextMenu(o, s) : this.openColumnContextMenu(o, s));
1064
+ }, this.origin);
862
1065
  }
863
- expandLogicalSpace() {
864
- const t = this.viewport.scrollTop + this.viewport.clientHeight >= this.viewport.scrollHeight - 280, e = this.viewport.scrollLeft + this.viewport.clientWidth >= this.viewport.scrollWidth - 280, s = t, o = e;
865
- if (t && (this.rowCountValue += 100), e && (this.columnCountValue += 5), this.selectionMode && (s || o)) {
866
- const r = this.selectionFocus ?? { row: 0, column: 0 };
867
- this.selectionFocus = at(this.selectionMode, r, this.rowCount, this.columnCount), this.publishSelection();
868
- }
869
- }
870
- publishSelection() {
871
- this.updateAwareness();
872
- }
873
- updateAwareness(t = {}) {
874
- const e = this.awareness.getLocalState() ?? {};
875
- this.awareness.setLocalState({
876
- ...e,
877
- ...t,
878
- selection: { anchor: this.selectionAnchor, focus: this.selectionFocus, mode: this.selectionMode }
879
- });
880
- }
881
- expandForRemoteSelections() {
882
- let t = this.rowCount, e = this.columnCount;
883
- this.awareness.getStates().forEach((o, r) => {
884
- if (r === this.awareness.clientID) return;
885
- const n = o.selection;
886
- !(n != null && n.anchor) || !n.focus || (t = Math.max(t, n.anchor.row + 1, n.focus.row + 1), e = Math.max(e, n.anchor.column + 1, n.focus.column + 1));
887
- });
888
- const s = t !== this.rowCount || e !== this.columnCount;
889
- return this.rowCountValue = t, this.columnCountValue = e, s;
890
- }
891
- getSelectionBounds() {
892
- const t = this.selectionAnchor ?? this.selectionFocus ?? { row: 0, column: 0 }, e = this.selectionFocus ?? t, s = $(t, e);
893
- return { top: s.start.row, bottom: s.end.row, left: s.start.column, right: s.end.column };
894
- }
895
- selectCell(t, e, s = !1) {
896
- const o = { row: t, column: e };
897
- this.selectionMode = void 0, (!s || !this.selectionAnchor) && (this.selectionAnchor = o);
898
- const r = this.expandSelectionToMerges(this.selectionAnchor, o);
899
- this.selectionAnchor = r.anchor, this.selectionFocus = r.focus, this.selectedKey = `${t}:${e}`, this.pendingAwarenessCursor = o;
900
- }
901
- isPositionSelected(t) {
902
- return T($(this.selectionAnchor, this.selectionFocus), t);
903
- }
904
- selectionToClipboard() {
905
- if (!this.selectionFocus) return;
906
- const t = $(this.selectionAnchor, this.selectionFocus), e = [], s = [];
907
- for (let o = t.start.row; o <= t.end.row; o += 1) {
908
- const r = [], n = [];
909
- for (let i = t.start.column; i <= t.end.column; i += 1) {
910
- const l = W({ row: o, column: i });
911
- r.push(this.cells.get(l) ?? "");
912
- const d = this.readStyle(l);
913
- n.push(Object.keys(d).length ? d : null);
914
- }
915
- e.push(r), s.push(n);
916
- }
917
- return { values: e, styles: s };
1066
+ }
1067
+ class Qe {
1068
+ constructor(e, t) {
1069
+ u(this, "menu");
1070
+ this.viewport = e, this.onHide = t;
918
1071
  }
919
- selectionToText() {
1072
+ contains(e) {
920
1073
  var t;
921
- return ((t = this.selectionToClipboard()) == null ? void 0 : t.values.map((e) => e.join(" ")).join(`
922
- `)) ?? "";
1074
+ return ((t = this.menu) == null ? void 0 : t.contains(e)) ?? !1;
923
1075
  }
924
- copySelection() {
1076
+ hide() {
925
1077
  var e;
926
- const t = this.selectionToText();
927
- t && ((e = navigator.clipboard) == null || e.writeText(t));
928
- }
929
- clearSelectionContents() {
930
- if (this.readOnly || this.selectionHasLocks()) return;
931
- const t = $(this.selectionAnchor, this.selectionFocus);
932
- this.doc.transact(() => {
933
- for (let e = t.start.row; e <= t.end.row; e += 1)
934
- for (let s = t.start.column; s <= t.end.column; s += 1) this.cells.delete(W({ row: e, column: s }));
935
- });
936
- }
937
- showCellContextMenu(t, e) {
938
- this.readOnly || this.showContextMenu(t, e, [
939
- { label: "编辑", actions: [
940
- ["复制", () => this.copySelection()],
941
- ["清空内容", () => this.clearSelectionContents()]
942
- ] },
943
- { label: "单元格", actions: [
944
- ["合并单元格", () => this.mergeSelection()],
945
- ["取消合并单元格", () => this.unmergeSelection()]
946
- ] },
947
- { label: "固定", actions: [
948
- ["固定至选中行", () => this.freezeSelection("row")],
949
- ["固定至选中列", () => this.freezeSelection("column")],
950
- ["取消固定", () => this.setFrozenPanes(0, 0)]
951
- ] },
952
- { label: "保护", actions: this.protectionActions() }
953
- ]);
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 });
954
1111
  }
955
- openCellContextMenu(t) {
956
- if (!this.readOnly && (t.preventDefault(), t.stopPropagation(), this.pendingCellContext = { x: t.clientX, y: t.clientY }, this.rightButtonReleased)) {
957
- this.pendingCellContext = void 0;
958
- const e = this.rightMouseUpPoint ?? { x: t.clientX, y: t.clientY };
959
- this.showCellContextMenu(e.x, e.y);
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;
960
1146
  }
961
- }
962
- sendAwareness(t) {
963
- this.pendingAwarenessCursor = void 0, this.updateAwareness({ cursor: t, editing: this.editingKey ?? null });
964
- }
965
- logChunk(t, e) {
966
- const s = Array.from(e, (o) => o.toString(16).padStart(2, "0")).join(" ");
967
- this.log(`${t} bytes=${e.byteLength} hex=${s}`);
968
- }
969
- inspectConnections() {
970
- var e, s;
971
- const t = this.provider;
972
- (e = t.signalingConns) == null || e.forEach((o) => {
973
- if (this.loggedSignals.has(o)) return;
974
- this.loggedSignals.add(o);
975
- const r = o.send.bind(o);
976
- o.send = (n) => {
977
- this.log(`signal:send ${JSON.stringify(n)}`), r(n);
978
- }, o.on("message", (n) => this.log(`signal:recv ${JSON.stringify(n)}`)), o.on("connect", () => this.log("signal:connect")), o.on("disconnect", () => this.log("signal:disconnect")), o.on("error", (n) => this.log(`signal:error ${String(n)}`));
979
- }), (s = t.room) == null || s.webrtcConns.forEach((o, r) => {
980
- const n = o.peer;
981
- if (this.loggedPeers.has(n)) return;
982
- this.loggedPeers.add(n);
983
- const i = n.send.bind(n);
984
- n.send = (l) => {
985
- this.logChunk(`webrtc:send peer=${r}`, l), i(l);
986
- }, n.on("data", (l) => this.logChunk(`webrtc:recv peer=${r}`, l)), n.on("connect", () => this.log(`webrtc:connect peer=${r}`)), n.on("close", () => this.log(`webrtc:close peer=${r}`)), n.on("error", (l) => this.log(`webrtc:error peer=${r} ${String(l)}`));
987
- });
988
- }
989
- seed(t) {
990
- t.forEach((e, s) => e.forEach((o, r) => {
991
- const n = `${s}:${r}`;
992
- !this.cells.has(n) && !this.isCellLocked(n) && this.cells.set(n, o);
993
- }));
994
- }
995
- seedDemoFormatting() {
996
- this.doc.transact(() => {
997
- this.cells.set("0:0", `设计协作表格
998
- 多人协作工作区`), this.cells.delete("0:1"), this.cells.delete("0:2"), this.merges.set("0:0-0:2", "1"), this.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 } })), this.styles.set("1:0", JSON.stringify({ bold: !0, underline: !0, background: "#fef3c7", border: { bottom: !0 } })), this.styles.set("1:1", JSON.stringify({ italic: !0, color: "#7c3aed" })), this.styles.set("1:2", JSON.stringify({ strike: !0, color: "#b91c1c" })), this.cells.set("2:0", "125000"), this.styles.set("2:0", JSON.stringify({ format: "number", fontSize: 14, border: { top: !0, bottom: !0 } })), this.cells.set("2:1", "0.72"), this.styles.set("2:1", JSON.stringify({ format: "percent", color: "#047857", align: "right" })), this.cells.set("2:2", "2026-08-09"), this.styles.set("2:2", JSON.stringify({ format: "date", background: "#dcfce7" })), this.cells.set("3:0", `这是一段较长的演示内容
999
- 可使用自动换行工具查看`), this.styles.set("3:0", JSON.stringify({ wrap: !0, background: "#f1f5f9", border: { top: !0, right: !0, bottom: !0, left: !0 } })), this.cells.set("4:0", "删除线示例"), this.styles.set("4:0", JSON.stringify({ strike: !0, color: "#64748b" })), this.cells.set("5:0", "合并区域示例"), this.cells.delete("5:1"), this.cells.delete("5:2"), this.merges.set("5:0-5:2", "1"), this.styles.set("5:0", JSON.stringify({ bold: !0, align: "center", background: "#ede9fe", border: { top: !0, right: !0, bottom: !0, left: !0 } })), this.rowHeights.set("0", 72), this.rowHeights.set("3", 72), this.rowHeights.set("5", 44), this.columnWidths.set("0", 220), this.columnWidths.set("1", 130), this.columnWidths.set("2", 130);
1000
- });
1001
- }
1002
- expandLogicalSizeFromDocument() {
1003
- const t = [...this.cells.keys(), ...this.styles.keys(), ...this.locks.keys(), ...this.rowHeights.keys(), ...this.columnWidths.keys()].map((e) => e.split(":").map(Number)).filter(([e, s]) => Number.isInteger(e) && Number.isInteger(s));
1004
- t.length && (this.rowCountValue = Math.max(this.rowCount, ...t.map(([e]) => e + 1)), this.columnCountValue = Math.max(this.columnCount, ...t.map(([, e]) => e + 1)));
1005
- }
1006
- render() {
1007
- this.editor && this.finishEdit(!0);
1008
- const t = this.columnCount, e = this.rowCount;
1009
- this.frozenRows = Math.min(this.frozenRows, e - 1), this.frozenColumns = Math.min(this.frozenColumns, t - 1);
1010
- const s = this.hasPartialMerge("row", 0, this.frozenRows - 1), o = this.hasPartialMerge("column", 0, this.frozenColumns - 1);
1011
- (s || o) && (s && (this.frozenRows = 0), o && (this.frozenColumns = 0), this.showLockMessage("合并区域已变化,已取消与合并块冲突的固定行列"));
1012
- const r = (u) => this.getRowHeight(u), n = (u) => this.getColumnWidth(u), i = zt({
1013
- scrollTop: this.viewport.scrollTop,
1014
- scrollLeft: this.viewport.scrollLeft,
1015
- clientHeight: this.viewport.clientHeight || 560,
1016
- clientWidth: this.viewport.clientWidth || 900,
1017
- rowCount: e,
1018
- columnCount: t,
1019
- rowSize: r,
1020
- columnSize: n,
1021
- overscan: 4
1022
- });
1023
- let l = !0;
1024
- const d = this.getMergeRanges();
1025
- for (; l; ) {
1026
- l = !1;
1027
- for (const u of d) {
1028
- const y = u.start.row <= i.bottom && (u.end.row >= i.top || u.start.row < this.frozenRows), b = u.start.column <= i.right && (u.end.column >= i.left || u.start.column < this.frozenColumns);
1029
- !y || !b || (u.start.row >= this.frozenRows && u.start.row < i.top && (i.top = u.start.row, l = !0), u.start.column >= this.frozenColumns && u.start.column < i.left && (i.left = u.start.column, l = !0), u.end.row > i.bottom && (i.bottom = u.end.row, l = !0), u.end.column > i.right && (i.right = u.end.column, l = !0));
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);
1030
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;
1031
1288
  }
1032
- i.bottom = Math.max(i.bottom, this.frozenRows - 1), i.right = Math.max(i.right, this.frozenColumns - 1);
1033
- const c = Math.max(this.frozenRows, i.top), m = Math.max(this.frozenColumns, i.left), g = (u, y, b) => [
1034
- ...Array.from({ length: u }, (L, C) => C),
1035
- -1,
1036
- // spacer between the frozen prefix and the virtual window
1037
- ...Array.from({ length: Math.max(0, b - y + 1) }, (L, C) => y + C)
1038
- ], p = g(this.frozenRows, c, i.bottom), M = g(this.frozenColumns, m, i.right), E = P(m, n) - P(this.frozenColumns, n), R = P(c, r) - P(this.frozenRows, r), H = (u, y, b) => {
1039
- const L = y >= 0 && y < this.frozenRows, C = b >= 0 && b < this.frozenColumns;
1040
- !L && !C || (u.classList.add("is-frozen"), u.style.position = "sticky", L && (u.style.top = `${this.columnHeaderHeight + P(y, r)}px`), C && (u.style.left = `${this.rowHeaderWidth + P(b, n)}px`), u.style.zIndex = String(y < 0 ? 10 : b < 0 ? 8 : L && C ? 5 : L ? 4 : 3));
1041
- }, q = document.createElement("thead"), O = document.createElement("tr"), z = document.createElement("th");
1042
- z.style.width = `${this.rowHeaderWidth}px`, z.style.height = `${this.columnHeaderHeight}px`, z.addEventListener("mousedown", (u) => {
1043
- u.preventDefault(), u.stopPropagation(), this.selectRange({ row: 0, column: 0 }, { row: e - 1, column: t - 1 }, "all");
1044
- }), O.append(z);
1045
- const U = (u) => {
1046
- const y = document.createElement("th");
1047
- return y.style.width = `${u}px`, y.style.padding = "0", y.style.border = "0", y;
1048
- };
1049
- for (const u of M) {
1050
- if (u === -1) {
1051
- O.append(U(E));
1052
- continue;
1053
- }
1054
- const y = document.createElement("th");
1055
- y.style.width = `${n(u)}px`, y.style.height = `${this.columnHeaderHeight}px`, y.style.fontSize = `${et * this.zoomRatio}px`;
1056
- const b = document.createElement("b");
1057
- b.className = "colwork-table__column-letter", b.textContent = At(u), y.append(b), this.addResizeHandle(y, "column", u), this.addHeaderSelection(y, "column", u), H(y, -1, u), O.append(y);
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;
1058
1305
  }
1059
- O.append(U(J(t, n) - P(i.right + 1, n))), q.append(O);
1060
- const D = document.createElement("tbody"), V = (u) => {
1061
- const y = document.createElement("tr");
1062
- y.className = "colwork-table__spacer", y.style.height = `${u}px`;
1063
- const b = document.createElement("td");
1064
- return b.colSpan = M.length + 2, b.style.height = `${u}px`, y.append(b), y;
1065
- };
1066
- for (const u of p) {
1067
- if (u === -1) {
1068
- D.append(V(R));
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);
1069
1314
  continue;
1070
1315
  }
1071
- const y = document.createElement("tr");
1072
- this.bandedRows && u % 2 === 1 && (y.className = "is-banded-row"), y.style.height = `${r(u)}px`;
1073
- const b = document.createElement("th");
1074
- b.style.width = `${this.rowHeaderWidth}px`, b.style.height = `${r(u)}px`, b.style.fontSize = `${et * this.zoomRatio}px`, b.textContent = String(u + 1), this.addResizeHandle(b, "row", u), this.addHeaderSelection(b, "row", u), y.append(b), H(b, u, -1);
1075
- for (const C of M) {
1076
- if (C === -1) {
1077
- const A = document.createElement("td");
1078
- A.style.width = `${E}px`, A.style.padding = "0", A.style.border = "0", y.append(A);
1079
- continue;
1080
- }
1081
- if (this.isMergeCovered(u, C)) continue;
1082
- const F = W({ row: u, column: C }), v = document.createElement("td");
1083
- v.style.width = `${n(C)}px`, v.style.height = `${r(u)}px`, v.dataset.key = F;
1084
- const x = this.getMergeStartingAt(u, C);
1085
- x && (v.rowSpan = x.end.row - x.start.row + 1, v.colSpan = x.end.column - x.start.column + 1);
1086
- const N = document.createElement("span");
1087
- N.className = "colwork-table__cell-value", N.style.height = `${Math.max(0, r(u) - 4)}px`, N.style.maxHeight = `${Math.max(0, r(u) - 4)}px`, N.textContent = this.displayValue(F), this.applyStyle(N, F), v.append(N), this.applyStyle(v, F), H(v, u, C);
1088
- const B = this.isCellLocked(F);
1089
- v.classList.toggle("is-locked", B), v.classList.toggle("is-password-locked", this.isCellPasswordLocked(F)), v.setAttribute("aria-readonly", String(this.readOnly || B)), B && (v.title = this.isCellPasswordLocked(F) ? "密码锁定:验证密码后可编辑" : "已锁定:解锁后可编辑"), v.addEventListener("mousedown", (A) => {
1090
- A.target instanceof HTMLTextAreaElement || A.button !== 0 && A.button !== 2 || (A.button === 2 ? (this.rightButtonReleased = !1, this.rightDrag = { start: { row: u, column: C }, moved: !1 }) : this.rightDrag = void 0, A.preventDefault(), this.viewport.focus({ preventScroll: !0 }), this.selecting = !0, (A.button === 0 || !this.isPositionSelected({ row: u, column: C })) && this.selectCell(u, C, A.shiftKey), this.refreshSelection());
1091
- }), v.addEventListener("mouseenter", () => {
1092
- if (!(!this.selecting || this.headerSelecting)) {
1093
- if (this.rightDrag) {
1094
- if (this.rightDrag.start.row === u && this.rightDrag.start.column === C) return;
1095
- this.rightDrag.moved || (this.rightDrag.moved = !0, this.selectionMode = void 0, this.selectionAnchor = this.rightDrag.start, this.selectedKey = W(this.rightDrag.start));
1096
- }
1097
- this.selectCell(u, C, !0), this.refreshSelection();
1098
- }
1099
- }), this.readOnly || v.addEventListener("dblclick", () => this.startEdit(v, F, !1)), v.addEventListener("contextmenu", (A) => this.openCellContextMenu(A)), y.append(v);
1100
- }
1101
- const L = document.createElement("td");
1102
- L.style.width = `${J(t, n) - P(i.right + 1, n)}px`, L.style.padding = "0", L.style.border = "0", y.append(L), D.append(y);
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);
1103
1324
  }
1104
- D.append(V(J(e, r) - P(i.bottom + 1, r))), this.table.style.setProperty("--colwork-zoom", String(this.zoomRatio)), this.table.style.width = `${this.rowHeaderWidth + J(t, n)}px`, this.table.classList.toggle("is-grid-hidden", !this.showGridLines), this.table.classList.toggle("is-banded-rows", this.bandedRows), this.table.style.fontSize = `${this.zoomRatio}em`, this.table.replaceChildren(q, D), this.refreshFrozenBoundaries(), this.refreshSelection(), this.refreshCursors();
1105
- }
1106
- refreshFrozenBoundaries() {
1107
- this.frozenBoundaryLayer.replaceChildren(), this.frozenBoundaryLayer.style.width = `${this.viewport.clientWidth}px`, this.frozenBoundaryLayer.style.height = `${this.viewport.clientHeight}px`;
1108
- const t = (e, s, o, r) => {
1109
- if (!s || o >= r) return;
1110
- const n = document.createElement("span");
1111
- n.className = `colwork-table__frozen-boundary colwork-table__frozen-boundary--${e}`, n.setAttribute("aria-hidden", "true"), n.style.left = `${e === "column" ? o - 1 : 0}px`, n.style.top = `${e === "row" ? o - 1 : 0}px`, e === "column" ? n.style.height = `${this.viewport.clientHeight}px` : n.style.width = `${this.viewport.clientWidth}px`, this.frozenBoundaryLayer.append(n);
1112
- };
1113
- t("row", this.frozenRows, this.columnHeaderHeight + P(this.frozenRows, (e) => this.getRowHeight(e)), this.viewport.clientHeight), t("column", this.frozenColumns, this.rowHeaderWidth + P(this.frozenColumns, (e) => this.getColumnWidth(e)), this.viewport.clientWidth);
1114
- }
1115
- refreshValues() {
1116
- const t = document.activeElement;
1117
- this.table.querySelectorAll("td[data-key]").forEach((e) => {
1118
- const s = e.dataset.key;
1119
- if (s && e !== t && s !== this.editingKey) {
1120
- const o = e.querySelector(".colwork-table__cell-value");
1121
- o ? o.textContent = this.displayValue(s) : e.textContent = this.displayValue(s);
1122
- }
1123
- });
1124
- }
1125
- refreshSelection() {
1126
- if (this.viewport.querySelectorAll(".colwork-table__selection").forEach((e) => e.remove()), !this.selectionFocus) return;
1127
- const t = this.getSelectionBounds();
1128
- this.table.querySelectorAll("th[data-selection-axis]").forEach((e) => {
1129
- const s = e.dataset.selectionAxis, o = Number(e.dataset.selectionIndex), r = this.selectionMode === "all" || this.selectionMode === s && (s === "row" ? o >= t.top && o <= t.bottom : o >= t.left && o <= t.right);
1130
- e.classList.toggle("is-selected-header", r);
1131
- }), this.addSelectionOverlay($({ row: t.top, column: t.left }, { row: t.bottom, column: t.right }), "colwork-table__selection", this.options.userColor ?? "#3b82f6");
1132
- }
1133
- refreshCursors() {
1134
- this.table && (this.table.querySelectorAll("td[data-key]").forEach((t) => {
1135
- t.querySelectorAll(".colwork-table__remote-cursor").forEach((e) => e.remove());
1136
- }), this.viewport.querySelectorAll(".colwork-table__remote-selection").forEach((t) => t.remove()), this.awareness.getStates().forEach((t, e) => {
1137
- var o;
1138
- if (e === this.awareness.clientID) return;
1139
- const s = t.selection;
1140
- if (s != null && s.anchor && s.focus) {
1141
- const r = wt(s, this.rowCount, this.columnCount);
1142
- r && this.addSelectionOverlay(r, "colwork-table__remote-selection", ((o = t.user) == null ? void 0 : o.color) ?? "#94a3b8");
1143
- const n = Math.min(s.anchor.row, s.focus.row), i = Math.min(s.anchor.column, s.focus.column), l = this.table.querySelector(`td[data-key="${n}:${i}"]`);
1144
- l && this.addCursorLabel(l, t, e);
1145
- } else {
1146
- const r = t.cursor, n = r && this.table.querySelector(`td[data-key="${r.row}:${r.column}"]`);
1147
- n && this.addCursorLabel(n, t, e);
1148
- }
1149
- }));
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);
1150
1327
  }
1151
- addSelectionOverlay(t, e, s) {
1152
- this.table.querySelectorAll("td[data-key]").forEach((o) => {
1153
- const [r, n] = o.dataset.key.split(":").map(Number), i = r + o.rowSpan - 1, l = n + o.colSpan - 1;
1154
- if (r > t.end.row || i < t.start.row || n > t.end.column || l < t.start.column) return;
1155
- const d = getComputedStyle(o), c = parseFloat(d.borderTopWidth), m = parseFloat(d.borderRightWidth), g = parseFloat(d.borderBottomWidth), p = parseFloat(d.borderLeftWidth), M = (z, U, D, V, u, y, b) => {
1156
- if (z >= D && U <= V) return [`${-y}px`, `${-b}px`];
1157
- let L = 0, C = 0, F = 0;
1158
- for (let x = z; x <= U; x++) {
1159
- const N = this.table.querySelector(`th[data-selection-axis="${u}"][data-selection-index="${x}"]`), B = N == null ? void 0 : N.getBoundingClientRect(), A = u === "row" ? (B == null ? void 0 : B.height) ?? this.getRowHeight(x) : (B == null ? void 0 : B.width) ?? this.getColumnWidth(x);
1160
- L += A, x < D && (C += A), x > V && (F += A);
1161
- }
1162
- const v = (x, N) => x === 0 ? `${-N}px` : `calc(${x / L * 100}% + ${(y + b) * x / L - N}px)`;
1163
- return [v(C, y), v(F, b)];
1164
- }, [E, R] = M(r, i, t.start.row, t.end.row, "row", c, g), [H, q] = M(n, l, t.start.column, t.end.column, "column", p, m), O = document.createElement("span");
1165
- O.className = e, O.setAttribute("aria-hidden", "true"), Object.assign(O.style, {
1166
- top: E,
1167
- right: q,
1168
- bottom: R,
1169
- left: H,
1170
- borderTopWidth: r <= t.start.row ? "2px" : "0",
1171
- borderRightWidth: l >= t.end.column ? "2px" : "0",
1172
- borderBottomWidth: i >= t.end.row ? "2px" : "0",
1173
- borderLeftWidth: n <= t.start.column ? "2px" : "0",
1174
- borderColor: s,
1175
- backgroundColor: ft(s, 0.1)
1176
- }), o.append(O);
1177
- });
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;
1178
1333
  }
1179
- addCursorLabel(t, e, s) {
1180
- var r, n;
1181
- const o = document.createElement("span");
1182
- o.className = "colwork-table__remote-cursor", o.style.backgroundColor = ((r = e.user) == null ? void 0 : r.color) ?? "#64748b", o.textContent = ((n = e.user) == null ? void 0 : n.name) ?? String(s).slice(0, 6), t.append(o);
1183
- }
1184
- startEdit(t, e, s = !0) {
1185
- if (this.readOnly || this.isCellLocked(e) || this.editingKey === e) return;
1186
- this.finishEdit(!0);
1187
- const o = Array.from(this.table.querySelectorAll("td[data-key]")).find((n) => n.dataset.key === e);
1188
- o && (t = o), this.editingKey = e, this.editingOriginal = this.cells.get(e) ?? "";
1189
- const r = document.createElement("textarea");
1190
- r.className = "colwork-table__editor", r.value = this.editingOriginal, this.applyStyle(r, e), this.editor = r, t.classList.add("is-editing"), t.append(r), s && this.sendAwareness({ ...this.selectionFocus ?? { row: 0, column: 0 }, offset: 0 }), r.addEventListener("blur", () => this.finishEdit(!0), { once: !0 }), r.addEventListener("keydown", (n) => {
1191
- n.key === "Enter" && !n.ctrlKey && !n.shiftKey && r.blur(), n.key === "Escape" && this.finishEdit(!1);
1192
- }), r.focus(), r.select();
1193
- }
1194
- readStyle(t) {
1334
+ readStyle(e) {
1195
1335
  try {
1196
- return JSON.parse(this.styles.get(t) ?? "{}");
1336
+ const t = JSON.parse(this.styles.get(e) ?? "{}");
1337
+ return se(t) ? t : {};
1197
1338
  } catch {
1198
1339
  return {};
1199
1340
  }
1200
1341
  }
1201
- applyStyle(t, e) {
1202
- var o, r, n, i;
1203
- const s = this.readStyle(e);
1204
- t.style.fontWeight = s.bold ? "700" : "", t.style.fontStyle = s.italic ? "oblique" : "", t.style.textDecoration = [s.underline ? "underline" : "", s.strike ? "line-through" : ""].filter(Boolean).join(" "), t.style.transform = t.classList.contains("colwork-table__cell-value") && s.italic ? "skewX(-8deg)" : "", t.style.fontSize = s.fontSize ? `${s.fontSize * this.zoomRatio}px` : "", t.style.color = s.color ?? "", t.style.backgroundColor = s.background ?? "", t.style.textAlign = s.align ?? "", t.classList.contains("colwork-table__cell-value") && (t.style.whiteSpace = s.wrap ? "pre-wrap" : "pre"), !t.classList.contains("colwork-table__cell-value") && !t.classList.contains("colwork-table__editor") && (t.style.borderTop = (o = s.border) != null && o.top ? "2px solid #64748b" : "", t.style.borderRight = (r = s.border) != null && r.right ? "2px solid #64748b" : "", t.style.borderBottom = (n = s.border) != null && n.bottom ? "2px solid #64748b" : "", t.style.borderLeft = (i = s.border) != null && i.left ? "2px solid #64748b" : "");
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" : "");
1205
1346
  }
1206
- displayValue(t) {
1207
- const e = this.cells.get(t) ?? "", s = this.readStyle(t).format ?? "general";
1208
- if (!e || s === "general") return e;
1347
+ displayValue(e) {
1348
+ const t = this.cells.get(e) ?? "", s = this.readStyle(e).format ?? "general";
1349
+ if (!t || s === "general") return t;
1209
1350
  if (s === "number") {
1210
- const r = Number(e);
1211
- return Number.isFinite(r) ? r.toLocaleString() : e;
1351
+ const r = Number(t);
1352
+ return Number.isFinite(r) ? r.toLocaleString() : t;
1212
1353
  }
1213
1354
  if (s === "percent") {
1214
- const r = Number(e.replace(/%$/, ""));
1215
- return Number.isFinite(r) ? `${e.endsWith("%") ? r : r * 100}%` : e;
1355
+ const r = Number(t.replace(/%$/, ""));
1356
+ return Number.isFinite(r) ? `${t.endsWith("%") ? r : r * 100}%` : t;
1216
1357
  }
1217
- const o = new Date(e);
1218
- return Number.isNaN(o.getTime()) ? e : o.toISOString().slice(0, 10);
1358
+ const n = new Date(t);
1359
+ return Number.isNaN(n.getTime()) ? t : n.toISOString().slice(0, 10);
1219
1360
  }
1220
- toggleFormat(t) {
1221
- if (this.readOnly || !this.selectedKey || this.selectionHasLocks()) return;
1222
- const { top: e, bottom: s, left: o, right: r } = this.getSelectionBounds(), n = this.readStyle(this.selectedKey)[t];
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];
1223
1364
  this.doc.transact(() => {
1224
- for (let i = e; i <= s; i += 1)
1225
- for (let l = o; l <= r; l += 1) {
1226
- const d = `${i}:${l}`, c = this.readStyle(d);
1227
- c[t] = !n, this.styles.set(d, JSON.stringify(c));
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));
1228
1369
  }
1229
- }), this.render();
1370
+ }, this.host.origin), this.host.render();
1230
1371
  }
1231
1372
  clearFormatting() {
1232
- if (this.readOnly || !this.selectedKey || this.selectionHasLocks()) return;
1233
- const { top: t, bottom: e, left: s, right: o } = this.getSelectionBounds();
1373
+ if (!this.host.canEdit() || !this.host.selectedKey()) return;
1374
+ const { top: e, bottom: t, left: s, right: n } = this.host.bounds();
1234
1375
  this.doc.transact(() => {
1235
- for (let r = t; r <= e; r += 1)
1236
- for (let n = s; n <= o; n += 1) this.styles.delete(W({ row: r, column: n }));
1237
- }), this.render();
1238
- }
1239
- toggleBorder(t) {
1240
- if (this.readOnly || !this.selectedKey || this.selectionHasLocks()) return;
1241
- const { top: e, bottom: s, left: o, right: r } = this.getSelectionBounds(), n = (c, m) => {
1242
- const g = [];
1243
- return t === "outer" && (c === e && g.push("top"), c === s && g.push("bottom"), m === o && g.push("left"), m === r && g.push("right")), (t === "inner" || t === "horizontal") && c < s && g.push("bottom"), (t === "inner" || t === "vertical") && m < r && g.push("right"), g;
1244
- }, i = Array.from({ length: s - e + 1 }, (c, m) => Array.from({ length: r - o + 1 }, (g, p) => ({
1245
- row: e + m,
1246
- column: o + p
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
1247
1388
  }))).flat();
1248
- if (!i.flatMap(({ row: c, column: m }) => n(c, m)).length) return;
1249
- const d = !i.every(({ row: c, column: m }) => n(c, m).every((g) => {
1250
- var p;
1251
- return (p = this.readStyle(W({ row: c, column: m })).border) == null ? void 0 : p[g];
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];
1252
1393
  }));
1253
1394
  this.doc.transact(() => {
1254
- for (let c = e; c <= s; c += 1)
1255
- for (let m = o; m <= r; m += 1) {
1256
- const g = W({ row: c, column: m }), p = this.readStyle(g), M = { ...p.border ?? {} };
1257
- n(c, m).forEach((E) => {
1258
- d ? M[E] = !0 : delete M[E];
1259
- }), Object.keys(M).length ? p.border = M : delete p.border, this.styles.set(g, JSON.stringify(p));
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));
1260
1401
  }
1261
- }), this.render();
1402
+ }, this.host.origin), this.host.render();
1262
1403
  }
1263
- setStyle(t, e) {
1264
- if (this.readOnly || !this.selectedKey || this.selectionHasLocks()) return;
1265
- const { top: s, bottom: o, left: r, right: n } = this.getSelectionBounds();
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();
1266
1407
  this.doc.transact(() => {
1267
- for (let i = s; i <= o; i += 1)
1268
- for (let l = r; l <= n; l += 1) {
1269
- const d = `${i}:${l}`, c = this.readStyle(d);
1270
- t === "align" ? c.align = e : t === "color" ? c.color = e : t === "background" ? c.background = e : t === "fontSize" ? c.fontSize = e : c.format = e, this.styles.set(d, JSON.stringify(c));
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));
1271
1412
  }
1272
- }), this.render();
1413
+ }, this.host.origin), this.host.render();
1273
1414
  }
1274
- refreshStyles() {
1275
- this.table.querySelectorAll("td[data-key]").forEach((t) => {
1276
- if (t.dataset.key) {
1277
- this.applyStyle(t, t.dataset.key);
1278
- const e = t.querySelector(".colwork-table__cell-value");
1279
- e && (this.applyStyle(e, t.dataset.key), e.textContent = this.displayValue(t.dataset.key));
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;
1280
1523
  }
1281
- }), this.refreshSelection(), this.refreshCursors();
1282
- }
1283
- finishEdit(t) {
1284
- if (!this.editor || !this.editingKey) return;
1285
- const e = this.editingKey, s = this.editor, o = t ? s.value : this.editingOriginal;
1286
- this.editor = void 0, this.editingKey = void 0, this.editingOriginal = "", !this.isCellLocked(e) && o !== this.cells.get(e) && this.cells.set(e, o);
1287
- const r = this.awareness.getLocalState() ?? {};
1288
- this.awareness.setLocalState({ ...r, editing: null }), s.remove();
1289
- const n = this.table.querySelector(`td[data-key="${e}"]`);
1290
- if (!n) {
1291
- this.render();
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("当前选择包含不完整的合并块,无法固定,请选择完整的合并块");
1292
1730
  return;
1293
1731
  }
1294
- this.table.querySelectorAll("td.is-editing").forEach((l) => l.classList.remove("is-editing"));
1295
- const i = n.querySelector(".colwork-table__cell-value") ?? document.createElement("span");
1296
- i.className = "colwork-table__cell-value", i.textContent = this.displayValue(e), i.parentElement || n.append(i), Array.from(n.childNodes).forEach((l) => {
1297
- l !== i && l.nodeType === Node.TEXT_NODE && l.remove();
1298
- }), this.applyStyle(n, e), this.applyStyle(i, e), this.refreshSelection(), this.refreshCursors();
1732
+ this.setFrozenPanes(
1733
+ e === "row" ? t.end.row + 1 : this.frozenRows,
1734
+ e === "column" ? t.end.column + 1 : this.frozenColumns
1735
+ );
1299
1736
  }
1300
- destroy() {
1301
- var t, e;
1302
- this.destroyed = !0, this.viewportResizeObserver.disconnect(), this.closeLockMessage(), (t = this.passwordDialog) == null || t.close(), this.finishEdit(!0), this.doc.off("update", this.onDocUpdate), this.awareness.off("update", this.onAwarenessUpdate), 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.onCopy, !0), this.viewport.removeEventListener("paste", this.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.hideContextMenu(), this.renderFrame !== void 0 && cancelAnimationFrame(this.renderFrame), (e = this.provider) == null || e.destroy(), this.undoManager.destroy(), this.doc.destroy(), this.root.replaceChildren();
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
+ }
1303
1766
  }
1304
- }
1305
- function nt(a) {
1306
- if (a != null && a.trim())
1307
- return JSON.parse(a);
1308
- }
1309
- function _t(a) {
1310
- if (!(!a || a.format === "colwork.update-log"))
1311
- return a.format === "colwork.archive" ? a.snapshot : a;
1312
- }
1313
- function rt(a) {
1314
- return !a || a.format === "colwork.snapshot" ? [] : a.updates ?? [];
1315
- }
1316
- function Ot(a, t) {
1317
- const e = nt(a), s = nt(t), o = _t(e), r = [...rt(e), ...rt(s)], n = new K.Doc();
1318
- o != null && o.snapshot && K.applyUpdate(n, st(o.snapshot));
1319
- const i = Number((o == null ? void 0 : o.sequence) ?? 0), l = /* @__PURE__ */ new Set(), d = /* @__PURE__ */ new Set();
1320
- let c = i;
1321
- for (const m of r.sort((g, p) => Number(g.seq) - Number(p.seq))) {
1322
- const g = Number(m.seq);
1323
- !Number.isInteger(g) || typeof m.update != "string" || g <= i || l.has(g) || d.has(m.update) || (K.applyUpdate(n, st(m.update)), l.add(g), d.add(m.update), c = Math.max(c, g));
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());
1324
1908
  }
1325
- return {
1326
- format: "colwork.snapshot",
1327
- version: 1,
1328
- room: o == null ? void 0 : o.room,
1329
- sequence: c,
1330
- snapshot: I(K.encodeStateAsUpdate(n)),
1331
- stateVector: I(K.encodeStateVector(n))
1332
- };
1333
1909
  }
1334
1910
  export {
1335
- Ft as ColworkTable,
1336
- W as cellKey,
1337
- T as containsPosition,
1338
- pt as normalizeRange,
1339
- Dt as rangeSize,
1340
- Ot as rebuildYjsSnapshot
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
1341
1928
  };