@svgrid/grid 2.2.0 → 2.2.2

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 (114) hide show
  1. package/dist/FlexRender.svelte +96 -96
  2. package/dist/GridFooter.svelte +178 -178
  3. package/dist/SvCarousel.svelte +141 -141
  4. package/dist/SvColorInput.svelte +187 -187
  5. package/dist/SvContextMenu.svelte +116 -116
  6. package/dist/SvDrawer.svelte +250 -250
  7. package/dist/SvGrid.svelte +3131 -3131
  8. package/dist/SvGridBoard.svelte +2339 -2339
  9. package/dist/SvGridChart.svelte +1724 -1724
  10. package/dist/SvGridChartPanel.svelte +485 -485
  11. package/dist/SvGridDropdown.svelte +689 -689
  12. package/dist/SvGroupCell.svelte +109 -109
  13. package/dist/SvMenu.svelte +124 -124
  14. package/dist/SvMenuList.svelte +117 -117
  15. package/dist/SvNumberInput.svelte +131 -131
  16. package/dist/SvOtpInput.svelte +158 -158
  17. package/dist/SvPopover.svelte +139 -139
  18. package/dist/SvRowGroupPanel.svelte +170 -170
  19. package/dist/SvScrollArea.svelte +61 -61
  20. package/dist/SvTooltip.svelte +127 -127
  21. package/dist/SvTour.svelte +204 -204
  22. package/dist/SvTree.svelte +377 -377
  23. package/dist/SvTreeSelect.svelte +230 -230
  24. package/dist/cdn/svgrid.js +8 -8
  25. package/dist/cdn/svgrid.svelte-external.js +8 -8
  26. package/dist/chart-export.js +8 -8
  27. package/package.json +10 -10
  28. package/src/FlexRender.svelte +96 -96
  29. package/src/GridFooter.svelte +178 -178
  30. package/src/SvCarousel.svelte +141 -141
  31. package/src/SvColorInput.svelte +187 -187
  32. package/src/SvContextMenu.svelte +116 -116
  33. package/src/SvDrawer.svelte +250 -250
  34. package/src/SvGrid.controller.svelte.ts +3158 -3158
  35. package/src/SvGrid.svelte +3131 -3131
  36. package/src/SvGrid.types.ts +1489 -1489
  37. package/src/SvGridBoard.svelte +2339 -2339
  38. package/src/SvGridChart.svelte +1724 -1724
  39. package/src/SvGridChartPanel.svelte +485 -485
  40. package/src/SvGridDropdown.svelte +689 -689
  41. package/src/SvGroupCell.svelte +109 -109
  42. package/src/SvMenu.svelte +124 -124
  43. package/src/SvMenu.test.ts +97 -97
  44. package/src/SvMenuList.svelte +117 -117
  45. package/src/SvNumberInput.svelte +131 -131
  46. package/src/SvOtpInput.svelte +158 -158
  47. package/src/SvPopover.svelte +139 -139
  48. package/src/SvRowGroupPanel.svelte +170 -170
  49. package/src/SvScrollArea.svelte +61 -61
  50. package/src/SvTooltip.svelte +127 -127
  51. package/src/SvTour.svelte +204 -204
  52. package/src/SvTree.svelte +377 -377
  53. package/src/SvTreeSelect.svelte +230 -230
  54. package/src/a11y.contract.test.ts +49 -49
  55. package/src/a11y.test.ts +59 -59
  56. package/src/a11y.ts +61 -61
  57. package/src/build-api.ts +870 -870
  58. package/src/cell-formatting.ts +169 -169
  59. package/src/cell-render.ts +469 -469
  60. package/src/chart-export.ts +201 -201
  61. package/src/chart.ts +2296 -2296
  62. package/src/collaboration.test.ts +104 -104
  63. package/src/collaboration.ts +167 -167
  64. package/src/core.performance.test.ts +30 -30
  65. package/src/core.ts +1111 -1111
  66. package/src/createAutocomplete.svelte.ts +132 -132
  67. package/src/createCombobox.svelte.ts +179 -179
  68. package/src/createCountryInput.svelte.ts +157 -157
  69. package/src/createDropdownList.svelte.ts +162 -162
  70. package/src/createGrid.svelte.ts +42 -42
  71. package/src/createGrid.test.ts +10 -10
  72. package/src/createGridState.svelte.ts +17 -17
  73. package/src/createMenu.svelte.ts +202 -202
  74. package/src/createPopoverSelect.svelte.ts +206 -206
  75. package/src/createTree.svelte.ts +319 -319
  76. package/src/editing.test.ts +859 -859
  77. package/src/editing.ts +675 -675
  78. package/src/export-data-api.test.ts +126 -126
  79. package/src/export-format.test.ts +107 -107
  80. package/src/export-format.ts +598 -598
  81. package/src/flex-render.ts +3 -3
  82. package/src/index.ts +623 -623
  83. package/src/keyboard.test.ts +59 -59
  84. package/src/keyboard.ts +97 -97
  85. package/src/list-nav.test.ts +49 -49
  86. package/src/list-nav.ts +29 -29
  87. package/src/menus.ts +639 -639
  88. package/src/merge-objects.ts +48 -48
  89. package/src/overlays.test.ts +90 -90
  90. package/src/render-component.ts +28 -28
  91. package/src/selection.test.ts +754 -754
  92. package/src/selection.ts +600 -600
  93. package/src/server-data-source.test.ts +289 -289
  94. package/src/server-data-source.ts +413 -413
  95. package/src/sparkline.test.ts +68 -68
  96. package/src/sparkline.ts +169 -169
  97. package/src/spreadsheet.test.ts +489 -489
  98. package/src/spreadsheet.ts +312 -312
  99. package/src/static-functions.ts +11 -11
  100. package/src/subscribe.ts +38 -38
  101. package/src/svgrid-wrapper.types.ts +501 -501
  102. package/src/svgrid.behavior.test.ts +706 -706
  103. package/src/svgrid.charting.test.ts +527 -527
  104. package/src/svgrid.features.test.ts +157 -157
  105. package/src/svgrid.new-features.wrapper.test.ts +251 -251
  106. package/src/svgrid.wrapper.test.ts +40 -40
  107. package/src/test-setup.ts +62 -62
  108. package/src/themes/index.ts +159 -159
  109. package/src/virtualization/column-virtualizer.test.ts +27 -27
  110. package/src/virtualization/column-virtualizer.ts +30 -30
  111. package/src/virtualization/svelte-virtualizer.svelte.ts +26 -26
  112. package/src/virtualization/types.ts +30 -30
  113. package/src/virtualization/virtualizer.test.ts +47 -47
  114. package/src/virtualization/virtualizer.ts +296 -296
@@ -1,201 +1,201 @@
1
- /**
2
- * Export a rendered `SvGridChart` to a standalone SVG file or a PNG image.
3
- *
4
- * The on-screen chart styles its axes / labels / gridlines with CSS classes
5
- * and `--sg-*` theme variables, which don't survive a raw serialization. So
6
- * we clone the SVG, read the live computed colors, and inline a small `<style>`
7
- * block with concrete values - the export looks like what's on screen.
8
- *
9
- * Pass the chart's `<svg class="sv-grid-chart-svg">` element (or any ancestor
10
- * that contains it).
11
- */
12
- import type { ChartSpec } from './chart'
13
-
14
- function resolveSvg(el: SVGSVGElement | HTMLElement): SVGSVGElement | null {
15
- if (el instanceof SVGSVGElement) return el
16
- return el.querySelector('svg.sv-grid-chart-svg') ?? el.querySelector('svg')
17
- }
18
-
19
- function cssVar(el: Element, name: string, fallback: string): string {
20
- const v = getComputedStyle(el).getPropertyValue(name).trim()
21
- return v || fallback
22
- }
23
-
24
- export type ChartExportOptions = {
25
- /** Background color of the exported image. Default: the grid background. */
26
- background?: string
27
- /** PNG pixel scale (1 = viewBox size). Default 2 (retina). */
28
- scale?: number
29
- }
30
-
31
- /** Serialize the chart SVG to a standalone, self-styled SVG string. */
32
- export function chartToSvgString(
33
- source: SVGSVGElement | HTMLElement,
34
- options: ChartExportOptions = {},
35
- ): string {
36
- const svg = resolveSvg(source)
37
- if (!svg) throw new Error('chartToSvgString: no <svg> found')
38
-
39
- const fg = cssVar(svg, '--sg-fg', '#0f172a')
40
- const muted = cssVar(svg, '--sg-muted', '#64748b')
41
- const border = cssVar(svg, '--sg-border', '#e2e8f0')
42
- const bg = options.background ?? cssVar(svg, '--sg-bg', '#ffffff')
43
-
44
- const vb = svg.viewBox.baseVal
45
- const w = vb && vb.width ? vb.width : svg.clientWidth || 520
46
- const h = vb && vb.height ? vb.height : svg.clientHeight || 300
47
-
48
- const clone = svg.cloneNode(true) as SVGSVGElement
49
- clone.setAttribute('width', String(w))
50
- clone.setAttribute('height', String(h))
51
- clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
52
-
53
- // Inline computed paint/text styles so the export is what's on screen -
54
- // dynamic SVG presentation attributes (a line's `stroke={color}`) and scoped
55
- // component CSS don't survive a raw clone + XMLSerializer. Walk the live tree
56
- // and its clone (1:1 here, before we prune hit layers) and copy the resolved
57
- // style, so line paths etc. export with their real stroke instead of nothing.
58
- const PAINT_PROPS = [
59
- 'fill', 'fill-opacity', 'stroke', 'stroke-width', 'stroke-opacity',
60
- 'stroke-dasharray', 'stroke-linecap', 'stroke-linejoin', 'opacity',
61
- 'font-size', 'font-family', 'font-weight', 'text-anchor',
62
- ]
63
- const liveNodes = svg.querySelectorAll('*')
64
- const cloneNodes = clone.querySelectorAll('*')
65
- for (let i = 0; i < liveNodes.length; i += 1) {
66
- const el = cloneNodes[i] as (SVGElement & { style: CSSStyleDeclaration }) | undefined
67
- if (!el || !el.style) continue
68
- const cs = getComputedStyle(liveNodes[i]!)
69
- for (const prop of PAINT_PROPS) {
70
- const v = cs.getPropertyValue(prop)
71
- if (v && v !== 'normal') el.style.setProperty(prop, v)
72
- }
73
- }
74
-
75
- // Drop interaction-only hit layers.
76
- clone.querySelectorAll('.sv-grid-chart-hit').forEach((n) => n.remove())
77
-
78
- const style = document.createElementNS('http://www.w3.org/2000/svg', 'style')
79
- style.textContent = `
80
- .sv-grid-chart-axis { fill: ${muted}; font-size: 10px; font-family: sans-serif; }
81
- .sv-grid-chart-gridline { stroke: ${border}; stroke-width: 1; opacity: 0.6; }
82
- .sv-grid-chart-gridline.is-zero { stroke: ${muted}; opacity: 0.9; }
83
- .sv-grid-chart-datalabel { fill: ${fg}; font-size: 9.5px; font-weight: 600; font-family: sans-serif; }
84
- .sv-grid-chart-datalabel.on-bar { fill: #fff; }
85
- .sv-grid-chart-donut-total { fill: ${fg}; font-size: 16px; font-weight: 800; font-family: sans-serif; }
86
- .sv-grid-chart-donut-label { fill: ${muted}; font-size: 10px; font-family: sans-serif; }
87
- `
88
- clone.insertBefore(style, clone.firstChild)
89
-
90
- const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect')
91
- rect.setAttribute('x', '0')
92
- rect.setAttribute('y', '0')
93
- rect.setAttribute('width', String(w))
94
- rect.setAttribute('height', String(h))
95
- rect.setAttribute('fill', bg)
96
- clone.insertBefore(rect, style.nextSibling)
97
-
98
- return new XMLSerializer().serializeToString(clone)
99
- }
100
-
101
- function triggerDownload(blobUrl: string, filename: string) {
102
- const a = document.createElement('a')
103
- a.href = blobUrl
104
- a.download = filename
105
- document.body.appendChild(a)
106
- a.click()
107
- a.remove()
108
- }
109
-
110
- /** Download the chart as an `.svg` file. */
111
- export function downloadChartSvg(
112
- source: SVGSVGElement | HTMLElement,
113
- filename = 'chart.svg',
114
- options: ChartExportOptions = {},
115
- ): void {
116
- const svg = chartToSvgString(source, options)
117
- const url = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' }))
118
- triggerDownload(url, filename)
119
- setTimeout(() => URL.revokeObjectURL(url), 1000)
120
- }
121
-
122
- /** Rasterize the chart to a PNG `Blob`. */
123
- export function chartToPngBlob(
124
- source: SVGSVGElement | HTMLElement,
125
- options: ChartExportOptions = {},
126
- ): Promise<Blob> {
127
- const svgStr = chartToSvgString(source, options)
128
- const scale = options.scale ?? 2
129
- const svgEl = resolveSvg(source)!
130
- const vb = svgEl.viewBox.baseVal
131
- const w = (vb && vb.width ? vb.width : svgEl.clientWidth || 520) * scale
132
- const h = (vb && vb.height ? vb.height : svgEl.clientHeight || 300) * scale
133
-
134
- return new Promise((resolve, reject) => {
135
- const url = URL.createObjectURL(new Blob([svgStr], { type: 'image/svg+xml' }))
136
- const img = new Image()
137
- img.onload = () => {
138
- const canvas = document.createElement('canvas')
139
- canvas.width = Math.round(w)
140
- canvas.height = Math.round(h)
141
- const ctx = canvas.getContext('2d')
142
- if (!ctx) {
143
- URL.revokeObjectURL(url)
144
- reject(new Error('canvas 2d context unavailable'))
145
- return
146
- }
147
- ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
148
- URL.revokeObjectURL(url)
149
- canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error('toBlob failed'))), 'image/png')
150
- }
151
- img.onerror = () => {
152
- URL.revokeObjectURL(url)
153
- reject(new Error('failed to rasterize chart SVG'))
154
- }
155
- img.src = url
156
- })
157
- }
158
-
159
- /** Download the chart as a `.png` file. */
160
- export async function downloadChartPng(
161
- source: SVGSVGElement | HTMLElement,
162
- filename = 'chart.png',
163
- options: ChartExportOptions = {},
164
- ): Promise<void> {
165
- const blob = await chartToPngBlob(source, options)
166
- const url = URL.createObjectURL(blob)
167
- triggerDownload(url, filename)
168
- setTimeout(() => URL.revokeObjectURL(url), 1000)
169
- }
170
-
171
- const csvCell = (v: unknown): string => {
172
- const s = v == null ? '' : String(v)
173
- return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s
174
- }
175
-
176
- /**
177
- * Serialize a chart's data to CSV: one row per category, one column per series
178
- * (`Category, <series 1>, ...`). Empty for exotic specs (sankey/treemap/gauge/
179
- * calendar) that don't carry a rectangular categories x series grid.
180
- */
181
- export function chartSpecToCsv(spec: ChartSpec): string {
182
- const cats = spec.categories ?? []
183
- const series = spec.series ?? []
184
- if (!cats.length || !series.length) return ''
185
- const header = ['Category', ...series.map((s) => s.label)].map(csvCell).join(',')
186
- const rows = cats.map((cat, i) =>
187
- [cat, ...series.map((s) => s.values[i] ?? '')].map(csvCell).join(','),
188
- )
189
- return [header, ...rows].join('\n')
190
- }
191
-
192
- /** Download the chart's data as a `.csv` file. Returns false if there's no
193
- * rectangular category/series data to export. */
194
- export function downloadChartCsv(spec: ChartSpec, filename = 'chart.csv'): boolean {
195
- const csv = chartSpecToCsv(spec)
196
- if (!csv) return false
197
- const url = URL.createObjectURL(new Blob([csv], { type: 'text/csv;charset=utf-8' }))
198
- triggerDownload(url, filename)
199
- setTimeout(() => URL.revokeObjectURL(url), 1000)
200
- return true
201
- }
1
+ /**
2
+ * Export a rendered `SvGridChart` to a standalone SVG file or a PNG image.
3
+ *
4
+ * The on-screen chart styles its axes / labels / gridlines with CSS classes
5
+ * and `--sg-*` theme variables, which don't survive a raw serialization. So
6
+ * we clone the SVG, read the live computed colors, and inline a small `<style>`
7
+ * block with concrete values - the export looks like what's on screen.
8
+ *
9
+ * Pass the chart's `<svg class="sv-grid-chart-svg">` element (or any ancestor
10
+ * that contains it).
11
+ */
12
+ import type { ChartSpec } from './chart'
13
+
14
+ function resolveSvg(el: SVGSVGElement | HTMLElement): SVGSVGElement | null {
15
+ if (el instanceof SVGSVGElement) return el
16
+ return el.querySelector('svg.sv-grid-chart-svg') ?? el.querySelector('svg')
17
+ }
18
+
19
+ function cssVar(el: Element, name: string, fallback: string): string {
20
+ const v = getComputedStyle(el).getPropertyValue(name).trim()
21
+ return v || fallback
22
+ }
23
+
24
+ export type ChartExportOptions = {
25
+ /** Background color of the exported image. Default: the grid background. */
26
+ background?: string
27
+ /** PNG pixel scale (1 = viewBox size). Default 2 (retina). */
28
+ scale?: number
29
+ }
30
+
31
+ /** Serialize the chart SVG to a standalone, self-styled SVG string. */
32
+ export function chartToSvgString(
33
+ source: SVGSVGElement | HTMLElement,
34
+ options: ChartExportOptions = {},
35
+ ): string {
36
+ const svg = resolveSvg(source)
37
+ if (!svg) throw new Error('chartToSvgString: no <svg> found')
38
+
39
+ const fg = cssVar(svg, '--sg-fg', '#0f172a')
40
+ const muted = cssVar(svg, '--sg-muted', '#64748b')
41
+ const border = cssVar(svg, '--sg-border', '#e2e8f0')
42
+ const bg = options.background ?? cssVar(svg, '--sg-bg', '#ffffff')
43
+
44
+ const vb = svg.viewBox.baseVal
45
+ const w = vb && vb.width ? vb.width : svg.clientWidth || 520
46
+ const h = vb && vb.height ? vb.height : svg.clientHeight || 300
47
+
48
+ const clone = svg.cloneNode(true) as SVGSVGElement
49
+ clone.setAttribute('width', String(w))
50
+ clone.setAttribute('height', String(h))
51
+ clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
52
+
53
+ // Inline computed paint/text styles so the export is what's on screen -
54
+ // dynamic SVG presentation attributes (a line's `stroke={color}`) and scoped
55
+ // component CSS don't survive a raw clone + XMLSerializer. Walk the live tree
56
+ // and its clone (1:1 here, before we prune hit layers) and copy the resolved
57
+ // style, so line paths etc. export with their real stroke instead of nothing.
58
+ const PAINT_PROPS = [
59
+ 'fill', 'fill-opacity', 'stroke', 'stroke-width', 'stroke-opacity',
60
+ 'stroke-dasharray', 'stroke-linecap', 'stroke-linejoin', 'opacity',
61
+ 'font-size', 'font-family', 'font-weight', 'text-anchor',
62
+ ]
63
+ const liveNodes = svg.querySelectorAll('*')
64
+ const cloneNodes = clone.querySelectorAll('*')
65
+ for (let i = 0; i < liveNodes.length; i += 1) {
66
+ const el = cloneNodes[i] as (SVGElement & { style: CSSStyleDeclaration }) | undefined
67
+ if (!el || !el.style) continue
68
+ const cs = getComputedStyle(liveNodes[i]!)
69
+ for (const prop of PAINT_PROPS) {
70
+ const v = cs.getPropertyValue(prop)
71
+ if (v && v !== 'normal') el.style.setProperty(prop, v)
72
+ }
73
+ }
74
+
75
+ // Drop interaction-only hit layers.
76
+ clone.querySelectorAll('.sv-grid-chart-hit').forEach((n) => n.remove())
77
+
78
+ const style = document.createElementNS('http://www.w3.org/2000/svg', 'style')
79
+ style.textContent = `
80
+ .sv-grid-chart-axis { fill: ${muted}; font-size: 10px; font-family: sans-serif; }
81
+ .sv-grid-chart-gridline { stroke: ${border}; stroke-width: 1; opacity: 0.6; }
82
+ .sv-grid-chart-gridline.is-zero { stroke: ${muted}; opacity: 0.9; }
83
+ .sv-grid-chart-datalabel { fill: ${fg}; font-size: 9.5px; font-weight: 600; font-family: sans-serif; }
84
+ .sv-grid-chart-datalabel.on-bar { fill: #fff; }
85
+ .sv-grid-chart-donut-total { fill: ${fg}; font-size: 16px; font-weight: 800; font-family: sans-serif; }
86
+ .sv-grid-chart-donut-label { fill: ${muted}; font-size: 10px; font-family: sans-serif; }
87
+ `
88
+ clone.insertBefore(style, clone.firstChild)
89
+
90
+ const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect')
91
+ rect.setAttribute('x', '0')
92
+ rect.setAttribute('y', '0')
93
+ rect.setAttribute('width', String(w))
94
+ rect.setAttribute('height', String(h))
95
+ rect.setAttribute('fill', bg)
96
+ clone.insertBefore(rect, style.nextSibling)
97
+
98
+ return new XMLSerializer().serializeToString(clone)
99
+ }
100
+
101
+ function triggerDownload(blobUrl: string, filename: string) {
102
+ const a = document.createElement('a')
103
+ a.href = blobUrl
104
+ a.download = filename
105
+ document.body.appendChild(a)
106
+ a.click()
107
+ a.remove()
108
+ }
109
+
110
+ /** Download the chart as an `.svg` file. */
111
+ export function downloadChartSvg(
112
+ source: SVGSVGElement | HTMLElement,
113
+ filename = 'chart.svg',
114
+ options: ChartExportOptions = {},
115
+ ): void {
116
+ const svg = chartToSvgString(source, options)
117
+ const url = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' }))
118
+ triggerDownload(url, filename)
119
+ setTimeout(() => URL.revokeObjectURL(url), 1000)
120
+ }
121
+
122
+ /** Rasterize the chart to a PNG `Blob`. */
123
+ export function chartToPngBlob(
124
+ source: SVGSVGElement | HTMLElement,
125
+ options: ChartExportOptions = {},
126
+ ): Promise<Blob> {
127
+ const svgStr = chartToSvgString(source, options)
128
+ const scale = options.scale ?? 2
129
+ const svgEl = resolveSvg(source)!
130
+ const vb = svgEl.viewBox.baseVal
131
+ const w = (vb && vb.width ? vb.width : svgEl.clientWidth || 520) * scale
132
+ const h = (vb && vb.height ? vb.height : svgEl.clientHeight || 300) * scale
133
+
134
+ return new Promise((resolve, reject) => {
135
+ const url = URL.createObjectURL(new Blob([svgStr], { type: 'image/svg+xml' }))
136
+ const img = new Image()
137
+ img.onload = () => {
138
+ const canvas = document.createElement('canvas')
139
+ canvas.width = Math.round(w)
140
+ canvas.height = Math.round(h)
141
+ const ctx = canvas.getContext('2d')
142
+ if (!ctx) {
143
+ URL.revokeObjectURL(url)
144
+ reject(new Error('canvas 2d context unavailable'))
145
+ return
146
+ }
147
+ ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
148
+ URL.revokeObjectURL(url)
149
+ canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error('toBlob failed'))), 'image/png')
150
+ }
151
+ img.onerror = () => {
152
+ URL.revokeObjectURL(url)
153
+ reject(new Error('failed to rasterize chart SVG'))
154
+ }
155
+ img.src = url
156
+ })
157
+ }
158
+
159
+ /** Download the chart as a `.png` file. */
160
+ export async function downloadChartPng(
161
+ source: SVGSVGElement | HTMLElement,
162
+ filename = 'chart.png',
163
+ options: ChartExportOptions = {},
164
+ ): Promise<void> {
165
+ const blob = await chartToPngBlob(source, options)
166
+ const url = URL.createObjectURL(blob)
167
+ triggerDownload(url, filename)
168
+ setTimeout(() => URL.revokeObjectURL(url), 1000)
169
+ }
170
+
171
+ const csvCell = (v: unknown): string => {
172
+ const s = v == null ? '' : String(v)
173
+ return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s
174
+ }
175
+
176
+ /**
177
+ * Serialize a chart's data to CSV: one row per category, one column per series
178
+ * (`Category, <series 1>, ...`). Empty for exotic specs (sankey/treemap/gauge/
179
+ * calendar) that don't carry a rectangular categories x series grid.
180
+ */
181
+ export function chartSpecToCsv(spec: ChartSpec): string {
182
+ const cats = spec.categories ?? []
183
+ const series = spec.series ?? []
184
+ if (!cats.length || !series.length) return ''
185
+ const header = ['Category', ...series.map((s) => s.label)].map(csvCell).join(',')
186
+ const rows = cats.map((cat, i) =>
187
+ [cat, ...series.map((s) => s.values[i] ?? '')].map(csvCell).join(','),
188
+ )
189
+ return [header, ...rows].join('\n')
190
+ }
191
+
192
+ /** Download the chart's data as a `.csv` file. Returns false if there's no
193
+ * rectangular category/series data to export. */
194
+ export function downloadChartCsv(spec: ChartSpec, filename = 'chart.csv'): boolean {
195
+ const csv = chartSpecToCsv(spec)
196
+ if (!csv) return false
197
+ const url = URL.createObjectURL(new Blob([csv], { type: 'text/csv;charset=utf-8' }))
198
+ triggerDownload(url, filename)
199
+ setTimeout(() => URL.revokeObjectURL(url), 1000)
200
+ return true
201
+ }