@svgrid/grid 2.1.23 → 2.2.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 (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,598 +1,598 @@
1
- /**
2
- * Pure, render-free value formatting for data export. The grid's on-screen
3
- * `formatCellValue` (see cell-render.ts) is a closure bound to a `Row<TData>`
4
- * and the live table, so it can't be reused directly by an exporter that only
5
- * has raw values + a column's `format` config. These helpers replicate the
6
- * numeric / date / percent branches of that formatter as standalone functions:
7
- *
8
- * - `formatValueForExport(value, format)` returns the display STRING a user
9
- * sees on screen, so CSV / TSV / HTML / PDF exports are faithful to the
10
- * grid ("what you see is what you export") instead of dumping raw values.
11
- * - `toExcelNumFmt(format)` maps a `CellFormatConfig` to an Excel number
12
- * format code, so an xlsx cell can stay a real number / date while still
13
- * displaying formatted (currency symbol, thousands, date pattern).
14
- *
15
- * Custom per-row `formatter` callbacks are intentionally NOT handled here -
16
- * they may close over row/table state. Columns that need custom export text
17
- * should provide an `exportValue(row)` hook at the export layer instead.
18
- */
19
- import type { CellFormatConfig } from './core'
20
- import {
21
- formatNumericWithConfig,
22
- getDateFormatter,
23
- resolveDatePattern,
24
- } from './cell-formatting'
25
-
26
- // Re-export the pure conditional-formatting engine here too, so the
27
- // Svelte-free `@svgrid/grid/format` subpath carries it for @svgrid/enterprise's
28
- // export code (which must not pull in SvGrid.svelte).
29
- export {
30
- computeColumnStat,
31
- contrastText,
32
- formatsNeedingStats,
33
- resolveCellFormat,
34
- type ColumnStat,
35
- type ConditionalFormat,
36
- type ResolvedCellFormat,
37
- } from './conditional-formatting'
38
-
39
- /** Best-effort coercion of a cell value to a Date. Accepts Date, epoch ms
40
- * numbers, and parseable date strings. Returns null when it isn't a date. */
41
- export function coerceExportDate(value: unknown): Date | null {
42
- if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value
43
- if (typeof value === 'number' && Number.isFinite(value)) {
44
- const d = new Date(value)
45
- return Number.isNaN(d.getTime()) ? null : d
46
- }
47
- if (typeof value === 'string' && value.trim() !== '') {
48
- const d = new Date(value)
49
- return Number.isNaN(d.getTime()) ? null : d
50
- }
51
- return null
52
- }
53
-
54
- /**
55
- * Format a raw cell value to its on-screen display string using the column's
56
- * `format` config. Mirrors the grid's own numeric / currency / percent / date
57
- * branches. Values with no (or an unrecognised) format fall back to
58
- * `String(value)`, and `null` / `undefined` become an empty string.
59
- */
60
- export function formatValueForExport(
61
- value: unknown,
62
- format: CellFormatConfig | undefined,
63
- ): string {
64
- if (value == null) return ''
65
- if (!format) return String(value)
66
-
67
- if (format.type === 'number' || format.type === 'currency' || format.type === 'percent') {
68
- return formatNumericWithConfig(value, {
69
- type: format.type,
70
- locales: format.locales,
71
- currency: format.type === 'currency' ? (format.currency ?? 'USD') : undefined,
72
- valueIsPercentPoints:
73
- format.type === 'percent' ? format.valueIsPercentPoints : undefined,
74
- options: format.options,
75
- })
76
- }
77
-
78
- if (format.type === 'date' || format.type === 'datetime') {
79
- const parsed = coerceExportDate(value)
80
- if (parsed) {
81
- const preset = resolveDatePattern(format.pattern, format.type)
82
- const merged: Intl.DateTimeFormatOptions =
83
- preset || format.options
84
- ? { ...preset, ...format.options }
85
- : format.type === 'date'
86
- ? { year: 'numeric', month: '2-digit', day: '2-digit' }
87
- : {
88
- year: 'numeric',
89
- month: '2-digit',
90
- day: '2-digit',
91
- hour: '2-digit',
92
- minute: '2-digit',
93
- }
94
- return getDateFormatter(format.locales, merged).format(parsed)
95
- }
96
- }
97
-
98
- return String(value)
99
- }
100
-
101
- /**
102
- * Map a `CellFormatConfig` to an Excel/OOXML number-format code, so an xlsx
103
- * writer can keep the cell numeric/date while displaying it formatted.
104
- * Returns `undefined` when the format has no natural Excel representation
105
- * (or the caller should just write a string).
106
- *
107
- * These are deliberately conservative, widely-recognised codes:
108
- * number → `#,##0[.00…]` (grouping + N decimals)
109
- * currency → `"$"#,##0.00` (symbol + grouping + 2 decimals)
110
- * percent → `0[.00…]%` (Excel multiplies by 100, so this pairs with a
111
- * 0..1 fraction; see `valueForExcel`)
112
- * date → `yyyy-mm-dd`, datetime → `yyyy-mm-dd hh:mm`
113
- */
114
- export function toExcelNumFmt(format: CellFormatConfig | undefined): string | undefined {
115
- if (!format) return undefined
116
-
117
- const decimals = (): number => {
118
- // `options` is a union across number/date formats; only the numeric ones
119
- // carry fraction-digit hints, so read them through a narrow shape.
120
- const o = format.options as
121
- | { maximumFractionDigits?: number; minimumFractionDigits?: number }
122
- | undefined
123
- if (o && typeof o.maximumFractionDigits === 'number') return o.maximumFractionDigits
124
- if (o && typeof o.minimumFractionDigits === 'number') return o.minimumFractionDigits
125
- return format.type === 'currency' ? 2 : format.type === 'number' ? 0 : 2
126
- }
127
- const dp = (n: number) => (n > 0 ? '.' + '0'.repeat(n) : '')
128
-
129
- switch (format.type) {
130
- case 'number':
131
- return `#,##0${dp(decimals())}`
132
- case 'currency': {
133
- const sym = currencySymbol(format.currency ?? 'USD')
134
- return `"${sym}"#,##0${dp(decimals())}`
135
- }
136
- case 'percent':
137
- return `0${dp(decimals())}%`
138
- case 'date':
139
- return 'yyyy-mm-dd'
140
- case 'datetime':
141
- return 'yyyy-mm-dd hh:mm'
142
- default:
143
- return undefined
144
- }
145
- }
146
-
147
- /**
148
- * Turn a grid's data rows + columns into the header-first `{ field: value }`
149
- * record shape the serializers consume, applying each column's `format` so
150
- * the export matches what's on screen (unless `rawValues`). Optionally
151
- * restricts + reorders columns to a `columns` field subset.
152
- */
153
- export function projectGridRows(
154
- dataRows: ReadonlyArray<Record<string, unknown>>,
155
- columns: ReadonlyArray<GridExportColumn>,
156
- opts: { columns?: ReadonlyArray<string>; rawValues?: boolean } = {},
157
- ): {
158
- records: Array<Record<string, unknown>>
159
- fields: string[]
160
- align: Record<string, 'left' | 'center' | 'right'>
161
- } {
162
- const chosen =
163
- opts.columns && opts.columns.length
164
- ? opts.columns
165
- .map((f) => columns.find((c) => c.field === f))
166
- .filter((c): c is GridExportColumn => !!c)
167
- : columns.filter((c) => c.field)
168
- const fields = chosen.map((c) => c.field)
169
- const align: Record<string, 'left' | 'center' | 'right'> = {}
170
- for (const c of chosen) if (c.align) align[c.field] = c.align
171
-
172
- const header: Record<string, unknown> = {}
173
- for (const c of chosen) header[c.field] = c.header
174
- const records: Array<Record<string, unknown>> = [header]
175
- for (const row of dataRows) {
176
- const rec: Record<string, unknown> = {}
177
- for (const c of chosen) {
178
- const raw = row[c.field]
179
- rec[c.field] = opts.rawValues ? raw : formatValueForExport(raw, c.format)
180
- }
181
- records.push(rec)
182
- }
183
- return { records, fields, align }
184
- }
185
-
186
- /** A tiny currency-code → symbol map for the Excel numFmt code. Falls back
187
- * to the ISO code itself (e.g. "CHF") when we don't have a glyph. */
188
- function currencySymbol(code: string): string {
189
- const map: Record<string, string> = {
190
- USD: '$',
191
- EUR: '€',
192
- GBP: '£',
193
- JPY: '¥',
194
- CNY: '¥',
195
- INR: '₹',
196
- KRW: '₩',
197
- RUB: '₽',
198
- BRL: 'R$',
199
- }
200
- return map[code.toUpperCase()] ?? code.toUpperCase()
201
- }
202
-
203
- /**
204
- * The value to write into a native xlsx cell that carries an Excel numFmt.
205
- * Numbers stay numbers; percent values are divided to the 0..1 fraction Excel
206
- * expects (unless the config already stores 0..1); dates become real `Date`s.
207
- * Returns `{ ok: false }` when the value can't be represented natively and the
208
- * caller should fall back to the formatted string.
209
- */
210
- export function valueForExcel(
211
- value: unknown,
212
- format: CellFormatConfig | undefined,
213
- ): { ok: true; value: number | Date } | { ok: false } {
214
- if (value == null || !format) return { ok: false }
215
-
216
- if (format.type === 'number' || format.type === 'currency') {
217
- const n = typeof value === 'number' ? value : Number(value)
218
- return Number.isFinite(n) ? { ok: true, value: n } : { ok: false }
219
- }
220
- if (format.type === 'percent') {
221
- const n = typeof value === 'number' ? value : Number(value)
222
- if (!Number.isFinite(n)) return { ok: false }
223
- // Excel's percent numFmt multiplies by 100, so it wants the fraction.
224
- return { ok: true, value: format.valueIsPercentPoints === true ? n / 100 : n }
225
- }
226
- if (format.type === 'date' || format.type === 'datetime') {
227
- const d = coerceExportDate(value)
228
- return d ? { ok: true, value: d } : { ok: false }
229
- }
230
- return { ok: false }
231
- }
232
-
233
- // ===========================================================================
234
- // Free data export (CSV / TSV / JSON) + delivery. Kept in this same
235
- // Svelte-free module (the `@svgrid/grid/format` subpath) so @svgrid/enterprise
236
- // re-uses ONE implementation of each serializer. Input is already-projected
237
- // rows: an array of `{ field: value }` records whose FIRST record is the
238
- // header row. Use `projectGridRows` above to build that shape.
239
- // ===========================================================================
240
-
241
- // ----- Public option types (shared by the grid API export methods) ---------
242
-
243
- export type GridExportScope = 'displayed' | 'selected' | 'all'
244
-
245
- /** The slice of a grid column an exporter needs. Accepts `api.getColumns()`. */
246
- export type GridExportColumn = {
247
- field: string
248
- header: string
249
- format?: CellFormatConfig | undefined
250
- align?: 'left' | 'center' | 'right'
251
- }
252
-
253
- export type GridExportOptions = {
254
- /** Base filename (no extension). Default 'grid'. */
255
- filename?: string
256
- /** Which rows to export. Default 'displayed' (current view). */
257
- rows?: GridExportScope
258
- /** Restrict to these fields, in this order. Default: all visible columns. */
259
- columns?: string[]
260
- /** Export raw values instead of the on-screen formatted display. Default false. */
261
- rawValues?: boolean
262
- /** Prepend a UTF-8 BOM (csv/tsv) so Excel detects UTF-8. Default true. */
263
- bom?: boolean
264
- /** Cancel a large export. */
265
- signal?: AbortSignal
266
- /** Progress for large exports. */
267
- onProgress?: (progress: SerializeProgress) => void
268
- /** When false, skip the browser download and just return the text. Default true. */
269
- download?: boolean
270
- }
271
-
272
- export type GridClipboardFormat = 'csv' | 'tsv' | 'markdown'
273
-
274
- export type GridClipboardOptions = {
275
- /** Clipboard payload format. Default 'tsv' (pastes straight into Excel). */
276
- format?: GridClipboardFormat
277
- rows?: GridExportScope
278
- columns?: string[]
279
- rawValues?: boolean
280
- }
281
-
282
- // ----- Serializers ---------------------------------------------------------
283
-
284
- export type SerializeProgress = {
285
- phase: 'serialize'
286
- /** 0..1 completion of the row walk. */
287
- ratio: number
288
- row: number
289
- total: number
290
- }
291
-
292
- export type CsvOptions = {
293
- /** Field delimiter. Default ',' (','→CSV, '\t'→TSV). */
294
- delimiter?: string
295
- /** Line ending between records. Default '\r\n' (Excel-friendly). */
296
- eol?: string
297
- /** Prepend a UTF-8 BOM so Excel detects UTF-8. Default true for csv/tsv. */
298
- bom?: boolean
299
- }
300
-
301
- export type SerializeOptions = {
302
- onProgress?: (p: SerializeProgress) => void
303
- signal?: AbortSignal
304
- csv?: CsvOptions
305
- /** Rows processed between event-loop yields. Default 5000. */
306
- chunkRows?: number
307
- }
308
-
309
- const EXPORT_BOM = ''
310
-
311
- function throwIfAborted(signal: AbortSignal | undefined): void {
312
- if (signal?.aborted) {
313
- throw new DOMException('Export aborted', 'AbortError')
314
- }
315
- }
316
-
317
- /** Let the event loop breathe (paint a progress bar, honour an abort). */
318
- const yieldToLoop = (): Promise<void> =>
319
- new Promise((resolve) => setTimeout(resolve, 0))
320
-
321
- /** RFC-4180 quoting: wrap in double quotes and double any embedded quote
322
- * when the value contains the delimiter, a quote, or a newline. */
323
- function csvCell(value: unknown, delimiter: string): string {
324
- const s =
325
- value == null
326
- ? ''
327
- : value instanceof Date
328
- ? value.toISOString()
329
- : String(value)
330
- if (s === '') return s
331
- if (s.includes(delimiter) || s.includes('"') || s.includes('\n') || s.includes('\r')) {
332
- return `"${s.replace(/"/g, '""')}"`
333
- }
334
- return s
335
- }
336
-
337
- /**
338
- * Serialize projected rows to a delimited string (CSV / TSV).
339
- * `rows[0]` is treated as the header row.
340
- */
341
- export async function serializeDelimited(
342
- rows: ReadonlyArray<Record<string, unknown>>,
343
- fields: ReadonlyArray<string>,
344
- opts: SerializeOptions = {},
345
- ): Promise<string> {
346
- const delimiter = opts.csv?.delimiter ?? ','
347
- const eol = opts.csv?.eol ?? '\r\n'
348
- const useBom = opts.csv?.bom ?? true
349
- const chunk = Math.max(1, opts.chunkRows ?? 5000)
350
- const total = rows.length
351
-
352
- const parts: string[] = []
353
- for (let i = 0; i < rows.length; i++) {
354
- throwIfAborted(opts.signal)
355
- const row = rows[i]!
356
- parts.push(fields.map((f) => csvCell(row[f], delimiter)).join(delimiter))
357
- if (i > 0 && i % chunk === 0) {
358
- opts.onProgress?.({ phase: 'serialize', ratio: i / total, row: i, total })
359
- await yieldToLoop()
360
- }
361
- }
362
- opts.onProgress?.({ phase: 'serialize', ratio: 1, row: total, total })
363
- const body = parts.join(eol)
364
- return (useBom ? EXPORT_BOM : '') + body
365
- }
366
-
367
- const HTML_ESCAPE: Record<string, string> = {
368
- '&': '&amp;',
369
- '<': '&lt;',
370
- '>': '&gt;',
371
- '"': '&quot;',
372
- "'": '&#39;',
373
- }
374
- function htmlCell(value: unknown): string {
375
- const s =
376
- value == null ? '' : value instanceof Date ? value.toISOString() : String(value)
377
- return s.replace(/[&<>"']/g, (c) => HTML_ESCAPE[c]!)
378
- }
379
-
380
- export type ExportCellVisual = { fill?: string; color?: string; bold?: boolean; icon?: string }
381
-
382
- /**
383
- * Serialize projected rows to a standalone HTML `<table>` document.
384
- * `rows[0]` is the header row (rendered as `<th>`); the rest are `<td>`.
385
- */
386
- export async function serializeHtml(
387
- rows: ReadonlyArray<Record<string, unknown>>,
388
- fields: ReadonlyArray<string>,
389
- opts: SerializeOptions & {
390
- title?: string
391
- align?: Record<string, 'left' | 'center' | 'right'>
392
- /** Per-data-cell conditional-format visual (`rowIdx` is 0-based over data). */
393
- cellStyle?: (rowIdx: number, colIdx: number) => ExportCellVisual | undefined
394
- /** Per-data-cell hyperlink URL. */
395
- cellLink?: (rowIdx: number, colIdx: number) => string | undefined
396
- } = {},
397
- ): Promise<string> {
398
- const chunk = Math.max(1, opts.chunkRows ?? 5000)
399
- const total = rows.length
400
- const align = opts.align ?? {}
401
- const cellStyle = opts.cellStyle
402
- const cellLink = opts.cellLink
403
- const title = opts.title ?? 'Grid export'
404
-
405
- const head = rows[0]
406
- const th = head
407
- ? fields.map((f) => `<th>${htmlCell(head[f])}</th>`).join('')
408
- : ''
409
-
410
- const bodyParts: string[] = []
411
- for (let i = 1; i < rows.length; i++) {
412
- throwIfAborted(opts.signal)
413
- const row = rows[i]!
414
- const tds = fields
415
- .map((f, ci) => {
416
- const a = align[f]
417
- const styles: string[] = []
418
- if (a && a !== 'left') styles.push(`text-align:${a}`)
419
- const cf = cellStyle?.(i - 1, ci)
420
- if (cf?.fill) styles.push(`background:${cf.fill}`)
421
- if (cf?.color) styles.push(`color:${cf.color}`)
422
- if (cf?.bold) styles.push('font-weight:700')
423
- const style = styles.length ? ` style="${styles.join(';')}"` : ''
424
- let text = cf?.icon ? `${cf.icon} ${htmlCell(row[f])}` : htmlCell(row[f])
425
- const href = cellLink?.(i - 1, ci)
426
- if (href) text = `<a href="${htmlCell(href)}">${text}</a>`
427
- return `<td${style}>${text}</td>`
428
- })
429
- .join('')
430
- bodyParts.push(`<tr>${tds}</tr>`)
431
- if (i > 0 && i % chunk === 0) {
432
- opts.onProgress?.({ phase: 'serialize', ratio: i / total, row: i, total })
433
- await yieldToLoop()
434
- }
435
- }
436
- opts.onProgress?.({ phase: 'serialize', ratio: 1, row: total, total })
437
-
438
- return (
439
- `<!doctype html><html><head><meta charset="utf-8"><title>${htmlCell(title)}</title>` +
440
- `<style>table{border-collapse:collapse;font-family:system-ui,sans-serif;font-size:13px}` +
441
- `th,td{border:1px solid #d0d7de;padding:6px 10px}th{background:#f6f8fa;text-align:left}</style>` +
442
- `</head><body><table><thead><tr>${th}</tr></thead><tbody>${bodyParts.join('')}</tbody></table></body></html>`
443
- )
444
- }
445
-
446
- /**
447
- * Serialize projected rows to a JSON array of `{ field: value }` objects.
448
- * `rows[0]` (the header row) is dropped - JSON keys are the field names.
449
- */
450
- export async function serializeJson(
451
- rows: ReadonlyArray<Record<string, unknown>>,
452
- fields: ReadonlyArray<string>,
453
- opts: SerializeOptions = {},
454
- ): Promise<string> {
455
- const chunk = Math.max(1, opts.chunkRows ?? 5000)
456
- const total = rows.length - 1
457
- const out: Array<Record<string, unknown>> = []
458
- for (let i = 1; i < rows.length; i++) {
459
- throwIfAborted(opts.signal)
460
- const src = rows[i]!
461
- const obj: Record<string, unknown> = {}
462
- for (const f of fields) obj[f] = src[f]
463
- out.push(obj)
464
- if (i > 0 && i % chunk === 0) {
465
- opts.onProgress?.({ phase: 'serialize', ratio: i / total, row: i, total })
466
- await yieldToLoop()
467
- }
468
- }
469
- opts.onProgress?.({ phase: 'serialize', ratio: 1, row: total, total })
470
- return JSON.stringify(out, null, 2)
471
- }
472
-
473
- /** Escape a Markdown table cell: pipes and newlines would break the row. */
474
- function mdCell(value: unknown): string {
475
- const s = value == null ? '' : value instanceof Date ? value.toISOString() : String(value)
476
- return s.replace(/\\/g, '\\\\').replace(/\|/g, '\\|').replace(/\r?\n/g, '<br>')
477
- }
478
-
479
- /**
480
- * Serialize projected rows to a GitHub-flavored Markdown table. `rows[0]` is
481
- * the header row; `align` sets the `:---`, `:--:`, `---:` markers per column.
482
- */
483
- export async function serializeMarkdown(
484
- rows: ReadonlyArray<Record<string, unknown>>,
485
- fields: ReadonlyArray<string>,
486
- opts: SerializeOptions & { align?: Record<string, 'left' | 'center' | 'right'> } = {},
487
- ): Promise<string> {
488
- const chunk = Math.max(1, opts.chunkRows ?? 5000)
489
- const total = rows.length
490
- const align = opts.align ?? {}
491
- const head = rows[0]
492
-
493
- const headerLine = `| ${fields.map((f) => mdCell(head?.[f])).join(' | ')} |`
494
- const sepLine = `| ${fields
495
- .map((f) => {
496
- const a = align[f]
497
- return a === 'right' ? '---:' : a === 'center' ? ':--:' : '---'
498
- })
499
- .join(' | ')} |`
500
-
501
- const bodyLines: string[] = []
502
- for (let i = 1; i < rows.length; i++) {
503
- throwIfAborted(opts.signal)
504
- const src = rows[i]!
505
- bodyLines.push(`| ${fields.map((f) => mdCell(src[f])).join(' | ')} |`)
506
- if (i > 0 && i % chunk === 0) {
507
- opts.onProgress?.({ phase: 'serialize', ratio: i / total, row: i, total })
508
- await yieldToLoop()
509
- }
510
- }
511
- opts.onProgress?.({ phase: 'serialize', ratio: 1, row: total, total })
512
- return [headerLine, sepLine, ...bodyLines].join('\n') + '\n'
513
- }
514
-
515
- const XML_ESCAPE: Record<string, string> = {
516
- '&': '&amp;',
517
- '<': '&lt;',
518
- '>': '&gt;',
519
- '"': '&quot;',
520
- "'": '&apos;',
521
- }
522
- function xmlText(value: unknown): string {
523
- const s = value == null ? '' : value instanceof Date ? value.toISOString() : String(value)
524
- return s.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, '').replace(/[&<>"']/g, (c) => XML_ESCAPE[c]!)
525
- }
526
- /** Coerce a field name into a valid XML element name. */
527
- function xmlTag(field: string): string {
528
- const t = field.replace(/[^A-Za-z0-9_.-]/g, '_')
529
- return /^[A-Za-z_]/.test(t) ? t : `_${t}`
530
- }
531
-
532
- /**
533
- * Serialize projected rows to a simple XML document:
534
- * `<rows><row><field>value</field>…</row>…</rows>`. `rows[0]` (header) is
535
- * dropped - element names come from the field names.
536
- */
537
- export async function serializeXml(
538
- rows: ReadonlyArray<Record<string, unknown>>,
539
- fields: ReadonlyArray<string>,
540
- opts: SerializeOptions & { rootTag?: string; rowTag?: string } = {},
541
- ): Promise<string> {
542
- const chunk = Math.max(1, opts.chunkRows ?? 5000)
543
- const total = rows.length - 1
544
- const root = opts.rootTag ?? 'rows'
545
- const rowTag = opts.rowTag ?? 'row'
546
- const tags = fields.map(xmlTag)
547
-
548
- const parts: string[] = [`<?xml version="1.0" encoding="UTF-8"?>`, `<${root}>`]
549
- for (let i = 1; i < rows.length; i++) {
550
- throwIfAborted(opts.signal)
551
- const src = rows[i]!
552
- const cells = fields
553
- .map((f, ci) => `<${tags[ci]}>${xmlText(src[f])}</${tags[ci]}>`)
554
- .join('')
555
- parts.push(` <${rowTag}>${cells}</${rowTag}>`)
556
- if (i > 0 && i % chunk === 0) {
557
- opts.onProgress?.({ phase: 'serialize', ratio: i / total, row: i, total })
558
- await yieldToLoop()
559
- }
560
- }
561
- parts.push(`</${root}>`)
562
- opts.onProgress?.({ phase: 'serialize', ratio: 1, row: total, total })
563
- return parts.join('\n')
564
- }
565
-
566
- // ----- Delivery: download + clipboard (browser-guarded) --------------------
567
-
568
- /** Trigger a browser download of an already-built Blob. No-op guard for SSR. */
569
- export function downloadBlobFile(blob: Blob, filename: string): void {
570
- if (typeof document === 'undefined' || typeof URL === 'undefined') {
571
- throw new Error('@svgrid/grid: export requires a browser environment')
572
- }
573
- const url = URL.createObjectURL(blob)
574
- const a = document.createElement('a')
575
- a.href = url
576
- a.download = filename
577
- document.body.appendChild(a)
578
- a.click()
579
- a.remove()
580
- setTimeout(() => URL.revokeObjectURL(url), 0)
581
- }
582
-
583
- /** Trigger a browser download of a text blob. No-op guard for SSR. */
584
- export function downloadTextFile(text: string, filename: string, mime: string): void {
585
- if (typeof document === 'undefined' || typeof URL === 'undefined') {
586
- throw new Error('@svgrid/grid: text export requires a browser environment')
587
- }
588
- downloadBlobFile(new Blob([text], { type: mime }), filename)
589
- }
590
-
591
- /** Write text to the system clipboard. Throws when the API is unavailable
592
- * (insecure context / SSR). */
593
- export async function copyTextToClipboard(text: string): Promise<void> {
594
- if (typeof navigator === 'undefined' || !navigator.clipboard) {
595
- throw new Error('@svgrid/grid: clipboard API is unavailable in this context')
596
- }
597
- await navigator.clipboard.writeText(text)
598
- }
1
+ /**
2
+ * Pure, render-free value formatting for data export. The grid's on-screen
3
+ * `formatCellValue` (see cell-render.ts) is a closure bound to a `Row<TData>`
4
+ * and the live table, so it can't be reused directly by an exporter that only
5
+ * has raw values + a column's `format` config. These helpers replicate the
6
+ * numeric / date / percent branches of that formatter as standalone functions:
7
+ *
8
+ * - `formatValueForExport(value, format)` returns the display STRING a user
9
+ * sees on screen, so CSV / TSV / HTML / PDF exports are faithful to the
10
+ * grid ("what you see is what you export") instead of dumping raw values.
11
+ * - `toExcelNumFmt(format)` maps a `CellFormatConfig` to an Excel number
12
+ * format code, so an xlsx cell can stay a real number / date while still
13
+ * displaying formatted (currency symbol, thousands, date pattern).
14
+ *
15
+ * Custom per-row `formatter` callbacks are intentionally NOT handled here -
16
+ * they may close over row/table state. Columns that need custom export text
17
+ * should provide an `exportValue(row)` hook at the export layer instead.
18
+ */
19
+ import type { CellFormatConfig } from './core'
20
+ import {
21
+ formatNumericWithConfig,
22
+ getDateFormatter,
23
+ resolveDatePattern,
24
+ } from './cell-formatting'
25
+
26
+ // Re-export the pure conditional-formatting engine here too, so the
27
+ // Svelte-free `@svgrid/grid/format` subpath carries it for @svgrid/enterprise's
28
+ // export code (which must not pull in SvGrid.svelte).
29
+ export {
30
+ computeColumnStat,
31
+ contrastText,
32
+ formatsNeedingStats,
33
+ resolveCellFormat,
34
+ type ColumnStat,
35
+ type ConditionalFormat,
36
+ type ResolvedCellFormat,
37
+ } from './conditional-formatting'
38
+
39
+ /** Best-effort coercion of a cell value to a Date. Accepts Date, epoch ms
40
+ * numbers, and parseable date strings. Returns null when it isn't a date. */
41
+ export function coerceExportDate(value: unknown): Date | null {
42
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value
43
+ if (typeof value === 'number' && Number.isFinite(value)) {
44
+ const d = new Date(value)
45
+ return Number.isNaN(d.getTime()) ? null : d
46
+ }
47
+ if (typeof value === 'string' && value.trim() !== '') {
48
+ const d = new Date(value)
49
+ return Number.isNaN(d.getTime()) ? null : d
50
+ }
51
+ return null
52
+ }
53
+
54
+ /**
55
+ * Format a raw cell value to its on-screen display string using the column's
56
+ * `format` config. Mirrors the grid's own numeric / currency / percent / date
57
+ * branches. Values with no (or an unrecognised) format fall back to
58
+ * `String(value)`, and `null` / `undefined` become an empty string.
59
+ */
60
+ export function formatValueForExport(
61
+ value: unknown,
62
+ format: CellFormatConfig | undefined,
63
+ ): string {
64
+ if (value == null) return ''
65
+ if (!format) return String(value)
66
+
67
+ if (format.type === 'number' || format.type === 'currency' || format.type === 'percent') {
68
+ return formatNumericWithConfig(value, {
69
+ type: format.type,
70
+ locales: format.locales,
71
+ currency: format.type === 'currency' ? (format.currency ?? 'USD') : undefined,
72
+ valueIsPercentPoints:
73
+ format.type === 'percent' ? format.valueIsPercentPoints : undefined,
74
+ options: format.options,
75
+ })
76
+ }
77
+
78
+ if (format.type === 'date' || format.type === 'datetime') {
79
+ const parsed = coerceExportDate(value)
80
+ if (parsed) {
81
+ const preset = resolveDatePattern(format.pattern, format.type)
82
+ const merged: Intl.DateTimeFormatOptions =
83
+ preset || format.options
84
+ ? { ...preset, ...format.options }
85
+ : format.type === 'date'
86
+ ? { year: 'numeric', month: '2-digit', day: '2-digit' }
87
+ : {
88
+ year: 'numeric',
89
+ month: '2-digit',
90
+ day: '2-digit',
91
+ hour: '2-digit',
92
+ minute: '2-digit',
93
+ }
94
+ return getDateFormatter(format.locales, merged).format(parsed)
95
+ }
96
+ }
97
+
98
+ return String(value)
99
+ }
100
+
101
+ /**
102
+ * Map a `CellFormatConfig` to an Excel/OOXML number-format code, so an xlsx
103
+ * writer can keep the cell numeric/date while displaying it formatted.
104
+ * Returns `undefined` when the format has no natural Excel representation
105
+ * (or the caller should just write a string).
106
+ *
107
+ * These are deliberately conservative, widely-recognised codes:
108
+ * number → `#,##0[.00…]` (grouping + N decimals)
109
+ * currency → `"$"#,##0.00` (symbol + grouping + 2 decimals)
110
+ * percent → `0[.00…]%` (Excel multiplies by 100, so this pairs with a
111
+ * 0..1 fraction; see `valueForExcel`)
112
+ * date → `yyyy-mm-dd`, datetime → `yyyy-mm-dd hh:mm`
113
+ */
114
+ export function toExcelNumFmt(format: CellFormatConfig | undefined): string | undefined {
115
+ if (!format) return undefined
116
+
117
+ const decimals = (): number => {
118
+ // `options` is a union across number/date formats; only the numeric ones
119
+ // carry fraction-digit hints, so read them through a narrow shape.
120
+ const o = format.options as
121
+ | { maximumFractionDigits?: number; minimumFractionDigits?: number }
122
+ | undefined
123
+ if (o && typeof o.maximumFractionDigits === 'number') return o.maximumFractionDigits
124
+ if (o && typeof o.minimumFractionDigits === 'number') return o.minimumFractionDigits
125
+ return format.type === 'currency' ? 2 : format.type === 'number' ? 0 : 2
126
+ }
127
+ const dp = (n: number) => (n > 0 ? '.' + '0'.repeat(n) : '')
128
+
129
+ switch (format.type) {
130
+ case 'number':
131
+ return `#,##0${dp(decimals())}`
132
+ case 'currency': {
133
+ const sym = currencySymbol(format.currency ?? 'USD')
134
+ return `"${sym}"#,##0${dp(decimals())}`
135
+ }
136
+ case 'percent':
137
+ return `0${dp(decimals())}%`
138
+ case 'date':
139
+ return 'yyyy-mm-dd'
140
+ case 'datetime':
141
+ return 'yyyy-mm-dd hh:mm'
142
+ default:
143
+ return undefined
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Turn a grid's data rows + columns into the header-first `{ field: value }`
149
+ * record shape the serializers consume, applying each column's `format` so
150
+ * the export matches what's on screen (unless `rawValues`). Optionally
151
+ * restricts + reorders columns to a `columns` field subset.
152
+ */
153
+ export function projectGridRows(
154
+ dataRows: ReadonlyArray<Record<string, unknown>>,
155
+ columns: ReadonlyArray<GridExportColumn>,
156
+ opts: { columns?: ReadonlyArray<string>; rawValues?: boolean } = {},
157
+ ): {
158
+ records: Array<Record<string, unknown>>
159
+ fields: string[]
160
+ align: Record<string, 'left' | 'center' | 'right'>
161
+ } {
162
+ const chosen =
163
+ opts.columns && opts.columns.length
164
+ ? opts.columns
165
+ .map((f) => columns.find((c) => c.field === f))
166
+ .filter((c): c is GridExportColumn => !!c)
167
+ : columns.filter((c) => c.field)
168
+ const fields = chosen.map((c) => c.field)
169
+ const align: Record<string, 'left' | 'center' | 'right'> = {}
170
+ for (const c of chosen) if (c.align) align[c.field] = c.align
171
+
172
+ const header: Record<string, unknown> = {}
173
+ for (const c of chosen) header[c.field] = c.header
174
+ const records: Array<Record<string, unknown>> = [header]
175
+ for (const row of dataRows) {
176
+ const rec: Record<string, unknown> = {}
177
+ for (const c of chosen) {
178
+ const raw = row[c.field]
179
+ rec[c.field] = opts.rawValues ? raw : formatValueForExport(raw, c.format)
180
+ }
181
+ records.push(rec)
182
+ }
183
+ return { records, fields, align }
184
+ }
185
+
186
+ /** A tiny currency-code → symbol map for the Excel numFmt code. Falls back
187
+ * to the ISO code itself (e.g. "CHF") when we don't have a glyph. */
188
+ function currencySymbol(code: string): string {
189
+ const map: Record<string, string> = {
190
+ USD: '$',
191
+ EUR: '€',
192
+ GBP: '£',
193
+ JPY: '¥',
194
+ CNY: '¥',
195
+ INR: '₹',
196
+ KRW: '₩',
197
+ RUB: '₽',
198
+ BRL: 'R$',
199
+ }
200
+ return map[code.toUpperCase()] ?? code.toUpperCase()
201
+ }
202
+
203
+ /**
204
+ * The value to write into a native xlsx cell that carries an Excel numFmt.
205
+ * Numbers stay numbers; percent values are divided to the 0..1 fraction Excel
206
+ * expects (unless the config already stores 0..1); dates become real `Date`s.
207
+ * Returns `{ ok: false }` when the value can't be represented natively and the
208
+ * caller should fall back to the formatted string.
209
+ */
210
+ export function valueForExcel(
211
+ value: unknown,
212
+ format: CellFormatConfig | undefined,
213
+ ): { ok: true; value: number | Date } | { ok: false } {
214
+ if (value == null || !format) return { ok: false }
215
+
216
+ if (format.type === 'number' || format.type === 'currency') {
217
+ const n = typeof value === 'number' ? value : Number(value)
218
+ return Number.isFinite(n) ? { ok: true, value: n } : { ok: false }
219
+ }
220
+ if (format.type === 'percent') {
221
+ const n = typeof value === 'number' ? value : Number(value)
222
+ if (!Number.isFinite(n)) return { ok: false }
223
+ // Excel's percent numFmt multiplies by 100, so it wants the fraction.
224
+ return { ok: true, value: format.valueIsPercentPoints === true ? n / 100 : n }
225
+ }
226
+ if (format.type === 'date' || format.type === 'datetime') {
227
+ const d = coerceExportDate(value)
228
+ return d ? { ok: true, value: d } : { ok: false }
229
+ }
230
+ return { ok: false }
231
+ }
232
+
233
+ // ===========================================================================
234
+ // Free data export (CSV / TSV / JSON) + delivery. Kept in this same
235
+ // Svelte-free module (the `@svgrid/grid/format` subpath) so @svgrid/enterprise
236
+ // re-uses ONE implementation of each serializer. Input is already-projected
237
+ // rows: an array of `{ field: value }` records whose FIRST record is the
238
+ // header row. Use `projectGridRows` above to build that shape.
239
+ // ===========================================================================
240
+
241
+ // ----- Public option types (shared by the grid API export methods) ---------
242
+
243
+ export type GridExportScope = 'displayed' | 'selected' | 'all'
244
+
245
+ /** The slice of a grid column an exporter needs. Accepts `api.getColumns()`. */
246
+ export type GridExportColumn = {
247
+ field: string
248
+ header: string
249
+ format?: CellFormatConfig | undefined
250
+ align?: 'left' | 'center' | 'right'
251
+ }
252
+
253
+ export type GridExportOptions = {
254
+ /** Base filename (no extension). Default 'grid'. */
255
+ filename?: string
256
+ /** Which rows to export. Default 'displayed' (current view). */
257
+ rows?: GridExportScope
258
+ /** Restrict to these fields, in this order. Default: all visible columns. */
259
+ columns?: string[]
260
+ /** Export raw values instead of the on-screen formatted display. Default false. */
261
+ rawValues?: boolean
262
+ /** Prepend a UTF-8 BOM (csv/tsv) so Excel detects UTF-8. Default true. */
263
+ bom?: boolean
264
+ /** Cancel a large export. */
265
+ signal?: AbortSignal
266
+ /** Progress for large exports. */
267
+ onProgress?: (progress: SerializeProgress) => void
268
+ /** When false, skip the browser download and just return the text. Default true. */
269
+ download?: boolean
270
+ }
271
+
272
+ export type GridClipboardFormat = 'csv' | 'tsv' | 'markdown'
273
+
274
+ export type GridClipboardOptions = {
275
+ /** Clipboard payload format. Default 'tsv' (pastes straight into Excel). */
276
+ format?: GridClipboardFormat
277
+ rows?: GridExportScope
278
+ columns?: string[]
279
+ rawValues?: boolean
280
+ }
281
+
282
+ // ----- Serializers ---------------------------------------------------------
283
+
284
+ export type SerializeProgress = {
285
+ phase: 'serialize'
286
+ /** 0..1 completion of the row walk. */
287
+ ratio: number
288
+ row: number
289
+ total: number
290
+ }
291
+
292
+ export type CsvOptions = {
293
+ /** Field delimiter. Default ',' (','→CSV, '\t'→TSV). */
294
+ delimiter?: string
295
+ /** Line ending between records. Default '\r\n' (Excel-friendly). */
296
+ eol?: string
297
+ /** Prepend a UTF-8 BOM so Excel detects UTF-8. Default true for csv/tsv. */
298
+ bom?: boolean
299
+ }
300
+
301
+ export type SerializeOptions = {
302
+ onProgress?: (p: SerializeProgress) => void
303
+ signal?: AbortSignal
304
+ csv?: CsvOptions
305
+ /** Rows processed between event-loop yields. Default 5000. */
306
+ chunkRows?: number
307
+ }
308
+
309
+ const EXPORT_BOM = ''
310
+
311
+ function throwIfAborted(signal: AbortSignal | undefined): void {
312
+ if (signal?.aborted) {
313
+ throw new DOMException('Export aborted', 'AbortError')
314
+ }
315
+ }
316
+
317
+ /** Let the event loop breathe (paint a progress bar, honour an abort). */
318
+ const yieldToLoop = (): Promise<void> =>
319
+ new Promise((resolve) => setTimeout(resolve, 0))
320
+
321
+ /** RFC-4180 quoting: wrap in double quotes and double any embedded quote
322
+ * when the value contains the delimiter, a quote, or a newline. */
323
+ function csvCell(value: unknown, delimiter: string): string {
324
+ const s =
325
+ value == null
326
+ ? ''
327
+ : value instanceof Date
328
+ ? value.toISOString()
329
+ : String(value)
330
+ if (s === '') return s
331
+ if (s.includes(delimiter) || s.includes('"') || s.includes('\n') || s.includes('\r')) {
332
+ return `"${s.replace(/"/g, '""')}"`
333
+ }
334
+ return s
335
+ }
336
+
337
+ /**
338
+ * Serialize projected rows to a delimited string (CSV / TSV).
339
+ * `rows[0]` is treated as the header row.
340
+ */
341
+ export async function serializeDelimited(
342
+ rows: ReadonlyArray<Record<string, unknown>>,
343
+ fields: ReadonlyArray<string>,
344
+ opts: SerializeOptions = {},
345
+ ): Promise<string> {
346
+ const delimiter = opts.csv?.delimiter ?? ','
347
+ const eol = opts.csv?.eol ?? '\r\n'
348
+ const useBom = opts.csv?.bom ?? true
349
+ const chunk = Math.max(1, opts.chunkRows ?? 5000)
350
+ const total = rows.length
351
+
352
+ const parts: string[] = []
353
+ for (let i = 0; i < rows.length; i++) {
354
+ throwIfAborted(opts.signal)
355
+ const row = rows[i]!
356
+ parts.push(fields.map((f) => csvCell(row[f], delimiter)).join(delimiter))
357
+ if (i > 0 && i % chunk === 0) {
358
+ opts.onProgress?.({ phase: 'serialize', ratio: i / total, row: i, total })
359
+ await yieldToLoop()
360
+ }
361
+ }
362
+ opts.onProgress?.({ phase: 'serialize', ratio: 1, row: total, total })
363
+ const body = parts.join(eol)
364
+ return (useBom ? EXPORT_BOM : '') + body
365
+ }
366
+
367
+ const HTML_ESCAPE: Record<string, string> = {
368
+ '&': '&amp;',
369
+ '<': '&lt;',
370
+ '>': '&gt;',
371
+ '"': '&quot;',
372
+ "'": '&#39;',
373
+ }
374
+ function htmlCell(value: unknown): string {
375
+ const s =
376
+ value == null ? '' : value instanceof Date ? value.toISOString() : String(value)
377
+ return s.replace(/[&<>"']/g, (c) => HTML_ESCAPE[c]!)
378
+ }
379
+
380
+ export type ExportCellVisual = { fill?: string; color?: string; bold?: boolean; icon?: string }
381
+
382
+ /**
383
+ * Serialize projected rows to a standalone HTML `<table>` document.
384
+ * `rows[0]` is the header row (rendered as `<th>`); the rest are `<td>`.
385
+ */
386
+ export async function serializeHtml(
387
+ rows: ReadonlyArray<Record<string, unknown>>,
388
+ fields: ReadonlyArray<string>,
389
+ opts: SerializeOptions & {
390
+ title?: string
391
+ align?: Record<string, 'left' | 'center' | 'right'>
392
+ /** Per-data-cell conditional-format visual (`rowIdx` is 0-based over data). */
393
+ cellStyle?: (rowIdx: number, colIdx: number) => ExportCellVisual | undefined
394
+ /** Per-data-cell hyperlink URL. */
395
+ cellLink?: (rowIdx: number, colIdx: number) => string | undefined
396
+ } = {},
397
+ ): Promise<string> {
398
+ const chunk = Math.max(1, opts.chunkRows ?? 5000)
399
+ const total = rows.length
400
+ const align = opts.align ?? {}
401
+ const cellStyle = opts.cellStyle
402
+ const cellLink = opts.cellLink
403
+ const title = opts.title ?? 'Grid export'
404
+
405
+ const head = rows[0]
406
+ const th = head
407
+ ? fields.map((f) => `<th>${htmlCell(head[f])}</th>`).join('')
408
+ : ''
409
+
410
+ const bodyParts: string[] = []
411
+ for (let i = 1; i < rows.length; i++) {
412
+ throwIfAborted(opts.signal)
413
+ const row = rows[i]!
414
+ const tds = fields
415
+ .map((f, ci) => {
416
+ const a = align[f]
417
+ const styles: string[] = []
418
+ if (a && a !== 'left') styles.push(`text-align:${a}`)
419
+ const cf = cellStyle?.(i - 1, ci)
420
+ if (cf?.fill) styles.push(`background:${cf.fill}`)
421
+ if (cf?.color) styles.push(`color:${cf.color}`)
422
+ if (cf?.bold) styles.push('font-weight:700')
423
+ const style = styles.length ? ` style="${styles.join(';')}"` : ''
424
+ let text = cf?.icon ? `${cf.icon} ${htmlCell(row[f])}` : htmlCell(row[f])
425
+ const href = cellLink?.(i - 1, ci)
426
+ if (href) text = `<a href="${htmlCell(href)}">${text}</a>`
427
+ return `<td${style}>${text}</td>`
428
+ })
429
+ .join('')
430
+ bodyParts.push(`<tr>${tds}</tr>`)
431
+ if (i > 0 && i % chunk === 0) {
432
+ opts.onProgress?.({ phase: 'serialize', ratio: i / total, row: i, total })
433
+ await yieldToLoop()
434
+ }
435
+ }
436
+ opts.onProgress?.({ phase: 'serialize', ratio: 1, row: total, total })
437
+
438
+ return (
439
+ `<!doctype html><html><head><meta charset="utf-8"><title>${htmlCell(title)}</title>` +
440
+ `<style>table{border-collapse:collapse;font-family:system-ui,sans-serif;font-size:13px}` +
441
+ `th,td{border:1px solid #d0d7de;padding:6px 10px}th{background:#f6f8fa;text-align:left}</style>` +
442
+ `</head><body><table><thead><tr>${th}</tr></thead><tbody>${bodyParts.join('')}</tbody></table></body></html>`
443
+ )
444
+ }
445
+
446
+ /**
447
+ * Serialize projected rows to a JSON array of `{ field: value }` objects.
448
+ * `rows[0]` (the header row) is dropped - JSON keys are the field names.
449
+ */
450
+ export async function serializeJson(
451
+ rows: ReadonlyArray<Record<string, unknown>>,
452
+ fields: ReadonlyArray<string>,
453
+ opts: SerializeOptions = {},
454
+ ): Promise<string> {
455
+ const chunk = Math.max(1, opts.chunkRows ?? 5000)
456
+ const total = rows.length - 1
457
+ const out: Array<Record<string, unknown>> = []
458
+ for (let i = 1; i < rows.length; i++) {
459
+ throwIfAborted(opts.signal)
460
+ const src = rows[i]!
461
+ const obj: Record<string, unknown> = {}
462
+ for (const f of fields) obj[f] = src[f]
463
+ out.push(obj)
464
+ if (i > 0 && i % chunk === 0) {
465
+ opts.onProgress?.({ phase: 'serialize', ratio: i / total, row: i, total })
466
+ await yieldToLoop()
467
+ }
468
+ }
469
+ opts.onProgress?.({ phase: 'serialize', ratio: 1, row: total, total })
470
+ return JSON.stringify(out, null, 2)
471
+ }
472
+
473
+ /** Escape a Markdown table cell: pipes and newlines would break the row. */
474
+ function mdCell(value: unknown): string {
475
+ const s = value == null ? '' : value instanceof Date ? value.toISOString() : String(value)
476
+ return s.replace(/\\/g, '\\\\').replace(/\|/g, '\\|').replace(/\r?\n/g, '<br>')
477
+ }
478
+
479
+ /**
480
+ * Serialize projected rows to a GitHub-flavored Markdown table. `rows[0]` is
481
+ * the header row; `align` sets the `:---`, `:--:`, `---:` markers per column.
482
+ */
483
+ export async function serializeMarkdown(
484
+ rows: ReadonlyArray<Record<string, unknown>>,
485
+ fields: ReadonlyArray<string>,
486
+ opts: SerializeOptions & { align?: Record<string, 'left' | 'center' | 'right'> } = {},
487
+ ): Promise<string> {
488
+ const chunk = Math.max(1, opts.chunkRows ?? 5000)
489
+ const total = rows.length
490
+ const align = opts.align ?? {}
491
+ const head = rows[0]
492
+
493
+ const headerLine = `| ${fields.map((f) => mdCell(head?.[f])).join(' | ')} |`
494
+ const sepLine = `| ${fields
495
+ .map((f) => {
496
+ const a = align[f]
497
+ return a === 'right' ? '---:' : a === 'center' ? ':--:' : '---'
498
+ })
499
+ .join(' | ')} |`
500
+
501
+ const bodyLines: string[] = []
502
+ for (let i = 1; i < rows.length; i++) {
503
+ throwIfAborted(opts.signal)
504
+ const src = rows[i]!
505
+ bodyLines.push(`| ${fields.map((f) => mdCell(src[f])).join(' | ')} |`)
506
+ if (i > 0 && i % chunk === 0) {
507
+ opts.onProgress?.({ phase: 'serialize', ratio: i / total, row: i, total })
508
+ await yieldToLoop()
509
+ }
510
+ }
511
+ opts.onProgress?.({ phase: 'serialize', ratio: 1, row: total, total })
512
+ return [headerLine, sepLine, ...bodyLines].join('\n') + '\n'
513
+ }
514
+
515
+ const XML_ESCAPE: Record<string, string> = {
516
+ '&': '&amp;',
517
+ '<': '&lt;',
518
+ '>': '&gt;',
519
+ '"': '&quot;',
520
+ "'": '&apos;',
521
+ }
522
+ function xmlText(value: unknown): string {
523
+ const s = value == null ? '' : value instanceof Date ? value.toISOString() : String(value)
524
+ return s.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, '').replace(/[&<>"']/g, (c) => XML_ESCAPE[c]!)
525
+ }
526
+ /** Coerce a field name into a valid XML element name. */
527
+ function xmlTag(field: string): string {
528
+ const t = field.replace(/[^A-Za-z0-9_.-]/g, '_')
529
+ return /^[A-Za-z_]/.test(t) ? t : `_${t}`
530
+ }
531
+
532
+ /**
533
+ * Serialize projected rows to a simple XML document:
534
+ * `<rows><row><field>value</field>…</row>…</rows>`. `rows[0]` (header) is
535
+ * dropped - element names come from the field names.
536
+ */
537
+ export async function serializeXml(
538
+ rows: ReadonlyArray<Record<string, unknown>>,
539
+ fields: ReadonlyArray<string>,
540
+ opts: SerializeOptions & { rootTag?: string; rowTag?: string } = {},
541
+ ): Promise<string> {
542
+ const chunk = Math.max(1, opts.chunkRows ?? 5000)
543
+ const total = rows.length - 1
544
+ const root = opts.rootTag ?? 'rows'
545
+ const rowTag = opts.rowTag ?? 'row'
546
+ const tags = fields.map(xmlTag)
547
+
548
+ const parts: string[] = [`<?xml version="1.0" encoding="UTF-8"?>`, `<${root}>`]
549
+ for (let i = 1; i < rows.length; i++) {
550
+ throwIfAborted(opts.signal)
551
+ const src = rows[i]!
552
+ const cells = fields
553
+ .map((f, ci) => `<${tags[ci]}>${xmlText(src[f])}</${tags[ci]}>`)
554
+ .join('')
555
+ parts.push(` <${rowTag}>${cells}</${rowTag}>`)
556
+ if (i > 0 && i % chunk === 0) {
557
+ opts.onProgress?.({ phase: 'serialize', ratio: i / total, row: i, total })
558
+ await yieldToLoop()
559
+ }
560
+ }
561
+ parts.push(`</${root}>`)
562
+ opts.onProgress?.({ phase: 'serialize', ratio: 1, row: total, total })
563
+ return parts.join('\n')
564
+ }
565
+
566
+ // ----- Delivery: download + clipboard (browser-guarded) --------------------
567
+
568
+ /** Trigger a browser download of an already-built Blob. No-op guard for SSR. */
569
+ export function downloadBlobFile(blob: Blob, filename: string): void {
570
+ if (typeof document === 'undefined' || typeof URL === 'undefined') {
571
+ throw new Error('@svgrid/grid: export requires a browser environment')
572
+ }
573
+ const url = URL.createObjectURL(blob)
574
+ const a = document.createElement('a')
575
+ a.href = url
576
+ a.download = filename
577
+ document.body.appendChild(a)
578
+ a.click()
579
+ a.remove()
580
+ setTimeout(() => URL.revokeObjectURL(url), 0)
581
+ }
582
+
583
+ /** Trigger a browser download of a text blob. No-op guard for SSR. */
584
+ export function downloadTextFile(text: string, filename: string, mime: string): void {
585
+ if (typeof document === 'undefined' || typeof URL === 'undefined') {
586
+ throw new Error('@svgrid/grid: text export requires a browser environment')
587
+ }
588
+ downloadBlobFile(new Blob([text], { type: mime }), filename)
589
+ }
590
+
591
+ /** Write text to the system clipboard. Throws when the API is unavailable
592
+ * (insecure context / SSR). */
593
+ export async function copyTextToClipboard(text: string): Promise<void> {
594
+ if (typeof navigator === 'undefined' || !navigator.clipboard) {
595
+ throw new Error('@svgrid/grid: clipboard API is unavailable in this context')
596
+ }
597
+ await navigator.clipboard.writeText(text)
598
+ }