@pixerate/editor 0.14.3 → 0.15.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/agent/index.cjs +28 -220
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts +1 -1
- package/dist/agent/index.d.ts +1 -1
- package/dist/agent/index.js +5 -154
- package/dist/agent/index.js.map +1 -1
- package/dist/canvas/index.cjs +113 -377
- package/dist/canvas/index.cjs.map +1 -1
- package/dist/canvas/index.d.cts +2 -2
- package/dist/canvas/index.d.ts +2 -2
- package/dist/canvas/index.js +18 -208
- package/dist/canvas/index.js.map +1 -1
- package/dist/chunk-33UVEDOS.cjs +233 -0
- package/dist/chunk-33UVEDOS.cjs.map +1 -0
- package/dist/chunk-7FWEWE6T.js +1888 -0
- package/dist/chunk-7FWEWE6T.js.map +1 -0
- package/dist/chunk-BYCOFZAA.js +514 -0
- package/dist/chunk-BYCOFZAA.js.map +1 -0
- package/dist/chunk-CYKQLDYH.cjs +1290 -0
- package/dist/chunk-CYKQLDYH.cjs.map +1 -0
- package/dist/chunk-GLSIZKOX.js +17 -0
- package/dist/chunk-GLSIZKOX.js.map +1 -0
- package/dist/chunk-GWHJVZPI.js +233 -0
- package/dist/chunk-GWHJVZPI.js.map +1 -0
- package/dist/chunk-LDES3EOS.cjs +1888 -0
- package/dist/chunk-LDES3EOS.cjs.map +1 -0
- package/dist/chunk-MPPXH7U5.cjs +336 -0
- package/dist/chunk-MPPXH7U5.cjs.map +1 -0
- package/dist/chunk-NNJRJJSC.js +1290 -0
- package/dist/chunk-NNJRJJSC.js.map +1 -0
- package/dist/chunk-O7LOPQMH.js +336 -0
- package/dist/chunk-O7LOPQMH.js.map +1 -0
- package/dist/chunk-SEDR75VH.cjs +17 -0
- package/dist/chunk-SEDR75VH.cjs.map +1 -0
- package/dist/chunk-SHWP2A43.cjs +514 -0
- package/dist/chunk-SHWP2A43.cjs.map +1 -0
- package/dist/chunk-VHZCXHS4.js +222 -0
- package/dist/chunk-VHZCXHS4.js.map +1 -0
- package/dist/chunk-WADCJ7A7.cjs +222 -0
- package/dist/chunk-WADCJ7A7.cjs.map +1 -0
- package/dist/extensions/index.cjs +25 -1920
- package/dist/extensions/index.cjs.map +1 -1
- package/dist/extensions/index.js +22 -1868
- package/dist/extensions/index.js.map +1 -1
- package/dist/grammar/index.cjs +44 -387
- package/dist/grammar/index.cjs.map +1 -1
- package/dist/grammar/index.js +23 -321
- package/dist/grammar/index.js.map +1 -1
- package/dist/history/index.cjs +6 -257
- package/dist/history/index.cjs.map +1 -1
- package/dist/history/index.js +4 -227
- package/dist/history/index.js.map +1 -1
- package/dist/image-editor/index.cjs +63 -106
- package/dist/image-editor/index.cjs.map +1 -1
- package/dist/index.cjs +324 -7232
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +0 -4
- package/dist/index.d.ts +0 -4
- package/dist/index.js +258 -7007
- package/dist/index.js.map +1 -1
- package/dist/serializers/index.cjs +28 -558
- package/dist/serializers/index.cjs.map +1 -1
- package/dist/serializers/index.js +16 -496
- package/dist/serializers/index.js.map +1 -1
- package/dist/spreadsheet/index.cjs +21 -1319
- package/dist/spreadsheet/index.cjs.map +1 -1
- package/dist/spreadsheet/index.js +14 -1274
- package/dist/spreadsheet/index.js.map +1 -1
- package/dist/{types-lGtRobRV.d.cts → types-DC8b2TsA.d.cts} +1 -1
- package/dist/{types-lGtRobRV.d.ts → types-DC8b2TsA.d.ts} +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,1290 @@
|
|
|
1
|
+
// src/spreadsheet/formula/lexer.ts
|
|
2
|
+
function tokenizeFormula(formula) {
|
|
3
|
+
const tokens = [];
|
|
4
|
+
let input = formula.trim();
|
|
5
|
+
let offset = 0;
|
|
6
|
+
if (input.startsWith("=")) {
|
|
7
|
+
input = input.slice(1);
|
|
8
|
+
offset = 1;
|
|
9
|
+
}
|
|
10
|
+
let i = 0;
|
|
11
|
+
while (i < input.length) {
|
|
12
|
+
const char = input[i];
|
|
13
|
+
if (/\s/.test(char)) {
|
|
14
|
+
i++;
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
if (/\d/.test(char) || char === "." && i + 1 < input.length && /\d/.test(input[i + 1])) {
|
|
18
|
+
const start = i;
|
|
19
|
+
let hasDot = char === ".";
|
|
20
|
+
i++;
|
|
21
|
+
while (i < input.length && (/\d/.test(input[i]) || input[i] === "." && !hasDot)) {
|
|
22
|
+
if (input[i] === ".") hasDot = true;
|
|
23
|
+
i++;
|
|
24
|
+
}
|
|
25
|
+
tokens.push({
|
|
26
|
+
type: "NUMBER",
|
|
27
|
+
value: input.slice(start, i),
|
|
28
|
+
position: start + offset
|
|
29
|
+
});
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
if (char === '"' || char === "'") {
|
|
33
|
+
const quote = char;
|
|
34
|
+
const start = i;
|
|
35
|
+
i++;
|
|
36
|
+
let str = "";
|
|
37
|
+
while (i < input.length && input[i] !== quote) {
|
|
38
|
+
if (input[i] === "\\" && i + 1 < input.length) {
|
|
39
|
+
i++;
|
|
40
|
+
}
|
|
41
|
+
str += input[i];
|
|
42
|
+
i++;
|
|
43
|
+
}
|
|
44
|
+
if (i < input.length && input[i] === quote) {
|
|
45
|
+
i++;
|
|
46
|
+
}
|
|
47
|
+
tokens.push({
|
|
48
|
+
type: "STRING",
|
|
49
|
+
value: str,
|
|
50
|
+
position: start + offset
|
|
51
|
+
});
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
if (char === "[") {
|
|
55
|
+
const start = i;
|
|
56
|
+
i++;
|
|
57
|
+
let prop = "";
|
|
58
|
+
while (i < input.length && input[i] !== "]") {
|
|
59
|
+
prop += input[i];
|
|
60
|
+
i++;
|
|
61
|
+
}
|
|
62
|
+
if (i < input.length && input[i] === "]") {
|
|
63
|
+
i++;
|
|
64
|
+
}
|
|
65
|
+
tokens.push({
|
|
66
|
+
type: "PROPERTY_REF",
|
|
67
|
+
value: prop.trim(),
|
|
68
|
+
position: start + offset
|
|
69
|
+
});
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (char === "(") {
|
|
73
|
+
tokens.push({ type: "LPAREN", value: "(", position: i + offset });
|
|
74
|
+
i++;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (char === ")") {
|
|
78
|
+
tokens.push({ type: "RPAREN", value: ")", position: i + offset });
|
|
79
|
+
i++;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (char === ",") {
|
|
83
|
+
tokens.push({ type: "COMMA", value: ",", position: i + offset });
|
|
84
|
+
i++;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const twoChars = input.slice(i, i + 2);
|
|
88
|
+
if (["<=", ">=", "<>", "!="].includes(twoChars)) {
|
|
89
|
+
tokens.push({
|
|
90
|
+
type: "OPERATOR",
|
|
91
|
+
value: twoChars === "!=" ? "<>" : twoChars,
|
|
92
|
+
position: i + offset
|
|
93
|
+
});
|
|
94
|
+
i += 2;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
if (["+", "-", "*", "/", "^", "&", "=", "<", ">"].includes(char)) {
|
|
98
|
+
tokens.push({ type: "OPERATOR", value: char, position: i + offset });
|
|
99
|
+
i++;
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (/[a-zA-Z_$]/.test(char)) {
|
|
103
|
+
const start = i;
|
|
104
|
+
while (i < input.length && /[a-zA-Z0-9_$.]/.test(input[i])) {
|
|
105
|
+
i++;
|
|
106
|
+
}
|
|
107
|
+
const rawWord = input.slice(start, i);
|
|
108
|
+
if (i < input.length && input[i] === ":") {
|
|
109
|
+
const colonPos = i;
|
|
110
|
+
i++;
|
|
111
|
+
const secondStart = i;
|
|
112
|
+
while (i < input.length && /[a-zA-Z0-9_$.]/.test(input[i])) {
|
|
113
|
+
i++;
|
|
114
|
+
}
|
|
115
|
+
const secondWord = input.slice(secondStart, i);
|
|
116
|
+
if (secondWord.length > 0) {
|
|
117
|
+
tokens.push({
|
|
118
|
+
type: "RANGE",
|
|
119
|
+
value: `${rawWord}:${secondWord}`.toUpperCase(),
|
|
120
|
+
position: start + offset
|
|
121
|
+
});
|
|
122
|
+
continue;
|
|
123
|
+
} else {
|
|
124
|
+
i = colonPos;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const upper = rawWord.toUpperCase();
|
|
128
|
+
if (upper === "TRUE" || upper === "FALSE") {
|
|
129
|
+
tokens.push({
|
|
130
|
+
type: "BOOLEAN",
|
|
131
|
+
value: upper,
|
|
132
|
+
position: start + offset
|
|
133
|
+
});
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (/^\$?[A-Za-z]+\$?[0-9]+$/.test(rawWord)) {
|
|
137
|
+
tokens.push({
|
|
138
|
+
type: "CELL_REF",
|
|
139
|
+
value: upper.replace(/\$/g, ""),
|
|
140
|
+
position: start + offset
|
|
141
|
+
});
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
tokens.push({
|
|
145
|
+
type: "IDENTIFIER",
|
|
146
|
+
value: upper,
|
|
147
|
+
position: start + offset
|
|
148
|
+
});
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
i++;
|
|
152
|
+
}
|
|
153
|
+
tokens.push({ type: "EOF", value: "", position: input.length + offset });
|
|
154
|
+
return tokens;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// src/spreadsheet/formula/parser.ts
|
|
158
|
+
function parseCellReference(ref) {
|
|
159
|
+
const match = ref.match(/^([A-Za-z]+)(\d+)$/);
|
|
160
|
+
if (!match) {
|
|
161
|
+
throw new Error(`Invalid cell reference: ${ref}`);
|
|
162
|
+
}
|
|
163
|
+
return {
|
|
164
|
+
col: match[1].toUpperCase(),
|
|
165
|
+
row: parseInt(match[2], 10)
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
function parseRange(rangeStr) {
|
|
169
|
+
const [start, end] = rangeStr.split(":");
|
|
170
|
+
const startRef = parseCellReference(start);
|
|
171
|
+
const endRef = parseCellReference(end);
|
|
172
|
+
return {
|
|
173
|
+
type: "Range",
|
|
174
|
+
raw: rangeStr.toUpperCase(),
|
|
175
|
+
startCol: startRef.col,
|
|
176
|
+
startRow: startRef.row,
|
|
177
|
+
endCol: endRef.col,
|
|
178
|
+
endRow: endRef.row
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
var FormulaParser = class {
|
|
182
|
+
tokens = [];
|
|
183
|
+
current = 0;
|
|
184
|
+
constructor(tokens) {
|
|
185
|
+
this.tokens = tokens;
|
|
186
|
+
}
|
|
187
|
+
parse() {
|
|
188
|
+
if (this.peek().type === "EOF") {
|
|
189
|
+
return { type: "Literal", value: "" };
|
|
190
|
+
}
|
|
191
|
+
const expr = this.expression();
|
|
192
|
+
if (this.peek().type !== "EOF") {
|
|
193
|
+
throw new Error(`Unexpected token at position ${this.peek().position}: ${this.peek().value}`);
|
|
194
|
+
}
|
|
195
|
+
return expr;
|
|
196
|
+
}
|
|
197
|
+
expression() {
|
|
198
|
+
return this.comparison();
|
|
199
|
+
}
|
|
200
|
+
comparison() {
|
|
201
|
+
let expr = this.concatenation();
|
|
202
|
+
while (this.matchOperator("=", "<>", "<", ">", "<=", ">=")) {
|
|
203
|
+
const op = this.previous().value;
|
|
204
|
+
const right = this.concatenation();
|
|
205
|
+
expr = { type: "BinaryOp", op, left: expr, right };
|
|
206
|
+
}
|
|
207
|
+
return expr;
|
|
208
|
+
}
|
|
209
|
+
concatenation() {
|
|
210
|
+
let expr = this.addition();
|
|
211
|
+
while (this.matchOperator("&")) {
|
|
212
|
+
const op = this.previous().value;
|
|
213
|
+
const right = this.addition();
|
|
214
|
+
expr = { type: "BinaryOp", op, left: expr, right };
|
|
215
|
+
}
|
|
216
|
+
return expr;
|
|
217
|
+
}
|
|
218
|
+
addition() {
|
|
219
|
+
let expr = this.multiplication();
|
|
220
|
+
while (this.matchOperator("+", "-")) {
|
|
221
|
+
const op = this.previous().value;
|
|
222
|
+
const right = this.multiplication();
|
|
223
|
+
expr = { type: "BinaryOp", op, left: expr, right };
|
|
224
|
+
}
|
|
225
|
+
return expr;
|
|
226
|
+
}
|
|
227
|
+
multiplication() {
|
|
228
|
+
let expr = this.exponentiation();
|
|
229
|
+
while (this.matchOperator("*", "/")) {
|
|
230
|
+
const op = this.previous().value;
|
|
231
|
+
const right = this.exponentiation();
|
|
232
|
+
expr = { type: "BinaryOp", op, left: expr, right };
|
|
233
|
+
}
|
|
234
|
+
return expr;
|
|
235
|
+
}
|
|
236
|
+
exponentiation() {
|
|
237
|
+
let expr = this.unary();
|
|
238
|
+
while (this.matchOperator("^")) {
|
|
239
|
+
const op = this.previous().value;
|
|
240
|
+
const right = this.unary();
|
|
241
|
+
expr = { type: "BinaryOp", op, left: expr, right };
|
|
242
|
+
}
|
|
243
|
+
return expr;
|
|
244
|
+
}
|
|
245
|
+
unary() {
|
|
246
|
+
if (this.matchOperator("-", "+")) {
|
|
247
|
+
const op = this.previous().value;
|
|
248
|
+
const argument = this.unary();
|
|
249
|
+
return { type: "UnaryOp", op, argument };
|
|
250
|
+
}
|
|
251
|
+
return this.primary();
|
|
252
|
+
}
|
|
253
|
+
primary() {
|
|
254
|
+
const token = this.peek();
|
|
255
|
+
if (token.type === "NUMBER") {
|
|
256
|
+
this.advance();
|
|
257
|
+
return { type: "Literal", value: parseFloat(token.value) };
|
|
258
|
+
}
|
|
259
|
+
if (token.type === "STRING") {
|
|
260
|
+
this.advance();
|
|
261
|
+
return { type: "Literal", value: token.value };
|
|
262
|
+
}
|
|
263
|
+
if (token.type === "BOOLEAN") {
|
|
264
|
+
this.advance();
|
|
265
|
+
return { type: "Literal", value: token.value === "TRUE" };
|
|
266
|
+
}
|
|
267
|
+
if (token.type === "CELL_REF") {
|
|
268
|
+
this.advance();
|
|
269
|
+
const parsed = parseCellReference(token.value);
|
|
270
|
+
return {
|
|
271
|
+
type: "CellRef",
|
|
272
|
+
ref: token.value,
|
|
273
|
+
col: parsed.col,
|
|
274
|
+
row: parsed.row
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
if (token.type === "RANGE") {
|
|
278
|
+
this.advance();
|
|
279
|
+
return parseRange(token.value);
|
|
280
|
+
}
|
|
281
|
+
if (token.type === "PROPERTY_REF") {
|
|
282
|
+
this.advance();
|
|
283
|
+
return {
|
|
284
|
+
type: "PropertyRef",
|
|
285
|
+
property: token.value
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
if (token.type === "IDENTIFIER") {
|
|
289
|
+
const name = token.value;
|
|
290
|
+
this.advance();
|
|
291
|
+
if (this.check("LPAREN")) {
|
|
292
|
+
this.consume("LPAREN", `Expected '(' after function ${name}`);
|
|
293
|
+
const args = [];
|
|
294
|
+
if (!this.check("RPAREN")) {
|
|
295
|
+
do {
|
|
296
|
+
args.push(this.expression());
|
|
297
|
+
} while (this.match("COMMA"));
|
|
298
|
+
}
|
|
299
|
+
this.consume("RPAREN", `Expected ')' after function arguments`);
|
|
300
|
+
return {
|
|
301
|
+
type: "FunctionCall",
|
|
302
|
+
name,
|
|
303
|
+
args
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
return { type: "Literal", value: name };
|
|
307
|
+
}
|
|
308
|
+
if (this.match("LPAREN")) {
|
|
309
|
+
const expr = this.expression();
|
|
310
|
+
this.consume("RPAREN", `Expected ')' after expression`);
|
|
311
|
+
return expr;
|
|
312
|
+
}
|
|
313
|
+
throw new Error(`Unexpected token at position ${token.position}: ${token.value || token.type}`);
|
|
314
|
+
}
|
|
315
|
+
match(...types) {
|
|
316
|
+
for (const type of types) {
|
|
317
|
+
if (this.check(type)) {
|
|
318
|
+
this.advance();
|
|
319
|
+
return true;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
return false;
|
|
323
|
+
}
|
|
324
|
+
matchOperator(...ops) {
|
|
325
|
+
if (this.check("OPERATOR") && ops.includes(this.peek().value)) {
|
|
326
|
+
this.advance();
|
|
327
|
+
return true;
|
|
328
|
+
}
|
|
329
|
+
return false;
|
|
330
|
+
}
|
|
331
|
+
check(type) {
|
|
332
|
+
if (this.isAtEnd()) return false;
|
|
333
|
+
return this.peek().type === type;
|
|
334
|
+
}
|
|
335
|
+
advance() {
|
|
336
|
+
if (!this.isAtEnd()) this.current++;
|
|
337
|
+
return this.previous();
|
|
338
|
+
}
|
|
339
|
+
isAtEnd() {
|
|
340
|
+
return this.peek().type === "EOF";
|
|
341
|
+
}
|
|
342
|
+
peek() {
|
|
343
|
+
return this.tokens[this.current];
|
|
344
|
+
}
|
|
345
|
+
previous() {
|
|
346
|
+
return this.tokens[this.current - 1];
|
|
347
|
+
}
|
|
348
|
+
consume(type, message) {
|
|
349
|
+
if (this.check(type)) return this.advance();
|
|
350
|
+
throw new Error(message);
|
|
351
|
+
}
|
|
352
|
+
};
|
|
353
|
+
function parseFormula(formula) {
|
|
354
|
+
const tokens = tokenizeFormula(formula);
|
|
355
|
+
const parser = new FormulaParser(tokens);
|
|
356
|
+
return parser.parse();
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// src/spreadsheet/formula/evaluator.ts
|
|
360
|
+
function colNameToIndex(col) {
|
|
361
|
+
let index = 0;
|
|
362
|
+
const upper = col.toUpperCase();
|
|
363
|
+
for (let i = 0; i < upper.length; i++) {
|
|
364
|
+
index = index * 26 + (upper.charCodeAt(i) - 65 + 1);
|
|
365
|
+
}
|
|
366
|
+
return index - 1;
|
|
367
|
+
}
|
|
368
|
+
function indexToColName(index) {
|
|
369
|
+
let num = index + 1;
|
|
370
|
+
let name = "";
|
|
371
|
+
while (num > 0) {
|
|
372
|
+
const mod = (num - 1) % 26;
|
|
373
|
+
name = String.fromCharCode(65 + mod) + name;
|
|
374
|
+
num = Math.floor((num - mod) / 26);
|
|
375
|
+
}
|
|
376
|
+
return name;
|
|
377
|
+
}
|
|
378
|
+
var FormulaEvaluator = class {
|
|
379
|
+
context;
|
|
380
|
+
constructor(context = {}) {
|
|
381
|
+
this.context = context;
|
|
382
|
+
}
|
|
383
|
+
evaluate(astOrFormula) {
|
|
384
|
+
const ast = typeof astOrFormula === "string" ? parseFormula(astOrFormula) : astOrFormula;
|
|
385
|
+
return this.evaluateNode(ast);
|
|
386
|
+
}
|
|
387
|
+
evaluateNode(node) {
|
|
388
|
+
switch (node.type) {
|
|
389
|
+
case "Literal":
|
|
390
|
+
return node.value;
|
|
391
|
+
case "CellRef": {
|
|
392
|
+
if (!this.context.resolveCell) {
|
|
393
|
+
throw new Error(`Cannot resolve cell reference ${node.ref}: no cell resolver provided`);
|
|
394
|
+
}
|
|
395
|
+
return this.context.resolveCell(node.col, node.row);
|
|
396
|
+
}
|
|
397
|
+
case "Range": {
|
|
398
|
+
if (!this.context.resolveRange) {
|
|
399
|
+
throw new Error(`Cannot resolve range ${node.raw}: no range resolver provided`);
|
|
400
|
+
}
|
|
401
|
+
return this.context.resolveRange(node.startCol, node.startRow, node.endCol, node.endRow);
|
|
402
|
+
}
|
|
403
|
+
case "PropertyRef": {
|
|
404
|
+
if (!this.context.resolveProperty) {
|
|
405
|
+
throw new Error(`Cannot resolve property [${node.property}]: no property resolver provided`);
|
|
406
|
+
}
|
|
407
|
+
return this.context.resolveProperty(node.property);
|
|
408
|
+
}
|
|
409
|
+
case "UnaryOp": {
|
|
410
|
+
const val = this.evaluateNode(node.argument);
|
|
411
|
+
if (node.op === "-") return -Number(val);
|
|
412
|
+
if (node.op === "+") return +Number(val);
|
|
413
|
+
throw new Error(`Unsupported unary operator: ${node.op}`);
|
|
414
|
+
}
|
|
415
|
+
case "BinaryOp": {
|
|
416
|
+
const left = this.evaluateNode(node.left);
|
|
417
|
+
const right = this.evaluateNode(node.right);
|
|
418
|
+
switch (node.op) {
|
|
419
|
+
case "+":
|
|
420
|
+
return Number(left) + Number(right);
|
|
421
|
+
case "-":
|
|
422
|
+
return Number(left) - Number(right);
|
|
423
|
+
case "*":
|
|
424
|
+
return Number(left) * Number(right);
|
|
425
|
+
case "/": {
|
|
426
|
+
const denom = Number(right);
|
|
427
|
+
if (denom === 0) return "#DIV/0!";
|
|
428
|
+
return Number(left) / denom;
|
|
429
|
+
}
|
|
430
|
+
case "^":
|
|
431
|
+
return Math.pow(Number(left), Number(right));
|
|
432
|
+
case "&":
|
|
433
|
+
return `${left ?? ""}${right ?? ""}`;
|
|
434
|
+
case "=":
|
|
435
|
+
return String(left).toLowerCase() === String(right).toLowerCase();
|
|
436
|
+
case "<>":
|
|
437
|
+
return String(left).toLowerCase() !== String(right).toLowerCase();
|
|
438
|
+
case "<":
|
|
439
|
+
return Number(left) < Number(right);
|
|
440
|
+
case "<=":
|
|
441
|
+
return Number(left) <= Number(right);
|
|
442
|
+
case ">":
|
|
443
|
+
return Number(left) > Number(right);
|
|
444
|
+
case ">=":
|
|
445
|
+
return Number(left) >= Number(right);
|
|
446
|
+
default:
|
|
447
|
+
throw new Error(`Unsupported binary operator: ${node.op}`);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
case "FunctionCall": {
|
|
451
|
+
return this.callFunction(node.name, node.args);
|
|
452
|
+
}
|
|
453
|
+
default:
|
|
454
|
+
throw new Error(`Unknown AST node: ${node.type}`);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
callFunction(name, args) {
|
|
458
|
+
const fnName = name.toUpperCase();
|
|
459
|
+
const evaluateAndFlatten = () => {
|
|
460
|
+
const items = [];
|
|
461
|
+
for (const arg of args) {
|
|
462
|
+
const val = this.evaluateNode(arg);
|
|
463
|
+
if (Array.isArray(val)) {
|
|
464
|
+
items.push(...val);
|
|
465
|
+
} else {
|
|
466
|
+
items.push(val);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
return items;
|
|
470
|
+
};
|
|
471
|
+
switch (fnName) {
|
|
472
|
+
case "SUM": {
|
|
473
|
+
const items = evaluateAndFlatten();
|
|
474
|
+
let total = 0;
|
|
475
|
+
for (const item of items) {
|
|
476
|
+
const num = Number(item);
|
|
477
|
+
if (!isNaN(num)) total += num;
|
|
478
|
+
}
|
|
479
|
+
return total;
|
|
480
|
+
}
|
|
481
|
+
case "AVERAGE": {
|
|
482
|
+
const items = evaluateAndFlatten();
|
|
483
|
+
let total = 0;
|
|
484
|
+
let count = 0;
|
|
485
|
+
for (const item of items) {
|
|
486
|
+
const num = Number(item);
|
|
487
|
+
if (!isNaN(num) && item !== "" && item !== null && item !== void 0) {
|
|
488
|
+
total += num;
|
|
489
|
+
count++;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
return count === 0 ? 0 : total / count;
|
|
493
|
+
}
|
|
494
|
+
case "COUNT": {
|
|
495
|
+
const items = evaluateAndFlatten();
|
|
496
|
+
let count = 0;
|
|
497
|
+
for (const item of items) {
|
|
498
|
+
const num = Number(item);
|
|
499
|
+
if (!isNaN(num) && item !== "" && item !== null && item !== void 0) {
|
|
500
|
+
count++;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
return count;
|
|
504
|
+
}
|
|
505
|
+
case "COUNTA": {
|
|
506
|
+
const items = evaluateAndFlatten();
|
|
507
|
+
let count = 0;
|
|
508
|
+
for (const item of items) {
|
|
509
|
+
if (item !== "" && item !== null && item !== void 0) {
|
|
510
|
+
count++;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
return count;
|
|
514
|
+
}
|
|
515
|
+
case "MIN": {
|
|
516
|
+
const items = evaluateAndFlatten().map(Number).filter((n) => !isNaN(n));
|
|
517
|
+
return items.length === 0 ? 0 : Math.min(...items);
|
|
518
|
+
}
|
|
519
|
+
case "MAX": {
|
|
520
|
+
const items = evaluateAndFlatten().map(Number).filter((n) => !isNaN(n));
|
|
521
|
+
return items.length === 0 ? 0 : Math.max(...items);
|
|
522
|
+
}
|
|
523
|
+
case "IF": {
|
|
524
|
+
if (args.length < 2) throw new Error("IF requires at least 2 arguments");
|
|
525
|
+
const condition = Boolean(this.evaluateNode(args[0]));
|
|
526
|
+
if (condition) {
|
|
527
|
+
return this.evaluateNode(args[1]);
|
|
528
|
+
} else {
|
|
529
|
+
return args.length > 2 ? this.evaluateNode(args[2]) : false;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
case "CONCAT": {
|
|
533
|
+
const items = evaluateAndFlatten();
|
|
534
|
+
return items.map((i) => i === null || i === void 0 ? "" : String(i)).join("");
|
|
535
|
+
}
|
|
536
|
+
case "UPPER": {
|
|
537
|
+
if (args.length !== 1) throw new Error("UPPER requires 1 argument");
|
|
538
|
+
const val = this.evaluateNode(args[0]);
|
|
539
|
+
return String(val ?? "").toUpperCase();
|
|
540
|
+
}
|
|
541
|
+
case "LOWER": {
|
|
542
|
+
if (args.length !== 1) throw new Error("LOWER requires 1 argument");
|
|
543
|
+
const val = this.evaluateNode(args[0]);
|
|
544
|
+
return String(val ?? "").toLowerCase();
|
|
545
|
+
}
|
|
546
|
+
case "TRIM": {
|
|
547
|
+
if (args.length !== 1) throw new Error("TRIM requires 1 argument");
|
|
548
|
+
const val = this.evaluateNode(args[0]);
|
|
549
|
+
return String(val ?? "").trim();
|
|
550
|
+
}
|
|
551
|
+
case "LEN": {
|
|
552
|
+
if (args.length !== 1) throw new Error("LEN requires 1 argument");
|
|
553
|
+
const val = this.evaluateNode(args[0]);
|
|
554
|
+
return String(val ?? "").length;
|
|
555
|
+
}
|
|
556
|
+
case "ROUND": {
|
|
557
|
+
if (args.length < 1) throw new Error("ROUND requires at least 1 argument");
|
|
558
|
+
const num = Number(this.evaluateNode(args[0]));
|
|
559
|
+
const decimals = args.length > 1 ? Number(this.evaluateNode(args[1])) : 0;
|
|
560
|
+
const factor = Math.pow(10, decimals);
|
|
561
|
+
return Math.round(num * factor) / factor;
|
|
562
|
+
}
|
|
563
|
+
case "ABS": {
|
|
564
|
+
if (args.length !== 1) throw new Error("ABS requires 1 argument");
|
|
565
|
+
return Math.abs(Number(this.evaluateNode(args[0])));
|
|
566
|
+
}
|
|
567
|
+
case "TODAY": {
|
|
568
|
+
return (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
569
|
+
}
|
|
570
|
+
case "DAYS": {
|
|
571
|
+
if (args.length !== 2) throw new Error("DAYS requires 2 arguments (end_date, start_date)");
|
|
572
|
+
const d1 = new Date(this.evaluateNode(args[0]));
|
|
573
|
+
const d2 = new Date(this.evaluateNode(args[1]));
|
|
574
|
+
const diffTime = d1.getTime() - d2.getTime();
|
|
575
|
+
return Math.round(diffTime / (1e3 * 60 * 60 * 24));
|
|
576
|
+
}
|
|
577
|
+
default:
|
|
578
|
+
throw new Error(`Unknown function: ${fnName}`);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
|
|
583
|
+
// src/spreadsheet/formula/dependency-graph.ts
|
|
584
|
+
function extractCellDependencies(node) {
|
|
585
|
+
const deps = [];
|
|
586
|
+
const visit = (curr) => {
|
|
587
|
+
if (curr.type === "CellRef") {
|
|
588
|
+
deps.push({ col: curr.col, row: curr.row });
|
|
589
|
+
} else if (curr.type === "Range") {
|
|
590
|
+
const startC = colNameToIndex(curr.startCol);
|
|
591
|
+
const endC = colNameToIndex(curr.endCol);
|
|
592
|
+
const minC = Math.min(startC, endC);
|
|
593
|
+
const maxC = Math.max(startC, endC);
|
|
594
|
+
const minR = Math.min(curr.startRow, curr.endRow);
|
|
595
|
+
const maxR = Math.max(curr.startRow, curr.endRow);
|
|
596
|
+
for (let c = minC; c <= maxC; c++) {
|
|
597
|
+
for (let r = minR; r <= maxR; r++) {
|
|
598
|
+
deps.push({ col: indexToColName(c), row: r });
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
} else if (curr.type === "BinaryOp") {
|
|
602
|
+
visit(curr.left);
|
|
603
|
+
visit(curr.right);
|
|
604
|
+
} else if (curr.type === "UnaryOp") {
|
|
605
|
+
visit(curr.argument);
|
|
606
|
+
} else if (curr.type === "FunctionCall") {
|
|
607
|
+
curr.args.forEach(visit);
|
|
608
|
+
}
|
|
609
|
+
};
|
|
610
|
+
visit(node);
|
|
611
|
+
return deps;
|
|
612
|
+
}
|
|
613
|
+
var DependencyGraph = class {
|
|
614
|
+
// Map of cellKey (e.g. "B2") -> Set of cellKeys that this cell depends ON
|
|
615
|
+
dependencies = /* @__PURE__ */ new Map();
|
|
616
|
+
// Map of cellKey (e.g. "A1") -> Set of cellKeys that depend ON this cell (dependents)
|
|
617
|
+
dependents = /* @__PURE__ */ new Map();
|
|
618
|
+
setCellFormula(cellKey, formulaStr) {
|
|
619
|
+
const key = cellKey.toUpperCase();
|
|
620
|
+
const oldDeps = this.dependencies.get(key) || /* @__PURE__ */ new Set();
|
|
621
|
+
for (const dep of oldDeps) {
|
|
622
|
+
this.dependents.get(dep)?.delete(key);
|
|
623
|
+
}
|
|
624
|
+
this.dependencies.delete(key);
|
|
625
|
+
if (!formulaStr || !formulaStr.startsWith("=")) {
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
try {
|
|
629
|
+
const ast = parseFormula(formulaStr);
|
|
630
|
+
const deps = extractCellDependencies(ast);
|
|
631
|
+
const newDeps = /* @__PURE__ */ new Set();
|
|
632
|
+
for (const d of deps) {
|
|
633
|
+
const depKey = `${d.col}${d.row}`.toUpperCase();
|
|
634
|
+
newDeps.add(depKey);
|
|
635
|
+
if (!this.dependents.has(depKey)) {
|
|
636
|
+
this.dependents.set(depKey, /* @__PURE__ */ new Set());
|
|
637
|
+
}
|
|
638
|
+
this.dependents.get(depKey).add(key);
|
|
639
|
+
}
|
|
640
|
+
this.dependencies.set(key, newDeps);
|
|
641
|
+
} catch {
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
getDependencies(cellKey) {
|
|
645
|
+
return Array.from(this.dependencies.get(cellKey.toUpperCase()) || []);
|
|
646
|
+
}
|
|
647
|
+
getDependents(cellKey) {
|
|
648
|
+
return Array.from(this.dependents.get(cellKey.toUpperCase()) || []);
|
|
649
|
+
}
|
|
650
|
+
/**
|
|
651
|
+
* Detects if there is a cycle containing cellKey.
|
|
652
|
+
*/
|
|
653
|
+
hasCycle(cellKey) {
|
|
654
|
+
const key = cellKey.toUpperCase();
|
|
655
|
+
const visited = /* @__PURE__ */ new Set();
|
|
656
|
+
const recStack = /* @__PURE__ */ new Set();
|
|
657
|
+
const dfs = (node) => {
|
|
658
|
+
visited.add(node);
|
|
659
|
+
recStack.add(node);
|
|
660
|
+
const deps = this.dependencies.get(node) || /* @__PURE__ */ new Set();
|
|
661
|
+
for (const neighbor of deps) {
|
|
662
|
+
if (!visited.has(neighbor)) {
|
|
663
|
+
if (dfs(neighbor)) return true;
|
|
664
|
+
} else if (recStack.has(neighbor)) {
|
|
665
|
+
return true;
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
recStack.delete(node);
|
|
669
|
+
return false;
|
|
670
|
+
};
|
|
671
|
+
return dfs(key);
|
|
672
|
+
}
|
|
673
|
+
/**
|
|
674
|
+
* Returns cells affected by updating cellKey in topological order.
|
|
675
|
+
*/
|
|
676
|
+
getEvaluationOrder(startCellKey) {
|
|
677
|
+
const start = startCellKey.toUpperCase();
|
|
678
|
+
const visited = /* @__PURE__ */ new Set();
|
|
679
|
+
const recStack = /* @__PURE__ */ new Set();
|
|
680
|
+
const order = [];
|
|
681
|
+
let cycleDetected = false;
|
|
682
|
+
const affected = /* @__PURE__ */ new Set();
|
|
683
|
+
const collectAffected = (node) => {
|
|
684
|
+
affected.add(node);
|
|
685
|
+
const directDependents = this.dependents.get(node) || /* @__PURE__ */ new Set();
|
|
686
|
+
for (const dep of directDependents) {
|
|
687
|
+
if (!affected.has(dep)) {
|
|
688
|
+
collectAffected(dep);
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
};
|
|
692
|
+
collectAffected(start);
|
|
693
|
+
const visit = (node) => {
|
|
694
|
+
if (recStack.has(node)) {
|
|
695
|
+
cycleDetected = true;
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
if (visited.has(node)) return;
|
|
699
|
+
recStack.add(node);
|
|
700
|
+
visited.add(node);
|
|
701
|
+
const deps = this.dependencies.get(node) || /* @__PURE__ */ new Set();
|
|
702
|
+
for (const neighbor of deps) {
|
|
703
|
+
if (affected.has(neighbor)) {
|
|
704
|
+
visit(neighbor);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
recStack.delete(node);
|
|
708
|
+
order.push(node);
|
|
709
|
+
};
|
|
710
|
+
for (const node of affected) {
|
|
711
|
+
if (!visited.has(node)) {
|
|
712
|
+
visit(node);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
return { order, hasCycle: cycleDetected };
|
|
716
|
+
}
|
|
717
|
+
};
|
|
718
|
+
|
|
719
|
+
// src/spreadsheet/datasource/index.ts
|
|
720
|
+
var DataSourceBinder = class {
|
|
721
|
+
dataSources = /* @__PURE__ */ new Map();
|
|
722
|
+
register(dataSource) {
|
|
723
|
+
this.dataSources.set(dataSource.id, dataSource);
|
|
724
|
+
}
|
|
725
|
+
unregister(dataSourceId) {
|
|
726
|
+
this.dataSources.delete(dataSourceId);
|
|
727
|
+
}
|
|
728
|
+
getDataSource(id) {
|
|
729
|
+
return this.dataSources.get(id);
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* Generates or reconciles spreadsheet rows from a primary data source.
|
|
733
|
+
*/
|
|
734
|
+
syncRows(currentRows, dataSourceId) {
|
|
735
|
+
const ds = this.dataSources.get(dataSourceId);
|
|
736
|
+
if (!ds) return currentRows;
|
|
737
|
+
const records = ds.getRecords();
|
|
738
|
+
const existingRecordRowMap = /* @__PURE__ */ new Map();
|
|
739
|
+
const freeformRows = [];
|
|
740
|
+
for (const row of currentRows) {
|
|
741
|
+
if (row.type === "record" && row.recordId) {
|
|
742
|
+
existingRecordRowMap.set(row.recordId, row);
|
|
743
|
+
} else {
|
|
744
|
+
freeformRows.push(row);
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
const nextRows = [];
|
|
748
|
+
let rowIndex = 0;
|
|
749
|
+
for (const record of records) {
|
|
750
|
+
const existing = existingRecordRowMap.get(record.id);
|
|
751
|
+
nextRows.push({
|
|
752
|
+
id: existing?.id || `row_${record.id}`,
|
|
753
|
+
index: rowIndex++,
|
|
754
|
+
height: existing?.height || 32,
|
|
755
|
+
recordId: record.id,
|
|
756
|
+
type: "record"
|
|
757
|
+
});
|
|
758
|
+
existingRecordRowMap.delete(record.id);
|
|
759
|
+
}
|
|
760
|
+
for (const freeform of freeformRows) {
|
|
761
|
+
nextRows.push({
|
|
762
|
+
...freeform,
|
|
763
|
+
index: rowIndex++
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
return nextRows;
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* Resolves a record's bound field value.
|
|
770
|
+
*/
|
|
771
|
+
resolveBoundValue(dataSourceId, recordId, field) {
|
|
772
|
+
const ds = this.dataSources.get(dataSourceId);
|
|
773
|
+
if (!ds) return void 0;
|
|
774
|
+
const records = ds.getRecords();
|
|
775
|
+
const record = records.find((r) => r.id === recordId);
|
|
776
|
+
return record ? record[field] : void 0;
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* Dispatches an update to the underlying data source.
|
|
780
|
+
*/
|
|
781
|
+
async commitBoundValue(dataSourceId, recordId, field, value) {
|
|
782
|
+
const ds = this.dataSources.get(dataSourceId);
|
|
783
|
+
if (!ds) return;
|
|
784
|
+
await ds.updateRecord(recordId, field, value);
|
|
785
|
+
}
|
|
786
|
+
};
|
|
787
|
+
|
|
788
|
+
// src/spreadsheet/controller.ts
|
|
789
|
+
var SpreadsheetController = class {
|
|
790
|
+
document;
|
|
791
|
+
activeCell = null;
|
|
792
|
+
selectedRange = null;
|
|
793
|
+
editingCell = null;
|
|
794
|
+
draftValue = "";
|
|
795
|
+
binder = new DataSourceBinder();
|
|
796
|
+
depGraph = new DependencyGraph();
|
|
797
|
+
evaluator;
|
|
798
|
+
primaryDataSourceId;
|
|
799
|
+
onDocumentChange;
|
|
800
|
+
onSelectionChange;
|
|
801
|
+
onCellCommit;
|
|
802
|
+
// History stack for undo/redo
|
|
803
|
+
undoStack = [];
|
|
804
|
+
redoStack = [];
|
|
805
|
+
isApplyingHistory = false;
|
|
806
|
+
constructor(options = {}) {
|
|
807
|
+
const defaultCols = [
|
|
808
|
+
{ id: "col_a", key: "A", title: "A", width: 120, type: "freeform" },
|
|
809
|
+
{ id: "col_b", key: "B", title: "B", width: 120, type: "freeform" },
|
|
810
|
+
{ id: "col_c", key: "C", title: "C", width: 120, type: "freeform" },
|
|
811
|
+
{ id: "col_d", key: "D", title: "D", width: 120, type: "freeform" }
|
|
812
|
+
];
|
|
813
|
+
const defaultRows = options.primaryDataSourceId ? [] : Array.from({ length: 10 }, (_, i) => ({
|
|
814
|
+
id: `row_${i + 1}`,
|
|
815
|
+
index: i,
|
|
816
|
+
height: 32,
|
|
817
|
+
type: "freeform"
|
|
818
|
+
}));
|
|
819
|
+
this.document = {
|
|
820
|
+
id: options.document?.id || `sheet_${Date.now()}`,
|
|
821
|
+
name: options.document?.name || "Sheet 1",
|
|
822
|
+
columns: options.document?.columns || defaultCols,
|
|
823
|
+
rows: options.document?.rows || defaultRows,
|
|
824
|
+
cells: options.document?.cells || {},
|
|
825
|
+
createdAt: options.document?.createdAt || Date.now(),
|
|
826
|
+
updatedAt: options.document?.updatedAt || Date.now()
|
|
827
|
+
};
|
|
828
|
+
this.primaryDataSourceId = options.primaryDataSourceId;
|
|
829
|
+
this.onDocumentChange = options.onDocumentChange;
|
|
830
|
+
this.onSelectionChange = options.onSelectionChange;
|
|
831
|
+
this.onCellCommit = options.onCellCommit;
|
|
832
|
+
if (options.dataSources) {
|
|
833
|
+
options.dataSources.forEach((ds) => this.binder.register(ds));
|
|
834
|
+
}
|
|
835
|
+
this.evaluator = new FormulaEvaluator({
|
|
836
|
+
resolveCell: (colStr, rowNum) => this.resolveCellByCoord(colStr, rowNum),
|
|
837
|
+
resolveRange: (sCol, sRow, eCol, eRow) => this.resolveRangeByCoords(sCol, sRow, eCol, eRow),
|
|
838
|
+
resolveProperty: (prop) => this.resolveCurrentRowProperty(prop)
|
|
839
|
+
});
|
|
840
|
+
this.syncWithDataSource();
|
|
841
|
+
this.recalculateAll();
|
|
842
|
+
}
|
|
843
|
+
loadDocument(document) {
|
|
844
|
+
this.document = JSON.parse(JSON.stringify(document));
|
|
845
|
+
this.activeCell = null;
|
|
846
|
+
this.selectedRange = null;
|
|
847
|
+
this.editingCell = null;
|
|
848
|
+
this.draftValue = "";
|
|
849
|
+
this.undoStack = [];
|
|
850
|
+
this.redoStack = [];
|
|
851
|
+
this.syncWithDataSource();
|
|
852
|
+
this.recalculateAll();
|
|
853
|
+
this.notifyChange();
|
|
854
|
+
}
|
|
855
|
+
registerDataSource(ds) {
|
|
856
|
+
this.binder.register(ds);
|
|
857
|
+
this.syncWithDataSource();
|
|
858
|
+
this.recalculateAll();
|
|
859
|
+
}
|
|
860
|
+
setPrimaryDataSource(dataSourceId) {
|
|
861
|
+
this.primaryDataSourceId = dataSourceId;
|
|
862
|
+
this.syncWithDataSource();
|
|
863
|
+
this.recalculateAll();
|
|
864
|
+
}
|
|
865
|
+
syncWithDataSource() {
|
|
866
|
+
if (!this.primaryDataSourceId) return;
|
|
867
|
+
this.document.rows = this.binder.syncRows(this.document.rows, this.primaryDataSourceId);
|
|
868
|
+
this.recomputeRowIndices();
|
|
869
|
+
}
|
|
870
|
+
recomputeRowIndices() {
|
|
871
|
+
this.document.rows.forEach((r, idx) => {
|
|
872
|
+
r.index = idx;
|
|
873
|
+
});
|
|
874
|
+
this.document.columns.forEach((c, idx) => {
|
|
875
|
+
c.key = indexToColName(idx);
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
getColumn(colIdOrKey) {
|
|
879
|
+
return this.document.columns.find(
|
|
880
|
+
(c) => c.id === colIdOrKey || c.key.toUpperCase() === colIdOrKey.toUpperCase()
|
|
881
|
+
);
|
|
882
|
+
}
|
|
883
|
+
getRow(rowIdOrIndex) {
|
|
884
|
+
if (typeof rowIdOrIndex === "number") {
|
|
885
|
+
return this.document.rows[rowIdOrIndex];
|
|
886
|
+
}
|
|
887
|
+
return this.document.rows.find((r) => r.id === rowIdOrIndex);
|
|
888
|
+
}
|
|
889
|
+
getCell(rowId, colId) {
|
|
890
|
+
const existing = this.document.cells[rowId]?.[colId];
|
|
891
|
+
if (existing) return existing;
|
|
892
|
+
const col = this.document.columns.find((c) => c.id === colId);
|
|
893
|
+
const row = this.document.rows.find((r) => r.id === rowId);
|
|
894
|
+
if (col && row && col.type === "bound" && col.binding && row.recordId) {
|
|
895
|
+
const boundVal = this.binder.resolveBoundValue(
|
|
896
|
+
col.binding.dataSource,
|
|
897
|
+
row.recordId,
|
|
898
|
+
col.binding.field
|
|
899
|
+
);
|
|
900
|
+
return {
|
|
901
|
+
raw: boundVal !== void 0 ? String(boundVal) : "",
|
|
902
|
+
value: boundVal ?? "",
|
|
903
|
+
format: col.format
|
|
904
|
+
};
|
|
905
|
+
}
|
|
906
|
+
if (col && col.type === "formula" && col.formula) {
|
|
907
|
+
return {
|
|
908
|
+
raw: col.formula,
|
|
909
|
+
value: "",
|
|
910
|
+
format: col.format
|
|
911
|
+
};
|
|
912
|
+
}
|
|
913
|
+
return { raw: "", value: "", format: col?.format };
|
|
914
|
+
}
|
|
915
|
+
setCellValue(rowId, colId, raw) {
|
|
916
|
+
this.recordSnapshot();
|
|
917
|
+
if (!this.document.cells[rowId]) {
|
|
918
|
+
this.document.cells[rowId] = {};
|
|
919
|
+
}
|
|
920
|
+
const col = this.document.columns.find((c) => c.id === colId);
|
|
921
|
+
const row = this.document.rows.find((r) => r.id === rowId);
|
|
922
|
+
if (col?.type === "bound" && col.binding && row?.recordId) {
|
|
923
|
+
this.binder.commitBoundValue(
|
|
924
|
+
col.binding.dataSource,
|
|
925
|
+
row.recordId,
|
|
926
|
+
col.binding.field,
|
|
927
|
+
raw
|
|
928
|
+
);
|
|
929
|
+
}
|
|
930
|
+
const cellKey = this.getCellKey(rowId, colId);
|
|
931
|
+
this.depGraph.setCellFormula(cellKey, raw.startsWith("=") ? raw : null);
|
|
932
|
+
this.document.cells[rowId][colId] = {
|
|
933
|
+
raw,
|
|
934
|
+
value: raw,
|
|
935
|
+
format: col?.format
|
|
936
|
+
};
|
|
937
|
+
this.document.updatedAt = Date.now();
|
|
938
|
+
this.recalculateCell(rowId, colId);
|
|
939
|
+
this.notifyChange();
|
|
940
|
+
const evaluatedVal = this.document.cells[rowId][colId]?.value;
|
|
941
|
+
this.onCellCommit?.(rowId, colId, raw, evaluatedVal);
|
|
942
|
+
}
|
|
943
|
+
getCellKey(rowId, colId) {
|
|
944
|
+
const row = this.document.rows.find((r) => r.id === rowId);
|
|
945
|
+
const col = this.document.columns.find((c) => c.id === colId);
|
|
946
|
+
if (!row || !col) return `${colId}_${rowId}`;
|
|
947
|
+
return `${col.key}${row.index + 1}`.toUpperCase();
|
|
948
|
+
}
|
|
949
|
+
recalculateCell(rowId, colId) {
|
|
950
|
+
const cellKey = this.getCellKey(rowId, colId);
|
|
951
|
+
const { order, hasCycle } = this.depGraph.getEvaluationOrder(cellKey);
|
|
952
|
+
if (hasCycle) {
|
|
953
|
+
if (this.document.cells[rowId]?.[colId]) {
|
|
954
|
+
this.document.cells[rowId][colId].error = "#CYCLE!";
|
|
955
|
+
this.document.cells[rowId][colId].value = "#CYCLE!";
|
|
956
|
+
}
|
|
957
|
+
return;
|
|
958
|
+
}
|
|
959
|
+
for (const key of order) {
|
|
960
|
+
this.evalSingleCellByKey(key);
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
recalculateAll() {
|
|
964
|
+
for (const row of this.document.rows) {
|
|
965
|
+
for (const col of this.document.columns) {
|
|
966
|
+
const cell = this.getCell(row.id, col.id);
|
|
967
|
+
const cellKey = `${col.key}${row.index + 1}`.toUpperCase();
|
|
968
|
+
if (cell.raw.startsWith("=")) {
|
|
969
|
+
this.depGraph.setCellFormula(cellKey, cell.raw);
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
for (const row of this.document.rows) {
|
|
974
|
+
for (const col of this.document.columns) {
|
|
975
|
+
const cellKey = `${col.key}${row.index + 1}`.toUpperCase();
|
|
976
|
+
this.evalSingleCellByKey(cellKey);
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
evalSingleCellByKey(cellKey) {
|
|
981
|
+
const match = cellKey.match(/^([A-Za-z]+)(\d+)$/);
|
|
982
|
+
if (!match) return;
|
|
983
|
+
const colName = match[1].toUpperCase();
|
|
984
|
+
const rowNum = parseInt(match[2], 10);
|
|
985
|
+
const col = this.document.columns.find((c) => c.key.toUpperCase() === colName);
|
|
986
|
+
const row = this.document.rows[rowNum - 1];
|
|
987
|
+
if (!col || !row) return;
|
|
988
|
+
const cell = this.getCell(row.id, col.id);
|
|
989
|
+
if (!cell.raw.startsWith("=")) {
|
|
990
|
+
if (cell.error === "#CYCLE!") {
|
|
991
|
+
cell.error = void 0;
|
|
992
|
+
}
|
|
993
|
+
return;
|
|
994
|
+
}
|
|
995
|
+
try {
|
|
996
|
+
const computed = this.evaluator.evaluate(cell.raw);
|
|
997
|
+
if (!this.document.cells[row.id]) {
|
|
998
|
+
this.document.cells[row.id] = {};
|
|
999
|
+
}
|
|
1000
|
+
this.document.cells[row.id][col.id] = {
|
|
1001
|
+
...cell,
|
|
1002
|
+
value: computed,
|
|
1003
|
+
error: void 0
|
|
1004
|
+
};
|
|
1005
|
+
} catch (err) {
|
|
1006
|
+
if (!this.document.cells[row.id]) {
|
|
1007
|
+
this.document.cells[row.id] = {};
|
|
1008
|
+
}
|
|
1009
|
+
this.document.cells[row.id][col.id] = {
|
|
1010
|
+
...cell,
|
|
1011
|
+
value: "#ERROR!",
|
|
1012
|
+
error: err?.message || "Formula error"
|
|
1013
|
+
};
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
resolveCellByCoord(colStr, rowNum) {
|
|
1017
|
+
const col = this.document.columns.find((c) => c.key.toUpperCase() === colStr.toUpperCase());
|
|
1018
|
+
const row = this.document.rows[rowNum - 1];
|
|
1019
|
+
if (!col || !row) return 0;
|
|
1020
|
+
const cell = this.getCell(row.id, col.id);
|
|
1021
|
+
return cell.value !== void 0 && cell.value !== "" ? cell.value : 0;
|
|
1022
|
+
}
|
|
1023
|
+
resolveRangeByCoords(sCol, sRow, eCol, eRow) {
|
|
1024
|
+
const startC = colNameToIndex(sCol);
|
|
1025
|
+
const endC = colNameToIndex(eCol);
|
|
1026
|
+
const minC = Math.min(startC, endC);
|
|
1027
|
+
const maxC = Math.max(startC, endC);
|
|
1028
|
+
const minR = Math.min(sRow, eRow);
|
|
1029
|
+
const maxR = Math.max(sRow, eRow);
|
|
1030
|
+
const results = [];
|
|
1031
|
+
for (let c = minC; c <= maxC; c++) {
|
|
1032
|
+
const colName = indexToColName(c);
|
|
1033
|
+
const col = this.document.columns.find((colDef) => colDef.key.toUpperCase() === colName);
|
|
1034
|
+
if (!col) continue;
|
|
1035
|
+
for (let r = minR; r <= maxR; r++) {
|
|
1036
|
+
const row = this.document.rows[r - 1];
|
|
1037
|
+
if (!row) continue;
|
|
1038
|
+
const cell = this.getCell(row.id, col.id);
|
|
1039
|
+
results.push(cell.value !== void 0 && cell.value !== "" ? cell.value : 0);
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
return results;
|
|
1043
|
+
}
|
|
1044
|
+
resolveCurrentRowProperty(prop) {
|
|
1045
|
+
if (!this.activeCell) return 0;
|
|
1046
|
+
const row = this.document.rows[this.activeCell.row];
|
|
1047
|
+
if (!row || !row.recordId || !this.primaryDataSourceId) return 0;
|
|
1048
|
+
return this.binder.resolveBoundValue(this.primaryDataSourceId, row.recordId, prop) ?? 0;
|
|
1049
|
+
}
|
|
1050
|
+
// --- Selection and Navigation ---
|
|
1051
|
+
selectCell(row, col, extendSelection = false) {
|
|
1052
|
+
const clampedRow = Math.max(0, Math.min(row, this.document.rows.length - 1));
|
|
1053
|
+
const clampedCol = Math.max(0, Math.min(col, this.document.columns.length - 1));
|
|
1054
|
+
const rowObj = this.document.rows[clampedRow];
|
|
1055
|
+
const colObj = this.document.columns[clampedCol];
|
|
1056
|
+
this.activeCell = {
|
|
1057
|
+
row: clampedRow,
|
|
1058
|
+
col: clampedCol,
|
|
1059
|
+
rowId: rowObj?.id,
|
|
1060
|
+
colId: colObj?.id
|
|
1061
|
+
};
|
|
1062
|
+
if (extendSelection && this.selectedRange) {
|
|
1063
|
+
this.selectedRange = {
|
|
1064
|
+
startRow: this.selectedRange.startRow,
|
|
1065
|
+
startCol: this.selectedRange.startCol,
|
|
1066
|
+
endRow: clampedRow,
|
|
1067
|
+
endCol: clampedCol
|
|
1068
|
+
};
|
|
1069
|
+
} else {
|
|
1070
|
+
this.selectedRange = {
|
|
1071
|
+
startRow: clampedRow,
|
|
1072
|
+
startCol: clampedCol,
|
|
1073
|
+
endRow: clampedRow,
|
|
1074
|
+
endCol: clampedCol
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
this.onSelectionChange?.(this.activeCell, this.selectedRange);
|
|
1078
|
+
}
|
|
1079
|
+
selectRange(range) {
|
|
1080
|
+
this.selectedRange = range;
|
|
1081
|
+
this.onSelectionChange?.(this.activeCell, this.selectedRange);
|
|
1082
|
+
}
|
|
1083
|
+
startEditing(row, col, initialValue) {
|
|
1084
|
+
const targetRow = row ?? this.activeCell?.row ?? 0;
|
|
1085
|
+
const targetCol = col ?? this.activeCell?.col ?? 0;
|
|
1086
|
+
this.selectCell(targetRow, targetCol);
|
|
1087
|
+
const rowObj = this.document.rows[targetRow];
|
|
1088
|
+
const colObj = this.document.columns[targetCol];
|
|
1089
|
+
if (!rowObj || !colObj) return;
|
|
1090
|
+
this.editingCell = {
|
|
1091
|
+
row: targetRow,
|
|
1092
|
+
col: targetCol,
|
|
1093
|
+
rowId: rowObj.id,
|
|
1094
|
+
colId: colObj.id
|
|
1095
|
+
};
|
|
1096
|
+
const cell = this.getCell(rowObj.id, colObj.id);
|
|
1097
|
+
this.draftValue = initialValue !== void 0 ? initialValue : cell.raw;
|
|
1098
|
+
}
|
|
1099
|
+
commitEditing(valueToCommit) {
|
|
1100
|
+
if (!this.editingCell) return;
|
|
1101
|
+
const val = valueToCommit !== void 0 ? valueToCommit : this.draftValue;
|
|
1102
|
+
if (this.editingCell.rowId && this.editingCell.colId) {
|
|
1103
|
+
this.setCellValue(this.editingCell.rowId, this.editingCell.colId, val);
|
|
1104
|
+
}
|
|
1105
|
+
this.editingCell = null;
|
|
1106
|
+
this.draftValue = "";
|
|
1107
|
+
}
|
|
1108
|
+
cancelEditing() {
|
|
1109
|
+
this.editingCell = null;
|
|
1110
|
+
this.draftValue = "";
|
|
1111
|
+
}
|
|
1112
|
+
moveCursor(direction, extendSelection = false) {
|
|
1113
|
+
if (!this.activeCell) {
|
|
1114
|
+
this.selectCell(0, 0);
|
|
1115
|
+
return;
|
|
1116
|
+
}
|
|
1117
|
+
let nextRow = this.activeCell.row;
|
|
1118
|
+
let nextCol = this.activeCell.col;
|
|
1119
|
+
switch (direction) {
|
|
1120
|
+
case "up":
|
|
1121
|
+
nextRow = Math.max(0, nextRow - 1);
|
|
1122
|
+
break;
|
|
1123
|
+
case "down":
|
|
1124
|
+
nextRow = Math.min(this.document.rows.length - 1, nextRow + 1);
|
|
1125
|
+
break;
|
|
1126
|
+
case "left":
|
|
1127
|
+
nextCol = Math.max(0, nextCol - 1);
|
|
1128
|
+
break;
|
|
1129
|
+
case "right":
|
|
1130
|
+
nextCol = Math.min(this.document.columns.length - 1, nextCol + 1);
|
|
1131
|
+
break;
|
|
1132
|
+
}
|
|
1133
|
+
this.selectCell(nextRow, nextCol, extendSelection);
|
|
1134
|
+
}
|
|
1135
|
+
// --- Grid Structure Mutations ---
|
|
1136
|
+
insertColumn(index, config) {
|
|
1137
|
+
this.recordSnapshot();
|
|
1138
|
+
const newId = config?.id || `col_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
|
|
1139
|
+
const newCol = {
|
|
1140
|
+
id: newId,
|
|
1141
|
+
key: indexToColName(index),
|
|
1142
|
+
title: config?.title || indexToColName(index),
|
|
1143
|
+
width: config?.width || 130,
|
|
1144
|
+
type: config?.type || "freeform",
|
|
1145
|
+
binding: config?.binding,
|
|
1146
|
+
formula: config?.formula,
|
|
1147
|
+
format: config?.format || "text",
|
|
1148
|
+
readOnly: config?.readOnly
|
|
1149
|
+
};
|
|
1150
|
+
this.document.columns.splice(index, 0, newCol);
|
|
1151
|
+
this.recomputeRowIndices();
|
|
1152
|
+
this.recalculateAll();
|
|
1153
|
+
this.notifyChange();
|
|
1154
|
+
}
|
|
1155
|
+
deleteColumn(colId) {
|
|
1156
|
+
this.recordSnapshot();
|
|
1157
|
+
this.document.columns = this.document.columns.filter((c) => c.id !== colId);
|
|
1158
|
+
for (const rowId of Object.keys(this.document.cells)) {
|
|
1159
|
+
delete this.document.cells[rowId][colId];
|
|
1160
|
+
}
|
|
1161
|
+
this.recomputeRowIndices();
|
|
1162
|
+
this.recalculateAll();
|
|
1163
|
+
this.notifyChange();
|
|
1164
|
+
}
|
|
1165
|
+
insertRow(index, config) {
|
|
1166
|
+
this.recordSnapshot();
|
|
1167
|
+
const newId = config?.id || `row_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
|
|
1168
|
+
const newRow = {
|
|
1169
|
+
id: newId,
|
|
1170
|
+
index,
|
|
1171
|
+
height: config?.height || 32,
|
|
1172
|
+
recordId: config?.recordId,
|
|
1173
|
+
type: config?.type || "freeform"
|
|
1174
|
+
};
|
|
1175
|
+
this.document.rows.splice(index, 0, newRow);
|
|
1176
|
+
this.recomputeRowIndices();
|
|
1177
|
+
this.recalculateAll();
|
|
1178
|
+
this.notifyChange();
|
|
1179
|
+
}
|
|
1180
|
+
deleteRow(rowId) {
|
|
1181
|
+
this.recordSnapshot();
|
|
1182
|
+
this.document.rows = this.document.rows.filter((r) => r.id !== rowId);
|
|
1183
|
+
delete this.document.cells[rowId];
|
|
1184
|
+
this.recomputeRowIndices();
|
|
1185
|
+
this.recalculateAll();
|
|
1186
|
+
this.notifyChange();
|
|
1187
|
+
}
|
|
1188
|
+
setColumnWidth(colId, width) {
|
|
1189
|
+
const col = this.document.columns.find((c) => c.id === colId);
|
|
1190
|
+
if (col) {
|
|
1191
|
+
col.width = Math.max(30, width);
|
|
1192
|
+
this.notifyChange();
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
autoFitColumnWidth(colId, customWidth) {
|
|
1196
|
+
if (customWidth !== void 0) {
|
|
1197
|
+
this.setColumnWidth(colId, customWidth);
|
|
1198
|
+
return;
|
|
1199
|
+
}
|
|
1200
|
+
const col = this.document.columns.find((c) => c.id === colId);
|
|
1201
|
+
if (!col) return;
|
|
1202
|
+
let maxLen = (col.title || "").length + (col.key ? col.key.length + 3 : 0);
|
|
1203
|
+
for (const row of this.document.rows) {
|
|
1204
|
+
const cell = this.getCell(row.id, col.id);
|
|
1205
|
+
const valStr = cell.value != null ? String(cell.value) : "";
|
|
1206
|
+
if (valStr.length > maxLen) {
|
|
1207
|
+
maxLen = valStr.length;
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
const estimatedWidth = Math.min(600, Math.max(50, Math.ceil(maxLen * 8.5 + 32)));
|
|
1211
|
+
this.setColumnWidth(colId, estimatedWidth);
|
|
1212
|
+
}
|
|
1213
|
+
// --- Clipboard TSV/CSV ---
|
|
1214
|
+
exportToTsv() {
|
|
1215
|
+
return this.document.rows.map(
|
|
1216
|
+
(row) => this.document.columns.map((col) => {
|
|
1217
|
+
const cell = this.getCell(row.id, col.id);
|
|
1218
|
+
return String(cell.value ?? "").replace(/\t/g, " ");
|
|
1219
|
+
}).join(" ")
|
|
1220
|
+
).join("\n");
|
|
1221
|
+
}
|
|
1222
|
+
importFromTsv(tsvData, startRow = 0, startCol = 0) {
|
|
1223
|
+
this.recordSnapshot();
|
|
1224
|
+
const lines = tsvData.trim().split("\n");
|
|
1225
|
+
lines.forEach((line, rIdx) => {
|
|
1226
|
+
const cells = line.split(" ");
|
|
1227
|
+
const targetR = startRow + rIdx;
|
|
1228
|
+
while (targetR >= this.document.rows.length) {
|
|
1229
|
+
this.insertRow(this.document.rows.length);
|
|
1230
|
+
}
|
|
1231
|
+
const row = this.document.rows[targetR];
|
|
1232
|
+
cells.forEach((val, cIdx) => {
|
|
1233
|
+
const targetC = startCol + cIdx;
|
|
1234
|
+
while (targetC >= this.document.columns.length) {
|
|
1235
|
+
this.insertColumn(this.document.columns.length);
|
|
1236
|
+
}
|
|
1237
|
+
const col = this.document.columns[targetC];
|
|
1238
|
+
this.setCellValue(row.id, col.id, val);
|
|
1239
|
+
});
|
|
1240
|
+
});
|
|
1241
|
+
this.recalculateAll();
|
|
1242
|
+
this.notifyChange();
|
|
1243
|
+
}
|
|
1244
|
+
// --- Undo/Redo Snapshots ---
|
|
1245
|
+
recordSnapshot() {
|
|
1246
|
+
if (this.isApplyingHistory) return;
|
|
1247
|
+
this.undoStack.push(JSON.stringify(this.document));
|
|
1248
|
+
if (this.undoStack.length > 50) this.undoStack.shift();
|
|
1249
|
+
this.redoStack = [];
|
|
1250
|
+
}
|
|
1251
|
+
undo() {
|
|
1252
|
+
if (this.undoStack.length === 0) return;
|
|
1253
|
+
this.isApplyingHistory = true;
|
|
1254
|
+
this.redoStack.push(JSON.stringify(this.document));
|
|
1255
|
+
const previous = JSON.parse(this.undoStack.pop());
|
|
1256
|
+
this.document = previous;
|
|
1257
|
+
this.recalculateAll();
|
|
1258
|
+
this.notifyChange();
|
|
1259
|
+
this.isApplyingHistory = false;
|
|
1260
|
+
}
|
|
1261
|
+
redo() {
|
|
1262
|
+
if (this.redoStack.length === 0) return;
|
|
1263
|
+
this.isApplyingHistory = true;
|
|
1264
|
+
this.undoStack.push(JSON.stringify(this.document));
|
|
1265
|
+
const next = JSON.parse(this.redoStack.pop());
|
|
1266
|
+
this.document = next;
|
|
1267
|
+
this.recalculateAll();
|
|
1268
|
+
this.notifyChange();
|
|
1269
|
+
this.isApplyingHistory = false;
|
|
1270
|
+
}
|
|
1271
|
+
notifyChange() {
|
|
1272
|
+
this.onDocumentChange?.(this.document);
|
|
1273
|
+
}
|
|
1274
|
+
};
|
|
1275
|
+
|
|
1276
|
+
export {
|
|
1277
|
+
tokenizeFormula,
|
|
1278
|
+
parseCellReference,
|
|
1279
|
+
parseRange,
|
|
1280
|
+
FormulaParser,
|
|
1281
|
+
parseFormula,
|
|
1282
|
+
colNameToIndex,
|
|
1283
|
+
indexToColName,
|
|
1284
|
+
FormulaEvaluator,
|
|
1285
|
+
extractCellDependencies,
|
|
1286
|
+
DependencyGraph,
|
|
1287
|
+
DataSourceBinder,
|
|
1288
|
+
SpreadsheetController
|
|
1289
|
+
};
|
|
1290
|
+
//# sourceMappingURL=chunk-NNJRJJSC.js.map
|