@universal-material/data-grid 0.0.0-stage → 0.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.
- package/LICENSE +21 -0
- package/README.md +172 -2
- package/custom-elements.json +4652 -0
- package/dist/attribute-converters.d.ts +53 -0
- package/dist/attribute-converters.js +98 -0
- package/dist/attribute-converters.js.map +1 -0
- package/dist/change-source.d.ts +3 -0
- package/dist/change-source.js +2 -0
- package/dist/change-source.js.map +1 -0
- package/dist/data/data-source.d.ts +164 -0
- package/dist/data/data-source.js +75 -0
- package/dist/data/data-source.js.map +1 -0
- package/dist/data/local-source.d.ts +20 -0
- package/dist/data/local-source.js +94 -0
- package/dist/data/local-source.js.map +1 -0
- package/dist/data/remote-loader.d.ts +190 -0
- package/dist/data/remote-loader.js +608 -0
- package/dist/data/remote-loader.js.map +1 -0
- package/dist/export/csv.d.ts +28 -0
- package/dist/export/csv.js +61 -0
- package/dist/export/csv.js.map +1 -0
- package/dist/export/download.d.ts +7 -0
- package/dist/export/download.js +17 -0
- package/dist/export/download.js.map +1 -0
- package/dist/export/rows.d.ts +75 -0
- package/dist/export/rows.js +134 -0
- package/dist/export/rows.js.map +1 -0
- package/dist/export/slice.d.ts +15 -0
- package/dist/export/slice.js +35 -0
- package/dist/export/slice.js.map +1 -0
- package/dist/export/types.d.ts +155 -0
- package/dist/export/types.js +2 -0
- package/dist/export/types.js.map +1 -0
- package/dist/export/write.d.ts +38 -0
- package/dist/export/write.js +178 -0
- package/dist/export/write.js.map +1 -0
- package/dist/export-pdf/client.d.ts +75 -0
- package/dist/export-pdf/client.js +155 -0
- package/dist/export-pdf/client.js.map +1 -0
- package/dist/export-pdf/engine.d.ts +73 -0
- package/dist/export-pdf/engine.js +131 -0
- package/dist/export-pdf/engine.js.map +1 -0
- package/dist/export-pdf/grid-pdf.wasm +0 -0
- package/dist/export-pdf/index.d.ts +27 -0
- package/dist/export-pdf/index.js +566 -0
- package/dist/export-pdf/index.js.map +1 -0
- package/dist/export-pdf/serialize.d.ts +23 -0
- package/dist/export-pdf/serialize.js +127 -0
- package/dist/export-pdf/serialize.js.map +1 -0
- package/dist/export-pdf/types.d.ts +150 -0
- package/dist/export-pdf/types.js +2 -0
- package/dist/export-pdf/types.js.map +1 -0
- package/dist/export-pdf/worker.d.ts +2 -0
- package/dist/export-pdf/worker.js +81 -0
- package/dist/export-pdf/worker.js.map +1 -0
- package/dist/export-xlsx/formats.d.ts +14 -0
- package/dist/export-xlsx/formats.js +40 -0
- package/dist/export-xlsx/formats.js.map +1 -0
- package/dist/export-xlsx/index.d.ts +74 -0
- package/dist/export-xlsx/index.js +137 -0
- package/dist/export-xlsx/index.js.map +1 -0
- package/dist/features/adaptive.d.ts +25 -0
- package/dist/features/adaptive.js +47 -0
- package/dist/features/adaptive.js.map +1 -0
- package/dist/features/cell-content-focus.d.ts +29 -0
- package/dist/features/cell-content-focus.js +95 -0
- package/dist/features/cell-content-focus.js.map +1 -0
- package/dist/features/cell-range.d.ts +97 -0
- package/dist/features/cell-range.js +75 -0
- package/dist/features/cell-range.js.map +1 -0
- package/dist/features/clipboard.d.ts +28 -0
- package/dist/features/clipboard.js +48 -0
- package/dist/features/clipboard.js.map +1 -0
- package/dist/features/column-chooser.d.ts +91 -0
- package/dist/features/column-chooser.js +451 -0
- package/dist/features/column-chooser.js.map +1 -0
- package/dist/features/column-dnd.d.ts +10 -0
- package/dist/features/column-dnd.js +126 -0
- package/dist/features/column-dnd.js.map +1 -0
- package/dist/features/context-menu.d.ts +122 -0
- package/dist/features/context-menu.js +153 -0
- package/dist/features/context-menu.js.map +1 -0
- package/dist/features/drag-helper.d.ts +39 -0
- package/dist/features/drag-helper.js +108 -0
- package/dist/features/drag-helper.js.map +1 -0
- package/dist/features/drop-position.d.ts +15 -0
- package/dist/features/drop-position.js +24 -0
- package/dist/features/drop-position.js.map +1 -0
- package/dist/features/editing.d.ts +111 -0
- package/dist/features/editing.js +244 -0
- package/dist/features/editing.js.map +1 -0
- package/dist/features/filter-row.d.ts +80 -0
- package/dist/features/filter-row.js +538 -0
- package/dist/features/filter-row.js.map +1 -0
- package/dist/features/filtering.d.ts +55 -0
- package/dist/features/filtering.js +209 -0
- package/dist/features/filtering.js.map +1 -0
- package/dist/features/group-dnd.d.ts +11 -0
- package/dist/features/group-dnd.js +119 -0
- package/dist/features/group-dnd.js.map +1 -0
- package/dist/features/header-filter.d.ts +100 -0
- package/dist/features/header-filter.js +588 -0
- package/dist/features/header-filter.js.map +1 -0
- package/dist/features/host-label.d.ts +36 -0
- package/dist/features/host-label.js +184 -0
- package/dist/features/host-label.js.map +1 -0
- package/dist/features/keyboard.d.ts +59 -0
- package/dist/features/keyboard.js +127 -0
- package/dist/features/keyboard.js.map +1 -0
- package/dist/features/menu.d.ts +113 -0
- package/dist/features/menu.js +491 -0
- package/dist/features/menu.js.map +1 -0
- package/dist/features/resize.d.ts +82 -0
- package/dist/features/resize.js +214 -0
- package/dist/features/resize.js.map +1 -0
- package/dist/features/scroll-port.d.ts +51 -0
- package/dist/features/scroll-port.js +329 -0
- package/dist/features/scroll-port.js.map +1 -0
- package/dist/features/search.d.ts +45 -0
- package/dist/features/search.js +123 -0
- package/dist/features/search.js.map +1 -0
- package/dist/features/selection.d.ts +37 -0
- package/dist/features/selection.js +103 -0
- package/dist/features/selection.js.map +1 -0
- package/dist/features/sorting.d.ts +39 -0
- package/dist/features/sorting.js +53 -0
- package/dist/features/sorting.js.map +1 -0
- package/dist/features/toolbar.d.ts +125 -0
- package/dist/features/toolbar.js +135 -0
- package/dist/features/toolbar.js.map +1 -0
- package/dist/features/tree.d.ts +53 -0
- package/dist/features/tree.js +94 -0
- package/dist/features/tree.js.map +1 -0
- package/dist/features/validation.d.ts +48 -0
- package/dist/features/validation.js +172 -0
- package/dist/features/validation.js.map +1 -0
- package/dist/grid-column-def.d.ts +521 -0
- package/dist/grid-column-def.js +32 -0
- package/dist/grid-column-def.js.map +1 -0
- package/dist/grid-column.d.ts +173 -0
- package/dist/grid-column.js +382 -0
- package/dist/grid-column.js.map +1 -0
- package/dist/grid-i18n.d.ts +469 -0
- package/dist/grid-i18n.js +3222 -0
- package/dist/grid-i18n.js.map +1 -0
- package/dist/grid.d.ts +1510 -0
- package/dist/grid.js +15972 -0
- package/dist/grid.js.map +1 -0
- package/dist/grid.min.js +3966 -0
- package/dist/grid.styles.d.ts +2 -0
- package/dist/grid.styles.js +2849 -0
- package/dist/grid.styles.js.map +1 -0
- package/dist/render/cell.d.ts +16 -0
- package/dist/render/cell.js +78 -0
- package/dist/render/cell.js.map +1 -0
- package/dist/render/column-window.d.ts +18 -0
- package/dist/render/column-window.js +50 -0
- package/dist/render/column-window.js.map +1 -0
- package/dist/render/content.d.ts +45 -0
- package/dist/render/content.js +140 -0
- package/dist/render/content.js.map +1 -0
- package/dist/render/editors.d.ts +28 -0
- package/dist/render/editors.js +41 -0
- package/dist/render/editors.js.map +1 -0
- package/dist/render/footer.d.ts +61 -0
- package/dist/render/footer.js +61 -0
- package/dist/render/footer.js.map +1 -0
- package/dist/render/group-row.d.ts +35 -0
- package/dist/render/group-row.js +60 -0
- package/dist/render/group-row.js.map +1 -0
- package/dist/render/header.d.ts +108 -0
- package/dist/render/header.js +124 -0
- package/dist/render/header.js.map +1 -0
- package/dist/render/keyed-rows.d.ts +25 -0
- package/dist/render/keyed-rows.js +98 -0
- package/dist/render/keyed-rows.js.map +1 -0
- package/dist/render/virtualizer.d.ts +158 -0
- package/dist/render/virtualizer.js +721 -0
- package/dist/render/virtualizer.js.map +1 -0
- package/dist/row-model/added-rows.d.ts +32 -0
- package/dist/row-model/added-rows.js +95 -0
- package/dist/row-model/added-rows.js.map +1 -0
- package/dist/row-model/cell-range.d.ts +71 -0
- package/dist/row-model/cell-range.js +187 -0
- package/dist/row-model/cell-range.js.map +1 -0
- package/dist/row-model/columns.d.ts +102 -0
- package/dist/row-model/columns.js +222 -0
- package/dist/row-model/columns.js.map +1 -0
- package/dist/row-model/compare.d.ts +40 -0
- package/dist/row-model/compare.js +590 -0
- package/dist/row-model/compare.js.map +1 -0
- package/dist/row-model/distinct.d.ts +39 -0
- package/dist/row-model/distinct.js +105 -0
- package/dist/row-model/distinct.js.map +1 -0
- package/dist/row-model/filter.d.ts +80 -0
- package/dist/row-model/filter.js +582 -0
- package/dist/row-model/filter.js.map +1 -0
- package/dist/row-model/flatten.d.ts +129 -0
- package/dist/row-model/flatten.js +511 -0
- package/dist/row-model/flatten.js.map +1 -0
- package/dist/row-model/fold.d.ts +25 -0
- package/dist/row-model/fold.js +104 -0
- package/dist/row-model/fold.js.map +1 -0
- package/dist/row-model/format.d.ts +58 -0
- package/dist/row-model/format.js +239 -0
- package/dist/row-model/format.js.map +1 -0
- package/dist/row-model/group.d.ts +30 -0
- package/dist/row-model/group.js +173 -0
- package/dist/row-model/group.js.map +1 -0
- package/dist/row-model/lru.d.ts +19 -0
- package/dist/row-model/lru.js +48 -0
- package/dist/row-model/lru.js.map +1 -0
- package/dist/row-model/sort.d.ts +30 -0
- package/dist/row-model/sort.js +107 -0
- package/dist/row-model/sort.js.map +1 -0
- package/dist/row-model/summary.d.ts +64 -0
- package/dist/row-model/summary.js +213 -0
- package/dist/row-model/summary.js.map +1 -0
- package/dist/row-model/tree.d.ts +116 -0
- package/dist/row-model/tree.js +478 -0
- package/dist/row-model/tree.js.map +1 -0
- package/dist/row-model/types.d.ts +109 -0
- package/dist/row-model/types.js +5 -0
- package/dist/row-model/types.js.map +1 -0
- package/dist/row-model/value.d.ts +20 -0
- package/dist/row-model/value.js +57 -0
- package/dist/row-model/value.js.map +1 -0
- package/dist/state/grid-state.d.ts +147 -0
- package/dist/state/grid-state.js +295 -0
- package/dist/state/grid-state.js.map +1 -0
- package/dist/state/storage.d.ts +33 -0
- package/dist/state/storage.js +62 -0
- package/dist/state/storage.js.map +1 -0
- package/dist/state/versioned.d.ts +18 -0
- package/dist/state/versioned.js +56 -0
- package/dist/state/versioned.js.map +1 -0
- package/package.json +145 -6
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import type { GridColumnAlignment, GridColumnDataType, GridColumnDef, GridGroupPath, GridRowFixed, GridSummaryValue } from '../grid-column-def.js';
|
|
2
|
+
import type { DataGrid } from '../grid.js';
|
|
3
|
+
/** Options of `getExportData()`, `exportCsv()`, `downloadCsv()` and the xlsx and PDF adapters. */
|
|
4
|
+
export interface GridExportOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Only the selected rows, in the current order and filter (not in the
|
|
7
|
+
* selection order of `getSelectedItems()`); group counts and summaries are
|
|
8
|
+
* computed over them. Default `false`.
|
|
9
|
+
*/
|
|
10
|
+
selectedOnly?: boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Group rows (`rowType: 'group'`) and indentation levels. `false` exports a
|
|
13
|
+
* flat list in the current order with the grouped columns first. Default `true`.
|
|
14
|
+
*/
|
|
15
|
+
includeGroups?: boolean;
|
|
16
|
+
/** Group footers and totals (`group-footer` / `total` rows) and summaries in group rows. Default `true`. */
|
|
17
|
+
includeSummaries?: boolean;
|
|
18
|
+
/**
|
|
19
|
+
* Fixed rows (`fixedTopItems` before the body rows, `fixedBottomItems`
|
|
20
|
+
* before the totals; `rowType: 'data'` with `fixed`, `level: 0`).
|
|
21
|
+
* Default `true`; `selectedOnly: true` leaves them out.
|
|
22
|
+
*/
|
|
23
|
+
includeFixedRows?: boolean;
|
|
24
|
+
/** Aborts the export: the promise rejects with an `AbortError` (the PDF adapter: with `signal.reason`). */
|
|
25
|
+
signal?: AbortSignal | null;
|
|
26
|
+
}
|
|
27
|
+
/** Options of `exportCsv()`. */
|
|
28
|
+
export interface GridCsvOptions extends GridExportOptions {
|
|
29
|
+
/**
|
|
30
|
+
* Field separator: one character other than `"`, CR and LF (a `RangeError`
|
|
31
|
+
* otherwise). `auto` (default): `;` when the grid
|
|
32
|
+
* language uses a decimal comma (what Excel expects there), `,` otherwise.
|
|
33
|
+
*/
|
|
34
|
+
separator?: 'auto' | (string & {});
|
|
35
|
+
/** UTF-8 byte order mark, so Excel opens the file as UTF-8. Default `true`. */
|
|
36
|
+
bom?: boolean;
|
|
37
|
+
/** First line with the column labels. Default `true`. */
|
|
38
|
+
includeHeaders?: boolean;
|
|
39
|
+
/**
|
|
40
|
+
* Prefixes `'` to text starting with `=`, `+`, `-`, `@`, tab or CR, which a
|
|
41
|
+
* spreadsheet would run as a formula (CSV injection). Numbers are not
|
|
42
|
+
* prefixed. Default `true`.
|
|
43
|
+
*/
|
|
44
|
+
escapeFormulas?: boolean;
|
|
45
|
+
/**
|
|
46
|
+
* Cell values instead of the displayed text: numbers with `.`, dates in
|
|
47
|
+
* ISO 8601, booleans `true`/`false`, empty values as empty fields. Group
|
|
48
|
+
* labels and summaries stay text. Default `false`.
|
|
49
|
+
*/
|
|
50
|
+
rawValues?: boolean;
|
|
51
|
+
}
|
|
52
|
+
/** Options of `downloadCsv()`. */
|
|
53
|
+
export interface GridCsvDownloadOptions extends GridCsvOptions {
|
|
54
|
+
/** Name of the downloaded file. Default `export.csv`. */
|
|
55
|
+
fileName?: string;
|
|
56
|
+
}
|
|
57
|
+
/** An exported column (`GridExportData.columns`). */
|
|
58
|
+
export interface GridExportColumn<TItem = any> {
|
|
59
|
+
column: GridColumnDef<TItem>;
|
|
60
|
+
/** The column's name as text: `label`, else `path`, else `name`. */
|
|
61
|
+
label: string;
|
|
62
|
+
/** Effective data type (declared or inferred). */
|
|
63
|
+
dataType?: GridColumnDataType;
|
|
64
|
+
/** Effective logical alignment. */
|
|
65
|
+
alignment: GridColumnAlignment;
|
|
66
|
+
/** Current width in px, when known. */
|
|
67
|
+
width?: number;
|
|
68
|
+
}
|
|
69
|
+
/** A data row. `values[i]` / `texts[i]` belong to `columns[i]`. */
|
|
70
|
+
export interface GridExportDataRow<TItem = any> {
|
|
71
|
+
rowType: 'data';
|
|
72
|
+
/** Indentation level: the number of grouping levels above the row (0 without groups), or the depth of a tree node (0 = root; kept with `includeGroups: false`). */
|
|
73
|
+
level: number;
|
|
74
|
+
item: TItem;
|
|
75
|
+
/** Cell values (`valueGetter` or `path`). */
|
|
76
|
+
values: unknown[];
|
|
77
|
+
/** Displayed texts (`displayValue` / `format`). */
|
|
78
|
+
texts: string[];
|
|
79
|
+
/** `'top'`/`'bottom'` for a fixed row (`fixedTopItems`/`fixedBottomItems`), `null` for a body row. */
|
|
80
|
+
fixed: GridRowFixed;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* A group row. `summaries[i]` / `texts[i]` are the summaries shown under `columns[i]`
|
|
84
|
+
* (`display: 'column'`); those of the first column, or of a column not exported, are part of `label`.
|
|
85
|
+
*/
|
|
86
|
+
export interface GridExportGroupRow<TItem = any> {
|
|
87
|
+
rowType: 'group';
|
|
88
|
+
/** Grouping level (0 = outermost). */
|
|
89
|
+
level: number;
|
|
90
|
+
groupPath: GridGroupPath;
|
|
91
|
+
/** Grouped column. */
|
|
92
|
+
column: GridColumnDef<TItem>;
|
|
93
|
+
/** Group value. */
|
|
94
|
+
value: unknown;
|
|
95
|
+
/** Formatted group value (`"Brazil"`). */
|
|
96
|
+
text: string;
|
|
97
|
+
/** Whole group label with the count and inline summaries (`"Country: Brazil (3)"`). */
|
|
98
|
+
label: string;
|
|
99
|
+
/** Rows in the group. */
|
|
100
|
+
itemCount: number;
|
|
101
|
+
summaries: GridSummaryValue<TItem>[][];
|
|
102
|
+
/** Summary texts of each column, joined with the list separator of the language as on screen. */
|
|
103
|
+
texts: string[];
|
|
104
|
+
}
|
|
105
|
+
/** A group footer or the totals row. `summaries[i]` / `texts[i]` belong to `columns[i]`. */
|
|
106
|
+
export interface GridExportSummaryRow<TItem = any> {
|
|
107
|
+
rowType: 'group-footer' | 'total';
|
|
108
|
+
/** Indentation level: a group footer is at the level of its rows; totals at 0. */
|
|
109
|
+
level: number;
|
|
110
|
+
/** Group of the footer; `null` in the totals row. */
|
|
111
|
+
groupPath: GridGroupPath | null;
|
|
112
|
+
summaries: GridSummaryValue<TItem>[][];
|
|
113
|
+
texts: string[];
|
|
114
|
+
}
|
|
115
|
+
/** A row of `GridExportData`, told apart by `rowType`. */
|
|
116
|
+
export type GridExportRow<TItem = any> = GridExportDataRow<TItem> | GridExportGroupRow<TItem> | GridExportSummaryRow<TItem>;
|
|
117
|
+
/** What `getExportData()` returns: the columns and rows the user sees, ready for any file format. */
|
|
118
|
+
export interface GridExportData<TItem = any> {
|
|
119
|
+
/** Visible exportable columns in the current order (with `includeGroups: false`, the grouped columns first). */
|
|
120
|
+
columns: GridExportColumn<TItem>[];
|
|
121
|
+
rows: GridExportRow<TItem>[];
|
|
122
|
+
}
|
|
123
|
+
/** Formats offered by the export UI (`exportFormats`). May gain members in minor versions. */
|
|
124
|
+
export type GridExportFormat = 'csv' | 'xlsx' | 'pdf';
|
|
125
|
+
/** Progress of an export (`onProgress`): data rows done, data rows in total, pages so far (PDF). */
|
|
126
|
+
export interface GridExportProgress {
|
|
127
|
+
readonly rowCount: number;
|
|
128
|
+
readonly totalCount: number;
|
|
129
|
+
readonly pageCount: number;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* An export run by the grid UI (`xlsxExporter`, `pdfExporter`): build and
|
|
133
|
+
* download the file of what the user sees. Reject to report an error; honor
|
|
134
|
+
* `signal` (aborted when the grid disconnects or the user cancels: reject with
|
|
135
|
+
* an `AbortError`, which the grid reports as canceled, not as an error); call
|
|
136
|
+
* `onProgress` to show the progress in the export button.
|
|
137
|
+
*/
|
|
138
|
+
export type GridExporter = (grid: DataGrid, options: {
|
|
139
|
+
readonly selectedOnly: boolean;
|
|
140
|
+
readonly signal: AbortSignal;
|
|
141
|
+
readonly onProgress?: (progress: GridExportProgress) => void;
|
|
142
|
+
}) => Promise<void>;
|
|
143
|
+
/** `detail` of `u-grid-exporting` and `u-grid-export`. */
|
|
144
|
+
export interface GridExportingEventDetail {
|
|
145
|
+
readonly format: GridExportFormat;
|
|
146
|
+
/** Only the selected rows ("Export selected rows"). */
|
|
147
|
+
readonly selectedOnly: boolean;
|
|
148
|
+
}
|
|
149
|
+
/** `detail` of `u-grid-export`. */
|
|
150
|
+
export type GridExportEventDetail = GridExportingEventDetail;
|
|
151
|
+
/** `detail` of `u-grid-export-error`. */
|
|
152
|
+
export interface GridExportErrorEventDetail extends GridExportingEventDetail {
|
|
153
|
+
readonly error: unknown;
|
|
154
|
+
}
|
|
155
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/export/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n GridColumnAlignment,\n GridColumnDataType,\n GridColumnDef,\n GridGroupPath,\n GridRowFixed,\n GridSummaryValue,\n} from '../grid-column-def.js';\nimport type { DataGrid } from '../grid.js';\n\n/** Options of `getExportData()`, `exportCsv()`, `downloadCsv()` and the xlsx and PDF adapters. */\nexport interface GridExportOptions {\n /**\n * Only the selected rows, in the current order and filter (not in the\n * selection order of `getSelectedItems()`); group counts and summaries are\n * computed over them. Default `false`.\n */\n selectedOnly?: boolean;\n /**\n * Group rows (`rowType: 'group'`) and indentation levels. `false` exports a\n * flat list in the current order with the grouped columns first. Default `true`.\n */\n includeGroups?: boolean;\n /** Group footers and totals (`group-footer` / `total` rows) and summaries in group rows. Default `true`. */\n includeSummaries?: boolean;\n /**\n * Fixed rows (`fixedTopItems` before the body rows, `fixedBottomItems`\n * before the totals; `rowType: 'data'` with `fixed`, `level: 0`).\n * Default `true`; `selectedOnly: true` leaves them out.\n */\n includeFixedRows?: boolean;\n /** Aborts the export: the promise rejects with an `AbortError` (the PDF adapter: with `signal.reason`). */\n signal?: AbortSignal | null;\n}\n\n/** Options of `exportCsv()`. */\nexport interface GridCsvOptions extends GridExportOptions {\n /**\n * Field separator: one character other than `\"`, CR and LF (a `RangeError`\n * otherwise). `auto` (default): `;` when the grid\n * language uses a decimal comma (what Excel expects there), `,` otherwise.\n */\n separator?: 'auto' | (string & {});\n /** UTF-8 byte order mark, so Excel opens the file as UTF-8. Default `true`. */\n bom?: boolean;\n /** First line with the column labels. Default `true`. */\n includeHeaders?: boolean;\n /**\n * Prefixes `'` to text starting with `=`, `+`, `-`, `@`, tab or CR, which a\n * spreadsheet would run as a formula (CSV injection). Numbers are not\n * prefixed. Default `true`.\n */\n escapeFormulas?: boolean;\n /**\n * Cell values instead of the displayed text: numbers with `.`, dates in\n * ISO 8601, booleans `true`/`false`, empty values as empty fields. Group\n * labels and summaries stay text. Default `false`.\n */\n rawValues?: boolean;\n}\n\n/** Options of `downloadCsv()`. */\nexport interface GridCsvDownloadOptions extends GridCsvOptions {\n /** Name of the downloaded file. Default `export.csv`. */\n fileName?: string;\n}\n\n/** An exported column (`GridExportData.columns`). */\nexport interface GridExportColumn<TItem = any> {\n column: GridColumnDef<TItem>;\n /** The column's name as text: `label`, else `path`, else `name`. */\n label: string;\n /** Effective data type (declared or inferred). */\n dataType?: GridColumnDataType;\n /** Effective logical alignment. */\n alignment: GridColumnAlignment;\n /** Current width in px, when known. */\n width?: number;\n}\n\n/** A data row. `values[i]` / `texts[i]` belong to `columns[i]`. */\nexport interface GridExportDataRow<TItem = any> {\n rowType: 'data';\n /** Indentation level: the number of grouping levels above the row (0 without groups), or the depth of a tree node (0 = root; kept with `includeGroups: false`). */\n level: number;\n item: TItem;\n /** Cell values (`valueGetter` or `path`). */\n values: unknown[];\n /** Displayed texts (`displayValue` / `format`). */\n texts: string[];\n /** `'top'`/`'bottom'` for a fixed row (`fixedTopItems`/`fixedBottomItems`), `null` for a body row. */\n fixed: GridRowFixed;\n}\n\n/**\n * A group row. `summaries[i]` / `texts[i]` are the summaries shown under `columns[i]`\n * (`display: 'column'`); those of the first column, or of a column not exported, are part of `label`.\n */\nexport interface GridExportGroupRow<TItem = any> {\n rowType: 'group';\n /** Grouping level (0 = outermost). */\n level: number;\n groupPath: GridGroupPath;\n /** Grouped column. */\n column: GridColumnDef<TItem>;\n /** Group value. */\n value: unknown;\n /** Formatted group value (`\"Brazil\"`). */\n text: string;\n /** Whole group label with the count and inline summaries (`\"Country: Brazil (3)\"`). */\n label: string;\n /** Rows in the group. */\n itemCount: number;\n summaries: GridSummaryValue<TItem>[][];\n /** Summary texts of each column, joined with the list separator of the language as on screen. */\n texts: string[];\n}\n\n/** A group footer or the totals row. `summaries[i]` / `texts[i]` belong to `columns[i]`. */\nexport interface GridExportSummaryRow<TItem = any> {\n rowType: 'group-footer' | 'total';\n /** Indentation level: a group footer is at the level of its rows; totals at 0. */\n level: number;\n /** Group of the footer; `null` in the totals row. */\n groupPath: GridGroupPath | null;\n summaries: GridSummaryValue<TItem>[][];\n texts: string[];\n}\n\n/** A row of `GridExportData`, told apart by `rowType`. */\nexport type GridExportRow<TItem = any> = GridExportDataRow<TItem> | GridExportGroupRow<TItem> | GridExportSummaryRow<TItem>;\n\n/** What `getExportData()` returns: the columns and rows the user sees, ready for any file format. */\nexport interface GridExportData<TItem = any> {\n /** Visible exportable columns in the current order (with `includeGroups: false`, the grouped columns first). */\n columns: GridExportColumn<TItem>[];\n rows: GridExportRow<TItem>[];\n}\n\n/** Formats offered by the export UI (`exportFormats`). May gain members in minor versions. */\nexport type GridExportFormat = 'csv' | 'xlsx' | 'pdf';\n\n/** Progress of an export (`onProgress`): data rows done, data rows in total, pages so far (PDF). */\nexport interface GridExportProgress {\n readonly rowCount: number;\n readonly totalCount: number;\n readonly pageCount: number;\n}\n\n/**\n * An export run by the grid UI (`xlsxExporter`, `pdfExporter`): build and\n * download the file of what the user sees. Reject to report an error; honor\n * `signal` (aborted when the grid disconnects or the user cancels: reject with\n * an `AbortError`, which the grid reports as canceled, not as an error); call\n * `onProgress` to show the progress in the export button.\n */\nexport type GridExporter = (\n grid: DataGrid,\n options: {\n readonly selectedOnly: boolean;\n readonly signal: AbortSignal;\n readonly onProgress?: (progress: GridExportProgress) => void;\n },\n) => Promise<void>;\n\n/** `detail` of `u-grid-exporting` and `u-grid-export`. */\nexport interface GridExportingEventDetail {\n readonly format: GridExportFormat;\n /** Only the selected rows (\"Export selected rows\"). */\n readonly selectedOnly: boolean;\n}\n\n/** `detail` of `u-grid-export`. */\nexport type GridExportEventDetail = GridExportingEventDetail;\n\n/** `detail` of `u-grid-export-error`. */\nexport interface GridExportErrorEventDetail extends GridExportingEventDetail {\n readonly error: unknown;\n}\n"]}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { type ExportColumnSource, type ExportSource } from './rows.js';
|
|
2
|
+
import { type Slicer } from './slice.js';
|
|
3
|
+
import type { GridCsvOptions, GridExportRow } from './types.js';
|
|
4
|
+
/** Linhas de HTML da área de transferência; acima disso, só o TSV (montar a tabela custaria caro). */
|
|
5
|
+
export declare const CLIPBOARD_HTML_LIMIT = 10000;
|
|
6
|
+
/** Valor cru como texto (`rawValues`): número com `.`, data ISO 8601, booleano, vazio. */
|
|
7
|
+
export declare const rawText: (value: unknown, column: ExportColumnSource) => string;
|
|
8
|
+
/**
|
|
9
|
+
* CSV (RFC 4180) do instantâneo, em fatias de tempo: cede a vez ao
|
|
10
|
+
* navegador a cada `SLICE_MS` e confere o `signal` nessas pausas.
|
|
11
|
+
*/
|
|
12
|
+
export declare const writeCsv: (source: ExportSource, options: GridCsvOptions, language: string | undefined, slicer?: Slicer) => Promise<Blob>;
|
|
13
|
+
/** Todas as linhas do instantâneo, em fatias de tempo (`getExportData`). */
|
|
14
|
+
export declare const collectRows: (source: ExportSource, signal: AbortSignal | null | undefined, slicer?: Slicer) => Promise<GridExportRow[]>;
|
|
15
|
+
/** Conteúdo da área de transferência: TSV e tabela HTML (sem cabeçalho, fórmulas sempre protegidas). */
|
|
16
|
+
export interface ClipboardContent {
|
|
17
|
+
text: string;
|
|
18
|
+
html: string;
|
|
19
|
+
}
|
|
20
|
+
/** Direção e idioma do grid, levados para a `<table>` copiada. */
|
|
21
|
+
export interface ClipboardHtmlOptions {
|
|
22
|
+
rtl?: boolean;
|
|
23
|
+
lang?: string;
|
|
24
|
+
}
|
|
25
|
+
export declare const clipboardContent: (rows: readonly GridExportRow[], columns: readonly ExportColumnSource[], options?: ClipboardHtmlOptions) => ClipboardContent;
|
|
26
|
+
/** Células de HTML na cópia de intervalos (frente 19); acima disso, só o TSV. */
|
|
27
|
+
export declare const CLIPBOARD_HTML_CELL_LIMIT = 100000;
|
|
28
|
+
/** Um intervalo copiado: linhas de dados com as colunas dele (frente 19). */
|
|
29
|
+
export interface ClipboardBlock {
|
|
30
|
+
rows: readonly GridExportRow[];
|
|
31
|
+
columns: readonly ExportColumnSource[];
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Vários intervalos empilhados na vertical (na ordem dada, como o AG Grid):
|
|
35
|
+
* mesmo TSV/HTML protegido da 12, uma `<table>` só.
|
|
36
|
+
*/
|
|
37
|
+
export declare const clipboardBlocks: (blocks: readonly ClipboardBlock[], cells: number, options?: ClipboardHtmlOptions) => ClipboardContent;
|
|
38
|
+
//# sourceMappingURL=write.d.ts.map
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Escritores de texto da exportação (frente 12): CSV em blocos (sem travar a
|
|
3
|
+
* interface) e o conteúdo da área de transferência (TSV + tabela HTML).
|
|
4
|
+
*/
|
|
5
|
+
import { BOM, CRLF, csvField, escapeFormula, escapeHtml, isFormulaEscaped, resolveSeparator, tsvField } from './csv.js';
|
|
6
|
+
import { exportRows } from './rows.js';
|
|
7
|
+
import { createSlicer } from './slice.js';
|
|
8
|
+
/** Linhas de HTML da área de transferência; acima disso, só o TSV (montar a tabela custaria caro). */
|
|
9
|
+
export const CLIPBOARD_HTML_LIMIT = 10_000;
|
|
10
|
+
/**
|
|
11
|
+
* Blobs de fatia juntados num só a cada tantos (juntar blobs não copia os
|
|
12
|
+
* bytes; só encurta a lista). Cada fatia vira `Blob` na hora: codificar
|
|
13
|
+
* pouco texto por vez evita uma pausa longa, e o texto sai do heap do JS.
|
|
14
|
+
*/
|
|
15
|
+
const PARTS_PER_BLOB = 64;
|
|
16
|
+
const pad = (value, length = 2) => String(value).padStart(length, '0');
|
|
17
|
+
/** Data local em ISO 8601 (`date`: só o dia; senão com a hora e o fuso). */
|
|
18
|
+
const isoDate = (date, dateOnly) => {
|
|
19
|
+
const day = `${pad(date.getFullYear(), 4)}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
|
20
|
+
if (dateOnly) {
|
|
21
|
+
return day;
|
|
22
|
+
}
|
|
23
|
+
const offset = -date.getTimezoneOffset();
|
|
24
|
+
const zone = offset === 0
|
|
25
|
+
? 'Z'
|
|
26
|
+
: `${offset > 0 ? '+' : '-'}${pad(Math.floor(Math.abs(offset) / 60))}:${pad(Math.abs(offset) % 60)}`;
|
|
27
|
+
const time = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
|
28
|
+
return `${day}T${time}${date.getMilliseconds() ? `.${pad(date.getMilliseconds(), 3)}` : ''}${zone}`;
|
|
29
|
+
};
|
|
30
|
+
/** Valor cru como texto (`rawValues`): número com `.`, data ISO 8601, booleano, vazio. */
|
|
31
|
+
export const rawText = (value, column) => {
|
|
32
|
+
if (value === null || value === undefined) {
|
|
33
|
+
return '';
|
|
34
|
+
}
|
|
35
|
+
if (value instanceof Date) {
|
|
36
|
+
return Number.isNaN(value.getTime()) ? '' : isoDate(value, column.info.dataType === 'date');
|
|
37
|
+
}
|
|
38
|
+
if (typeof value === 'number') {
|
|
39
|
+
return Number.isFinite(value) ? String(value) : '';
|
|
40
|
+
}
|
|
41
|
+
return typeof value === 'object' ? JSON.stringify(value) ?? '' : String(value);
|
|
42
|
+
};
|
|
43
|
+
/** O valor tem texto confiável (número/data com a formatação embutida): fica sem o prefixo `'`. */
|
|
44
|
+
const isTrusted = (value, column) => (typeof value === 'number' || typeof value === 'bigint' || value instanceof Date) && column.builtIn;
|
|
45
|
+
/** Campos de uma linha (texto ainda sem escape de CSV). */
|
|
46
|
+
const fieldsOf = (row, columns, escape, raw) => {
|
|
47
|
+
const guard = (text) => escape ? escapeFormula(text) : text;
|
|
48
|
+
switch (row.rowType) {
|
|
49
|
+
case 'data':
|
|
50
|
+
return row.texts.map((text, index) => {
|
|
51
|
+
const column = columns[index];
|
|
52
|
+
const value = row.values[index];
|
|
53
|
+
const field = raw ? rawText(value, column) : text;
|
|
54
|
+
return escape && !isTrusted(value, column) ? escapeFormula(field) : field;
|
|
55
|
+
});
|
|
56
|
+
case 'group':
|
|
57
|
+
return row.texts.map((text, index) => guard(index ? text : row.label));
|
|
58
|
+
default:
|
|
59
|
+
return row.texts.map(guard);
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
/** Linha do CSV (sem a quebra). */
|
|
63
|
+
const csvLine = (fields, separator) => fields.map(field => csvField(field, separator)).join(separator);
|
|
64
|
+
/** Para no ponto de corte se `signal` abortou (`AbortError`). */
|
|
65
|
+
const checkAborted = (signal) => {
|
|
66
|
+
signal?.throwIfAborted();
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* CSV (RFC 4180) do instantâneo, em fatias de tempo: cede a vez ao
|
|
70
|
+
* navegador a cada `SLICE_MS` e confere o `signal` nessas pausas.
|
|
71
|
+
*/
|
|
72
|
+
export const writeCsv = async (source, options, language, slicer = createSlicer()) => {
|
|
73
|
+
const { signal } = options;
|
|
74
|
+
checkAborted(signal);
|
|
75
|
+
const separator = resolveSeparator(options.separator, language);
|
|
76
|
+
if (separator.length !== 1 || ['"', '\r', '\n'].includes(separator)) {
|
|
77
|
+
throw new RangeError(`Invalid CSV separator: ${JSON.stringify(separator)} (one character other than a quote, CR or LF).`);
|
|
78
|
+
}
|
|
79
|
+
const escape = options.escapeFormulas !== false;
|
|
80
|
+
const raw = options.rawValues === true;
|
|
81
|
+
const columns = source.columns;
|
|
82
|
+
let parts = [];
|
|
83
|
+
let lines = [];
|
|
84
|
+
if (options.bom !== false) {
|
|
85
|
+
lines.push(BOM);
|
|
86
|
+
}
|
|
87
|
+
const flush = () => {
|
|
88
|
+
if (lines.length) {
|
|
89
|
+
parts.push(new Blob([lines.join('')]));
|
|
90
|
+
lines = [];
|
|
91
|
+
}
|
|
92
|
+
if (parts.length >= PARTS_PER_BLOB) {
|
|
93
|
+
parts = [new Blob(parts)];
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
if (options.includeHeaders !== false) {
|
|
97
|
+
lines.push(csvLine(columns.map(column => escape ? escapeFormula(column.info.label) : column.info.label), separator), CRLF);
|
|
98
|
+
}
|
|
99
|
+
for (const row of exportRows(source)) {
|
|
100
|
+
lines.push(csvLine(fieldsOf(row, columns, escape, raw), separator), CRLF);
|
|
101
|
+
const pause = slicer.tick();
|
|
102
|
+
if (pause) {
|
|
103
|
+
flush();
|
|
104
|
+
await pause;
|
|
105
|
+
checkAborted(signal);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
flush();
|
|
109
|
+
return new Blob(parts, { type: 'text/csv;charset=utf-8' });
|
|
110
|
+
};
|
|
111
|
+
/** Todas as linhas do instantâneo, em fatias de tempo (`getExportData`). */
|
|
112
|
+
export const collectRows = async (source, signal, slicer = createSlicer()) => {
|
|
113
|
+
checkAborted(signal);
|
|
114
|
+
const rows = [];
|
|
115
|
+
for (const row of exportRows(source)) {
|
|
116
|
+
rows.push(row);
|
|
117
|
+
const pause = slicer.tick();
|
|
118
|
+
if (pause) {
|
|
119
|
+
await pause;
|
|
120
|
+
checkAborted(signal);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return rows;
|
|
124
|
+
};
|
|
125
|
+
/**
|
|
126
|
+
* Célula HTML. Texto protegido contra fórmula vai com
|
|
127
|
+
* `mso-number-format:"\@"` (o Excel cola como célula de texto) e MANTÉM o
|
|
128
|
+
* `'`: o LibreOffice ignora o `mso-number-format` na colagem e avaliaria o
|
|
129
|
+
* `=` (spec 12, "Referência medida").
|
|
130
|
+
*/
|
|
131
|
+
const htmlCell = (field) => isFormulaEscaped(field)
|
|
132
|
+
? `<td style='mso-number-format:"\\@"'>${escapeHtml(field)}</td>`
|
|
133
|
+
: `<td>${escapeHtml(field)}</td>`;
|
|
134
|
+
export const clipboardContent = (rows, columns, options = {}) => {
|
|
135
|
+
const lines = [];
|
|
136
|
+
const htmlRows = [];
|
|
137
|
+
const withHtml = rows.length <= CLIPBOARD_HTML_LIMIT;
|
|
138
|
+
for (const row of rows) {
|
|
139
|
+
const fields = fieldsOf(row, columns, true, false);
|
|
140
|
+
lines.push(fields.map(tsvField).join('\t'));
|
|
141
|
+
if (withHtml) {
|
|
142
|
+
htmlRows.push(`<tr>${fields.map(htmlCell).join('')}</tr>`);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const dir = options.rtl ? ' dir="rtl"' : '';
|
|
146
|
+
const lang = options.lang ? ` lang="${escapeHtml(options.lang)}"` : '';
|
|
147
|
+
return {
|
|
148
|
+
text: lines.join(CRLF),
|
|
149
|
+
html: withHtml ? `<table${dir}${lang}><tbody>${htmlRows.join('')}</tbody></table>` : '',
|
|
150
|
+
};
|
|
151
|
+
};
|
|
152
|
+
/** Células de HTML na cópia de intervalos (frente 19); acima disso, só o TSV. */
|
|
153
|
+
export const CLIPBOARD_HTML_CELL_LIMIT = 100_000;
|
|
154
|
+
/**
|
|
155
|
+
* Vários intervalos empilhados na vertical (na ordem dada, como o AG Grid):
|
|
156
|
+
* mesmo TSV/HTML protegido da 12, uma `<table>` só.
|
|
157
|
+
*/
|
|
158
|
+
export const clipboardBlocks = (blocks, cells, options = {}) => {
|
|
159
|
+
const lines = [];
|
|
160
|
+
const htmlRows = [];
|
|
161
|
+
const withHtml = cells <= CLIPBOARD_HTML_CELL_LIMIT;
|
|
162
|
+
for (const { rows, columns } of blocks) {
|
|
163
|
+
for (const row of rows) {
|
|
164
|
+
const fields = fieldsOf(row, columns, true, false);
|
|
165
|
+
lines.push(fields.map(tsvField).join('\t'));
|
|
166
|
+
if (withHtml) {
|
|
167
|
+
htmlRows.push(`<tr>${fields.map(htmlCell).join('')}</tr>`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
const dir = options.rtl ? ' dir="rtl"' : '';
|
|
172
|
+
const lang = options.lang ? ` lang="${escapeHtml(options.lang)}"` : '';
|
|
173
|
+
return {
|
|
174
|
+
text: lines.join(CRLF),
|
|
175
|
+
html: withHtml ? `<table${dir}${lang}><tbody>${htmlRows.join('')}</tbody></table>` : '',
|
|
176
|
+
};
|
|
177
|
+
};
|
|
178
|
+
//# sourceMappingURL=write.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"write.js","sourceRoot":"","sources":["../../src/export/write.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,QAAQ,EAAE,aAAa,EAAE,UAAU,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AACxH,OAAO,EAA2B,UAAU,EAAqB,MAAM,WAAW,CAAC;AACnF,OAAO,EAAE,YAAY,EAAe,MAAM,YAAY,CAAC;AAGvD,sGAAsG;AACtG,MAAM,CAAC,MAAM,oBAAoB,GAAG,MAAM,CAAC;AAE3C;;;;GAIG;AACH,MAAM,cAAc,GAAG,EAAE,CAAC;AAE1B,MAAM,GAAG,GAAG,CAAC,KAAa,EAAE,MAAM,GAAG,CAAC,EAAU,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAEvF,4EAA4E;AAC5E,MAAM,OAAO,GAAG,CAAC,IAAU,EAAE,QAAiB,EAAU,EAAE;IACxD,MAAM,GAAG,GAAG,GAAG,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC;IAE/F,IAAI,QAAQ,EAAE,CAAC;QACb,OAAO,GAAG,CAAC;IACb,CAAC;IAED,MAAM,MAAM,GAAG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AK,GAAa,EAAE,CAAC;IAC3B,MAAM,QAAQ,GAAa,EAAE,CAAC;IAC9B,MAAM,QAAQ,GAAG,KAAK,IAAI,yBAAyB,CAAC;IAEpD,KAAK,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,MAAM,EAAE,CAAC;QACvC,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;YACvB,MAAM,MAAM,GAAG,QAAQ,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;YACnD,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;YAE5C,IAAI,QAAQ,EAAE,CAAC;gBACb,QAAQ,CAAC,IAAI,CAAC,OAAO,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC;YAC7D,CAAC;QACH,CAAC;IACH,CAAC;IAED,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,CAAC;IAC5C,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,UAAU,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;IAEvE,OAAO;QACL,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC;QACtB,IAAI,EAAE,QAAQ,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG,IAAI,WAAW,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,kBAAkB,CAAC,CAAC,CAAC,EAAE;KACxF,CAAC;AACJ,CAAC,CAAC","sourcesContent":["/**\n * Escritores de texto da exportação (frente 12): CSV em blocos (sem travar a\n * interface) e o conteúdo da área de transferência (TSV + tabela HTML).\n */\nimport { BOM, CRLF, csvField, escapeFormula, escapeHtml, isFormulaEscaped, resolveSeparator, tsvField } from './csv.js';\nimport { type ExportColumnSource, exportRows, type ExportSource } from './rows.js';\nimport { createSlicer, type Slicer } from './slice.js';\nimport type { GridCsvOptions, GridExportRow } from './types.js';\n\n/** Linhas de HTML da área de transferência; acima disso, só o TSV (montar a tabela custaria caro). */\nexport const CLIPBOARD_HTML_LIMIT = 10_000;\n\n/**\n * Blobs de fatia juntados num só a cada tantos (juntar blobs não copia os\n * bytes; só encurta a lista). Cada fatia vira `Blob` na hora: codificar\n * pouco texto por vez evita uma pausa longa, e o texto sai do heap do JS.\n */\nconst PARTS_PER_BLOB = 64;\n\nconst pad = (value: number, length = 2): string => String(value).padStart(length, '0');\n\n/** Data local em ISO 8601 (`date`: só o dia; senão com a hora e o fuso). */\nconst isoDate = (date: Date, dateOnly: boolean): string => {\n const day = `${pad(date.getFullYear(), 4)}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;\n\n if (dateOnly) {\n return day;\n }\n\n const offset = -date.getTimezoneOffset();\n const zone = offset === 0\n ? 'Z'\n : `${offset > 0 ? '+' : '-'}${pad(Math.floor(Math.abs(offset) / 60))}:${pad(Math.abs(offset) % 60)}`;\n const time = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;\n\n return `${day}T${time}${date.getMilliseconds() ? `.${pad(date.getMilliseconds(), 3)}` : ''}${zone}`;\n};\n\n/** Valor cru como texto (`rawValues`): número com `.`, data ISO 8601, booleano, vazio. */\nexport const rawText = (value: unknown, column: ExportColumnSource): string => {\n if (value === null || value === undefined) {\n return '';\n }\n\n if (value instanceof Date) {\n return Number.isNaN(value.getTime()) ? '' : isoDate(value, column.info.dataType === 'date');\n }\n\n if (typeof value === 'number') {\n return Number.isFinite(value) ? String(value) : '';\n }\n\n return typeof value === 'object' ? JSON.stringify(value) ?? '' : String(value);\n};\n\n/** O valor tem texto confiável (número/data com a formatação embutida): fica sem o prefixo `'`. */\nconst isTrusted = (value: unknown, column: ExportColumnSource): boolean =>\n (typeof value === 'number' || typeof value === 'bigint' || value instanceof Date) && column.builtIn;\n\n/** Campos de uma linha (texto ainda sem escape de CSV). */\nconst fieldsOf = (\n row: GridExportRow,\n columns: readonly ExportColumnSource[],\n escape: boolean,\n raw: boolean,\n): string[] => {\n const guard = (text: string): string => escape ? escapeFormula(text) : text;\n\n switch (row.rowType) {\n case 'data':\n return row.texts.map((text, index) => {\n const column = columns[index];\n const value = row.values[index];\n const field = raw ? rawText(value, column) : text;\n\n return escape && !isTrusted(value, column) ? escapeFormula(field) : field;\n });\n case 'group':\n return row.texts.map((text, index) => guard(index ? text : row.label));\n default:\n return row.texts.map(guard);\n }\n};\n\n/** Linha do CSV (sem a quebra). */\nconst csvLine = (fields: readonly string[], separator: string): string =>\n fields.map(field => csvField(field, separator)).join(separator);\n\n/** Para no ponto de corte se `signal` abortou (`AbortError`). */\nconst checkAborted = (signal: AbortSignal | null | undefined): void => {\n signal?.throwIfAborted();\n};\n\n/**\n * CSV (RFC 4180) do instantâneo, em fatias de tempo: cede a vez ao\n * navegador a cada `SLICE_MS` e confere o `signal` nessas pausas.\n */\nexport const writeCsv = async (\n source: ExportSource,\n options: GridCsvOptions,\n language: string | undefined,\n slicer: Slicer = createSlicer(),\n): Promise<Blob> => {\n const { signal } = options;\n checkAborted(signal);\n\n const separator = resolveSeparator(options.separator, language);\n\n if (separator.length !== 1 || ['\"', '\\r', '\\n'].includes(separator)) {\n throw new RangeError(`Invalid CSV separator: ${JSON.stringify(separator)} (one character other than a quote, CR or LF).`);\n }\n\n const escape = options.escapeFormulas !== false;\n const raw = options.rawValues === true;\n const columns = source.columns;\n let parts: BlobPart[] = [];\n let lines: string[] = [];\n\n if (options.bom !== false) {\n lines.push(BOM);\n }\n\n const flush = (): void => {\n if (lines.length) {\n parts.push(new Blob([lines.join('')]));\n lines = [];\n }\n\n if (parts.length >= PARTS_PER_BLOB) {\n parts = [new Blob(parts)];\n }\n };\n\n if (options.includeHeaders !== false) {\n lines.push(csvLine(columns.map(column => escape ? escapeFormula(column.info.label) : column.info.label), separator), CRLF);\n }\n\n for (const row of exportRows(source)) {\n lines.push(csvLine(fieldsOf(row, columns, escape, raw), separator), CRLF);\n\n const pause = slicer.tick();\n\n if (pause) {\n flush();\n await pause;\n checkAborted(signal);\n }\n }\n\n flush();\n return new Blob(parts, { type: 'text/csv;charset=utf-8' });\n};\n\n/** Todas as linhas do instantâneo, em fatias de tempo (`getExportData`). */\nexport const collectRows = async (source: ExportSource, signal: AbortSignal | null | undefined, slicer: Slicer = createSlicer()): Promise<GridExportRow[]> => {\n checkAborted(signal);\n\n const rows: GridExportRow[] = [];\n\n for (const row of exportRows(source)) {\n rows.push(row);\n\n const pause = slicer.tick();\n\n if (pause) {\n await pause;\n checkAborted(signal);\n }\n }\n\n return rows;\n};\n\n/** Conteúdo da área de transferência: TSV e tabela HTML (sem cabeçalho, fórmulas sempre protegidas). */\nexport interface ClipboardContent {\n text: string;\n html: string;\n}\n\n/** Direção e idioma do grid, levados para a `<table>` copiada. */\nexport interface ClipboardHtmlOptions {\n rtl?: boolean;\n lang?: string;\n}\n\n/**\n * Célula HTML. Texto protegido contra fórmula vai com\n * `mso-number-format:\"\\@\"` (o Excel cola como célula de texto) e MANTÉM o\n * `'`: o LibreOffice ignora o `mso-number-format` na colagem e avaliaria o\n * `=` (spec 12, \"Referência medida\").\n */\nconst htmlCell = (field: string): string =>\n isFormulaEscaped(field)\n ? `<td style='mso-number-format:\"\\\\@\"'>${escapeHtml(field)}</td>`\n : `<td>${escapeHtml(field)}</td>`;\n\nexport const clipboardContent = (\n rows: readonly GridExportRow[],\n columns: readonly ExportColumnSource[],\n options: ClipboardHtmlOptions = {},\n): ClipboardContent => {\n const lines: string[] = [];\n const htmlRows: string[] = [];\n const withHtml = rows.length <= CLIPBOARD_HTML_LIMIT;\n\n for (const row of rows) {\n const fields = fieldsOf(row, columns, true, false);\n lines.push(fields.map(tsvField).join('\\t'));\n\n if (withHtml) {\n htmlRows.push(`<tr>${fields.map(htmlCell).join('')}</tr>`);\n }\n }\n\n const dir = options.rtl ? ' dir=\"rtl\"' : '';\n const lang = options.lang ? ` lang=\"${escapeHtml(options.lang)}\"` : '';\n\n return {\n text: lines.join(CRLF),\n html: withHtml ? `<table${dir}${lang}><tbody>${htmlRows.join('')}</tbody></table>` : '',\n };\n};\n\n/** Células de HTML na cópia de intervalos (frente 19); acima disso, só o TSV. */\nexport const CLIPBOARD_HTML_CELL_LIMIT = 100_000;\n\n/** Um intervalo copiado: linhas de dados com as colunas dele (frente 19). */\nexport interface ClipboardBlock {\n rows: readonly GridExportRow[];\n columns: readonly ExportColumnSource[];\n}\n\n/**\n * Vários intervalos empilhados na vertical (na ordem dada, como o AG Grid):\n * mesmo TSV/HTML protegido da 12, uma `<table>` só.\n */\nexport const clipboardBlocks = (\n blocks: readonly ClipboardBlock[],\n cells: number,\n options: ClipboardHtmlOptions = {},\n): ClipboardContent => {\n const lines: string[] = [];\n const htmlRows: string[] = [];\n const withHtml = cells <= CLIPBOARD_HTML_CELL_LIMIT;\n\n for (const { rows, columns } of blocks) {\n for (const row of rows) {\n const fields = fieldsOf(row, columns, true, false);\n lines.push(fields.map(tsvField).join('\\t'));\n\n if (withHtml) {\n htmlRows.push(`<tr>${fields.map(htmlCell).join('')}</tr>`);\n }\n }\n }\n\n const dir = options.rtl ? ' dir=\"rtl\"' : '';\n const lang = options.lang ? ` lang=\"${escapeHtml(options.lang)}\"` : '';\n\n return {\n text: lines.join(CRLF),\n html: withHtml ? `<table${dir}${lang}><tbody>${htmlRows.join('')}</tbody></table>` : '',\n };\n};\n"]}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
export interface RowsResult {
|
|
2
|
+
chunks: Uint8Array[];
|
|
3
|
+
pages: number;
|
|
4
|
+
done: boolean;
|
|
5
|
+
}
|
|
6
|
+
export interface Client {
|
|
7
|
+
addFont(bytes: Uint8Array, bold: boolean, italic: boolean): Promise<void>;
|
|
8
|
+
begin(config: Uint8Array): Promise<void>;
|
|
9
|
+
addImage(bytes: Uint8Array, format: number, width: number, height: number): Promise<number>;
|
|
10
|
+
/** Entrega um bloco de linhas (passa a ser do cliente) e espera o layout dele (`last`: fecha a entrada). */
|
|
11
|
+
rows(data: Uint8Array, last: boolean): Promise<RowsResult>;
|
|
12
|
+
finish(): Promise<Uint8Array[]>;
|
|
13
|
+
dispose(): void;
|
|
14
|
+
}
|
|
15
|
+
/** Pedido ao worker. */
|
|
16
|
+
export type WorkerRequest = {
|
|
17
|
+
id: number;
|
|
18
|
+
op: 'init';
|
|
19
|
+
module: WebAssembly.Module;
|
|
20
|
+
role: 'engine' | 'assembler';
|
|
21
|
+
deferred: boolean;
|
|
22
|
+
} | {
|
|
23
|
+
id: number;
|
|
24
|
+
op: 'segments';
|
|
25
|
+
data: ArrayBuffer[];
|
|
26
|
+
} | {
|
|
27
|
+
id: number;
|
|
28
|
+
op: 'font';
|
|
29
|
+
bytes: ArrayBuffer;
|
|
30
|
+
bold: boolean;
|
|
31
|
+
italic: boolean;
|
|
32
|
+
} | {
|
|
33
|
+
id: number;
|
|
34
|
+
op: 'begin';
|
|
35
|
+
config: ArrayBuffer;
|
|
36
|
+
} | {
|
|
37
|
+
id: number;
|
|
38
|
+
op: 'image';
|
|
39
|
+
bytes: ArrayBuffer;
|
|
40
|
+
format: number;
|
|
41
|
+
width: number;
|
|
42
|
+
height: number;
|
|
43
|
+
} | {
|
|
44
|
+
id: number;
|
|
45
|
+
op: 'rows';
|
|
46
|
+
data: ArrayBuffer;
|
|
47
|
+
last: boolean;
|
|
48
|
+
} | {
|
|
49
|
+
id: number;
|
|
50
|
+
op: 'finish';
|
|
51
|
+
};
|
|
52
|
+
/** Resposta do worker. */
|
|
53
|
+
export type WorkerResponse = {
|
|
54
|
+
id: number;
|
|
55
|
+
ok: true;
|
|
56
|
+
value?: number;
|
|
57
|
+
chunks?: ArrayBuffer[];
|
|
58
|
+
pages?: number;
|
|
59
|
+
done?: boolean;
|
|
60
|
+
} | {
|
|
61
|
+
id: number;
|
|
62
|
+
ok: false;
|
|
63
|
+
code: number;
|
|
64
|
+
message: string;
|
|
65
|
+
};
|
|
66
|
+
/** Na thread principal: layout em fatias com `scheduler.yield()` entre elas. */
|
|
67
|
+
export declare const localClient: (wasmUrl: string) => Promise<Client>;
|
|
68
|
+
/**
|
|
69
|
+
* Em Web Workers: o motor faz o layout e entrega segmentos crus; o montador
|
|
70
|
+
* (segundo worker) comprime e escreve o arquivo, em paralelo com o layout das
|
|
71
|
+
* próximas linhas. Encerrar (`dispose`) rejeita o pedido pendente com
|
|
72
|
+
* `AbortError`.
|
|
73
|
+
*/
|
|
74
|
+
export declare const workerClient: (worker: Worker, assemblerWorker: Worker, wasmUrl: string) => Promise<Client>;
|
|
75
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* O motor de um lado só: no Web Worker (mensagens) ou na thread principal
|
|
3
|
+
* (fatias de tempo). A API é a mesma; o PDF volta em blocos.
|
|
4
|
+
*/
|
|
5
|
+
import { yieldToHost } from '../export/slice.js';
|
|
6
|
+
import { compileEngine, Engine, EngineError } from './engine.js';
|
|
7
|
+
/** Orçamento de uma fatia na thread principal (ms). */
|
|
8
|
+
const SLICE_MS = 8;
|
|
9
|
+
/** Na thread principal: layout em fatias com `scheduler.yield()` entre elas. */
|
|
10
|
+
export const localClient = async (wasmUrl) => {
|
|
11
|
+
const engine = new Engine((await WebAssembly.instantiate(await compileEngine(wasmUrl), {})).exports);
|
|
12
|
+
// erro síncrono do motor vira promessa rejeitada
|
|
13
|
+
const run = (f) => new Promise(resolve => resolve(f()));
|
|
14
|
+
return {
|
|
15
|
+
addFont: (bytes, bold, italic) => run(() => engine.addFont(bytes, bold, italic)),
|
|
16
|
+
begin: config => run(() => engine.begin(config)),
|
|
17
|
+
addImage: (bytes, format, width, height) => run(() => engine.addImage(bytes, format, width, height)),
|
|
18
|
+
rows: async (data, last) => {
|
|
19
|
+
engine.pushRows(data);
|
|
20
|
+
if (last) {
|
|
21
|
+
engine.endInput();
|
|
22
|
+
}
|
|
23
|
+
let done = false;
|
|
24
|
+
const chunks = [];
|
|
25
|
+
for (;;) {
|
|
26
|
+
const start = performance.now();
|
|
27
|
+
do {
|
|
28
|
+
done = engine.layout(1);
|
|
29
|
+
} while (!done && engine.pendingRows > 0 && performance.now() - start < SLICE_MS);
|
|
30
|
+
chunks.push(...engine.takeChunks());
|
|
31
|
+
if (done || engine.pendingRows === 0) {
|
|
32
|
+
break;
|
|
33
|
+
}
|
|
34
|
+
await yieldToHost();
|
|
35
|
+
}
|
|
36
|
+
return { chunks, pages: engine.pageCount, done };
|
|
37
|
+
},
|
|
38
|
+
finish: () => run(() => {
|
|
39
|
+
engine.finish();
|
|
40
|
+
return engine.takeChunks();
|
|
41
|
+
}),
|
|
42
|
+
dispose: () => engine.dispose(),
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
/** Cópia do conteúdo num `ArrayBuffer` próprio (pode ser transferido sem esvaziar o do hospedeiro). */
|
|
46
|
+
const own = (bytes) => bytes.slice().buffer;
|
|
47
|
+
/** Canal de pedidos a um worker: cada pedido com `id`, resposta casada pelo `id`. */
|
|
48
|
+
const channel = (worker) => {
|
|
49
|
+
let next = 0;
|
|
50
|
+
const pending = new Map();
|
|
51
|
+
const fail = (error) => {
|
|
52
|
+
for (const p of pending.values()) {
|
|
53
|
+
p.reject(error);
|
|
54
|
+
}
|
|
55
|
+
pending.clear();
|
|
56
|
+
};
|
|
57
|
+
worker.onmessage = (event) => {
|
|
58
|
+
const r = event.data;
|
|
59
|
+
const p = pending.get(r.id);
|
|
60
|
+
if (!p) {
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
pending.delete(r.id);
|
|
64
|
+
if (r.ok) {
|
|
65
|
+
p.resolve(r);
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
p.reject(new EngineError(r.code, r.message));
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
worker.onerror = event => {
|
|
72
|
+
event.preventDefault();
|
|
73
|
+
fail(new Error(`PDF worker failed: ${event.message || 'unknown error'}`));
|
|
74
|
+
};
|
|
75
|
+
const call = (request, transfer = []) => new Promise((resolve, reject) => {
|
|
76
|
+
const id = ++next;
|
|
77
|
+
pending.set(id, { resolve, reject });
|
|
78
|
+
worker.postMessage({ ...request, id }, transfer);
|
|
79
|
+
});
|
|
80
|
+
return { call, fail };
|
|
81
|
+
};
|
|
82
|
+
/** Montagens em voo antes de o motor esperar (limita os segmentos crus na fila do montador). */
|
|
83
|
+
const ASSEMBLER_INFLIGHT = 2;
|
|
84
|
+
/**
|
|
85
|
+
* Em Web Workers: o motor faz o layout e entrega segmentos crus; o montador
|
|
86
|
+
* (segundo worker) comprime e escreve o arquivo, em paralelo com o layout das
|
|
87
|
+
* próximas linhas. Encerrar (`dispose`) rejeita o pedido pendente com
|
|
88
|
+
* `AbortError`.
|
|
89
|
+
*/
|
|
90
|
+
export const workerClient = async (worker, assemblerWorker, wasmUrl) => {
|
|
91
|
+
const engine = channel(worker);
|
|
92
|
+
const asm = channel(assemblerWorker);
|
|
93
|
+
// o módulo compilado uma vez na thread principal (o código e a otimização ficam entre exportações)
|
|
94
|
+
const module = await compileEngine(wasmUrl);
|
|
95
|
+
await Promise.all([
|
|
96
|
+
engine.call({ op: 'init', module, role: 'engine', deferred: true }),
|
|
97
|
+
asm.call({ op: 'init', module, role: 'assembler', deferred: false }),
|
|
98
|
+
]);
|
|
99
|
+
// blocos do arquivo na ordem em que o montador os devolve; montagens em voo, na ordem
|
|
100
|
+
const ready = [];
|
|
101
|
+
const inflight = [];
|
|
102
|
+
let done = false;
|
|
103
|
+
const assemble = (segments) => {
|
|
104
|
+
const p = asm.call({ op: 'segments', data: segments }, segments).then(r => {
|
|
105
|
+
ready.push(...(r.chunks ?? []).map(c => new Uint8Array(c)));
|
|
106
|
+
done ||= !!r.done;
|
|
107
|
+
});
|
|
108
|
+
// falha tratada no próximo `await` dela (sem "unhandled rejection")
|
|
109
|
+
p.catch(() => undefined);
|
|
110
|
+
inflight.push(p);
|
|
111
|
+
};
|
|
112
|
+
const drain = async (keep) => {
|
|
113
|
+
while (inflight.length > keep) {
|
|
114
|
+
await inflight.shift();
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
return {
|
|
118
|
+
addFont: async (bytes, bold, italic) => {
|
|
119
|
+
const buffer = own(bytes);
|
|
120
|
+
await engine.call({ op: 'font', bytes: buffer, bold, italic }, [buffer]);
|
|
121
|
+
},
|
|
122
|
+
begin: async (config) => {
|
|
123
|
+
const buffer = own(config);
|
|
124
|
+
await engine.call({ op: 'begin', config: buffer }, [buffer]);
|
|
125
|
+
},
|
|
126
|
+
addImage: async (bytes, format, width, height) => {
|
|
127
|
+
const buffer = own(bytes);
|
|
128
|
+
return (await engine.call({ op: 'image', bytes: buffer, format, width, height }, [buffer])).value ?? 0;
|
|
129
|
+
},
|
|
130
|
+
rows: async (data, last) => {
|
|
131
|
+
// o bloco é do cliente a partir daqui: transfere sem copiar quando ocupa o buffer inteiro
|
|
132
|
+
const buffer = data.byteOffset === 0 && data.byteLength === data.buffer.byteLength ? data.buffer : own(data);
|
|
133
|
+
const r = await engine.call({ op: 'rows', data: buffer, last }, [buffer]);
|
|
134
|
+
assemble(r.chunks ?? []);
|
|
135
|
+
await drain(ASSEMBLER_INFLIGHT);
|
|
136
|
+
return { chunks: ready.splice(0), pages: r.pages ?? 0, done: !!r.done };
|
|
137
|
+
},
|
|
138
|
+
finish: async () => {
|
|
139
|
+
assemble((await engine.call({ op: 'finish' })).chunks ?? []);
|
|
140
|
+
await drain(0);
|
|
141
|
+
if (!done) {
|
|
142
|
+
throw new Error('PDF assembler did not finish the file');
|
|
143
|
+
}
|
|
144
|
+
return ready.splice(0);
|
|
145
|
+
},
|
|
146
|
+
dispose: () => {
|
|
147
|
+
worker.terminate();
|
|
148
|
+
assemblerWorker.terminate();
|
|
149
|
+
const abort = new DOMException('The PDF export was aborted.', 'AbortError');
|
|
150
|
+
engine.fail(abort);
|
|
151
|
+
asm.fail(abort);
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
};
|
|
155
|
+
//# sourceMappingURL=client.js.map
|