@svgrid/grid 1.2.21 → 1.2.23

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 (190) hide show
  1. package/dist/GridFooter.svelte +34 -20
  2. package/dist/GridFooter.svelte.d.ts +8 -0
  3. package/dist/SvAutoComplete.svelte +100 -0
  4. package/dist/SvAutoComplete.svelte.d.ts +16 -0
  5. package/dist/SvButton.svelte +97 -0
  6. package/dist/SvButton.svelte.d.ts +23 -0
  7. package/dist/SvCalendar.svelte +669 -0
  8. package/dist/SvCalendar.svelte.d.ts +70 -0
  9. package/dist/SvCheckBox.svelte +81 -0
  10. package/dist/SvCheckBox.svelte.d.ts +19 -0
  11. package/dist/SvColorInput.svelte +187 -0
  12. package/dist/SvColorInput.svelte.d.ts +15 -0
  13. package/dist/SvComboBox.svelte +130 -0
  14. package/dist/SvComboBox.svelte.d.ts +15 -0
  15. package/dist/SvCountryInput.svelte +123 -0
  16. package/dist/SvCountryInput.svelte.d.ts +14 -0
  17. package/dist/SvDateTimePicker.svelte +322 -0
  18. package/dist/SvDateTimePicker.svelte.d.ts +37 -0
  19. package/dist/SvDropDownList.svelte +143 -0
  20. package/dist/SvDropDownList.svelte.d.ts +15 -0
  21. package/dist/SvForm.svelte +147 -0
  22. package/dist/SvForm.svelte.d.ts +29 -0
  23. package/dist/SvGauge.svelte +99 -0
  24. package/dist/SvGauge.svelte.d.ts +31 -0
  25. package/dist/SvGrid.controller.svelte.d.ts +16 -2
  26. package/dist/SvGrid.controller.svelte.js +63 -8
  27. package/dist/SvGrid.css +84 -31
  28. package/dist/SvGrid.helpers.d.ts +4 -0
  29. package/dist/SvGrid.helpers.js +40 -12
  30. package/dist/SvGrid.svelte +84 -5
  31. package/dist/SvGrid.types.d.ts +36 -0
  32. package/dist/SvGridDropdown.svelte +16 -30
  33. package/dist/SvGridDropdown.svelte.d.ts +4 -0
  34. package/dist/SvListBox.svelte +122 -0
  35. package/dist/SvListBox.svelte.d.ts +19 -0
  36. package/dist/SvMaskedInput.svelte +0 -0
  37. package/dist/SvMaskedInput.svelte.d.ts +15 -0
  38. package/dist/SvNumberInput.svelte +0 -0
  39. package/dist/SvNumberInput.svelte.d.ts +22 -0
  40. package/dist/SvPasswordInput.svelte +110 -0
  41. package/dist/SvPasswordInput.svelte.d.ts +22 -0
  42. package/dist/SvPhoneInput.svelte +0 -0
  43. package/dist/SvPhoneInput.svelte.d.ts +19 -0
  44. package/dist/SvRadioGroup.svelte +108 -0
  45. package/dist/SvRadioGroup.svelte.d.ts +23 -0
  46. package/dist/SvRating.svelte +111 -0
  47. package/dist/SvRating.svelte.d.ts +20 -0
  48. package/dist/SvRepeatButton.svelte +89 -0
  49. package/dist/SvRepeatButton.svelte.d.ts +21 -0
  50. package/dist/SvSlider.svelte +182 -0
  51. package/dist/SvSlider.svelte.d.ts +25 -0
  52. package/dist/SvSwitchButton.svelte +94 -0
  53. package/dist/SvSwitchButton.svelte.d.ts +19 -0
  54. package/dist/SvTabs.svelte +122 -0
  55. package/dist/SvTabs.svelte.d.ts +26 -0
  56. package/dist/SvTagsInput.svelte +81 -0
  57. package/dist/SvTagsInput.svelte.d.ts +19 -0
  58. package/dist/SvTimePicker.svelte +359 -0
  59. package/dist/SvTimePicker.svelte.d.ts +27 -0
  60. package/dist/SvToggleButton.svelte +57 -0
  61. package/dist/SvToggleButton.svelte.d.ts +16 -0
  62. package/dist/SvTree.svelte +210 -0
  63. package/dist/SvTree.svelte.d.ts +29 -0
  64. package/dist/build-api.js +78 -1
  65. package/dist/cdn/svgrid.js +10022 -5904
  66. package/dist/cdn/svgrid.svelte-external.js +8531 -4429
  67. package/dist/cell-render.d.ts +4 -0
  68. package/dist/cell-render.js +35 -1
  69. package/dist/clipboard.js +19 -1
  70. package/dist/collaboration.d.ts +2 -0
  71. package/dist/collaboration.js +4 -0
  72. package/dist/core.d.ts +22 -1
  73. package/dist/countries.d.ts +15 -0
  74. package/dist/countries.js +61 -0
  75. package/dist/datetime/date-core.d.ts +88 -0
  76. package/dist/datetime/date-core.js +165 -0
  77. package/dist/datetime/date-format.d.ts +39 -0
  78. package/dist/datetime/date-format.js +371 -0
  79. package/dist/datetime/date-restrict.d.ts +23 -0
  80. package/dist/datetime/date-restrict.js +50 -0
  81. package/dist/datetime/date-selection.d.ts +25 -0
  82. package/dist/datetime/date-selection.js +94 -0
  83. package/dist/datetime/mask.d.ts +21 -0
  84. package/dist/datetime/mask.js +90 -0
  85. package/dist/editing.d.ts +1 -1
  86. package/dist/editing.js +7 -0
  87. package/dist/editors/cell-editors.d.ts +2 -2
  88. package/dist/editors/cell-editors.js +3 -1
  89. package/dist/export-format.d.ts +178 -0
  90. package/dist/export-format.js +419 -0
  91. package/dist/hyperformula-adapter.d.ts +4 -0
  92. package/dist/hyperformula-adapter.js +15 -6
  93. package/dist/index.d.ts +36 -0
  94. package/dist/index.js +41 -0
  95. package/dist/list-option.d.ts +10 -0
  96. package/dist/list-option.js +7 -0
  97. package/dist/menus.js +18 -2
  98. package/dist/popover.d.ts +48 -0
  99. package/dist/popover.js +65 -0
  100. package/dist/row-resize.d.ts +4 -4
  101. package/dist/row-resize.js +8 -5
  102. package/dist/selection.d.ts +6 -0
  103. package/dist/selection.js +31 -5
  104. package/dist/server-data-source.d.ts +43 -0
  105. package/dist/server-data-source.js +100 -0
  106. package/dist/sparkline.js +8 -4
  107. package/dist/svgrid-wrapper.types.d.ts +26 -1
  108. package/package.json +6 -1
  109. package/src/GridFooter.svelte +34 -20
  110. package/src/SvAutoComplete.svelte +100 -0
  111. package/src/SvButton.svelte +97 -0
  112. package/src/SvCalendar.svelte +669 -0
  113. package/src/SvCalendar.test.ts +211 -0
  114. package/src/SvCheckBox.svelte +81 -0
  115. package/src/SvColorInput.svelte +187 -0
  116. package/src/SvComboBox.svelte +130 -0
  117. package/src/SvCountryInput.svelte +123 -0
  118. package/src/SvDateTimePicker.svelte +322 -0
  119. package/src/SvDateTimePicker.test.ts +136 -0
  120. package/src/SvDropDownList.svelte +143 -0
  121. package/src/SvForm.svelte +147 -0
  122. package/src/SvGauge.svelte +99 -0
  123. package/src/SvGrid.controller.svelte.ts +74 -8
  124. package/src/SvGrid.css +84 -31
  125. package/src/SvGrid.helpers.ts +41 -12
  126. package/src/SvGrid.svelte +84 -5
  127. package/src/SvGrid.types.ts +33 -0
  128. package/src/SvGridDropdown.svelte +16 -30
  129. package/src/SvListBox.svelte +122 -0
  130. package/src/SvMaskedInput.svelte +0 -0
  131. package/src/SvNumberInput.svelte +0 -0
  132. package/src/SvPasswordInput.svelte +110 -0
  133. package/src/SvPhoneInput.svelte +0 -0
  134. package/src/SvRadioGroup.svelte +108 -0
  135. package/src/SvRating.svelte +111 -0
  136. package/src/SvRepeatButton.svelte +89 -0
  137. package/src/SvSlider.svelte +182 -0
  138. package/src/SvSwitchButton.svelte +94 -0
  139. package/src/SvTabs.svelte +122 -0
  140. package/src/SvTagsInput.svelte +81 -0
  141. package/src/SvTimePicker.svelte +359 -0
  142. package/src/SvTimePicker.test.ts +98 -0
  143. package/src/SvToggleButton.svelte +57 -0
  144. package/src/SvTree.svelte +210 -0
  145. package/src/build-api.ts +115 -0
  146. package/src/cell-render.test.ts +38 -0
  147. package/src/cell-render.ts +43 -0
  148. package/src/clipboard.test.ts +18 -0
  149. package/src/clipboard.ts +24 -1
  150. package/src/collaboration.test.ts +30 -0
  151. package/src/collaboration.ts +6 -0
  152. package/src/core.ts +27 -3
  153. package/src/countries.ts +71 -0
  154. package/src/datetime/date-core.test.ts +217 -0
  155. package/src/datetime/date-core.ts +204 -0
  156. package/src/datetime/date-format.test.ts +121 -0
  157. package/src/datetime/date-format.ts +317 -0
  158. package/src/datetime/date-restrict.ts +60 -0
  159. package/src/datetime/date-selection.test.ts +129 -0
  160. package/src/datetime/date-selection.ts +137 -0
  161. package/src/datetime/mask.test.ts +36 -0
  162. package/src/datetime/mask.ts +84 -0
  163. package/src/editing.test.ts +22 -0
  164. package/src/editing.ts +7 -1
  165. package/src/editors/cell-editors.ts +7 -1
  166. package/src/export-data-api.test.ts +126 -0
  167. package/src/export-format.test.ts +107 -0
  168. package/src/export-format.ts +598 -0
  169. package/src/hyperformula-adapter.test.ts +35 -1
  170. package/src/hyperformula-adapter.ts +18 -6
  171. package/src/index.ts +71 -0
  172. package/src/list-option.ts +15 -0
  173. package/src/menus.ts +21 -2
  174. package/src/popover.ts +79 -0
  175. package/src/row-resize.test.ts +25 -0
  176. package/src/row-resize.ts +8 -5
  177. package/src/selection.test.ts +36 -4
  178. package/src/selection.ts +30 -9
  179. package/src/server-data-source.test.ts +201 -0
  180. package/src/server-data-source.ts +148 -0
  181. package/src/sparkline.test.ts +9 -0
  182. package/src/sparkline.ts +9 -4
  183. package/src/svgrid-wrapper.types.ts +28 -1
  184. package/src/svgrid.behavior.test.ts +27 -0
  185. package/src/svgrid.new-features.wrapper.test.ts +27 -1
  186. package/src/ui-buttons.test.ts +105 -0
  187. package/src/ui-composite.test.ts +89 -0
  188. package/src/ui-inputs.test.ts +92 -0
  189. package/src/ui-range.test.ts +61 -0
  190. package/src/ui-selection.test.ts +106 -0
@@ -0,0 +1,84 @@
1
+ /**
2
+ * mask - a tiny pattern-mask engine shared by SvMaskedInput / SvPhoneInput.
3
+ * Pattern tokens:
4
+ * # a digit (0-9)
5
+ * A a letter (a-z A-Z)
6
+ * * a letter or digit
7
+ * Any other character is a literal that is auto-inserted. Framework-free.
8
+ */
9
+
10
+ const isDigit = (c: string) => c >= '0' && c <= '9'
11
+ const isAlpha = (c: string) => /[a-zA-Z]/.test(c)
12
+
13
+ function matches(token: string, ch: string): boolean {
14
+ if (token === '#') return isDigit(ch)
15
+ if (token === 'A') return isAlpha(ch)
16
+ if (token === '*') return isDigit(ch) || isAlpha(ch)
17
+ return false
18
+ }
19
+
20
+ const isToken = (c: string) => c === '#' || c === 'A' || c === '*'
21
+
22
+ /**
23
+ * Apply `pattern` to raw input `value`, inserting literals and dropping chars
24
+ * that don't fit the next token. Returns the formatted string and the count of
25
+ * consumed input characters (useful for caret math).
26
+ */
27
+ export function applyMask(value: string, pattern: string): { formatted: string; filled: number } {
28
+ let out = ''
29
+ let vi = 0
30
+ let filled = 0
31
+ for (let pi = 0; pi < pattern.length; pi++) {
32
+ const token = pattern[pi]!
33
+ if (!isToken(token)) {
34
+ // Literal: emit it only once we have (or will have) more input to place.
35
+ out += token
36
+ // Skip a matching literal the user may have typed.
37
+ if (value[vi] === token) vi++
38
+ continue
39
+ }
40
+ // Advance through input until a char fits this token.
41
+ while (vi < value.length && !matches(token, value[vi]!)) vi++
42
+ if (vi >= value.length) break // no more input for this token
43
+ out += value[vi]!
44
+ vi++
45
+ filled++
46
+ }
47
+ // Drop any trailing literals with no following data char.
48
+ return { formatted: trimTrailingLiterals(out), filled }
49
+ }
50
+
51
+ function trimTrailingLiterals(out: string): string {
52
+ // Count how many token-positions are filled; cut the string at the last
53
+ // filled data char plus any literals strictly before the next token.
54
+ let lastData = -1
55
+ for (let i = 0; i < out.length; i++) {
56
+ const c = out[i]!
57
+ if (isDigit(c) || isAlpha(c)) lastData = i
58
+ }
59
+ if (lastData < 0) return ''
60
+ // Keep literals that sit between data chars but trim the tail after last data.
61
+ return out.slice(0, lastData + 1)
62
+ }
63
+
64
+ /** Strip literals, returning only the data characters the user supplied. */
65
+ export function unmask(value: string, pattern: string): string {
66
+ let out = ''
67
+ let vi = 0
68
+ for (let pi = 0; pi < pattern.length && vi < value.length; pi++) {
69
+ const token = pattern[pi]!
70
+ if (!isToken(token)) {
71
+ if (value[vi] === token) vi++
72
+ continue
73
+ }
74
+ while (vi < value.length && !matches(token, value[vi]!)) vi++
75
+ if (vi < value.length) { out += value[vi]!; vi++ }
76
+ }
77
+ return out
78
+ }
79
+
80
+ /** True when every token position in the pattern is filled. */
81
+ export function isMaskComplete(value: string, pattern: string): boolean {
82
+ const tokenCount = [...pattern].filter(isToken).length
83
+ return unmask(value, pattern).length >= tokenCount
84
+ }
@@ -834,4 +834,26 @@ describe('clipboard fallbacks (non-paste branches only)', () => {
834
834
  expect(ctx.internalData[0]).toMatchObject({ a: 'X', b: 'Y' })
835
835
  expect(ctx.internalData[1]).toMatchObject({ a: 'Z', b: 'W' })
836
836
  })
837
+
838
+ it('onGridPaste bails while a cell is being edited (native editor paste wins)', () => {
839
+ Object.defineProperty(navigator, 'clipboard', {
840
+ value: undefined, // fallback path (Firefox / insecure) - would otherwise hijack
841
+ configurable: true,
842
+ })
843
+ const { ctx, ed } = editingFor({
844
+ columns: [{ id: 'a', field: 'a', editorType: 'text', editable: true }],
845
+ data: [{ a: 'orig' }],
846
+ })
847
+ ctx.selectionRange = { anchor: { rowIndex: 0, colIndex: 0 }, focus: { rowIndex: 0, colIndex: 0 } }
848
+ ctx.editingCell = { rowId: '0', columnId: 'a', editorType: 'text', value: 'orig' }
849
+ const ev = {
850
+ clipboardData: { getData: () => 'PASTED' },
851
+ preventDefault: vi.fn(),
852
+ } as unknown as ClipboardEvent
853
+ ed.onGridPaste(ev)
854
+ // The grid must NOT preventDefault (so the editor's native paste proceeds)
855
+ // and must NOT write to the data cell.
856
+ expect(ev.preventDefault).not.toHaveBeenCalled()
857
+ expect(ctx.internalData[0]).toMatchObject({ a: 'orig' })
858
+ })
837
859
  })
package/src/editing.ts CHANGED
@@ -342,7 +342,7 @@ export function createEditing<
342
342
  }
343
343
  }
344
344
 
345
- function updateEditingCellValue(value: string) {
345
+ function updateEditingCellValue(value: unknown) {
346
346
  ctx.editingCell = ctx.editingCell ? { ...ctx.editingCell, value } : ctx.editingCell;
347
347
  }
348
348
 
@@ -442,6 +442,12 @@ export function createEditing<
442
442
  * (no preventDefault) whenever the async API is unavailable.
443
443
  */
444
444
  function onGridPaste(event: ClipboardEvent) {
445
+ // A cell is being edited: the focused editor input handles its own paste
446
+ // natively. Never hijack it for a range paste - doing so (on Firefox /
447
+ // insecure contexts, where the async Clipboard API is unavailable) would
448
+ // preventDefault the editor's paste and write to the data cell instead,
449
+ // so the edit "wouldn't update".
450
+ if (ctx.editingCell) return;
445
451
  // When the async API is available the keydown handler already pasted via
446
452
  // pasteFromClipboard(); ignore the (suppressed) native event so we don't
447
453
  // paste twice.
@@ -4,6 +4,10 @@
4
4
  | 'date'
5
5
  | 'datetime'
6
6
  | 'time'
7
+ // Opt-out of the rich date/time pickers: render the plain native inputs.
8
+ | 'date-native'
9
+ | 'datetime-native'
10
+ | 'time-native'
7
11
  | 'password'
8
12
  | 'checkbox'
9
13
  | 'list'
@@ -50,10 +54,12 @@ export function normalizeEditorOptions(
50
54
  }
51
55
 
52
56
  export function parseEditorValue(
53
- type: CellEditorType,
57
+ rawType: CellEditorType,
54
58
  value: unknown,
55
59
  opts?: ParseEditorValueOptions,
56
60
  ) {
61
+ // `date-native` etc. parse identically to their rich counterparts.
62
+ const type = rawType.replace(/-native$/, '') as CellEditorType
57
63
  if (type === 'number') {
58
64
  const parsed = Number(value)
59
65
  return Number.isFinite(parsed) ? parsed : null
@@ -0,0 +1,126 @@
1
+ /**
2
+ * The free CSV / TSV / JSON export + copy-to-clipboard now on the grid API.
3
+ * Mounts a real <SvGrid /> and drives api.exportCsv/exportTsv/exportJson/
4
+ * copyToClipboard with download:false so nothing hits the DOM download path.
5
+ */
6
+ import { afterEach, describe, expect, it, vi } from 'vitest'
7
+ import { mount, unmount } from 'svelte'
8
+ import SvGrid from './SvGrid.svelte'
9
+ import {
10
+ columnFilteringFeature,
11
+ rowSelectionFeature,
12
+ rowSortingFeature,
13
+ tableFeatures,
14
+ } from './index'
15
+ import type { ColumnDef, SvGridApi } from './index'
16
+
17
+ type Row = { id: number; name: string; price: number; when: string }
18
+ const rows: Row[] = [
19
+ { id: 1, name: 'ACME, Inc', price: 1234.5, when: '2026-03-04' },
20
+ { id: 2, name: 'Globex', price: 20, when: '2026-06-01' },
21
+ ]
22
+ const columns: ColumnDef<any, Row>[] = [
23
+ { field: 'name', header: 'Company', width: 180 },
24
+ { field: 'price', header: 'Price', width: 120, align: 'right', format: { type: 'currency', currency: 'USD' } },
25
+ { field: 'when', header: 'Date', width: 120 }, // plain string, no format (deterministic)
26
+ ]
27
+
28
+ const features = tableFeatures({ columnFilteringFeature, rowSortingFeature, rowSelectionFeature })
29
+
30
+ function mountGrid(): Promise<{ api: SvGridApi<any, Row>; destroy: () => void }> {
31
+ return new Promise((resolve, reject) => {
32
+ const target = document.createElement('div')
33
+ document.body.appendChild(target)
34
+ let done = false
35
+ const app = mount(SvGrid, {
36
+ target,
37
+ props: {
38
+ data: rows.map((r) => ({ ...r })),
39
+ columns: columns.map((c) => ({ ...c })),
40
+ features,
41
+ getRowId: (r: Row) => String(r.id),
42
+ rowHeight: 34,
43
+ containerHeight: 400,
44
+ virtualization: false,
45
+ onApiReady(api: SvGridApi<any, Row>) {
46
+ done = true
47
+ resolve({ api, destroy: () => { unmount(app); target.remove() } })
48
+ },
49
+ } as any,
50
+ })
51
+ queueMicrotask(() => { if (!done) reject(new Error('onApiReady never fired')) })
52
+ })
53
+ }
54
+
55
+ let cleanup: (() => void) | null = null
56
+ afterEach(() => { cleanup?.(); cleanup = null; vi.restoreAllMocks() })
57
+
58
+ describe('free grid export: exportCsv', () => {
59
+ it('serializes visible rows with faithful formatted values + a BOM header', async () => {
60
+ const { api, destroy } = await mountGrid()
61
+ cleanup = destroy
62
+ const csv = await api.exportCsv({ download: false })
63
+ const lines = csv.replace(/^/, '').split('\r\n')
64
+ expect(lines[0]).toBe('Company,Price,Date')
65
+ // Formatted as on screen; the comma in "ACME, Inc" AND in "$1,234.50" both
66
+ // force RFC-4180 quoting.
67
+ expect(lines[1]).toBe('"ACME, Inc","$1,234.50",2026-03-04')
68
+ expect(csv.startsWith('')).toBe(true)
69
+ })
70
+
71
+ it('rawValues:true writes the underlying numbers/strings', async () => {
72
+ const { api, destroy } = await mountGrid()
73
+ cleanup = destroy
74
+ const csv = await api.exportCsv({ download: false, rawValues: true, bom: false })
75
+ const lines = csv.split('\r\n')
76
+ expect(lines[1]).toBe('"ACME, Inc",1234.5,2026-03-04')
77
+ })
78
+
79
+ it('honors a column subset in the given order', async () => {
80
+ const { api, destroy } = await mountGrid()
81
+ cleanup = destroy
82
+ const csv = await api.exportCsv({ download: false, bom: false, columns: ['when', 'name'] })
83
+ expect(csv.split('\r\n')[0]).toBe('Date,Company')
84
+ })
85
+ })
86
+
87
+ describe('free grid export: exportTsv / exportJson', () => {
88
+ it('exportTsv is tab-delimited', async () => {
89
+ const { api, destroy } = await mountGrid()
90
+ cleanup = destroy
91
+ const tsv = await api.exportTsv({ download: false, bom: false })
92
+ expect(tsv.split('\r\n')[0]).toBe('Company\tPrice\tDate')
93
+ })
94
+
95
+ it('exportJson emits an array of formatted records', async () => {
96
+ const { api, destroy } = await mountGrid()
97
+ cleanup = destroy
98
+ const json = JSON.parse(await api.exportJson({ download: false }))
99
+ expect(json).toHaveLength(2)
100
+ expect(json[0]).toEqual({ name: 'ACME, Inc', price: '$1,234.50', when: '2026-03-04' })
101
+ })
102
+ })
103
+
104
+ describe('free grid export: copyToClipboard', () => {
105
+ it('writes TSV to the clipboard by default', async () => {
106
+ const writeText = vi.fn().mockResolvedValue(undefined)
107
+ vi.stubGlobal('navigator', { clipboard: { writeText } })
108
+ const { api, destroy } = await mountGrid()
109
+ cleanup = destroy
110
+ const text = await api.copyToClipboard()
111
+ expect(writeText).toHaveBeenCalledOnce()
112
+ expect(text.split('\r\n')[0]).toBe('Company\tPrice\tDate')
113
+ expect(text.startsWith('')).toBe(false) // no BOM on clipboard
114
+ })
115
+
116
+ it('can copy a Markdown table', async () => {
117
+ const writeText = vi.fn().mockResolvedValue(undefined)
118
+ vi.stubGlobal('navigator', { clipboard: { writeText } })
119
+ const { api, destroy } = await mountGrid()
120
+ cleanup = destroy
121
+ const md = await api.copyToClipboard({ format: 'markdown' })
122
+ const lines = md.split('\n')
123
+ expect(lines[0]).toBe('| Company | Price | Date |')
124
+ expect(lines[1]).toBe('| --- | ---: | --- |') // Price is right-aligned
125
+ })
126
+ })
@@ -0,0 +1,107 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import {
3
+ coerceExportDate,
4
+ formatValueForExport,
5
+ toExcelNumFmt,
6
+ valueForExcel,
7
+ } from './export-format'
8
+ import type { CellFormatConfig } from './core'
9
+
10
+ describe('formatValueForExport', () => {
11
+ it('returns "" for null / undefined', () => {
12
+ expect(formatValueForExport(null, undefined)).toBe('')
13
+ expect(formatValueForExport(undefined, { type: 'number' })).toBe('')
14
+ })
15
+
16
+ it('stringifies when there is no format', () => {
17
+ expect(formatValueForExport(42, undefined)).toBe('42')
18
+ expect(formatValueForExport('hi', undefined)).toBe('hi')
19
+ })
20
+
21
+ it('formats currency like the grid does', () => {
22
+ const f: CellFormatConfig = { type: 'currency', currency: 'USD', locales: 'en-US' }
23
+ expect(formatValueForExport(19.95, f)).toBe('$19.95')
24
+ })
25
+
26
+ it('formats a percent from 0..100 points', () => {
27
+ const f: CellFormatConfig = { type: 'percent', valueIsPercentPoints: true, locales: 'en-US' }
28
+ expect(formatValueForExport(42, f)).toBe('42%')
29
+ })
30
+
31
+ it('formats a number with grouping', () => {
32
+ const f: CellFormatConfig = {
33
+ type: 'number',
34
+ locales: 'en-US',
35
+ options: { minimumFractionDigits: 2 },
36
+ }
37
+ expect(formatValueForExport(1234567, f)).toBe('1,234,567.00')
38
+ })
39
+
40
+ it('formats a date with the y-m-d pattern', () => {
41
+ const f: CellFormatConfig = { type: 'date', pattern: 'y-m-d', locales: 'en-US' }
42
+ expect(formatValueForExport(new Date('2026-03-04T00:00:00Z'), f)).toMatch(/2026/)
43
+ })
44
+
45
+ it('falls back to String() when a date value is not parseable', () => {
46
+ const f: CellFormatConfig = { type: 'date' }
47
+ expect(formatValueForExport('not-a-date', f)).toBe('not-a-date')
48
+ })
49
+ })
50
+
51
+ describe('coerceExportDate', () => {
52
+ it('accepts Date, epoch ms, and ISO strings; rejects junk', () => {
53
+ expect(coerceExportDate(new Date('2020-01-01')) instanceof Date).toBe(true)
54
+ expect(coerceExportDate(1_600_000_000_000) instanceof Date).toBe(true)
55
+ expect(coerceExportDate('2021-06-15') instanceof Date).toBe(true)
56
+ expect(coerceExportDate('nope')).toBeNull()
57
+ expect(coerceExportDate(new Date('bad'))).toBeNull()
58
+ expect(coerceExportDate(null)).toBeNull()
59
+ })
60
+ })
61
+
62
+ describe('toExcelNumFmt', () => {
63
+ it('maps number/currency/percent/date to Excel codes', () => {
64
+ expect(toExcelNumFmt({ type: 'number' })).toBe('#,##0')
65
+ expect(toExcelNumFmt({ type: 'number', options: { maximumFractionDigits: 2 } })).toBe('#,##0.00')
66
+ expect(toExcelNumFmt({ type: 'currency', currency: 'USD' })).toBe('"$"#,##0.00')
67
+ expect(toExcelNumFmt({ type: 'currency', currency: 'EUR' })).toBe('"€"#,##0.00')
68
+ expect(toExcelNumFmt({ type: 'percent' })).toBe('0.00%')
69
+ expect(toExcelNumFmt({ type: 'date' })).toBe('yyyy-mm-dd')
70
+ expect(toExcelNumFmt({ type: 'datetime' })).toBe('yyyy-mm-dd hh:mm')
71
+ })
72
+
73
+ it('falls back to the ISO code for currencies without a glyph', () => {
74
+ expect(toExcelNumFmt({ type: 'currency', currency: 'CHF' })).toBe('"CHF"#,##0.00')
75
+ })
76
+
77
+ it('returns undefined without a format', () => {
78
+ expect(toExcelNumFmt(undefined)).toBeUndefined()
79
+ })
80
+ })
81
+
82
+ describe('valueForExcel', () => {
83
+ it('keeps numbers/currency numeric', () => {
84
+ expect(valueForExcel(19.95, { type: 'currency' })).toEqual({ ok: true, value: 19.95 })
85
+ expect(valueForExcel(1234, { type: 'number' })).toEqual({ ok: true, value: 1234 })
86
+ })
87
+
88
+ it('divides percent points to a fraction', () => {
89
+ expect(valueForExcel(42, { type: 'percent', valueIsPercentPoints: true })).toEqual({
90
+ ok: true,
91
+ value: 0.42,
92
+ })
93
+ expect(valueForExcel(0.42, { type: 'percent' })).toEqual({ ok: true, value: 0.42 })
94
+ })
95
+
96
+ it('returns real Dates for date formats', () => {
97
+ const r = valueForExcel('2026-03-04', { type: 'date' })
98
+ expect(r.ok).toBe(true)
99
+ if (r.ok) expect(r.value).toBeInstanceOf(Date)
100
+ })
101
+
102
+ it('reports not-ok for non-representable values', () => {
103
+ expect(valueForExcel('abc', { type: 'number' })).toEqual({ ok: false })
104
+ expect(valueForExcel(5, undefined)).toEqual({ ok: false })
105
+ expect(valueForExcel(null, { type: 'number' })).toEqual({ ok: false })
106
+ })
107
+ })