mapa-library-ui 2.13.1 → 2.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- # Exportação de listagens (2.13.1)
1
+ # Exportação de listagens (2.13.2)
2
2
 
3
3
  `mapa-library-ui/export` fornece o modal e as tarefas. `mapa-library-ui/excel-export`
4
4
  continua disponível para geração de baixo nível, inclusive modo simples e download
@@ -8,7 +8,7 @@ imediato nas assinaturas anteriores. ExcelJS permanece um peer opcional.
8
8
 
9
9
  Inclua `MapaExportJobsComponent` uma única vez no shell, fora do `router-outlet`.
10
10
  Compartilhe os subpacotes da lib como singletons no Native Federation, mantenha
11
- `exceljs` em `skip` e alinhe a versão 2.13.1 no shell e nos remotes.
11
+ `exceljs` em `skip` e alinhe a versão 2.13.2 no shell e nos remotes.
12
12
 
13
13
  Ao testar um pacote local recompilado com a mesma versão, invalide os caches do
14
14
  Angular e do Native Federation nos consumidores. O cache de compartilhamento usa
@@ -132,6 +132,98 @@ são ignoradas e o texto permanece intacto. O CSV contém somente os valores.
132
132
  Atualize a lib também no shell e recompile seu worker compartilhado antes de
133
133
  usar essas regras nos remotes.
134
134
 
135
+ A partir de 2.13.2, a largura automática no modo Mapa considera o cabeçalho em
136
+ maiúsculas, com folga para o recuo e o filtro, mantendo-o em uma linha. Textos
137
+ dos dados continuam limitados a 60 unidades na largura automática; cabeçalhos
138
+ podem ampliar a coluna até o limite de 255 do Excel. `width` explícito continua
139
+ prevalecendo, inclusive permitindo cabeçalhos com quebra de linha. O modo simples
140
+ mantém seu cálculo anterior.
141
+
142
+ ## Estilos, alinhamento e formatos (2.13.2)
143
+
144
+ `ExportDataset` e `ExcelSheetRequest` aceitam `style` (somente dados),
145
+ `headerStyle`, `autoWidth`, `rowHeight` e `headerHeight`. Cada coluna pode
146
+ sobrescrever `style`, `headerStyle` e `autoWidth`; `width` continua sendo a
147
+ largura explícita, com precedência sobre o cálculo automático.
148
+
149
+ O tema Mapa é aplicado primeiro, seguido das opções da tabela e da coluna.
150
+ Os campos internos de fonte, alinhamento e bordas são combinados. Assim,
151
+ definir apenas alinhamento à direita mantém Arial, cores e divisórias existentes.
152
+ As regras condicionais de `status` prevalecem quando o valor corresponde.
153
+ Os estilos de dados não alteram banner, metadados, filtros, rodapé ou totais.
154
+ O cabeçalho tem configuração separada. No modo `plain`, as mesmas opções podem
155
+ ser utilizadas sem o cabeçalho institucional.
156
+
157
+ ```ts
158
+ import {
159
+ EXCEL_FORMATS,
160
+ excelCurrencyFormat,
161
+ excelNumberFormat,
162
+ excelPercentFormat,
163
+ } from 'mapa-library-ui/excel-export';
164
+
165
+ // Dentro de datasets: [{ ... }]
166
+ const tableOptions = {
167
+ style: { alignment: { vertical: 'middle' as const, wrapText: false } },
168
+ headerStyle: { alignment: { horizontal: 'left' as const } },
169
+ rowHeight: 26, // Pontos, de 0 exclusivo até 409.
170
+ headerHeight: 34,
171
+ autoWidth: { mode: 'both' as const, min: 14, max: 50 },
172
+ columns: [
173
+ { key: 'codigo', label: 'Código', numFmt: EXCEL_FORMATS.text },
174
+ {
175
+ key: 'valor', label: 'Valor', numFmt: excelCurrencyFormat('R$', 2),
176
+ total: 'sum' as const,
177
+ style: {
178
+ alignment: { horizontal: 'right' as const },
179
+ backgroundColor: '#f2f7f8',
180
+ font: { bold: true, color: '#41566a' },
181
+ border: { left: { style: 'thin' as const, color: '#dce5e8' } },
182
+ },
183
+ headerStyle: { alignment: { horizontal: 'right' as const } },
184
+ },
185
+ { key: 'quantidade', label: 'Quantidade', numFmt: excelNumberFormat(0) },
186
+ { key: 'progresso', label: 'Progresso', numFmt: excelPercentFormat(1) },
187
+ { key: 'data', label: 'Enviado em', numFmt: EXCEL_FORMATS.dateTime },
188
+ {
189
+ key: 'observacao', label: 'Observação',
190
+ autoWidth: { mode: 'content' as const, min: 20, max: 36 },
191
+ style: { alignment: { wrapText: true } },
192
+ },
193
+ ],
194
+ };
195
+ ```
196
+
197
+ - `alignment`: `horizontal`, `vertical`, `wrapText`, `shrinkToFit`, `indent`
198
+ (inteiro de 0 a 250) e `textRotation` (inteiro de -90 a 90 ou `'vertical'`).
199
+ Para reduzir o texto com `shrinkToFit`, configure também `wrapText: false`.
200
+ - `font`: `name`, `size` (pontos), `bold`, `italic`, `underline`, `strike` e
201
+ `color`. `backgroundColor` e cores de fonte/bordas aceitam HEX `#RGB` ou
202
+ `#RRGGBB`. Cores de estilo inválidas encerram a geração com erro.
203
+ - `border`: lados `top`, `bottom`, `left` e `right`, com estilo de linha e cor
204
+ opcional. Lados não configurados preservam as divisórias do tema.
205
+ - `autoWidth.mode`: `'header'`, `'content'` ou `'both'` (padrão). `min`/`max`
206
+ usam unidades de caracteres do Excel, entre 0 exclusivo e 255, e `padding`
207
+ reserva espaço adicional ao cabeçalho. A largura é uma estimativa, não uma
208
+ medição de pixels da fonte. Limites explícitos podem truncar um título;
209
+ nesse caso, ajuste o limite ou habilite `headerStyle.alignment.wrapText` e
210
+ defina `headerHeight`. Altura de linha não é calculada automaticamente.
211
+
212
+ `EXCEL_FORMATS` contém `text`, `integer`, `number`, `currency` (R$), `percent`,
213
+ `date`, `dateTime` e `time`. Os helpers aceitam 0 a 15 casas decimais;
214
+ `excelNumberFormat(decimals, useGrouping)` também controla o separador de milhar.
215
+ `numFmt` continua aceitando um código Excel personalizado e também se aplica
216
+ ao total da coluna. Um percentual de 25% deve ser fornecido como `0.25`.
217
+ Moedas devem ser números e identificadores com zeros iniciais devem ser strings.
218
+ O formato não converte strings em números ou datas. O Excel localiza os
219
+ separadores na exibição do código `#,##0.00`.
220
+
221
+ As opções são objetos simples e são congeladas por cópia na confirmação do
222
+ modal, inclusive fonte, bordas e alinhamento. Funcionam no worker e nas partes
223
+ do arquivo. Não adicione callbacks de estilo ao payload do worker.
224
+ CSV ignora estilos, dimensões e `numFmt`, preservando o conteúdo dos registros
225
+ e a representação de datas já adotada pelo exportador.
226
+
135
227
  O limite é 100.000 **registros somados entre as abas de cada XLSX**, sem contar
136
228
  cabeçalhos e totais. Os fragmentos preservam a ordem e têm indicadores locais.
137
229
  O nome segue `mapahds_<listagem>_<empresa>_<aaaammdd-hhmm>`, com `_parte1` etc.
@@ -8,6 +8,33 @@ class ExcelExportCancelledError extends Error {
8
8
  }
9
9
  }
10
10
 
11
+ /** Excel format codes; values must already be typed numbers, strings or dates. */
12
+ const EXCEL_FORMATS = {
13
+ text: '@',
14
+ integer: '#,##0',
15
+ number: '#,##0.00',
16
+ currency: '"R$" #,##0.00',
17
+ percent: '0%',
18
+ date: 'dd/mm/yyyy',
19
+ dateTime: 'dd/mm/yyyy hh:mm',
20
+ time: 'hh:mm',
21
+ };
22
+ function fraction(decimals) {
23
+ if (!Number.isInteger(decimals) || decimals < 0 || decimals > 15)
24
+ throw new Error('Informe de 0 a 15 casas decimais.');
25
+ return decimals ? `.${'0'.repeat(decimals)}` : '';
26
+ }
27
+ function excelNumberFormat(decimals = 2, useGrouping = true) {
28
+ return `${useGrouping ? '#,##0' : '0'}${fraction(decimals)}`;
29
+ }
30
+ function excelCurrencyFormat(symbol = 'R$', decimals = 2) {
31
+ const literal = symbol.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
32
+ return `"${literal}" ${excelNumberFormat(decimals)}`;
33
+ }
34
+ function excelPercentFormat(decimals = 0) {
35
+ return `0${fraction(decimals)}%`;
36
+ }
37
+
11
38
  function excelFileName(value) {
12
39
  return (value
13
40
  .replace(/\.xlsx$/i, '')
@@ -337,6 +364,111 @@ function finishMapaExcelTable(sheet, request) {
337
364
  }
338
365
  }
339
366
 
367
+ function argb(color) {
368
+ const match = /^#([\da-f]{3}|[\da-f]{6})$/i.exec(color.trim());
369
+ if (!match)
370
+ throw new Error('Cor de exportação inválida. Use HEX #RGB ou #RRGGBB.');
371
+ return `FF${(match[1].length === 3 ? [...match[1]].map((c) => c + c).join('') : match[1]).toUpperCase()}`;
372
+ }
373
+ function validateExcelCellStyle(style) {
374
+ if (!style)
375
+ return;
376
+ const { alignment, font } = style;
377
+ const invalid = (font?.size !== undefined &&
378
+ (!Number.isFinite(font.size) || font.size <= 0 || font.size > 409)) ||
379
+ (alignment?.indent !== undefined &&
380
+ (!Number.isInteger(alignment.indent) ||
381
+ alignment.indent < 0 ||
382
+ alignment.indent > 250)) ||
383
+ (alignment?.textRotation !== undefined &&
384
+ alignment.textRotation !== 'vertical' &&
385
+ (!Number.isInteger(alignment.textRotation) ||
386
+ Math.abs(alignment.textRotation) > 90)) ||
387
+ (alignment?.horizontal !== undefined &&
388
+ ![
389
+ 'left',
390
+ 'center',
391
+ 'right',
392
+ 'fill',
393
+ 'justify',
394
+ 'centerContinuous',
395
+ 'distributed',
396
+ ].includes(alignment.horizontal)) ||
397
+ (alignment?.vertical !== undefined &&
398
+ !['top', 'middle', 'bottom', 'distributed', 'justify'].includes(alignment.vertical));
399
+ if (invalid)
400
+ throw new Error('Estilo de exportação inválido. Confira fonte e alinhamento.');
401
+ for (const color of [font?.color, style.backgroundColor])
402
+ if (color !== undefined)
403
+ argb(color);
404
+ for (const line of Object.values(style.border ?? {})) {
405
+ if (![
406
+ 'thin',
407
+ 'medium',
408
+ 'thick',
409
+ 'dotted',
410
+ 'hair',
411
+ 'dashed',
412
+ 'double',
413
+ 'dashDot',
414
+ 'dashDotDot',
415
+ 'mediumDashed',
416
+ 'mediumDashDot',
417
+ 'mediumDashDotDot',
418
+ 'slantDashDot',
419
+ ].includes(line.style))
420
+ throw new Error('Borda de exportação inválida.');
421
+ if (line.color !== undefined)
422
+ argb(line.color);
423
+ }
424
+ }
425
+ /** Merge components without sharing mutable ExcelJS style objects with the request. */
426
+ function applyExcelCellStyle(cell, style) {
427
+ if (!style)
428
+ return;
429
+ if (style.alignment)
430
+ cell.alignment = { ...cell.alignment, ...style.alignment };
431
+ if (style.font) {
432
+ const { color, ...font } = style.font;
433
+ cell.font = {
434
+ ...cell.font,
435
+ ...font,
436
+ ...(color ? { color: { argb: argb(color) } } : {}),
437
+ };
438
+ }
439
+ if (style.backgroundColor)
440
+ cell.fill = {
441
+ type: 'pattern',
442
+ pattern: 'solid',
443
+ fgColor: { argb: argb(style.backgroundColor) },
444
+ };
445
+ if (style.border) {
446
+ cell.border = { ...cell.border };
447
+ for (const side of ['top', 'bottom', 'left', 'right']) {
448
+ const line = style.border[side];
449
+ if (line)
450
+ cell.border[side] = {
451
+ ...cell.border[side],
452
+ style: line.style,
453
+ ...(line.color ? { color: { argb: argb(line.color) } } : {}),
454
+ };
455
+ }
456
+ }
457
+ }
458
+ function validateExcelAutoWidth(options) {
459
+ const min = options.min ?? 1;
460
+ const max = options.max ?? 255;
461
+ if (![min, max].every((value) => Number.isFinite(value) && value > 0 && value <= 255) ||
462
+ min > max ||
463
+ (options.padding !== undefined &&
464
+ (!Number.isFinite(options.padding) ||
465
+ options.padding < 0 ||
466
+ options.padding > 255)) ||
467
+ (options.mode !== undefined &&
468
+ !['header', 'content', 'both'].includes(options.mode)))
469
+ throw new Error('Configuração de largura automática inválida.');
470
+ }
471
+
340
472
  function resolveWorkbookConstructor(module) {
341
473
  const constructor = module.default?.Workbook ?? module.Workbook;
342
474
  if (typeof constructor !== 'function')
@@ -386,9 +518,19 @@ async function addExcelTable(book, request, options = {}) {
386
518
  if ((request.metadata?.length ?? 0) > 3)
387
519
  throw new Error('Informe no máximo três linhas de metadados.');
388
520
  const headerRow = branded ? 9 : 1;
521
+ validateExcelCellStyle(request.style);
522
+ validateExcelCellStyle(request.headerStyle);
523
+ for (const height of [request.rowHeight, request.headerHeight]) {
524
+ if (height !== undefined &&
525
+ (!Number.isFinite(height) || height <= 0 || height > 409))
526
+ throw new Error('Altura de linha inválida. Use até 409 pontos.');
527
+ }
389
528
  if (request.rows.length + headerRow > 1048576)
390
529
  throw new Error('Quantidade de linhas excede o limite do Excel.');
391
530
  request.columns.forEach((column) => {
531
+ validateExcelAutoWidth({ ...request.autoWidth, ...column.autoWidth });
532
+ validateExcelCellStyle(column.style);
533
+ validateExcelCellStyle(column.headerStyle);
392
534
  if (!column.value && !column.key)
393
535
  throw new Error('A coluna deve ter uma chave ou um extrator.');
394
536
  if (column.width !== undefined &&
@@ -411,13 +553,27 @@ async function addExcelTable(book, request, options = {}) {
411
553
  const count = branded
412
554
  ? Math.max(request.columns.length, 2)
413
555
  : request.columns.length;
414
- sheet.getRow(headerRow).values = request.columns.map((column) => branded ? column.label.toLocaleUpperCase() : column.label);
415
- const widths = request.columns.map((column) => column.label.length);
556
+ const headers = request.columns.map((column) => branded ? column.label.toLocaleUpperCase() : column.label);
557
+ sheet.getRow(headerRow).values = headers;
558
+ const widths = headers.map(() => 0);
416
559
  if (branded) {
417
- request.columns.forEach((_, index) => styleMapaExcelHeaderCell(sheet, headerRow, index + 1));
560
+ request.columns.forEach((column, index) => {
561
+ styleMapaExcelHeaderCell(sheet, headerRow, index + 1);
562
+ if (column.width === undefined) {
563
+ const cell = sheet.getCell(headerRow, index + 1);
564
+ cell.alignment = { ...cell.alignment, wrapText: false };
565
+ }
566
+ });
418
567
  sheet.getRow(headerRow).height = 30;
419
568
  sheet.pageSetup.printTitlesRow = '9:9';
420
569
  }
570
+ if (request.headerHeight !== undefined)
571
+ sheet.getRow(headerRow).height = request.headerHeight;
572
+ request.columns.forEach((column, index) => {
573
+ const cell = sheet.getCell(headerRow, index + 1);
574
+ applyExcelCellStyle(cell, request.headerStyle);
575
+ applyExcelCellStyle(cell, column.headerStyle);
576
+ });
421
577
  let lastYield = performance.now();
422
578
  for (let index = 0; index < request.rows.length; index++) {
423
579
  checkCancelled(isCancelled);
@@ -448,6 +604,8 @@ async function addExcelTable(book, request, options = {}) {
448
604
  cell.numFmt = 'dd/mm/yyyy hh:mm';
449
605
  else if (branded && typeof value === 'number')
450
606
  cell.numFmt = Number.isInteger(value) ? '#,##0' : '#,##0.###############';
607
+ applyExcelCellStyle(cell, request.style);
608
+ applyExcelCellStyle(cell, column.style);
451
609
  widths[columnIndex] = Math.max(widths[columnIndex], value instanceof Date ? 16 : String(value ?? '').length);
452
610
  });
453
611
  // Let cancellation and the UI run between batches; ZIP serialization may still require a worker.
@@ -458,8 +616,21 @@ async function addExcelTable(book, request, options = {}) {
458
616
  }
459
617
  }
460
618
  request.columns.forEach((column, index) => {
619
+ const options = { ...request.autoWidth, ...column.autoWidth };
620
+ const fontSize = sheet.getCell(headerRow, index + 1).font?.size ?? (branded ? 8 : 11);
621
+ const headerLength = Math.max(...headers[index].split(/\r?\n/).map((line) => line.length));
622
+ // Header sizing is an estimate in Excel character units, with room for filters.
623
+ const headerWidth = Math.ceil(headerLength * (branded ? 1.2 : 1) * fontSize / (branded ? 8 : 11)) +
624
+ (options.padding ?? (branded ? 4 : 2));
625
+ const contentWidth = Math.min(options.max ?? 60, widths[index] + 2);
626
+ const desired = options.mode === 'header'
627
+ ? headerWidth
628
+ : options.mode === 'content'
629
+ ? contentWidth
630
+ : Math.max(headerWidth, contentWidth);
461
631
  sheet.getColumn(index + 1).width =
462
- column.width ?? Math.min(60, Math.max(12, widths[index] + 2));
632
+ column.width ??
633
+ Math.min(options.max ?? (branded ? 255 : 60), Math.max(options.min ?? 12, desired));
463
634
  });
464
635
  if (branded && request.columns.length === 1)
465
636
  sheet.getColumn(2).width = 28;
@@ -810,5 +981,5 @@ function getExcelWorkerConstructor() {
810
981
  * Generated bundle index. Do not edit.
811
982
  */
812
983
 
813
- export { ExcelExportCancelledError, MAPA_EXCEL_COLORS, MAPA_EXCEL_STATUS_COLORS, MapaExcelExportService, addExcelTable, addMapaExcelLogo, applyMapaExcelBanner, buildExcelWorkbook, createExcelWorkbook, excelFileName, excelFileNameWithDate, excelSheetName, fillExcelCell, fitExcelSheetTitle, getExcelWorkerConstructor, resolveWorkbookConstructor, serializeExcelRequest, serializeExcelWorkbook, styleMapaExcelHeaderCell, uniqueExcelSheetNames };
984
+ export { EXCEL_FORMATS, ExcelExportCancelledError, MAPA_EXCEL_COLORS, MAPA_EXCEL_STATUS_COLORS, MapaExcelExportService, addExcelTable, addMapaExcelLogo, applyMapaExcelBanner, buildExcelWorkbook, createExcelWorkbook, excelCurrencyFormat, excelFileName, excelFileNameWithDate, excelNumberFormat, excelPercentFormat, excelSheetName, fillExcelCell, fitExcelSheetTitle, getExcelWorkerConstructor, resolveWorkbookConstructor, serializeExcelRequest, serializeExcelWorkbook, styleMapaExcelHeaderCell, uniqueExcelSheetNames };
814
985
  //# sourceMappingURL=mapa-library-ui-src-lib-core-excel-export.mjs.map