@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.
Files changed (237) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +172 -2
  3. package/custom-elements.json +4652 -0
  4. package/dist/attribute-converters.d.ts +53 -0
  5. package/dist/attribute-converters.js +98 -0
  6. package/dist/attribute-converters.js.map +1 -0
  7. package/dist/change-source.d.ts +3 -0
  8. package/dist/change-source.js +2 -0
  9. package/dist/change-source.js.map +1 -0
  10. package/dist/data/data-source.d.ts +164 -0
  11. package/dist/data/data-source.js +75 -0
  12. package/dist/data/data-source.js.map +1 -0
  13. package/dist/data/local-source.d.ts +20 -0
  14. package/dist/data/local-source.js +94 -0
  15. package/dist/data/local-source.js.map +1 -0
  16. package/dist/data/remote-loader.d.ts +190 -0
  17. package/dist/data/remote-loader.js +608 -0
  18. package/dist/data/remote-loader.js.map +1 -0
  19. package/dist/export/csv.d.ts +28 -0
  20. package/dist/export/csv.js +61 -0
  21. package/dist/export/csv.js.map +1 -0
  22. package/dist/export/download.d.ts +7 -0
  23. package/dist/export/download.js +17 -0
  24. package/dist/export/download.js.map +1 -0
  25. package/dist/export/rows.d.ts +75 -0
  26. package/dist/export/rows.js +134 -0
  27. package/dist/export/rows.js.map +1 -0
  28. package/dist/export/slice.d.ts +15 -0
  29. package/dist/export/slice.js +35 -0
  30. package/dist/export/slice.js.map +1 -0
  31. package/dist/export/types.d.ts +155 -0
  32. package/dist/export/types.js +2 -0
  33. package/dist/export/types.js.map +1 -0
  34. package/dist/export/write.d.ts +38 -0
  35. package/dist/export/write.js +178 -0
  36. package/dist/export/write.js.map +1 -0
  37. package/dist/export-pdf/client.d.ts +75 -0
  38. package/dist/export-pdf/client.js +155 -0
  39. package/dist/export-pdf/client.js.map +1 -0
  40. package/dist/export-pdf/engine.d.ts +73 -0
  41. package/dist/export-pdf/engine.js +131 -0
  42. package/dist/export-pdf/engine.js.map +1 -0
  43. package/dist/export-pdf/grid-pdf.wasm +0 -0
  44. package/dist/export-pdf/index.d.ts +27 -0
  45. package/dist/export-pdf/index.js +566 -0
  46. package/dist/export-pdf/index.js.map +1 -0
  47. package/dist/export-pdf/serialize.d.ts +23 -0
  48. package/dist/export-pdf/serialize.js +127 -0
  49. package/dist/export-pdf/serialize.js.map +1 -0
  50. package/dist/export-pdf/types.d.ts +150 -0
  51. package/dist/export-pdf/types.js +2 -0
  52. package/dist/export-pdf/types.js.map +1 -0
  53. package/dist/export-pdf/worker.d.ts +2 -0
  54. package/dist/export-pdf/worker.js +81 -0
  55. package/dist/export-pdf/worker.js.map +1 -0
  56. package/dist/export-xlsx/formats.d.ts +14 -0
  57. package/dist/export-xlsx/formats.js +40 -0
  58. package/dist/export-xlsx/formats.js.map +1 -0
  59. package/dist/export-xlsx/index.d.ts +74 -0
  60. package/dist/export-xlsx/index.js +137 -0
  61. package/dist/export-xlsx/index.js.map +1 -0
  62. package/dist/features/adaptive.d.ts +25 -0
  63. package/dist/features/adaptive.js +47 -0
  64. package/dist/features/adaptive.js.map +1 -0
  65. package/dist/features/cell-content-focus.d.ts +29 -0
  66. package/dist/features/cell-content-focus.js +95 -0
  67. package/dist/features/cell-content-focus.js.map +1 -0
  68. package/dist/features/cell-range.d.ts +97 -0
  69. package/dist/features/cell-range.js +75 -0
  70. package/dist/features/cell-range.js.map +1 -0
  71. package/dist/features/clipboard.d.ts +28 -0
  72. package/dist/features/clipboard.js +48 -0
  73. package/dist/features/clipboard.js.map +1 -0
  74. package/dist/features/column-chooser.d.ts +91 -0
  75. package/dist/features/column-chooser.js +451 -0
  76. package/dist/features/column-chooser.js.map +1 -0
  77. package/dist/features/column-dnd.d.ts +10 -0
  78. package/dist/features/column-dnd.js +126 -0
  79. package/dist/features/column-dnd.js.map +1 -0
  80. package/dist/features/context-menu.d.ts +122 -0
  81. package/dist/features/context-menu.js +153 -0
  82. package/dist/features/context-menu.js.map +1 -0
  83. package/dist/features/drag-helper.d.ts +39 -0
  84. package/dist/features/drag-helper.js +108 -0
  85. package/dist/features/drag-helper.js.map +1 -0
  86. package/dist/features/drop-position.d.ts +15 -0
  87. package/dist/features/drop-position.js +24 -0
  88. package/dist/features/drop-position.js.map +1 -0
  89. package/dist/features/editing.d.ts +111 -0
  90. package/dist/features/editing.js +244 -0
  91. package/dist/features/editing.js.map +1 -0
  92. package/dist/features/filter-row.d.ts +80 -0
  93. package/dist/features/filter-row.js +538 -0
  94. package/dist/features/filter-row.js.map +1 -0
  95. package/dist/features/filtering.d.ts +55 -0
  96. package/dist/features/filtering.js +209 -0
  97. package/dist/features/filtering.js.map +1 -0
  98. package/dist/features/group-dnd.d.ts +11 -0
  99. package/dist/features/group-dnd.js +119 -0
  100. package/dist/features/group-dnd.js.map +1 -0
  101. package/dist/features/header-filter.d.ts +100 -0
  102. package/dist/features/header-filter.js +588 -0
  103. package/dist/features/header-filter.js.map +1 -0
  104. package/dist/features/host-label.d.ts +36 -0
  105. package/dist/features/host-label.js +184 -0
  106. package/dist/features/host-label.js.map +1 -0
  107. package/dist/features/keyboard.d.ts +59 -0
  108. package/dist/features/keyboard.js +127 -0
  109. package/dist/features/keyboard.js.map +1 -0
  110. package/dist/features/menu.d.ts +113 -0
  111. package/dist/features/menu.js +491 -0
  112. package/dist/features/menu.js.map +1 -0
  113. package/dist/features/resize.d.ts +82 -0
  114. package/dist/features/resize.js +214 -0
  115. package/dist/features/resize.js.map +1 -0
  116. package/dist/features/scroll-port.d.ts +51 -0
  117. package/dist/features/scroll-port.js +329 -0
  118. package/dist/features/scroll-port.js.map +1 -0
  119. package/dist/features/search.d.ts +45 -0
  120. package/dist/features/search.js +123 -0
  121. package/dist/features/search.js.map +1 -0
  122. package/dist/features/selection.d.ts +37 -0
  123. package/dist/features/selection.js +103 -0
  124. package/dist/features/selection.js.map +1 -0
  125. package/dist/features/sorting.d.ts +39 -0
  126. package/dist/features/sorting.js +53 -0
  127. package/dist/features/sorting.js.map +1 -0
  128. package/dist/features/toolbar.d.ts +125 -0
  129. package/dist/features/toolbar.js +135 -0
  130. package/dist/features/toolbar.js.map +1 -0
  131. package/dist/features/tree.d.ts +53 -0
  132. package/dist/features/tree.js +94 -0
  133. package/dist/features/tree.js.map +1 -0
  134. package/dist/features/validation.d.ts +48 -0
  135. package/dist/features/validation.js +172 -0
  136. package/dist/features/validation.js.map +1 -0
  137. package/dist/grid-column-def.d.ts +521 -0
  138. package/dist/grid-column-def.js +32 -0
  139. package/dist/grid-column-def.js.map +1 -0
  140. package/dist/grid-column.d.ts +173 -0
  141. package/dist/grid-column.js +382 -0
  142. package/dist/grid-column.js.map +1 -0
  143. package/dist/grid-i18n.d.ts +469 -0
  144. package/dist/grid-i18n.js +3222 -0
  145. package/dist/grid-i18n.js.map +1 -0
  146. package/dist/grid.d.ts +1510 -0
  147. package/dist/grid.js +15972 -0
  148. package/dist/grid.js.map +1 -0
  149. package/dist/grid.min.js +3966 -0
  150. package/dist/grid.styles.d.ts +2 -0
  151. package/dist/grid.styles.js +2849 -0
  152. package/dist/grid.styles.js.map +1 -0
  153. package/dist/render/cell.d.ts +16 -0
  154. package/dist/render/cell.js +78 -0
  155. package/dist/render/cell.js.map +1 -0
  156. package/dist/render/column-window.d.ts +18 -0
  157. package/dist/render/column-window.js +50 -0
  158. package/dist/render/column-window.js.map +1 -0
  159. package/dist/render/content.d.ts +45 -0
  160. package/dist/render/content.js +140 -0
  161. package/dist/render/content.js.map +1 -0
  162. package/dist/render/editors.d.ts +28 -0
  163. package/dist/render/editors.js +41 -0
  164. package/dist/render/editors.js.map +1 -0
  165. package/dist/render/footer.d.ts +61 -0
  166. package/dist/render/footer.js +61 -0
  167. package/dist/render/footer.js.map +1 -0
  168. package/dist/render/group-row.d.ts +35 -0
  169. package/dist/render/group-row.js +60 -0
  170. package/dist/render/group-row.js.map +1 -0
  171. package/dist/render/header.d.ts +108 -0
  172. package/dist/render/header.js +124 -0
  173. package/dist/render/header.js.map +1 -0
  174. package/dist/render/keyed-rows.d.ts +25 -0
  175. package/dist/render/keyed-rows.js +98 -0
  176. package/dist/render/keyed-rows.js.map +1 -0
  177. package/dist/render/virtualizer.d.ts +158 -0
  178. package/dist/render/virtualizer.js +721 -0
  179. package/dist/render/virtualizer.js.map +1 -0
  180. package/dist/row-model/added-rows.d.ts +32 -0
  181. package/dist/row-model/added-rows.js +95 -0
  182. package/dist/row-model/added-rows.js.map +1 -0
  183. package/dist/row-model/cell-range.d.ts +71 -0
  184. package/dist/row-model/cell-range.js +187 -0
  185. package/dist/row-model/cell-range.js.map +1 -0
  186. package/dist/row-model/columns.d.ts +102 -0
  187. package/dist/row-model/columns.js +222 -0
  188. package/dist/row-model/columns.js.map +1 -0
  189. package/dist/row-model/compare.d.ts +40 -0
  190. package/dist/row-model/compare.js +590 -0
  191. package/dist/row-model/compare.js.map +1 -0
  192. package/dist/row-model/distinct.d.ts +39 -0
  193. package/dist/row-model/distinct.js +105 -0
  194. package/dist/row-model/distinct.js.map +1 -0
  195. package/dist/row-model/filter.d.ts +80 -0
  196. package/dist/row-model/filter.js +582 -0
  197. package/dist/row-model/filter.js.map +1 -0
  198. package/dist/row-model/flatten.d.ts +129 -0
  199. package/dist/row-model/flatten.js +511 -0
  200. package/dist/row-model/flatten.js.map +1 -0
  201. package/dist/row-model/fold.d.ts +25 -0
  202. package/dist/row-model/fold.js +104 -0
  203. package/dist/row-model/fold.js.map +1 -0
  204. package/dist/row-model/format.d.ts +58 -0
  205. package/dist/row-model/format.js +239 -0
  206. package/dist/row-model/format.js.map +1 -0
  207. package/dist/row-model/group.d.ts +30 -0
  208. package/dist/row-model/group.js +173 -0
  209. package/dist/row-model/group.js.map +1 -0
  210. package/dist/row-model/lru.d.ts +19 -0
  211. package/dist/row-model/lru.js +48 -0
  212. package/dist/row-model/lru.js.map +1 -0
  213. package/dist/row-model/sort.d.ts +30 -0
  214. package/dist/row-model/sort.js +107 -0
  215. package/dist/row-model/sort.js.map +1 -0
  216. package/dist/row-model/summary.d.ts +64 -0
  217. package/dist/row-model/summary.js +213 -0
  218. package/dist/row-model/summary.js.map +1 -0
  219. package/dist/row-model/tree.d.ts +116 -0
  220. package/dist/row-model/tree.js +478 -0
  221. package/dist/row-model/tree.js.map +1 -0
  222. package/dist/row-model/types.d.ts +109 -0
  223. package/dist/row-model/types.js +5 -0
  224. package/dist/row-model/types.js.map +1 -0
  225. package/dist/row-model/value.d.ts +20 -0
  226. package/dist/row-model/value.js +57 -0
  227. package/dist/row-model/value.js.map +1 -0
  228. package/dist/state/grid-state.d.ts +147 -0
  229. package/dist/state/grid-state.js +295 -0
  230. package/dist/state/grid-state.js.map +1 -0
  231. package/dist/state/storage.d.ts +33 -0
  232. package/dist/state/storage.js +62 -0
  233. package/dist/state/storage.js.map +1 -0
  234. package/dist/state/versioned.d.ts +18 -0
  235. package/dist/state/versioned.js +56 -0
  236. package/dist/state/versioned.js.map +1 -0
  237. package/package.json +145 -6
@@ -0,0 +1,566 @@
1
+ /* eslint-disable no-bitwise -- bits de estilo das células no protocolo do motor. */
2
+ /**
3
+ * Exportação em PDF (frente 26): `@universal-material/data-grid/export-pdf`.
4
+ *
5
+ * PDF marcado (alvo PDF/UA-1) gerado por um motor WebAssembly (crate `pdf/`)
6
+ * num Web Worker: lê o que o usuário vê em blocos (`_exportStream`), aplica
7
+ * `customizeCell`, serializa e manda ao motor; o arquivo volta em blocos.
8
+ * O `.wasm` e o worker só são baixados ao exportar.
9
+ */
10
+ import { downloadBlob } from '../export/download.js';
11
+ import { createSlicer } from '../export/slice.js';
12
+ import { resolveGridTranslation } from '../grid-i18n.js';
13
+ import { LruCache } from '../row-model/lru.js';
14
+ import { localClient, workerClient } from './client.js';
15
+ import { EngineCode, EngineError, readFileUrl } from './engine.js';
16
+ import { contrast, parseColor, Writer } from './serialize.js';
17
+ /** Some characters have no glyph in any of the `fonts`: the PDF would lose them (PDF/UA). Add a font that covers them. */
18
+ export class GridPdfMissingGlyphError extends Error {
19
+ constructor(codePoints) {
20
+ const list = codePoints.slice(0, 12).map(cp => `U+${cp.toString(16).toUpperCase()
21
+ .padStart(4, '0')}`)
22
+ .join(', ');
23
+ super(`No font covers ${codePoints.length} character(s): ${list}${codePoints.length > 12 ? ', …' : ''}. Add a font for them to "fonts".`);
24
+ this.name = 'GridPdfMissingGlyphError';
25
+ this.codePoints = Object.freeze([...codePoints]);
26
+ }
27
+ }
28
+ // ------------------------------------------------------------------ padrões
29
+ const PAPER = {
30
+ a4: [595.28, 841.89],
31
+ letter: [612, 792],
32
+ legal: [612, 1008],
33
+ a3: [841.89, 1190.55],
34
+ };
35
+ /** Regiões que usam Carta (Letter). */
36
+ const LETTER_REGIONS = new Set(['US', 'CA', 'MX', 'PH', 'CL', 'CO', 'VE', 'PR', 'GT', 'CR', 'PA', 'DO', 'SV', 'NI', 'HN', 'BO', 'BZ']);
37
+ const THEME = {
38
+ color: 0x1a1a1a,
39
+ headerBackgroundColor: 0xe6e6e6,
40
+ groupBackgroundColor: 0xf0f0f0,
41
+ stripedBackgroundColor: 0xf7f7f7,
42
+ summaryBackgroundColor: 0xececec,
43
+ lineColor: 0x8a8a8a,
44
+ };
45
+ const WHITE = 0xffffff;
46
+ const MIN_CONTRAST = 4.5;
47
+ const MARGIN = 36;
48
+ const BATCH_ROWS = 2000;
49
+ const PROGRESS_MS = 250;
50
+ /** Orçamento de uma fatia de serialização na thread principal (ms de relógio). */
51
+ const PDF_SLICE_MS = 4;
52
+ /** Tamanho da fonte do grid quando não há grid (px). */
53
+ const GRID_FONT_PX = 14;
54
+ /** Largura de coluna sem largura conhecida (px), como a regra da spec 21. */
55
+ const DEFAULT_COLUMN_PX = 150;
56
+ // ------------------------------------------------------------------ avisos limitados
57
+ const warned = new LruCache(64);
58
+ const warnOnce = (key, message) => {
59
+ if (!warned.get(key)) {
60
+ warned.set(key, true);
61
+ console.warn(`<u-grid> PDF: ${message}`);
62
+ }
63
+ };
64
+ // ------------------------------------------------------------------ fontes
65
+ /** Fontes lidas (cópias), por origem: limitado. */
66
+ const fontCache = new LruCache(8);
67
+ const loadFont = (font, signal) => {
68
+ const source = font.source;
69
+ const key = typeof source === 'string' || source instanceof URL ? String(source) : source;
70
+ let bytes = fontCache.get(key);
71
+ if (!bytes) {
72
+ bytes = (async () => {
73
+ if (typeof source === 'string' || source instanceof URL) {
74
+ const href = String(source);
75
+ if (href.startsWith('file:')) {
76
+ return readFileUrl(href);
77
+ }
78
+ const response = await fetch(source, { signal: signal ?? undefined });
79
+ if (!response.ok) {
80
+ throw new Error(`could not load font ${String(source)} (${response.status})`);
81
+ }
82
+ return new Uint8Array(await response.arrayBuffer());
83
+ }
84
+ // cópia: o buffer do hospedeiro nunca é transferido nem mudado
85
+ return source instanceof Uint8Array ? source.slice() : new Uint8Array(source.slice(0));
86
+ })();
87
+ bytes.catch(() => fontCache.delete(key));
88
+ fontCache.set(key, bytes);
89
+ }
90
+ return bytes;
91
+ };
92
+ const validate = (options) => {
93
+ if (!options || !Array.isArray(options.fonts) || options.fonts.length === 0) {
94
+ throw new TypeError('<u-grid> PDF: "fonts" must be a non-empty array of fonts.');
95
+ }
96
+ options.fonts.forEach((font, i) => {
97
+ const s = font?.source;
98
+ if (!(s instanceof ArrayBuffer || s instanceof Uint8Array || typeof s === 'string' || s instanceof URL)) {
99
+ throw new TypeError(`<u-grid> PDF: fonts[${i}].source must be an ArrayBuffer, a Uint8Array or a URL.`);
100
+ }
101
+ });
102
+ if (options.layout && !['table', 'sections', 'list'].includes(options.layout)) {
103
+ throw new TypeError(`<u-grid> PDF: unknown layout "${options.layout}".`);
104
+ }
105
+ };
106
+ const isGrid = (source) => typeof source._exportStream === 'function';
107
+ const validLanguage = (language) => {
108
+ if (!language) {
109
+ return undefined;
110
+ }
111
+ try {
112
+ return Intl.getCanonicalLocales(language)[0];
113
+ }
114
+ catch {
115
+ warnOnce(`lang:${language}`, `"${language}" is not a valid language tag; it was ignored.`);
116
+ return undefined;
117
+ }
118
+ };
119
+ const contextOf = (source, options) => {
120
+ const includeGroups = options.layout !== 'list';
121
+ if (isGrid(source)) {
122
+ const stream = source._exportStream({ ...options, includeGroups });
123
+ const { content, text } = source._exportLanguages;
124
+ const language = validLanguage(options.language) ?? validLanguage(content) ?? 'en';
125
+ const translation = source._exportTranslation;
126
+ const style = getComputedStyle(source);
127
+ return {
128
+ title: options.title?.trim() || source._exportName.trim() || translation.pdfDefaultTitle,
129
+ language,
130
+ textLanguage: text,
131
+ rtl: (options.direction ?? style.direction) === 'rtl',
132
+ translation,
133
+ striped: options.striped ?? source.striped,
134
+ autoHide: options.autoHideColumns ?? source.autoHideColumns,
135
+ gridFontPx: parseFloat(style.fontSize) || GRID_FONT_PX,
136
+ columns: stream.columns,
137
+ rows: stream.rows,
138
+ totalCount: stream.totalCount,
139
+ };
140
+ }
141
+ const language = validLanguage(options.language) ?? 'en';
142
+ const translation = resolveGridTranslation(language);
143
+ return {
144
+ title: options.title?.trim() || translation.pdfDefaultTitle,
145
+ language,
146
+ textLanguage: language,
147
+ rtl: options.direction === 'rtl',
148
+ translation,
149
+ striped: !!options.striped,
150
+ autoHide: !!options.autoHideColumns,
151
+ gridFontPx: GRID_FONT_PX,
152
+ columns: source.columns,
153
+ rows: source.rows[Symbol.iterator](),
154
+ totalCount: source.rows.filter(row => row.rowType === 'data').length,
155
+ };
156
+ };
157
+ // ------------------------------------------------------------------ configuração
158
+ const paperOf = (size, language) => {
159
+ if (size && size !== 'auto') {
160
+ return PAPER[size] ?? PAPER.a4;
161
+ }
162
+ let region;
163
+ try {
164
+ region = new Intl.Locale(language).maximize().region;
165
+ }
166
+ catch {
167
+ region = undefined;
168
+ }
169
+ return region && LETTER_REGIONS.has(region) ? PAPER.letter : PAPER.a4;
170
+ };
171
+ /** Tema com contraste: a cor reprovada volta ao padrão (com aviso). */
172
+ const themeOf = (options) => {
173
+ const t = options.theme ?? {};
174
+ const pick = (name) => {
175
+ const value = t[name];
176
+ if (value === undefined) {
177
+ return THEME[name];
178
+ }
179
+ const parsed = parseColor(value);
180
+ if (parsed === undefined) {
181
+ warnOnce(`color:${value}`, `"${value}" is not a color; the default ${name} was used.`);
182
+ return THEME[name];
183
+ }
184
+ return parsed;
185
+ };
186
+ let color = pick('color');
187
+ if (contrast(color, WHITE) < MIN_CONTRAST) {
188
+ warnOnce(`theme-color:${color}`, 'theme.color has a contrast below 4.5:1 with the page; the default was used.');
189
+ color = THEME.color;
190
+ }
191
+ const background = (name) => {
192
+ const bg = pick(name);
193
+ if (contrast(color, bg) < MIN_CONTRAST) {
194
+ warnOnce(`theme-${name}:${bg}`, `theme.${name} has a contrast below 4.5:1 with the text; the default was used.`);
195
+ return THEME[name];
196
+ }
197
+ return bg;
198
+ };
199
+ return {
200
+ color,
201
+ header: background('headerBackgroundColor'),
202
+ group: background('groupBackgroundColor'),
203
+ stripe: background('stripedBackgroundColor'),
204
+ summary: background('summaryBackgroundColor'),
205
+ line: pick('lineColor'),
206
+ };
207
+ };
208
+ const ALIGN = { start: 0, left: 0, center: 1, end: 2, right: 2 };
209
+ const configOf = (ctx, options, theme) => {
210
+ const w = new Writer();
211
+ const fontSize = Math.max(6, options.theme?.fontSize ?? 8);
212
+ const [pw, ph] = paperOf(options.paperSize, ctx.language);
213
+ const scale = fontSize / ctx.gridFontPx;
214
+ const anyPriority = ctx.columns.some(c => Number.isFinite(c.column.hidingPriority));
215
+ w.u8(1);
216
+ w.str(ctx.title);
217
+ w.str(ctx.language);
218
+ w.str(ctx.textLanguage);
219
+ w.u8(ctx.rtl ? 1 : 0);
220
+ w.u8(options.layout === 'sections' ? 1 : options.layout === 'list' ? 2 : 0);
221
+ w.f32(pw);
222
+ w.f32(ph);
223
+ w.u8(options.orientation === 'portrait' ? 1 : options.orientation === 'landscape' ? 2 : 0);
224
+ w.f32(MARGIN);
225
+ w.f32(fontSize);
226
+ w.u32((options.includePageNumbers !== false ? 1 : 0)
227
+ | (options.bookmarks !== false ? 2 : 0)
228
+ | (ctx.striped ? 4 : 0)
229
+ | (ctx.autoHide ? 8 : 0)
230
+ | (anyPriority ? 16 : 0));
231
+ for (const c of [theme.color, theme.header, theme.group, theme.stripe, theme.summary, theme.line]) {
232
+ w.u32(c);
233
+ }
234
+ w.str(ctx.translation.pdfPageNumber);
235
+ w.str(ctx.translation.adaptiveLabelSeparator);
236
+ w.str(ctx.translation.pdfTotalRow);
237
+ w.u16(ctx.columns.length);
238
+ for (const c of ctx.columns) {
239
+ const px = c.width ?? Math.max(Number(c.column.minWidth) || 0, DEFAULT_COLUMN_PX);
240
+ w.str(c.label);
241
+ w.f32(px * scale);
242
+ w.u8(ALIGN[c.alignment] ?? 0);
243
+ w.i32(Number.isFinite(c.column.hidingPriority) ? Math.trunc(c.column.hidingPriority) : -2147483648);
244
+ w.u8(c.column.fixed ? 1 : 0);
245
+ }
246
+ return w.take();
247
+ };
248
+ const rowBackground = (rowType, theme) => rowType === 'header' ? [theme.header] : rowType === 'group' ? [theme.group] : rowType === 'data' ? [WHITE, theme.stripe] : [theme.summary];
249
+ /** Célula sem `customizeCell` (o caso comum): só texto e negrito. */
250
+ const writePlain = (w, text, bold) => {
251
+ w.u16(bold ? 1 : 0);
252
+ w.str(text);
253
+ };
254
+ /** Aplica `customizeCell` e escreve a célula (síncrono: a imagem nova é registrada sem esperar). */
255
+ const writeCell = (w, pending, theme, options, base) => {
256
+ if (!options.customizeCell) {
257
+ writePlain(w, base.text, !!base.style.bold);
258
+ return;
259
+ }
260
+ const cell = { ...base, style: { ...base.style } };
261
+ options.customizeCell?.(cell);
262
+ const text = typeof cell.text === 'string' ? cell.text : String(cell.text ?? '');
263
+ const style = cell.style ?? {};
264
+ let color = parseColor(style.color);
265
+ let bg = parseColor(style.backgroundColor);
266
+ const finalBgs = bg !== undefined ? [bg] : rowBackground(base.rowType, theme);
267
+ const finalColor = color ?? theme.color;
268
+ if (finalBgs.some(b => contrast(finalColor, b) < MIN_CONTRAST)) {
269
+ warnOnce(`cell:${finalColor}:${finalBgs.join()}`, 'a cell color has a contrast below 4.5:1 with its background; the theme colors were used.');
270
+ color = undefined;
271
+ if (bg !== undefined && contrast(theme.color, bg) < MIN_CONTRAST) {
272
+ bg = undefined;
273
+ }
274
+ }
275
+ const lang = validLanguage(cell.lang);
276
+ let image;
277
+ let alt = '';
278
+ if (cell.image) {
279
+ const img = cell.image;
280
+ if (!(img.data instanceof Uint8Array) || (img.format !== 'png' && img.format !== 'jpeg')) {
281
+ warnOnce('image-format', 'customizeCell image needs "data" (Uint8Array) and "format" (png or jpeg); it was ignored.');
282
+ }
283
+ else if (typeof img.alt !== 'string') {
284
+ warnOnce('image-alt', 'customizeCell image without "alt" was ignored (use "" for a decorative image).');
285
+ }
286
+ else if ((base.rowType === 'header' || base.rowType === 'group') && !text && !img.alt.trim()) {
287
+ warnOnce('image-header', 'an image in a header or group cell needs a text or a non-empty "alt"; it was ignored.');
288
+ }
289
+ else {
290
+ let id = pending.images.get(img.data);
291
+ if (id === undefined) {
292
+ // as mensagens ao motor são em ordem: a imagem chega antes do bloco que a usa
293
+ id = pending.nextImage++;
294
+ const registering = pending.client.addImage(img.data, img.format === 'jpeg' ? 1 : 0, Math.max(1, img.width || 0), Math.max(1, img.height || 0));
295
+ registering.catch(() => undefined);
296
+ pending.registering.push(registering);
297
+ pending.images.set(img.data, id);
298
+ }
299
+ image = id;
300
+ alt = img.alt;
301
+ }
302
+ }
303
+ let link;
304
+ if (cell.link) {
305
+ const url = String(cell.link.url ?? '').trim();
306
+ const description = String(cell.link.description ?? '');
307
+ if (!(/^(https?:|mailto:)/i).test(url)) {
308
+ warnOnce(`link:${url.slice(0, 20)}`, `link "${url.slice(0, 40)}" was ignored (only http:, https: and mailto:).`);
309
+ }
310
+ else if (!text && !alt && !description) {
311
+ warnOnce('link-text', 'a link without text, alt or description was ignored.');
312
+ }
313
+ else {
314
+ link = [url, description];
315
+ }
316
+ }
317
+ const align = style.alignment ? ALIGN[style.alignment] + 1 : 0;
318
+ const flags = (style.bold ? 1 : 0)
319
+ | (style.italic ? 2 : 0)
320
+ | (color !== undefined ? 4 : 0)
321
+ | (bg !== undefined ? 8 : 0)
322
+ | (lang ? 16 : 0)
323
+ | (image !== undefined ? 32 : 0)
324
+ | (link ? 64 : 0)
325
+ | (align << 8);
326
+ w.u16(flags);
327
+ w.str(text);
328
+ if (color !== undefined) {
329
+ w.u32(color);
330
+ }
331
+ if (bg !== undefined) {
332
+ w.u32(bg);
333
+ }
334
+ if (lang) {
335
+ w.str(lang);
336
+ }
337
+ if (image !== undefined) {
338
+ w.u32(image);
339
+ w.str(alt);
340
+ }
341
+ if (link) {
342
+ w.str(link[0]);
343
+ w.str(link[1]);
344
+ }
345
+ };
346
+ const KIND = { data: 0, group: 1, 'group-footer': 2, total: 3 };
347
+ // ------------------------------------------------------------------ exportação
348
+ const clientOf = async (options) => {
349
+ // `new URL('./…', import.meta.url)` literal: os bundlers (Vite, webpack, esbuild) copiam o arquivo
350
+ const wasm = options.assetsUrl ? new URL('grid-pdf.wasm', options.assetsUrl).href : new URL('./grid-pdf.wasm', import.meta.url).href;
351
+ const factory = options.worker;
352
+ if (factory === false || (typeof factory !== 'function' && typeof Worker === 'undefined')) {
353
+ return localClient(wasm);
354
+ }
355
+ // dois workers: o motor (layout) e o montador (deflate e escrita), em paralelo
356
+ const create = typeof factory === 'function'
357
+ ? factory
358
+ : () => options.assetsUrl
359
+ ? new Worker(new URL('worker.js', options.assetsUrl), { type: 'module' })
360
+ : new Worker(new URL('./worker.js', import.meta.url), { type: 'module' });
361
+ const engine = create();
362
+ let assembler;
363
+ try {
364
+ assembler = create();
365
+ return await workerClient(engine, assembler, wasm);
366
+ }
367
+ catch (error) {
368
+ engine.terminate();
369
+ assembler?.terminate();
370
+ throw error;
371
+ }
372
+ };
373
+ const rethrow = (error) => {
374
+ if (error instanceof EngineError && error.code === EngineCode.MissingGlyph) {
375
+ throw new GridPdfMissingGlyphError(error.message.split(',').filter(Boolean)
376
+ .map(hex => parseInt(hex, 16)));
377
+ }
378
+ throw error;
379
+ };
380
+ /**
381
+ * The PDF of what the user sees (with a grid: visible columns in the current
382
+ * order, filter, sorting, groups and summaries) or of ready data: a tagged PDF
383
+ * (PDF/UA-1 target) with the given fonts embedded. Runs in a Web Worker; the
384
+ * `.wasm` and the worker load on the first export.
385
+ */
386
+ export const exportPdf = async (source, options) => {
387
+ validate(options);
388
+ const signal = options.signal;
389
+ signal?.throwIfAborted();
390
+ const ctx = contextOf(source, options);
391
+ const theme = themeOf(options);
392
+ const fonts = await Promise.all(options.fonts.map(font => loadFont(font, signal)));
393
+ signal?.throwIfAborted();
394
+ const client = await clientOf(options);
395
+ const onAbort = () => client.dispose();
396
+ signal?.addEventListener('abort', onAbort, { once: true });
397
+ const parts = [];
398
+ const keep = (chunks) => {
399
+ for (const chunk of chunks) {
400
+ parts.push(new Blob([chunk]));
401
+ }
402
+ };
403
+ let pageCount = 0;
404
+ let rowCount = 0;
405
+ let lastProgress = 0;
406
+ const progress = (force = false) => {
407
+ const now = performance.now();
408
+ if (options.onProgress && !signal?.aborted && (force || now - lastProgress >= PROGRESS_MS)) {
409
+ lastProgress = now;
410
+ try {
411
+ options.onProgress({ rowCount, totalCount: Math.max(ctx.totalCount, rowCount), pageCount });
412
+ }
413
+ catch (error) {
414
+ console.error('<u-grid> PDF: onProgress failed.', error);
415
+ }
416
+ }
417
+ };
418
+ try {
419
+ for (const [i, bytes] of fonts.entries()) {
420
+ const font = options.fonts[i];
421
+ await client.addFont(bytes, font.weight === 'bold', font.style === 'italic');
422
+ }
423
+ await client.begin(configOf(ctx, options, theme));
424
+ const pending = { images: new Map(), client, nextImage: 0, registering: [] };
425
+ const w = new Writer();
426
+ let count = 0;
427
+ // Um bloco em voo: o worker faz o layout de um enquanto a thread principal serializa o próximo.
428
+ let inflight = null;
429
+ // o bloco começa pelo total de linhas, preenchido no envio
430
+ w.u32(0);
431
+ const flush = async (last) => {
432
+ w.setU32(0, count);
433
+ const data = w.take();
434
+ w.u32(0);
435
+ count = 0;
436
+ if (pending.registering.length) {
437
+ const registering = pending.registering;
438
+ pending.registering = [];
439
+ await Promise.all(registering);
440
+ }
441
+ if (inflight) {
442
+ await inflight;
443
+ }
444
+ signal?.throwIfAborted();
445
+ inflight = client.rows(data, last).then(r => {
446
+ keep(r.chunks);
447
+ pageCount = r.pages;
448
+ progress();
449
+ });
450
+ // Falha do bloco em voo: tratada aqui e relançada no próximo `await` (sem "unhandled rejection").
451
+ inflight.catch(() => undefined);
452
+ if (last) {
453
+ await inflight;
454
+ inflight = null;
455
+ }
456
+ };
457
+ // cabeçalho
458
+ w.u8(4);
459
+ w.u8(0);
460
+ w.u16(ctx.columns.length);
461
+ for (const [i, column] of ctx.columns.entries()) {
462
+ writeCell(w, pending, theme, options, { rowType: 'header', row: null, column, columnIndex: i, value: column.label, text: column.label, style: { bold: true } });
463
+ }
464
+ count++;
465
+ const groupText = [];
466
+ // fatia menor que a do CSV: a thread principal também recebe os blocos do worker (Blobs,
467
+ // repasse ao montador) e o GC desses objetos cai nas mesmas tarefas
468
+ const slicer = createSlicer(PDF_SLICE_MS);
469
+ let next = ctx.rows.next();
470
+ while (!next.done) {
471
+ const row = next.value;
472
+ const kind = KIND[row.rowType];
473
+ if (kind === undefined) {
474
+ warnOnce(`row:${String(row.rowType)}`, `rows of type "${String(row.rowType)}" are not supported and were left out.`);
475
+ next = ctx.rows.next();
476
+ continue;
477
+ }
478
+ w.u8(kind);
479
+ w.u8(Math.min(255, row.level));
480
+ if (row.rowType === 'group') {
481
+ groupText[row.level] = row.text;
482
+ groupText.length = row.level + 1;
483
+ w.u16(1 + ctx.columns.length);
484
+ writeCell(w, pending, theme, options, { rowType: 'group', row, column: null, columnIndex: -1, value: row.value, text: row.label, style: { bold: true } });
485
+ for (const [i, column] of ctx.columns.entries()) {
486
+ writeCell(w, pending, theme, options, { rowType: 'group', row, column, columnIndex: i, value: row.summaries[i], text: row.texts[i] ?? '', style: {} });
487
+ }
488
+ }
489
+ else if (row.rowType === 'data' && !options.customizeCell) {
490
+ // caminho rápido (o caso comum): só os textos, sem objetos por célula
491
+ const texts = row.texts;
492
+ const n = ctx.columns.length;
493
+ w.u16(n);
494
+ for (let i = 0; i < n; i++) {
495
+ writePlain(w, texts[i] ?? '', false);
496
+ }
497
+ rowCount++;
498
+ }
499
+ else {
500
+ const total = row.rowType === 'total';
501
+ w.u16(ctx.columns.length);
502
+ for (const [i, column] of ctx.columns.entries()) {
503
+ let text = row.texts[i] ?? '';
504
+ // 1ª célula do rodapé de grupo: o grupo (cabeçalho de linha no PDF)
505
+ if (i === 0 && !text && row.rowType === 'group-footer') {
506
+ text = groupText[Math.max(0, row.level - 1)] ?? '';
507
+ }
508
+ const value = row.rowType === 'data' ? row.values[i] : row.summaries[i];
509
+ writeCell(w, pending, theme, options, { rowType: row.rowType, row, column, columnIndex: i, value, text, style: { bold: total } });
510
+ }
511
+ if (row.rowType === 'data') {
512
+ rowCount++;
513
+ }
514
+ }
515
+ count++;
516
+ if (count >= BATCH_ROWS) {
517
+ await flush(false);
518
+ }
519
+ const pause = slicer.tick();
520
+ if (pause) {
521
+ await pause;
522
+ signal?.throwIfAborted();
523
+ }
524
+ next = ctx.rows.next();
525
+ }
526
+ await flush(true);
527
+ keep(await client.finish());
528
+ signal?.throwIfAborted();
529
+ progress(true);
530
+ }
531
+ catch (error) {
532
+ client.dispose();
533
+ if (signal?.aborted) {
534
+ throw signal.reason;
535
+ }
536
+ rethrow(error);
537
+ }
538
+ finally {
539
+ signal?.removeEventListener('abort', onAbort);
540
+ }
541
+ client.dispose();
542
+ return new Blob(parts, { type: 'application/pdf' });
543
+ };
544
+ /** Builds the PDF (`exportPdf`) and downloads it as `fileName` (default `export.pdf`). */
545
+ export const downloadPdf = async (source, options) => {
546
+ downloadBlob(await exportPdf(source, options), options.fileName || 'export.pdf');
547
+ };
548
+ /**
549
+ * The PDF entry of the grid export UI: `grid.pdfExporter =
550
+ * createPdfExporter({ fonts })` (with `export-formats="… pdf"`). The grid
551
+ * passes `selectedOnly`, a `signal` (cancel, disconnect) and `onProgress`
552
+ * (shown in the export button). Options are checked now (`TypeError`).
553
+ */
554
+ export const createPdfExporter = (options) => {
555
+ validate(options);
556
+ return (grid, { selectedOnly, signal, onProgress }) => downloadPdf(grid, {
557
+ ...options,
558
+ selectedOnly,
559
+ signal,
560
+ onProgress: progress => {
561
+ options.onProgress?.(progress);
562
+ onProgress?.(progress);
563
+ },
564
+ });
565
+ };
566
+ //# sourceMappingURL=index.js.map