@svgrid/grid 1.0.2 → 1.1.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 (143) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +137 -39
  3. package/dist/GridFooter.svelte +164 -0
  4. package/dist/GridFooter.svelte.d.ts +29 -0
  5. package/dist/GridMenus.svelte +570 -0
  6. package/dist/GridMenus.svelte.d.ts +31 -0
  7. package/dist/SvGrid.controller.svelte.d.ts +429 -0
  8. package/dist/SvGrid.controller.svelte.js +1732 -0
  9. package/dist/SvGrid.css +1709 -0
  10. package/dist/SvGrid.helpers.d.ts +35 -0
  11. package/dist/SvGrid.helpers.js +160 -0
  12. package/dist/SvGrid.svelte +344 -7043
  13. package/dist/SvGrid.svelte.d.ts +4 -357
  14. package/dist/SvGrid.types.d.ts +436 -0
  15. package/dist/SvGrid.types.js +1 -0
  16. package/dist/SvGridChart.svelte +1060 -23
  17. package/dist/SvGridChart.svelte.d.ts +17 -0
  18. package/dist/build-api.d.ts +5 -0
  19. package/dist/build-api.js +527 -0
  20. package/dist/cell-render.d.ts +15 -0
  21. package/dist/cell-render.js +246 -0
  22. package/dist/cell-values.d.ts +28 -0
  23. package/dist/cell-values.js +89 -0
  24. package/dist/chart.d.ts +370 -3
  25. package/dist/chart.js +1135 -42
  26. package/dist/clipboard.d.ts +15 -0
  27. package/dist/clipboard.js +356 -0
  28. package/dist/columns.d.ts +30 -0
  29. package/dist/columns.js +277 -0
  30. package/dist/core.d.ts +1 -1
  31. package/dist/css.d.ts +3 -0
  32. package/dist/editing.d.ts +24 -0
  33. package/dist/editing.js +343 -0
  34. package/dist/editors/cell-editors.d.ts +1 -1
  35. package/dist/facet-buckets.d.ts +13 -0
  36. package/dist/facet-buckets.js +54 -0
  37. package/dist/features.d.ts +5 -0
  38. package/dist/features.js +30 -0
  39. package/dist/filter-operators.d.ts +16 -0
  40. package/dist/filter-operators.js +69 -0
  41. package/dist/hyperformula-adapter.d.ts +82 -0
  42. package/dist/hyperformula-adapter.js +73 -0
  43. package/dist/index.d.ts +5 -2
  44. package/dist/index.js +5 -2
  45. package/dist/keyboard-handlers.d.ts +7 -0
  46. package/dist/keyboard-handlers.js +197 -0
  47. package/dist/menus.d.ts +40 -0
  48. package/dist/menus.js +389 -0
  49. package/dist/named-views.d.ts +27 -0
  50. package/dist/named-views.js +39 -0
  51. package/dist/row-resize.d.ts +43 -0
  52. package/dist/row-resize.js +158 -0
  53. package/dist/scroll-sync.d.ts +9 -0
  54. package/dist/scroll-sync.js +86 -0
  55. package/dist/selection.d.ts +26 -0
  56. package/dist/selection.js +387 -0
  57. package/dist/spreadsheet.d.ts +80 -0
  58. package/dist/spreadsheet.js +194 -0
  59. package/dist/summaries.d.ts +12 -0
  60. package/dist/summaries.js +65 -0
  61. package/dist/svgrid-wrapper.types.d.ts +12 -1
  62. package/dist/svgrid.comments-autocomplete.test.d.ts +1 -0
  63. package/dist/svgrid.comments-autocomplete.test.js +96 -0
  64. package/dist/svgrid.context-menu.test.d.ts +1 -0
  65. package/dist/svgrid.context-menu.test.js +102 -0
  66. package/dist/svgrid.new-features.wrapper.test.js +30 -4
  67. package/dist/svgrid.wrapper.test.js +27 -1
  68. package/dist/virtualization/column-virtualizer.d.ts +2 -0
  69. package/dist/virtualization/scroll-scaling.d.ts +28 -0
  70. package/dist/virtualization/scroll-scaling.js +64 -0
  71. package/dist/virtualization/scroll-scaling.test.d.ts +1 -0
  72. package/dist/virtualization/scroll-scaling.test.js +86 -0
  73. package/dist/virtualization/svelte-virtualizer.svelte.d.ts +2 -0
  74. package/dist/virtualization/svelte-virtualizer.svelte.js +2 -0
  75. package/dist/virtualization/virtualizer.d.ts +7 -0
  76. package/dist/virtualization/virtualizer.js +30 -0
  77. package/package.json +1 -1
  78. package/src/GridFooter.svelte +164 -0
  79. package/src/GridMenus.svelte +570 -0
  80. package/src/SvGrid.controller.svelte.ts +2195 -0
  81. package/src/SvGrid.css +1747 -0
  82. package/src/SvGrid.helpers.test.ts +415 -0
  83. package/src/SvGrid.helpers.ts +185 -0
  84. package/src/SvGrid.svelte +348 -7043
  85. package/src/SvGrid.types.ts +456 -0
  86. package/src/SvGridChart.svelte +1060 -23
  87. package/src/build-api.coverage.test.ts +532 -0
  88. package/src/build-api.ts +663 -0
  89. package/src/cell-render.test.ts +451 -0
  90. package/src/cell-render.ts +426 -0
  91. package/src/cell-values.ts +114 -0
  92. package/src/chart-export.test.ts +370 -0
  93. package/src/chart.coverage.test.ts +814 -0
  94. package/src/chart.ts +1352 -47
  95. package/src/clipboard.test.ts +731 -0
  96. package/src/clipboard.ts +524 -0
  97. package/src/collaboration.coverage.test.ts +220 -0
  98. package/src/columns.test.ts +702 -0
  99. package/src/columns.ts +419 -0
  100. package/src/core.ts +8 -0
  101. package/src/css.d.ts +3 -0
  102. package/src/editing.test.ts +837 -0
  103. package/src/editing.ts +513 -0
  104. package/src/editors/cell-editors.coverage.test.ts +156 -0
  105. package/src/editors/cell-editors.ts +1 -0
  106. package/src/facet-buckets.test.ts +353 -0
  107. package/src/facet-buckets.ts +67 -0
  108. package/src/features.ts +128 -0
  109. package/src/filter-operators.test.ts +174 -0
  110. package/src/filter-operators.ts +87 -0
  111. package/src/hyperformula-adapter.test.ts +256 -0
  112. package/src/hyperformula-adapter.ts +124 -0
  113. package/src/index.ts +37 -0
  114. package/src/keyboard-handlers.coverage.test.ts +560 -0
  115. package/src/keyboard-handlers.ts +353 -0
  116. package/src/keyboard.ts +97 -97
  117. package/src/menus.test.ts +620 -0
  118. package/src/menus.ts +554 -0
  119. package/src/named-views.coverage.test.ts +210 -0
  120. package/src/named-views.ts +48 -0
  121. package/src/row-resize.test.ts +369 -0
  122. package/src/row-resize.ts +171 -0
  123. package/src/scroll-sync.test.ts +330 -0
  124. package/src/scroll-sync.ts +216 -0
  125. package/src/selection.test.ts +722 -0
  126. package/src/selection.ts +545 -0
  127. package/src/server-data-source.coverage.test.ts +180 -0
  128. package/src/spreadsheet.test.ts +445 -0
  129. package/src/spreadsheet.ts +246 -0
  130. package/src/summaries.ts +204 -0
  131. package/src/sv-grid-scrollbar.ts +13 -1
  132. package/src/svgrid-wrapper.types.ts +12 -1
  133. package/src/svgrid.behavior.test.ts +22 -0
  134. package/src/svgrid.comments-autocomplete.test.ts +112 -0
  135. package/src/svgrid.context-menu.test.ts +126 -0
  136. package/src/svgrid.interaction.test.ts +30 -0
  137. package/src/svgrid.new-features.wrapper.test.ts +65 -4
  138. package/src/svgrid.wrapper.test.ts +27 -1
  139. package/src/test-setup.ts +9 -6
  140. package/src/virtualization/scroll-scaling.test.ts +148 -0
  141. package/src/virtualization/scroll-scaling.ts +121 -0
  142. package/src/virtualization/svelte-virtualizer.svelte.ts +2 -0
  143. package/src/virtualization/virtualizer.ts +26 -0
@@ -0,0 +1,174 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import {
3
+ filterOperatorOptions,
4
+ fallbackOperatorOption,
5
+ TEXT_OPERATORS,
6
+ NUMBER_OPERATORS,
7
+ DATE_OPERATORS,
8
+ CHECKBOX_OPERATORS,
9
+ operatorOption,
10
+ operatorsForColumn,
11
+ defaultOperatorFor,
12
+ operatorLabelFor,
13
+ } from "./filter-operators";
14
+ import type { FilterOperator, FilterOption } from "./SvGrid.types";
15
+
16
+ // `operatorsForColumn` / `defaultOperatorFor` / `operatorLabelFor` only ever
17
+ // read `column?.columnDef.editorType`, so a minimal duck-typed stub is enough
18
+ // to exercise every branch without standing up a real grid/column instance.
19
+ function col(editorType?: string): any {
20
+ return editorType === undefined
21
+ ? { columnDef: {} }
22
+ : { columnDef: { editorType } };
23
+ }
24
+
25
+ describe("filter-operators: catalogue integrity", () => {
26
+ it("every option exposes value/label/iconName and a unique value", () => {
27
+ const values = filterOperatorOptions.map((o) => o.value);
28
+ expect(new Set(values).size).toBe(values.length);
29
+ for (const o of filterOperatorOptions) {
30
+ expect(typeof o.value).toBe("string");
31
+ expect(typeof o.label).toBe("string");
32
+ expect(o.iconName).toMatch(/^op-/);
33
+ }
34
+ });
35
+
36
+ it("fallback option is the 'contains' operator", () => {
37
+ expect(fallbackOperatorOption.value).toBe("contains");
38
+ expect(fallbackOperatorOption.label).toBe("Contains");
39
+ });
40
+
41
+ it("each type's operator list only references catalogued operators", () => {
42
+ const known = new Set(filterOperatorOptions.map((o) => o.value));
43
+ for (const list of [
44
+ TEXT_OPERATORS,
45
+ NUMBER_OPERATORS,
46
+ DATE_OPERATORS,
47
+ CHECKBOX_OPERATORS,
48
+ ]) {
49
+ for (const id of list) expect(known.has(id)).toBe(true);
50
+ }
51
+ });
52
+
53
+ it("the catalogue includes between / isBlank for numeric + date filtering", () => {
54
+ const values = filterOperatorOptions.map((o) => o.value);
55
+ expect(values).toContain("between");
56
+ expect(values).toContain("isBlank");
57
+ });
58
+ });
59
+
60
+ describe("operatorOption", () => {
61
+ it("returns the matching option for every catalogued operator", () => {
62
+ for (const o of filterOperatorOptions) {
63
+ expect(operatorOption(o.value)).toBe(o);
64
+ }
65
+ });
66
+
67
+ it("looks up a specific operator by value", () => {
68
+ expect(operatorOption("between")).toMatchObject({
69
+ value: "between",
70
+ label: "Between",
71
+ });
72
+ expect(operatorOption("greaterThan").label).toBe("Greater than");
73
+ expect(operatorOption("lessThan").label).toBe("Less than");
74
+ expect(operatorOption("startsWith").label).toBe("Starts with");
75
+ });
76
+
77
+ it("falls back to 'contains' for an unknown operator value", () => {
78
+ const result = operatorOption("nope" as FilterOperator);
79
+ expect(result).toBe(fallbackOperatorOption);
80
+ expect(result.value).toBe("contains");
81
+ });
82
+ });
83
+
84
+ describe("operatorsForColumn", () => {
85
+ const labels = (opts: FilterOption[]) => opts.map((o) => o.value);
86
+
87
+ it("number columns get equals/greaterThan/lessThan/between/isBlank", () => {
88
+ expect(labels(operatorsForColumn(col("number")))).toEqual(NUMBER_OPERATORS);
89
+ });
90
+
91
+ it("date columns get the date operator set", () => {
92
+ expect(labels(operatorsForColumn(col("date")))).toEqual(DATE_OPERATORS);
93
+ });
94
+
95
+ it("datetime columns share the date operator set", () => {
96
+ expect(labels(operatorsForColumn(col("datetime")))).toEqual(DATE_OPERATORS);
97
+ });
98
+
99
+ it("checkbox columns get only equals + isBlank", () => {
100
+ expect(labels(operatorsForColumn(col("checkbox")))).toEqual(
101
+ CHECKBOX_OPERATORS,
102
+ );
103
+ });
104
+
105
+ it("text columns get the text operator set", () => {
106
+ expect(labels(operatorsForColumn(col("text")))).toEqual(TEXT_OPERATORS);
107
+ });
108
+
109
+ it("an unknown editor type defaults to the text operator set", () => {
110
+ expect(labels(operatorsForColumn(col("currency")))).toEqual(TEXT_OPERATORS);
111
+ });
112
+
113
+ it("a column with no editorType defaults to text", () => {
114
+ expect(labels(operatorsForColumn(col()))).toEqual(TEXT_OPERATORS);
115
+ });
116
+
117
+ it("an undefined column defaults to the text operator set", () => {
118
+ expect(labels(operatorsForColumn(undefined))).toEqual(TEXT_OPERATORS);
119
+ });
120
+
121
+ it("returns full FilterOption objects (value+label+iconName), in order", () => {
122
+ const opts = operatorsForColumn(col("number"));
123
+ expect(opts[0]).toMatchObject({ value: "equals", iconName: "op-equals" });
124
+ for (const o of opts) {
125
+ expect(o).toHaveProperty("label");
126
+ expect(o).toHaveProperty("iconName");
127
+ }
128
+ });
129
+ });
130
+
131
+ describe("defaultOperatorFor", () => {
132
+ it("picks the first operator valid for the column type", () => {
133
+ expect(defaultOperatorFor(col("number"))).toBe("equals");
134
+ expect(defaultOperatorFor(col("date"))).toBe("equals");
135
+ expect(defaultOperatorFor(col("checkbox"))).toBe("equals");
136
+ expect(defaultOperatorFor(col("text"))).toBe("contains");
137
+ });
138
+
139
+ it("defaults to 'contains' for text / unknown / undefined columns", () => {
140
+ expect(defaultOperatorFor(col())).toBe("contains");
141
+ expect(defaultOperatorFor(undefined)).toBe("contains");
142
+ expect(defaultOperatorFor(col("mystery"))).toBe("contains");
143
+ });
144
+ });
145
+
146
+ describe("operatorLabelFor", () => {
147
+ const less = operatorOption("lessThan");
148
+ const greater = operatorOption("greaterThan");
149
+ const equals = operatorOption("equals");
150
+
151
+ it("renames lessThan/greaterThan to Before/After for date columns", () => {
152
+ expect(operatorLabelFor(less, col("date"))).toBe("Before");
153
+ expect(operatorLabelFor(greater, col("date"))).toBe("After");
154
+ });
155
+
156
+ it("applies the date relabelling for datetime columns too", () => {
157
+ expect(operatorLabelFor(less, col("datetime"))).toBe("Before");
158
+ expect(operatorLabelFor(greater, col("datetime"))).toBe("After");
159
+ });
160
+
161
+ it("leaves non-relabelled operators untouched on date columns", () => {
162
+ expect(operatorLabelFor(equals, col("date"))).toBe(equals.label);
163
+ });
164
+
165
+ it("keeps the catalogue label for non-date columns", () => {
166
+ expect(operatorLabelFor(less, col("number"))).toBe("Less than");
167
+ expect(operatorLabelFor(greater, col("number"))).toBe("Greater than");
168
+ expect(operatorLabelFor(less, col("text"))).toBe("Less than");
169
+ });
170
+
171
+ it("keeps the catalogue label when the column is undefined", () => {
172
+ expect(operatorLabelFor(greater, undefined)).toBe("Greater than");
173
+ });
174
+ });
@@ -0,0 +1,87 @@
1
+ // Filter-operator catalogue + the pure helpers that pick which operators
2
+ // apply to a column and how they're labelled. Fully static - no grid state -
3
+ // so it lives outside the controller.
4
+ import type { Column, RowData } from "./index";
5
+ import type { FilterOperator, FilterOption } from "./SvGrid.types";
6
+
7
+ export const filterOperatorOptions: Array<FilterOption> = [
8
+ { value: "contains", label: "Contains", iconName: "op-contains" },
9
+ { value: "equals", label: "Equals", iconName: "op-equals" },
10
+ { value: "startsWith", label: "Starts with", iconName: "op-startsWith" },
11
+ { value: "greaterThan", label: "Greater than", iconName: "op-greaterThan" },
12
+ { value: "lessThan", label: "Less than", iconName: "op-lessThan" },
13
+ { value: "between", label: "Between", iconName: "op-between" },
14
+ { value: "isBlank", label: "Is blank", iconName: "op-isBlank" },
15
+ ];
16
+ /** Which operators make sense for each column editor type. */
17
+ export const TEXT_OPERATORS: Array<FilterOperator> = [
18
+ "contains",
19
+ "equals",
20
+ "startsWith",
21
+ "isBlank",
22
+ ];
23
+ export const NUMBER_OPERATORS: Array<FilterOperator> = [
24
+ "equals",
25
+ "greaterThan",
26
+ "lessThan",
27
+ "between",
28
+ "isBlank",
29
+ ];
30
+ export const DATE_OPERATORS: Array<FilterOperator> = [
31
+ "equals",
32
+ "lessThan",
33
+ "greaterThan",
34
+ "between",
35
+ "isBlank",
36
+ ];
37
+ export const CHECKBOX_OPERATORS: Array<FilterOperator> = ["equals", "isBlank"];
38
+ export const fallbackOperatorOption: FilterOption = {
39
+ value: "contains",
40
+ label: "Contains",
41
+ iconName: "op-contains",
42
+ };
43
+
44
+ export function operatorOption(value: FilterOperator): FilterOption {
45
+ return (
46
+ filterOperatorOptions.find((option) => option.value === value) ??
47
+ fallbackOperatorOption
48
+ );
49
+ }
50
+
51
+ /** Returns the operators that make sense for the given column's data type. */
52
+ export function operatorsForColumn<TData extends RowData>(
53
+ column: Column<TData> | undefined,
54
+ ): Array<FilterOption> {
55
+ const editorType = column?.columnDef.editorType ?? "text";
56
+ const ids =
57
+ editorType === "number"
58
+ ? NUMBER_OPERATORS
59
+ : editorType === "date" || editorType === "datetime"
60
+ ? DATE_OPERATORS
61
+ : editorType === "checkbox"
62
+ ? CHECKBOX_OPERATORS
63
+ : TEXT_OPERATORS;
64
+ return ids
65
+ .map((id) => filterOperatorOptions.find((option) => option.value === id))
66
+ .filter((option): option is FilterOption => Boolean(option));
67
+ }
68
+
69
+ /** Default operator for a column (first one valid for its type). */
70
+ export function defaultOperatorFor<TData extends RowData>(
71
+ column: Column<TData> | undefined,
72
+ ): FilterOperator {
73
+ return operatorsForColumn(column)[0]?.value ?? "contains";
74
+ }
75
+
76
+ /** Date columns get friendlier labels for "less / greater than". */
77
+ export function operatorLabelFor<TData extends RowData>(
78
+ option: FilterOption,
79
+ column: Column<TData> | undefined,
80
+ ): string {
81
+ const editorType = column?.columnDef.editorType;
82
+ if (editorType === "date" || editorType === "datetime") {
83
+ if (option.value === "lessThan") return "Before";
84
+ if (option.value === "greaterThan") return "After";
85
+ }
86
+ return option.label;
87
+ }
@@ -0,0 +1,256 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest'
2
+ import {
3
+ createHyperFormulaSheet,
4
+ type HyperFormulaInstance,
5
+ } from './hyperformula-adapter'
6
+
7
+ /**
8
+ * A tiny in-memory fake that emulates just the slice of the HyperFormula
9
+ * API the adapter touches: setCellContents / getCellValue / destroy.
10
+ *
11
+ * It stores raw cell contents in a Map keyed by "sheet:row:col" and
12
+ * evaluates `=A1+B1` style formulas with a deliberately small expression
13
+ * engine so we can assert the adapter wires reads/writes correctly without
14
+ * needing the real ~1MB hyperformula package.
15
+ */
16
+ function makeFakeEngine() {
17
+ const raw = new Map<string, unknown>()
18
+ const key = (s: number, r: number, c: number) => `${s}:${r}:${c}`
19
+
20
+ // Resolve an A1 reference (e.g. "A1", "B2") to a cell value.
21
+ const colLetterToIndex = (letters: string) => {
22
+ let n = 0
23
+ for (const ch of letters) n = n * 26 + (ch.charCodeAt(0) - 64)
24
+ return n - 1
25
+ }
26
+
27
+ function evalCell(sheet: number, row: number, col: number): unknown {
28
+ const stored = raw.get(key(sheet, row, col))
29
+ if (typeof stored !== 'string' || !stored.startsWith('=')) return stored
30
+ const expr = stored.slice(1)
31
+ // Replace A1-style refs with their numeric values.
32
+ const substituted = expr.replace(/([A-Z]+)(\d+)/g, (_m, letters, digits) => {
33
+ const refCol = colLetterToIndex(letters)
34
+ const refRow = Number(digits) - 1
35
+ const v = evalCell(sheet, refRow, refCol)
36
+ return String(typeof v === 'number' ? v : 0)
37
+ })
38
+ try {
39
+ // Only ever digits / operators after substitution: safe to eval here.
40
+ // eslint-disable-next-line no-new-func
41
+ return Function(`"use strict";return (${substituted})`)()
42
+ } catch {
43
+ return '#ERROR!'
44
+ }
45
+ }
46
+
47
+ const engine = {
48
+ setCellContents: vi.fn(
49
+ (cell: { sheet: number; row: number; col: number }, contents: unknown) => {
50
+ raw.set(key(cell.sheet, cell.row, cell.col), contents)
51
+ return [
52
+ {
53
+ address: { sheet: cell.sheet, row: cell.row, col: cell.col },
54
+ newValue: evalCell(cell.sheet, cell.row, cell.col),
55
+ },
56
+ ]
57
+ },
58
+ ),
59
+ getCellValue: vi.fn((cell: { sheet: number; row: number; col: number }) =>
60
+ evalCell(cell.sheet, cell.row, cell.col),
61
+ ),
62
+ destroy: vi.fn(() => {}),
63
+ rebuildAndRecalculate: vi.fn(() => {}),
64
+ // test-only introspection
65
+ _raw: raw,
66
+ }
67
+ return engine as HyperFormulaInstance & {
68
+ setCellContents: ReturnType<typeof vi.fn>
69
+ getCellValue: ReturnType<typeof vi.fn>
70
+ destroy: ReturnType<typeof vi.fn>
71
+ _raw: Map<string, unknown>
72
+ }
73
+ }
74
+
75
+ describe('createHyperFormulaSheet', () => {
76
+ let hf: ReturnType<typeof makeFakeEngine>
77
+
78
+ beforeEach(() => {
79
+ hf = makeFakeEngine()
80
+ })
81
+
82
+ it('seeds the engine with one setCellContents per cell in field order', () => {
83
+ const rows = [
84
+ { a: 1, b: 2 },
85
+ { a: 10, b: 20 },
86
+ ]
87
+ createHyperFormulaSheet({ hyperformula: hf, rows, fields: ['a', 'b'] })
88
+
89
+ // 2 rows x 2 fields = 4 seeded cells.
90
+ expect(hf.setCellContents).toHaveBeenCalledTimes(4)
91
+ // Field 'a' is column 0, field 'b' is column 1 (order = column index).
92
+ expect(hf.setCellContents).toHaveBeenCalledWith(
93
+ { sheet: 0, row: 0, col: 0 },
94
+ 1,
95
+ )
96
+ expect(hf.setCellContents).toHaveBeenCalledWith(
97
+ { sheet: 0, row: 1, col: 1 },
98
+ 20,
99
+ )
100
+ })
101
+
102
+ it('computed snapshot pulls evaluated values out of the engine', () => {
103
+ const rows = [{ a: 2, b: 3, total: '=A1+B1' }]
104
+ const sheet = createHyperFormulaSheet({
105
+ hyperformula: hf,
106
+ rows,
107
+ fields: ['a', 'b', 'total'],
108
+ })
109
+ expect(sheet.computed[0]).toEqual({ a: 2, b: 3, total: 5 })
110
+ // getCellValue called once per cell in the snapshot (3 fields).
111
+ expect(hf.getCellValue).toHaveBeenCalledTimes(3)
112
+ })
113
+
114
+ it('raw snapshot keeps the original formula strings untouched', () => {
115
+ const rows = [{ a: 2, b: 3, total: '=A1+B1' }]
116
+ const sheet = createHyperFormulaSheet({
117
+ hyperformula: hf,
118
+ rows,
119
+ fields: ['a', 'b', 'total'],
120
+ })
121
+ expect(sheet.raw[0]!.total).toBe('=A1+B1')
122
+ // raw is a copy, not the same object reference as the input row.
123
+ expect(sheet.raw[0]).not.toBe(rows[0])
124
+ })
125
+
126
+ it('preserves non-formula fields not listed in `fields`', () => {
127
+ const rows = [{ a: 1, b: 2, name: 'keep-me' }]
128
+ const sheet = createHyperFormulaSheet({
129
+ hyperformula: hf,
130
+ rows,
131
+ fields: ['a', 'b'],
132
+ })
133
+ // `name` was never registered as a column but survives in computed.
134
+ expect(sheet.computed[0]!.name).toBe('keep-me')
135
+ expect(sheet.raw[0]!.name).toBe('keep-me')
136
+ })
137
+
138
+ it('update() writes the edited cell back and re-evaluates dependents', () => {
139
+ const rows = [{ a: 2, b: 3, total: '=A1+B1' }]
140
+ const sheet = createHyperFormulaSheet({
141
+ hyperformula: hf,
142
+ rows,
143
+ fields: ['a', 'b', 'total'],
144
+ })
145
+ expect(sheet.computed[0]!.total).toBe(5)
146
+
147
+ hf.setCellContents.mockClear()
148
+ const next = sheet.update(0, 'a', 100)
149
+
150
+ // The edited cell was pushed into the engine at its column index (a => col 0).
151
+ expect(hf.setCellContents).toHaveBeenCalledWith(
152
+ { sheet: 0, row: 0, col: 0 },
153
+ 100,
154
+ )
155
+ // Dependent formula recomputed from the engine.
156
+ expect(next.computed[0]).toEqual({ a: 100, b: 3, total: 103 })
157
+ // raw reflects the new edited literal but keeps the formula string.
158
+ expect(next.raw[0]).toEqual({ a: 100, b: 3, total: '=A1+B1' })
159
+ })
160
+
161
+ it('update() with an unregistered field skips the engine write but updates rows', () => {
162
+ const rows = [{ a: 1, b: 2, note: 'x' }]
163
+ const sheet = createHyperFormulaSheet({
164
+ hyperformula: hf,
165
+ rows,
166
+ fields: ['a', 'b'],
167
+ })
168
+ hf.setCellContents.mockClear()
169
+
170
+ const next = sheet.update(0, 'note' as 'a', 'edited')
171
+
172
+ // `note` is not a registered column => no setCellContents call.
173
+ expect(hf.setCellContents).not.toHaveBeenCalled()
174
+ // But the raw/computed row still carries the new value.
175
+ expect(next.raw[0]!.note).toBe('edited')
176
+ expect(next.computed[0]!.note).toBe('edited')
177
+ })
178
+
179
+ it('respects a custom sheetId for every read and write', () => {
180
+ const rows = [{ a: 1 }]
181
+ const sheet = createHyperFormulaSheet({
182
+ hyperformula: hf,
183
+ rows,
184
+ fields: ['a'],
185
+ sheetId: 7,
186
+ })
187
+ expect(hf.setCellContents).toHaveBeenCalledWith(
188
+ { sheet: 7, row: 0, col: 0 },
189
+ 1,
190
+ )
191
+ expect(hf.getCellValue).toHaveBeenCalledWith({ sheet: 7, row: 0, col: 0 })
192
+
193
+ hf.setCellContents.mockClear()
194
+ sheet.update(0, 'a', 9)
195
+ expect(hf.setCellContents).toHaveBeenCalledWith(
196
+ { sheet: 7, row: 0, col: 0 },
197
+ 9,
198
+ )
199
+ })
200
+
201
+ it('defaults sheetId to 0 when omitted', () => {
202
+ createHyperFormulaSheet({ hyperformula: hf, rows: [{ a: 1 }], fields: ['a'] })
203
+ expect(hf.setCellContents).toHaveBeenCalledWith(
204
+ { sheet: 0, row: 0, col: 0 },
205
+ 1,
206
+ )
207
+ })
208
+
209
+ it('handles an empty rows array without touching the engine', () => {
210
+ const sheet = createHyperFormulaSheet({
211
+ hyperformula: hf,
212
+ rows: [],
213
+ fields: ['a', 'b'],
214
+ })
215
+ expect(hf.setCellContents).not.toHaveBeenCalled()
216
+ expect(sheet.computed).toEqual([])
217
+ expect(sheet.raw).toEqual([])
218
+ })
219
+
220
+ it('cross-row formula references resolve through the engine', () => {
221
+ const rows = [
222
+ { a: 5 },
223
+ { a: 7 },
224
+ { a: '=A1+A2' },
225
+ ]
226
+ const sheet = createHyperFormulaSheet({
227
+ hyperformula: hf,
228
+ rows,
229
+ fields: ['a'],
230
+ })
231
+ expect(sheet.computed[2]!.a).toBe(12)
232
+ })
233
+
234
+ it('destroy() tears down the underlying engine', () => {
235
+ const sheet = createHyperFormulaSheet({
236
+ hyperformula: hf,
237
+ rows: [{ a: 1 }],
238
+ fields: ['a'],
239
+ })
240
+ sheet.destroy()
241
+ expect(hf.destroy).toHaveBeenCalledTimes(1)
242
+ })
243
+
244
+ it('update() returns fresh array instances each call (no shared mutation)', () => {
245
+ const rows = [{ a: 1, b: 1 }]
246
+ const sheet = createHyperFormulaSheet({
247
+ hyperformula: hf,
248
+ rows,
249
+ fields: ['a', 'b'],
250
+ })
251
+ const first = sheet.update(0, 'a', 2)
252
+ const second = sheet.update(0, 'b', 3)
253
+ expect(first.computed).not.toBe(second.computed)
254
+ expect(second.computed[0]).toEqual({ a: 2, b: 3 })
255
+ })
256
+ })
@@ -0,0 +1,124 @@
1
+ /**
2
+ * HyperFormula adapter — Excel-class formula evaluation for SvGrid.
3
+ *
4
+ * `hyperformula` is an OPTIONAL peer dependency. Consumers who want
5
+ * full Excel-compatible formulas install it themselves:
6
+ *
7
+ * ```bash
8
+ * pnpm add hyperformula
9
+ * ```
10
+ *
11
+ * The adapter wraps an HF instance around the grid's flat-row data:
12
+ *
13
+ * - Treats each `data[]` row as a spreadsheet row
14
+ * - Each registered field maps to a spreadsheet column
15
+ * - Values that start with `=` are evaluated by HF
16
+ * - The adapter returns the computed rows ready to render
17
+ * - On edit, call `update(rowIdx, field, value)` and the adapter
18
+ * re-evaluates only the cells HF tells it are dirty
19
+ *
20
+ * Why not bundle HF: it's ~1MB minified and 99% of grids never need it.
21
+ * Keeping it peer-optional means tiny default bundle + heavy-formula
22
+ * users get the ~400 functions (VLOOKUP, INDIRECT, IFS, XLOOKUP, full
23
+ * date/time/financial libraries) on demand.
24
+ */
25
+
26
+ /** Minimal HF type surface this adapter uses. Mirrored here (rather
27
+ * than importing) so consumers without `hyperformula` installed still
28
+ * type-check. */
29
+ export type HyperFormulaInstance = {
30
+ setCellContents(
31
+ cell: { sheet: number; row: number; col: number },
32
+ contents: unknown,
33
+ ): Array<{ address: { sheet: number; row: number; col: number }; newValue: unknown }>
34
+ getCellValue(cell: { sheet: number; row: number; col: number }): unknown
35
+ destroy(): void
36
+ rebuildAndRecalculate(): void
37
+ }
38
+
39
+ export type HyperFormulaSheetConfig<T extends Record<string, unknown>> = {
40
+ /** The HF instance the consumer constructed (so they pick the
41
+ * license key + options). */
42
+ hyperformula: HyperFormulaInstance
43
+ /** Sheet index inside the HF instance. Default 0. */
44
+ sheetId?: number
45
+ /** Source rows. Cell values starting with `=` are evaluated. */
46
+ rows: T[]
47
+ /** Ordered list of fields to expose to the formula engine. The
48
+ * order determines the HF column index, which is how A1-style
49
+ * references resolve. */
50
+ fields: ReadonlyArray<keyof T & string>
51
+ }
52
+
53
+ export type HyperFormulaSheet<T extends Record<string, unknown>> = {
54
+ /** Rows with every `=...` formula replaced by its evaluated value.
55
+ * Use this in a custom cell renderer to DISPLAY the result. */
56
+ computed: T[]
57
+ /** Rows with formulas kept as their raw `=SUM(...)` strings.
58
+ * Pass this as `<SvGrid data={...}>` so the inline editor lets the
59
+ * user edit the formula text itself, not the evaluated value. */
60
+ raw: T[]
61
+ /** Call when a cell edit lands. Returns the new computed + raw
62
+ * snapshots so the consumer can reassign both. */
63
+ update(rowIndex: number, field: keyof T & string, value: unknown): {
64
+ computed: T[]
65
+ raw: T[]
66
+ }
67
+ /** Tear the adapter + the HF instance down (releases memory). */
68
+ destroy(): void
69
+ }
70
+
71
+ /** Build a live spreadsheet adapter around a HyperFormula instance.
72
+ * Returns computed rows + an `update()` hook to push edits back into
73
+ * the engine. */
74
+ export function createHyperFormulaSheet<T extends Record<string, unknown>>(
75
+ config: HyperFormulaSheetConfig<T>,
76
+ ): HyperFormulaSheet<T> {
77
+ const { hyperformula: hf, rows, fields } = config
78
+ const sheetId = config.sheetId ?? 0
79
+ const colByField = new Map<string, number>()
80
+ fields.forEach((f, i) => colByField.set(f as string, i))
81
+
82
+ // 1. Seed HF with every cell. HF expects raw strings for formulas
83
+ // (`'=A1+B1'`) and primitives for everything else.
84
+ for (let r = 0; r < rows.length; r += 1) {
85
+ const row = rows[r]!
86
+ for (let c = 0; c < fields.length; c += 1) {
87
+ const field = fields[c]! as string
88
+ hf.setCellContents({ sheet: sheetId, row: r, col: c }, row[field as keyof T])
89
+ }
90
+ }
91
+
92
+ /** Pull computed values out of HF into a fresh row array. Preserves
93
+ * any non-formula fields (i.e. those not in `fields`) untouched. */
94
+ function snapshot(): T[] {
95
+ const out: T[] = new Array(rows.length)
96
+ for (let r = 0; r < rows.length; r += 1) {
97
+ const next: Record<string, unknown> = { ...rows[r]! }
98
+ for (let c = 0; c < fields.length; c += 1) {
99
+ const field = fields[c]! as string
100
+ const v = hf.getCellValue({ sheet: sheetId, row: r, col: c })
101
+ next[field] = v
102
+ }
103
+ out[r] = next as T
104
+ }
105
+ return out
106
+ }
107
+
108
+ function rawSnapshot(): T[] {
109
+ return rows.map((r) => ({ ...r }))
110
+ }
111
+ return {
112
+ computed: snapshot(),
113
+ raw: rawSnapshot(),
114
+ update(rowIndex, field, value) {
115
+ const col = colByField.get(field as string)
116
+ if (col !== undefined) {
117
+ hf.setCellContents({ sheet: sheetId, row: rowIndex, col }, value)
118
+ }
119
+ rows[rowIndex] = { ...rows[rowIndex]!, [field]: value } as T
120
+ return { computed: snapshot(), raw: rawSnapshot() }
121
+ },
122
+ destroy() { hf.destroy() },
123
+ }
124
+ }