@ember-lattice/sheet 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/LICENSE.md +21 -0
  3. package/NOTICE +30 -0
  4. package/README.md +75 -2
  5. package/addon-main.cjs +4 -0
  6. package/declarations/format/index.d.ts +41 -0
  7. package/declarations/format/index.d.ts.map +1 -0
  8. package/declarations/index.d.ts +6 -0
  9. package/declarations/index.d.ts.map +1 -0
  10. package/declarations/sheet.d.ts +54 -0
  11. package/declarations/sheet.d.ts.map +1 -0
  12. package/declarations/surface/index.d.ts +6 -0
  13. package/declarations/surface/index.d.ts.map +1 -0
  14. package/declarations/surface/later.d.ts +6 -0
  15. package/declarations/surface/later.d.ts.map +1 -0
  16. package/declarations/surface/lattice-sheet.d.ts +89 -0
  17. package/declarations/surface/lattice-sheet.d.ts.map +1 -0
  18. package/declarations/surface/model.d.ts +7 -0
  19. package/declarations/surface/model.d.ts.map +1 -0
  20. package/declarations/surface/refs.d.ts +22 -0
  21. package/declarations/surface/refs.d.ts.map +1 -0
  22. package/declarations/surface/sheet-cell.d.ts +25 -0
  23. package/declarations/surface/sheet-cell.d.ts.map +1 -0
  24. package/declarations/surface/sheet-editor.d.ts +19 -0
  25. package/declarations/surface/sheet-editor.d.ts.map +1 -0
  26. package/declarations/surface/surface.d.ts +139 -0
  27. package/declarations/surface/surface.d.ts.map +1 -0
  28. package/declarations/types.d.ts +144 -0
  29. package/declarations/types.d.ts.map +1 -0
  30. package/declarations/workbook.d.ts +67 -0
  31. package/declarations/workbook.d.ts.map +1 -0
  32. package/dist/index.js +1135 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/surface/index.js +1214 -0
  35. package/dist/surface/index.js.map +1 -0
  36. package/package.json +93 -3
package/dist/index.js ADDED
@@ -0,0 +1,1135 @@
1
+ import { createAtom, latticeLocale } from '@ember-lattice/core';
2
+ import { isBoolean, isNumber, isString } from '@sindresorhus/is';
3
+ import { createRefContext, shrinkDeleted, toA1, toStored, fromR1C1, toR1C1, scanStored, printStored } from '@ember-lattice/formula';
4
+
5
+ // Number formats in Excel format-code syntax (plan 8.2): a parser and a formatter. Separators
6
+ // and month and day names come from `Intl` for the locale. Dates are Excel serials in the 1900
7
+ // system, computed in UTC, with Excel's leap-year bug (serial 60 is 1900-02-29).
8
+ //
9
+ // shortcut: no fractions (`# ?/?`), no `[$-409]` locale codes, no fill (`*x`) width; add them
10
+ // when import from XLSX needs them.
11
+ const COLORS = ['black', 'blue', 'cyan', 'green', 'magenta', 'red', 'white', 'yellow'];
12
+ function splitSections(code) {
13
+ const out = [];
14
+ let cur = '';
15
+ let quote = false;
16
+ let bracket = false;
17
+ for (let i = 0; i < code.length; i++) {
18
+ const ch = code[i];
19
+ if (ch === '\\' && !quote) {
20
+ cur += ch + (code[++i] ?? '');
21
+ continue;
22
+ }
23
+ if (ch === '"') quote = !quote;else if (!quote && ch === '[') bracket = true;else if (!quote && ch === ']') bracket = false;else if (!quote && !bracket && ch === ';') {
24
+ out.push(cur);
25
+ cur = '';
26
+ continue;
27
+ }
28
+ cur += ch;
29
+ }
30
+ out.push(cur);
31
+ return out;
32
+ }
33
+ function parseSection(src) {
34
+ const section = {
35
+ tokens: [],
36
+ percent: false
37
+ };
38
+ const tokens = section.tokens;
39
+ const lit = v => {
40
+ const last = tokens[tokens.length - 1];
41
+ if (last?.t === 'lit') last.v += v;else tokens.push({
42
+ t: 'lit',
43
+ v
44
+ });
45
+ };
46
+ let i = 0;
47
+ while (i < src.length) {
48
+ const ch = src[i];
49
+ const rest = src.slice(i);
50
+ if (ch === '"') {
51
+ const end = src.indexOf('"', i + 1);
52
+ const stop = end < 0 ? src.length : end;
53
+ lit(src.slice(i + 1, stop));
54
+ i = stop + 1;
55
+ } else if (ch === '\\') {
56
+ lit(src[i + 1] ?? '');
57
+ i += 2;
58
+ } else if (ch === '_') {
59
+ lit(' ');
60
+ i += 2;
61
+ } else if (ch === '*') {
62
+ i += 2;
63
+ } else if (ch === '[') {
64
+ const end = src.indexOf(']', i);
65
+ const inner = src.slice(i + 1, end < 0 ? src.length : end);
66
+ i = end < 0 ? src.length : end + 1;
67
+ const lower = inner.toLowerCase();
68
+ const cond = /^(<=|>=|<>|<|>|=)\s*(-?[\d.]+)$/.exec(inner);
69
+ if (COLORS.includes(lower)) section.color = lower;else if (cond) section.cond = {
70
+ op: cond[1],
71
+ value: Number(cond[2])
72
+ };else if (/^(h+|m+|s+)$/.test(lower)) {
73
+ tokens.push({
74
+ t: 'date',
75
+ part: `e${lower[0]}`,
76
+ len: lower.length
77
+ });
78
+ } else if (inner.startsWith('$')) lit(inner.slice(1).split('-')[0]);
79
+ } else if (/^general/i.test(rest)) {
80
+ tokens.push({
81
+ t: 'general'
82
+ });
83
+ i += 7;
84
+ } else if (/^(am\/pm|a\/p)/i.test(rest)) {
85
+ const len = /^am\/pm/i.test(rest) ? 5 : 3;
86
+ tokens.push({
87
+ t: 'date',
88
+ part: 'ampm',
89
+ len,
90
+ ampm: rest.slice(0, len)
91
+ });
92
+ i += len;
93
+ } else if (/[ymdhs]/i.test(ch)) {
94
+ let j = i;
95
+ while (src[j]?.toLowerCase() === ch.toLowerCase()) j++;
96
+ const part = ch.toLowerCase() === 'm' ? 'M' : ch.toLowerCase();
97
+ tokens.push({
98
+ t: 'date',
99
+ part,
100
+ len: j - i
101
+ });
102
+ i = j;
103
+ } else if (ch === '@') {
104
+ tokens.push({
105
+ t: 'text'
106
+ });
107
+ i++;
108
+ } else if (ch === '%') {
109
+ section.percent = true;
110
+ lit('%');
111
+ i++;
112
+ } else if (/[0#?.,]/.test(ch)) {
113
+ const m = /^[0#?.,]+/.exec(rest)[0];
114
+ i += m.length;
115
+ if (!/[0#?]/.test(m)) {
116
+ lit(m);
117
+ continue;
118
+ }
119
+ const exp = /^[eE]([+-])(0+)/.exec(src.slice(i));
120
+ if (exp) i += exp[0].length;
121
+ tokens.push({
122
+ t: 'num',
123
+ pattern: m,
124
+ ...(exp ? {
125
+ exp: {
126
+ sign: exp[1] === '+',
127
+ digits: exp[2].length
128
+ }
129
+ } : {})
130
+ });
131
+ } else {
132
+ lit(ch);
133
+ i++;
134
+ }
135
+ }
136
+ // `m` is minutes after an hour or before a second, else it is the month.
137
+ const dates = tokens.filter(t => t.t === 'date');
138
+ dates.forEach((tok, k) => {
139
+ if (tok.part !== 'M' || tok.len > 2) return;
140
+ const prev = dates[k - 1]?.part;
141
+ const next = dates[k + 1]?.part;
142
+ if (prev === 'h' || prev === 'eh' || next === 's' || next === 'es') tok.part = 'm';
143
+ });
144
+ return section;
145
+ }
146
+ const cache = new Map();
147
+
148
+ /** Parses a format code into its sections. The result is cached for each code. */
149
+ function parseFormat(code) {
150
+ let sections = cache.get(code);
151
+ if (!sections) cache.set(code, sections = splitSections(code).map(parseSection));
152
+ return sections;
153
+ }
154
+ const locales = new Map();
155
+ function separators(locale) {
156
+ let sep = locales.get(locale);
157
+ if (!sep) {
158
+ const parts = new Intl.NumberFormat(locale).formatToParts(1234567.5);
159
+ sep = {
160
+ group: parts.find(p => p.type === 'group')?.value ?? ',',
161
+ decimal: parts.find(p => p.type === 'decimal')?.value ?? '.'
162
+ };
163
+ locales.set(locale, sep);
164
+ }
165
+ return sep;
166
+ }
167
+
168
+ /** Rounds a value of 0 or more half away from zero, without the `toFixed` binary error. */
169
+ function round(v, digits) {
170
+ const f = 10 ** digits;
171
+ return Math.round(Number((v * f).toPrecision(15))) / f;
172
+ }
173
+ function groupDigits(int, group) {
174
+ return int.replace(/\B(?=(\d{3})+(?!\d))/g, group);
175
+ }
176
+ function formatNum(v, tok, locale) {
177
+ const sep = separators(locale);
178
+ const [intPat = '', fracPat = ''] = tok.pattern.split('.');
179
+ const hasDot = tok.pattern.includes('.');
180
+ const scale = /,+$/.exec(intPat)?.[0].length ?? 0;
181
+ const intPlaces = intPat.replace(/,+$/, '');
182
+ const thousands = intPlaces.includes(',');
183
+ const minInt = (intPlaces.match(/0/g) ?? []).length;
184
+ const fracMax = (fracPat.match(/[0#?]/g) ?? []).length;
185
+ const fracMin = fracPat.replace(/[#]+$/, '').length;
186
+ v = v / 1000 ** scale;
187
+ let exponent = '';
188
+ if (tok.exp) {
189
+ const intDigits = Math.max(1, (intPlaces.match(/[0#?]/g) ?? []).length);
190
+ let e = v === 0 ? 0 : Math.floor(Math.log10(v)) - (intDigits - 1);
191
+ let mant = round(v / 10 ** e, fracMax);
192
+ if (mant >= 10 ** intDigits) {
193
+ e += 1;
194
+ mant = round(v / 10 ** e, fracMax);
195
+ }
196
+ v = mant;
197
+ const sign = e < 0 ? '-' : tok.exp.sign ? '+' : '';
198
+ exponent = `E${sign}${String(Math.abs(e)).padStart(tok.exp.digits, '0')}`;
199
+ }
200
+ const [rawInt, rawFrac = ''] = round(v, fracMax).toFixed(fracMax).split('.');
201
+ let int = rawInt === '0' ? '' : rawInt;
202
+ int = int.padStart(minInt, '0');
203
+ if (thousands) int = groupDigits(int, sep.group);
204
+ let frac = rawFrac;
205
+ while (frac.length > fracMin && frac.endsWith('0')) frac = frac.slice(0, -1);
206
+ frac = frac.padEnd(fracMin, '0');
207
+ return int + (hasDot ? sep.decimal + frac : '') + exponent;
208
+ }
209
+ function formatGeneral(v, locale) {
210
+ const abs = Math.abs(v);
211
+ if (abs !== 0 && (abs >= 1e11 || abs < 1e-9)) {
212
+ const [m, e] = v.toExponential(5).split('e');
213
+ const mant = m.replace(/\.?0+$/, '');
214
+ const exp = Number(e);
215
+ return `${mant}E${exp < 0 ? '-' : '+'}${String(Math.abs(exp)).padStart(2, '0')}`.replace('.', separators(locale).decimal);
216
+ }
217
+ const intLen = String(Math.floor(abs)).length;
218
+ const text = round(abs, Math.max(0, 10 - intLen)).toFixed(Math.max(0, 10 - intLen)).replace(/\.?0+$/, '');
219
+ return (v < 0 ? '-' : '') + text.replace('.', separators(locale).decimal);
220
+ }
221
+ const DAY_MS = 86_400_000;
222
+
223
+ /** Splits an Excel serial (1900 system) into UTC date and time parts. */
224
+ function serialParts(serial) {
225
+ let day = Math.floor(serial);
226
+ let seconds = Math.round((serial - day) * 86400);
227
+ if (seconds >= 86400) {
228
+ day += 1;
229
+ seconds -= 86400;
230
+ }
231
+ let date;
232
+ let leap = false;
233
+ if (day === 60) {
234
+ leap = true;
235
+ date = new Date(Date.UTC(1900, 1, 28));
236
+ } else date = new Date(Date.UTC(1899, 11, day < 60 ? 31 : 30) + day * DAY_MS);
237
+ return {
238
+ y: date.getUTCFullYear(),
239
+ M: date.getUTCMonth(),
240
+ d: leap ? 29 : date.getUTCDate(),
241
+ // 1900-02-29 is a Wednesday in Excel.
242
+ weekday: leap ? 3 : date.getUTCDay(),
243
+ h: Math.floor(seconds / 3600),
244
+ m: Math.floor(seconds / 60) % 60,
245
+ s: seconds % 60,
246
+ totalSeconds: serial * 86400
247
+ };
248
+ }
249
+ const names = new Map();
250
+ function name(locale, option, date) {
251
+ const key = `${locale}|${JSON.stringify(option)}|${date.getTime()}`;
252
+ let out = names.get(key);
253
+ if (out === undefined) {
254
+ out = new Intl.DateTimeFormat(locale, {
255
+ ...option,
256
+ timeZone: 'UTC'
257
+ }).format(date);
258
+ names.set(key, out);
259
+ }
260
+ return out;
261
+ }
262
+ function formatDate(serial, section, locale) {
263
+ const p = serialParts(serial);
264
+ const twelve = section.tokens.some(t => t.t === 'date' && t.part === 'ampm');
265
+ const pad = (n, len) => String(n).padStart(len >= 2 ? 2 : 1, '0');
266
+ const monthDate = new Date(Date.UTC(2001, p.M, 1));
267
+ // 2001-01-07 is a Sunday, so day `weekday` of that week has the right name.
268
+ const dayDate = new Date(Date.UTC(2001, 0, 7 + p.weekday));
269
+ return section.tokens.map(tok => {
270
+ if (tok.t === 'lit') return tok.v;
271
+ if (tok.t !== 'date') return '';
272
+ const len = tok.len;
273
+ switch (tok.part) {
274
+ case 'y':
275
+ return len <= 2 ? pad(p.y % 100, 2) : String(p.y);
276
+ case 'M':
277
+ if (len <= 2) return pad(p.M + 1, len);
278
+ if (len === 3) return name(locale, {
279
+ month: 'short'
280
+ }, monthDate);
281
+ if (len === 4) return name(locale, {
282
+ month: 'long'
283
+ }, monthDate);
284
+ return name(locale, {
285
+ month: 'narrow'
286
+ }, monthDate);
287
+ case 'd':
288
+ if (len <= 2) return pad(p.d, len);
289
+ return name(locale, {
290
+ weekday: len === 3 ? 'short' : 'long'
291
+ }, dayDate);
292
+ case 'h':
293
+ return pad(twelve ? p.h % 12 || 12 : p.h, len);
294
+ case 'm':
295
+ return pad(p.m, len);
296
+ case 's':
297
+ return pad(p.s, len);
298
+ case 'ampm':
299
+ {
300
+ const pm = p.h >= 12;
301
+ return tok.ampm.length > 3 ? pm ? 'PM' : 'AM' : pm ? 'P' : 'A';
302
+ }
303
+ case 'eh':
304
+ return pad(Math.floor(p.totalSeconds / 3600), len);
305
+ case 'em':
306
+ return pad(Math.floor(p.totalSeconds / 60), len);
307
+ case 'es':
308
+ return pad(Math.floor(p.totalSeconds), len);
309
+ }
310
+ }).join('');
311
+ }
312
+ const matches = (cond, v) => {
313
+ switch (cond.op) {
314
+ case '<':
315
+ return v < cond.value;
316
+ case '<=':
317
+ return v <= cond.value;
318
+ case '>':
319
+ return v > cond.value;
320
+ case '>=':
321
+ return v >= cond.value;
322
+ case '=':
323
+ return v === cond.value;
324
+ default:
325
+ return v !== cond.value;
326
+ }
327
+ };
328
+ function pickSection(sections, v) {
329
+ const numeric = sections.filter(s => !s.tokens.some(t => t.t === 'text'));
330
+ if (sections.some(s => s.cond)) {
331
+ const hit = sections.find(s => s.cond && matches(s.cond, v));
332
+ return {
333
+ section: hit ?? numeric.find(s => !s.cond) ?? sections[0],
334
+ abs: false
335
+ };
336
+ }
337
+ if (v < 0 && sections.length >= 2) return {
338
+ section: sections[1],
339
+ abs: true
340
+ };
341
+ if (v === 0 && sections.length >= 3) return {
342
+ section: sections[2],
343
+ abs: true
344
+ };
345
+ return {
346
+ section: sections[0],
347
+ abs: false
348
+ };
349
+ }
350
+
351
+ /** Formats a cell value with an Excel format code. */
352
+ function formatValue(value, code = 'General', locale = 'en-US') {
353
+ if (value === null || value === undefined) return {
354
+ text: ''
355
+ };
356
+ if (isBoolean(value)) return {
357
+ text: value ? 'TRUE' : 'FALSE'
358
+ };
359
+ if (!isNumber(value) && !isString(value)) return {
360
+ text: value.error
361
+ };
362
+ const sections = parseFormat(code);
363
+ if (isString(value)) {
364
+ const section = sections[3] ?? sections.find(s => s.tokens.some(t => t.t === 'text'));
365
+ if (!section) return {
366
+ text: value
367
+ };
368
+ const text = section.tokens.map(t => t.t === 'lit' ? t.v : t.t === 'text' ? value : '').join('');
369
+ return section.color ? {
370
+ text,
371
+ color: section.color
372
+ } : {
373
+ text
374
+ };
375
+ }
376
+ const {
377
+ section,
378
+ abs
379
+ } = pickSection(sections, value);
380
+ let v = abs ? Math.abs(value) : value;
381
+ let text;
382
+ if (section.tokens.some(t => t.t === 'date')) text = formatDate(v, section, locale);else {
383
+ const negative = v < 0;
384
+ v = Math.abs(v) * (section.percent ? 100 : 1);
385
+ let shown = false;
386
+ text = section.tokens.map(tok => {
387
+ if (tok.t === 'lit') return tok.v;
388
+ if (tok.t === 'general') {
389
+ shown = true;
390
+ return formatGeneral(v, locale);
391
+ }
392
+ if (tok.t === 'num' && !shown) {
393
+ shown = true;
394
+ return formatNum(v, tok, locale);
395
+ }
396
+ return '';
397
+ }).join('');
398
+ if (negative) text = `-${text}`;
399
+ if (section.tokens.length === 0) text = formatGeneral(negative ? -v : v, locale);
400
+ }
401
+ return section.color ? {
402
+ text,
403
+ color: section.color
404
+ } : {
405
+ text
406
+ };
407
+ }
408
+
409
+ // One tracked slot for each cell that is read or written. A change to one cell dirties only its
410
+ // slot, so only the readers of that cell run again. A read of an empty cell makes an empty slot,
411
+ // so the reader runs again when a value appears there.
412
+ class Slot {
413
+ #cell = createAtom(undefined);
414
+ get cell() {
415
+ return this.#cell.get();
416
+ }
417
+ set cell(cell) {
418
+ this.#cell.set(cell);
419
+ }
420
+ }
421
+ const isEmpty = cell => Object.values(cell).every(v => v === undefined);
422
+
423
+ /**
424
+ * One sheet of the model: sparse cells `Map<rowId, Map<colId, Cell>>`, the row and column order,
425
+ * frozen panes, merges, conditional formats and data validation. Change it through
426
+ * `Workbook.apply`, so the engine and the op log see each change.
427
+ */
428
+ class Sheet {
429
+ id;
430
+ #name = createAtom('');
431
+ #rows = createAtom([]);
432
+ #cols = createAtom([]);
433
+ #frozen = createAtom({
434
+ rows: 0,
435
+ cols: 0
436
+ });
437
+ #merges = createAtom([]);
438
+ #rules = createAtom([]);
439
+ #validations = createAtom([]);
440
+ #cells = new Map();
441
+ constructor(id, name, rows, cols) {
442
+ this.id = id;
443
+ this.name = name;
444
+ this.rows = rows;
445
+ this.cols = cols;
446
+ }
447
+ get name() {
448
+ return this.#name.get();
449
+ }
450
+ set name(value) {
451
+ this.#name.set(value);
452
+ }
453
+ get rows() {
454
+ return this.#rows.get();
455
+ }
456
+ set rows(value) {
457
+ this.#rows.set(value);
458
+ }
459
+ get cols() {
460
+ return this.#cols.get();
461
+ }
462
+ set cols(value) {
463
+ this.#cols.set(value);
464
+ }
465
+ get frozen() {
466
+ return this.#frozen.get();
467
+ }
468
+ set frozen(value) {
469
+ this.#frozen.set(value);
470
+ }
471
+ get merges() {
472
+ return this.#merges.get();
473
+ }
474
+ set merges(value) {
475
+ this.#merges.set(value);
476
+ }
477
+ get rules() {
478
+ return this.#rules.get();
479
+ }
480
+ set rules(value) {
481
+ this.#rules.set(value);
482
+ }
483
+ get validations() {
484
+ return this.#validations.get();
485
+ }
486
+ set validations(value) {
487
+ this.#validations.set(value);
488
+ }
489
+ #slot(row, col) {
490
+ let cols = this.#cells.get(row);
491
+ if (!cols) this.#cells.set(row, cols = new Map());
492
+ let slot = cols.get(col);
493
+ if (!slot) cols.set(col, slot = new Slot());
494
+ return slot;
495
+ }
496
+ cell(row, col) {
497
+ return this.#slot(row, col).cell;
498
+ }
499
+
500
+ /** Replaces a cell. An empty record clears it. */
501
+ setCell(row, col, cell) {
502
+ this.#slot(row, col).cell = cell && !isEmpty(cell) ? cell : undefined;
503
+ }
504
+
505
+ /** Changes some fields of a cell. */
506
+ updateCell(row, col, change) {
507
+ this.setCell(row, col, {
508
+ ...this.cell(row, col),
509
+ ...change
510
+ });
511
+ }
512
+
513
+ /** The cells with content, in no order. */
514
+ *entries() {
515
+ for (const [row, cols] of this.#cells) {
516
+ for (const [col, slot] of cols) if (slot.cell) yield [row, col, slot.cell];
517
+ }
518
+ }
519
+ get cellCount() {
520
+ let n = 0;
521
+ for (const _ of this.entries()) n++;
522
+ return n;
523
+ }
524
+
525
+ /** Removes the cells of deleted rows or columns. */
526
+ dropCells(rows, cols) {
527
+ for (const [row, map] of this.#cells) {
528
+ for (const [col, slot] of map) {
529
+ if (rows.has(row) || cols.has(col)) slot.cell = undefined;
530
+ }
531
+ if (rows.has(row)) this.#cells.delete(row);else for (const col of cols) map.delete(col);
532
+ }
533
+ }
534
+
535
+ // shortcut: `indexOf` on each lookup, O(rows) for each merge and rule check. Cache an index
536
+ // map for each order array when the surface reads merges for every visible cell.
537
+ /** The row and column indices of an area, or undefined when an end is gone. */
538
+ bounds(area) {
539
+ const r0 = this.rows.indexOf(area.start.row);
540
+ const r1 = this.rows.indexOf(area.end.row);
541
+ const c0 = this.cols.indexOf(area.start.col);
542
+ const c1 = this.cols.indexOf(area.end.col);
543
+ if (r0 < 0 || r1 < 0 || c0 < 0 || c1 < 0) return undefined;
544
+ return {
545
+ r0,
546
+ r1,
547
+ c0,
548
+ c1
549
+ };
550
+ }
551
+ contains(area, row, col) {
552
+ const b = this.bounds(area);
553
+ const r = this.rows.indexOf(row);
554
+ const c = this.cols.indexOf(col);
555
+ return !!b && r >= b.r0 && r <= b.r1 && c >= b.c0 && c <= b.c1;
556
+ }
557
+
558
+ /** The cells of an area, row by row. */
559
+ *cellsOf(area) {
560
+ const b = this.bounds(area);
561
+ if (!b) return;
562
+ for (let r = b.r0; r <= b.r1; r++) {
563
+ for (let c = b.c0; c <= b.c1; c++) yield [this.rows[r], this.cols[c]];
564
+ }
565
+ }
566
+
567
+ /** The merge that holds the cell, if there is one. */
568
+ mergeAt(row, col) {
569
+ return this.merges.find(m => this.contains(m, row, col));
570
+ }
571
+ }
572
+
573
+ const ENGINE_OPS = new Set(['setCell', 'insertRows', 'deleteRows', 'insertCols', 'deleteCols', 'setFormat', 'setStyle', 'merge', 'unmerge', 'setName', 'addSheet', 'removeSheet', 'renameSheet']);
574
+ const isEngineOp = op => ENGINE_OPS.has(op.type);
575
+ const sameArea = (a, b) => a.start.row === b.start.row && a.start.col === b.start.col && a.end.row === b.end.row && a.end.col === b.end.col;
576
+
577
+ /** Reads typed text: a formula, a number, a boolean or text. */
578
+ function parseInput(text) {
579
+ if (text === '') return {};
580
+ if (text.startsWith('=') && text.length > 1) return {
581
+ formula: text
582
+ };
583
+ const n = Number(text.trim());
584
+ if (text.trim() !== '' && Number.isFinite(n)) return {
585
+ value: n
586
+ };
587
+ const upper = text.toUpperCase();
588
+ if (upper === 'TRUE' || upper === 'FALSE') return {
589
+ value: upper === 'TRUE'
590
+ };
591
+ return {
592
+ value: text
593
+ };
594
+ }
595
+ function literal(value) {
596
+ if (isNumber(value)) return String(value);
597
+ if (isBoolean(value)) return value ? 'TRUE' : 'FALSE';
598
+ if (isString(value)) return `"${value.replace(/"/g, '""')}"`;
599
+ return value === null ? '""' : value.error;
600
+ }
601
+ function mix(a, b, t) {
602
+ const ch = (hex, i) => parseInt(hex.slice(1 + 2 * i, 3 + 2 * i), 16);
603
+ return '#' + [0, 1, 2].map(i => Math.round(ch(a, i) + (ch(b, i) - ch(a, i)) * t)).map(v => v.toString(16).padStart(2, '0')).join('');
604
+ }
605
+
606
+ /**
607
+ * The sheet model: the sheets, named ranges and styles of one document. `apply` changes the
608
+ * model at once (optimistic), then sends the engine ops and sets the computed values from the
609
+ * `CellChange[]` that the engine gives back.
610
+ */
611
+ class Workbook {
612
+ engine;
613
+ locale;
614
+ #sheets = createAtom([]);
615
+ #names = createAtom({});
616
+ /** Style ID to style. Cells with the same style share one ID. */
617
+ styles = new Map();
618
+ #styleIds = new Map();
619
+ constructor(engine, options = {}) {
620
+ this.engine = engine;
621
+ this.locale = options.locale ?? 'en-US';
622
+ }
623
+ get sheets() {
624
+ return this.#sheets.get();
625
+ }
626
+ set sheets(sheets) {
627
+ this.#sheets.set(sheets);
628
+ }
629
+
630
+ /** Name to the stored ref, without `=`. */
631
+ get names() {
632
+ return this.#names.get();
633
+ }
634
+ set names(names) {
635
+ this.#names.set(names);
636
+ }
637
+ sheet(id) {
638
+ const sheet = this.sheets.find(s => s.id === id);
639
+ if (!sheet) throw new Error(`Lattice: no sheet with the ID "${id}"`);
640
+ return sheet;
641
+ }
642
+
643
+ /** A `RefContext` on the current row and column order. */
644
+ refs() {
645
+ return createRefContext({
646
+ sheets: this.sheets
647
+ });
648
+ }
649
+ async load(doc) {
650
+ this.styles = new Map(Object.entries(doc.styles ?? {}));
651
+ this.#styleIds = new Map([...this.styles].map(([id, style]) => [JSON.stringify(style), id]));
652
+ this.sheets = doc.sheets.map(data => {
653
+ const sheet = new Sheet(data.id, data.name, [...data.rows], [...data.cols]);
654
+ for (const {
655
+ row,
656
+ col,
657
+ ...cell
658
+ } of data.cells) {
659
+ sheet.setCell(row, col, {
660
+ ...cell,
661
+ computed: cell.formula ? undefined : cell.value
662
+ });
663
+ }
664
+ if (data.frozen) sheet.frozen = data.frozen;
665
+ sheet.merges = data.merges ?? [];
666
+ sheet.rules = data.rules ?? [];
667
+ sheet.validations = data.validations ?? [];
668
+ return sheet;
669
+ });
670
+ this.names = Object.fromEntries((doc.names ?? []).map(n => [n.name, n.ref]));
671
+ await this.engine.load({
672
+ sheets: doc.sheets.map(({
673
+ id,
674
+ name,
675
+ rows,
676
+ cols,
677
+ cells
678
+ }) => ({
679
+ id,
680
+ name,
681
+ rows,
682
+ cols,
683
+ cells: cells.map(({
684
+ row,
685
+ col,
686
+ value,
687
+ formula
688
+ }) => ({
689
+ row,
690
+ col,
691
+ value,
692
+ formula
693
+ }))
694
+ })),
695
+ names: doc.names ?? []
696
+ });
697
+ if (this.engine.watch) this.#take(await this.engine.watch(null));
698
+ }
699
+
700
+ /** Applies ops to the model at once, then gives the engine ops to the engine. */
701
+ async apply(ops) {
702
+ // The computed value of each set cell before the batch: the last value the engine read. A
703
+ // formula keeps it until the engine reports a change, also after a plain value in the batch.
704
+ const read = new Map();
705
+ for (const op of ops) {
706
+ if (op.type === 'setCell') {
707
+ const at = `${op.sheet} ${op.row} ${op.col}`;
708
+ if (!read.has(at)) read.set(at, this.sheet(op.sheet).cell(op.row, op.col)?.computed);
709
+ this.#apply(op, read.get(at));
710
+ } else this.#apply(op);
711
+ }
712
+ const engineOps = ops.filter(isEngineOp);
713
+ if (engineOps.length === 0) return [];
714
+ const changes = await this.engine.apply(engineOps);
715
+ this.#take(changes);
716
+ return changes;
717
+ }
718
+ #take(changes) {
719
+ for (const {
720
+ sheet,
721
+ row,
722
+ col,
723
+ value
724
+ } of changes) {
725
+ const s = this.sheets.find(x => x.id === sheet);
726
+ s?.updateCell(row, col, {
727
+ computed: value
728
+ });
729
+ }
730
+ }
731
+ #apply(op, read) {
732
+ switch (op.type) {
733
+ case 'setCell':
734
+ {
735
+ const sheet = this.sheet(op.sheet);
736
+ sheet.updateCell(op.row, op.col, {
737
+ value: op.formula ? undefined : op.value,
738
+ formula: op.formula,
739
+ computed: op.formula ? read : op.value
740
+ });
741
+ return;
742
+ }
743
+ case 'insertRows':
744
+ case 'insertCols':
745
+ {
746
+ const sheet = this.sheet(op.sheet);
747
+ const key = op.type === 'insertRows' ? 'rows' : 'cols';
748
+ const ids = [...sheet[key]];
749
+ const at = op.before === null ? ids.length : ids.indexOf(op.before);
750
+ if (at < 0) throw new Error(`Lattice: no row or column "${op.before}"`);
751
+ ids.splice(at, 0, ...op.ids);
752
+ sheet[key] = ids;
753
+ return;
754
+ }
755
+ case 'deleteRows':
756
+ case 'deleteCols':
757
+ return this.#delete(op);
758
+ case 'setFormat':
759
+ case 'setStyle':
760
+ {
761
+ const sheet = this.sheet(op.range.sheet);
762
+ const change = op.type === 'setFormat' ? {
763
+ format: op.format ?? undefined
764
+ } : {
765
+ style: op.style ? this.styleId(op.style) : undefined
766
+ };
767
+ for (const [row, col] of sheet.cellsOf(op.range)) sheet.updateCell(row, col, change);
768
+ return;
769
+ }
770
+ case 'merge':
771
+ {
772
+ const sheet = this.sheet(op.range.sheet);
773
+ sheet.merges = [...sheet.merges, {
774
+ start: op.range.start,
775
+ end: op.range.end
776
+ }];
777
+ return;
778
+ }
779
+ case 'unmerge':
780
+ {
781
+ const sheet = this.sheet(op.range.sheet);
782
+ sheet.merges = sheet.merges.filter(m => !sameArea(m, op.range));
783
+ return;
784
+ }
785
+ case 'setName':
786
+ {
787
+ const names = {
788
+ ...this.names
789
+ };
790
+ if (op.ref === null) delete names[op.name];else names[op.name] = op.ref;
791
+ this.names = names;
792
+ return;
793
+ }
794
+ case 'addSheet':
795
+ this.sheets = [...this.sheets, new Sheet(op.id, op.name, [...op.rows], [...op.cols])];
796
+ return;
797
+ case 'removeSheet':
798
+ this.sheets = this.sheets.filter(s => s.id !== op.id);
799
+ return;
800
+ case 'renameSheet':
801
+ this.sheet(op.id).name = op.name;
802
+ return;
803
+ case 'setNote':
804
+ this.sheet(op.sheet).updateCell(op.row, op.col, {
805
+ note: op.note ?? undefined
806
+ });
807
+ return;
808
+ case 'freeze':
809
+ this.sheet(op.sheet).frozen = {
810
+ rows: op.rows,
811
+ cols: op.cols
812
+ };
813
+ return;
814
+ case 'addRule':
815
+ {
816
+ const sheet = this.sheet(op.sheet);
817
+ sheet.rules = [...sheet.rules, op.rule];
818
+ return;
819
+ }
820
+ case 'removeRule':
821
+ {
822
+ const sheet = this.sheet(op.sheet);
823
+ sheet.rules = sheet.rules.filter(r => r.id !== op.id);
824
+ return;
825
+ }
826
+ case 'addValidation':
827
+ {
828
+ const sheet = this.sheet(op.sheet);
829
+ sheet.validations = [...sheet.validations, op.validation];
830
+ return;
831
+ }
832
+ case 'removeValidation':
833
+ {
834
+ const sheet = this.sheet(op.sheet);
835
+ sheet.validations = sheet.validations.filter(v => v.id !== op.id);
836
+ }
837
+ }
838
+ }
839
+ #delete(op) {
840
+ const sheet = this.sheet(op.sheet);
841
+ const rows = op.type === 'deleteRows';
842
+ const deletion = {
843
+ sheet: op.sheet,
844
+ [rows ? 'rows' : 'cols']: op.ids
845
+ };
846
+ const ctx = this.refs();
847
+ // Move range ends inward, as Excel does, with the order from before the delete.
848
+ for (const s of this.sheets) {
849
+ for (const [row, col, cell] of [...s.entries()]) {
850
+ if (!cell.formula) continue;
851
+ const formula = shrinkDeleted(cell.formula, s.id, ctx, deletion);
852
+ if (formula !== cell.formula) s.updateCell(row, col, {
853
+ formula
854
+ });
855
+ }
856
+ }
857
+ this.names = Object.fromEntries(Object.entries(this.names).map(([name, ref]) => [name, shrinkDeleted(ref, op.sheet, ctx, deletion)]));
858
+ const gone = new Set(op.ids);
859
+ const shrink = area => {
860
+ const key = rows ? 'row' : 'col';
861
+ const ids = rows ? sheet.rows : sheet.cols;
862
+ const from = ids.indexOf(area.start[key]);
863
+ const to = ids.indexOf(area.end[key]);
864
+ const keep = ids.slice(from, to + 1).filter(id => !gone.has(id));
865
+ if (keep.length === 0) return undefined;
866
+ return {
867
+ start: {
868
+ ...area.start,
869
+ [key]: keep[0]
870
+ },
871
+ end: {
872
+ ...area.end,
873
+ [key]: keep[keep.length - 1]
874
+ }
875
+ };
876
+ };
877
+ const shrinkAll = items => items.flatMap(item => {
878
+ const range = shrink(item.range);
879
+ return range ? [{
880
+ ...item,
881
+ range
882
+ }] : [];
883
+ });
884
+ sheet.merges = sheet.merges.flatMap(m => shrink(m) ?? []);
885
+ sheet.rules = shrinkAll(sheet.rules);
886
+ sheet.validations = shrinkAll(sheet.validations);
887
+ sheet.dropCells(rows ? gone : new Set(), rows ? new Set() : gone);
888
+ if (rows) sheet.rows = sheet.rows.filter(id => !gone.has(id));else sheet.cols = sheet.cols.filter(id => !gone.has(id));
889
+ }
890
+
891
+ /** The ID of a style. Equal styles get the same ID. */
892
+ styleId(style) {
893
+ const key = JSON.stringify(style);
894
+ let id = this.#styleIds.get(key);
895
+ if (!id) {
896
+ id = `st${this.styles.size + 1}`;
897
+ this.#styleIds.set(key, id);
898
+ this.styles.set(id, style);
899
+ }
900
+ return id;
901
+ }
902
+
903
+ /** The text for the editor: the formula in A1, or the raw value. */
904
+ formulaText(sheet, row, col) {
905
+ const cell = this.sheet(sheet).cell(row, col);
906
+ if (cell?.formula) return toA1(cell.formula, sheet, this.refs());
907
+ return formatValue(cell?.value, 'General', this.locale).text;
908
+ }
909
+
910
+ /** The text to show: the computed value with the number format of the cell. */
911
+ display(sheet, row, col) {
912
+ const cell = this.sheet(sheet).cell(row, col);
913
+ return formatValue(cell?.computed, cell?.format, this.locale);
914
+ }
915
+
916
+ /**
917
+ * Sets a cell from typed text. A formula goes from A1 to the stored form. A value must pass
918
+ * the data validation of the cell; if not, the cell keeps its value and the result has the
919
+ * note to show. `locale` gives the default notes (ADR 0024). Without it, they are in English.
920
+ */
921
+ async setInput(sheet, row, col, text, locale) {
922
+ const input = parseInput(text);
923
+ if (!input.formula && input.value !== undefined) {
924
+ const check = await this.validate(sheet, row, col, input.value, locale);
925
+ if (!check.ok) return check;
926
+ }
927
+ const formula = input.formula && toStored(input.formula, sheet, this.refs());
928
+ await this.apply([formula ? {
929
+ type: 'setCell',
930
+ sheet,
931
+ row,
932
+ col,
933
+ formula
934
+ } : {
935
+ type: 'setCell',
936
+ sheet,
937
+ row,
938
+ col,
939
+ value: input.value ?? null
940
+ }]);
941
+ return {
942
+ ok: true
943
+ };
944
+ }
945
+
946
+ /** Defines a named range from A1 text, for example `Data!$A$1:$B$9`. */
947
+ async defineName(name, a1) {
948
+ const ref = toStored(a1, this.sheets[0]?.id ?? '', this.refs());
949
+ await this.apply([{
950
+ type: 'setName',
951
+ name,
952
+ ref
953
+ }]);
954
+ }
955
+ nameText(name) {
956
+ const ref = this.names[name];
957
+ return ref === undefined ? undefined : toA1(ref, this.sheets[0]?.id ?? '', this.refs());
958
+ }
959
+
960
+ /** A stored formula for the top-left cell of `area`, moved to the cell at `row`, `col`. */
961
+ #formulaAt(sheet, area, formula, row, col) {
962
+ const ctx = this.refs();
963
+ const from = {
964
+ row: sheet.rows.indexOf(area.start.row),
965
+ col: sheet.cols.indexOf(area.start.col)
966
+ };
967
+ const to = {
968
+ row: sheet.rows.indexOf(row),
969
+ col: sheet.cols.indexOf(col)
970
+ };
971
+ const moved = fromR1C1(toR1C1(toA1(formula, sheet.id, ctx), from), to);
972
+ return toStored(moved, sheet.id, ctx);
973
+ }
974
+
975
+ /** The conditional format of a cell: styles, a color scale fill and a data bar. */
976
+ async conditionalFormat(sheetId, row, col) {
977
+ const sheet = this.sheet(sheetId);
978
+ const value = sheet.cell(row, col)?.computed;
979
+ const out = {};
980
+ for (const rule of sheet.rules) {
981
+ if (!sheet.contains(rule.range, row, col)) continue;
982
+ if (rule.kind === 'colorScale' || rule.kind === 'dataBar') {
983
+ if (!isNumber(value)) continue;
984
+ const t = this.#position(sheet, rule, value);
985
+ if (rule.kind === 'dataBar') out.bar = {
986
+ length: t,
987
+ color: rule.color
988
+ };else if (rule.mid) {
989
+ out.fill = t < 0.5 ? mix(rule.min, rule.mid, t * 2) : mix(rule.mid, rule.max, t * 2 - 1);
990
+ } else out.fill = mix(rule.min, rule.max, t);
991
+ continue;
992
+ }
993
+ if (await this.#ruleMatches(sheet, rule, value, row, col)) {
994
+ out.style = {
995
+ ...out.style,
996
+ ...rule.style
997
+ };
998
+ }
999
+ }
1000
+ return out;
1001
+ }
1002
+
1003
+ /** Where a value is between the minimum and the maximum of the rule range, from 0 to 1. */
1004
+ #position(sheet, rule, value) {
1005
+ const values = [...sheet.cellsOf(rule.range)].map(([r, c]) => sheet.cell(r, c)?.computed).filter(isNumber);
1006
+ const min = Math.min(...values);
1007
+ const max = Math.max(...values);
1008
+ return max === min ? 1 : (value - min) / (max - min);
1009
+ }
1010
+ async #ruleMatches(sheet, rule, value, row, col) {
1011
+ if (rule.kind === 'formula') {
1012
+ const formula = this.#formulaAt(sheet, rule.range, rule.formula, row, col);
1013
+ return (await this.engine.evaluate(sheet.id, formula)) === true;
1014
+ }
1015
+ if (!isNumber(value) && !isString(value)) return false;
1016
+ if (rule.kind === 'between') return isNumber(value) && value >= rule.min && value <= rule.max;
1017
+ const v = rule.value;
1018
+ switch (rule.op) {
1019
+ case '>':
1020
+ return value > v;
1021
+ case '<':
1022
+ return value < v;
1023
+ case '>=':
1024
+ return value >= v;
1025
+ case '<=':
1026
+ return value <= v;
1027
+ case '=':
1028
+ return value === v;
1029
+ case '<>':
1030
+ return value !== v;
1031
+ }
1032
+ }
1033
+
1034
+ /** Checks a value against the data validation of a cell. `locale` gives the default notes. */
1035
+ async validate(sheetId, row, col, value, locale = latticeLocale(undefined, undefined, this.locale)) {
1036
+ const sheet = this.sheet(sheetId);
1037
+ for (const validation of sheet.validations) {
1038
+ if (!sheet.contains(validation.range, row, col)) continue;
1039
+ if (!(await this.#valid(sheet, validation, value, row, col))) {
1040
+ return {
1041
+ ok: false,
1042
+ message: validation.message ?? this.#message(validation, locale)
1043
+ };
1044
+ }
1045
+ }
1046
+ return {
1047
+ ok: true
1048
+ };
1049
+ }
1050
+ #message(validation, l) {
1051
+ const rule = validation.rule;
1052
+ if (rule.kind === 'list') return l.t('sheet.validation.oneOf', {
1053
+ values: rule.values.join(', ')
1054
+ });
1055
+ if (rule.kind === 'range') {
1056
+ return l.t('sheet.validation.range', {
1057
+ min: rule.min ?? '-∞',
1058
+ max: rule.max ?? '∞'
1059
+ });
1060
+ }
1061
+ return l.t('sheet.validation.invalid');
1062
+ }
1063
+ async #valid(sheet, v, value, row, col) {
1064
+ const rule = v.rule;
1065
+ if (rule.kind === 'list') return rule.values.includes(String(value));
1066
+ if (rule.kind === 'range') {
1067
+ return isNumber(value) && (rule.min === undefined || value >= rule.min) && (rule.max === undefined || value <= rule.max);
1068
+ }
1069
+ const formula = scanStored(this.#formulaAt(sheet, v.range, rule.formula, row, col)).map(t => {
1070
+ if (t.kind === 'text') return t.text;
1071
+ const self = !t.ref.end && (t.ref.sheet ?? sheet.id) === sheet.id && t.ref.start.row === row;
1072
+ return self && t.ref.start.col === col ? literal(value) : printStored(t.ref);
1073
+ }).join('');
1074
+ return (await this.engine.evaluate(sheet.id, formula)) === true;
1075
+ }
1076
+ #searchText(sheet, row, col, formulas) {
1077
+ const cell = sheet.cell(row, col);
1078
+ return formulas && cell?.formula ? this.formulaText(sheet.id, row, col) : this.display(sheet.id, row, col).text;
1079
+ }
1080
+
1081
+ /**
1082
+ * Finds cells whose shown text holds `query`. With `formulas`, a formula cell is searched by
1083
+ * its A1 text. Results are in sheet, row and column order.
1084
+ */
1085
+ find(query, options = {}) {
1086
+ const norm = s => options.matchCase ? s : s.toLowerCase();
1087
+ const q = norm(query);
1088
+ const out = [];
1089
+ for (const sheet of this.sheets) {
1090
+ const rowIndex = new Map(sheet.rows.map((id, i) => [id, i]));
1091
+ const colIndex = new Map(sheet.cols.map((id, i) => [id, i]));
1092
+ const hits = [...sheet.entries()].filter(([row, col]) => norm(this.#searchText(sheet, row, col, !!options.formulas)).includes(q)).map(([row, col]) => ({
1093
+ row,
1094
+ col
1095
+ })).sort((a, b) => rowIndex.get(a.row) - rowIndex.get(b.row) || colIndex.get(a.col) - colIndex.get(b.col));
1096
+ out.push(...hits.map(h => ({
1097
+ sheet: sheet.id,
1098
+ ...h
1099
+ })));
1100
+ }
1101
+ return out;
1102
+ }
1103
+
1104
+ /**
1105
+ * Replaces `query` in the raw text of values and, with `formulas`, in the A1 text of formulas.
1106
+ * The stored ID form is never searched. Gives the count of changed cells.
1107
+ */
1108
+ async replace(query, replacement, options = {}) {
1109
+ const flags = options.matchCase ? 'g' : 'gi';
1110
+ const pattern = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), flags);
1111
+ const ops = [];
1112
+ for (const ref of this.find(query, options)) {
1113
+ const sheet = this.sheet(ref.sheet);
1114
+ const cell = sheet.cell(ref.row, ref.col);
1115
+ if (cell?.formula && !options.formulas) continue;
1116
+ const next = this.formulaText(ref.sheet, ref.row, ref.col).replace(pattern, replacement);
1117
+ const input = parseInput(next);
1118
+ const formula = input.formula && toStored(input.formula, ref.sheet, this.refs());
1119
+ ops.push(formula ? {
1120
+ type: 'setCell',
1121
+ ...ref,
1122
+ formula
1123
+ } : {
1124
+ type: 'setCell',
1125
+ ...ref,
1126
+ value: input.value ?? null
1127
+ });
1128
+ }
1129
+ if (ops.length) await this.apply(ops);
1130
+ return ops.length;
1131
+ }
1132
+ }
1133
+
1134
+ export { Sheet, Workbook, formatValue, parseFormat };
1135
+ //# sourceMappingURL=index.js.map