mapa-library-ui 2.13.0 → 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.0)
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.0 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
@@ -124,6 +124,106 @@ Colunas podem declarar `total: 'sum'` e `status: [{value, tone}]`, com tons `ok`
124
124
  `absolute` opcionais. Não somar percentuais ou saldos automaticamente. Fórmulas
125
125
  avançadas podem receber `{formula, result}` como valor; ExcelJS não as calcula.
126
126
 
127
+ A partir de 2.13.1, para classificações com paleta própria, `status` também aceita
128
+ `{value: 'Adequado', backgroundColor: '#cceecc', textColor: '#41566a'}` em vez de
129
+ `tone`. Cores usam HEX `#RGB` ou `#RRGGBB`; `textColor` é opcional. Fundos
130
+ personalizados preservam o peso da fonte dos dados. Regras com fundo inválido
131
+ são ignoradas e o texto permanece intacto. O CSV contém somente os valores.
132
+ Atualize a lib também no shell e recompile seu worker compartilhado antes de
133
+ usar essas regras nos remotes.
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
+
127
227
  O limite é 100.000 **registros somados entre as abas de cada XLSX**, sem contar
128
228
  cabeçalhos e totais. Os fragmentos preservam a ordem e têm indicadores locais.
129
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, '')
@@ -130,6 +157,15 @@ const quote = (value) => `"${String(value).replace(/"/g, '""')}"`;
130
157
  const scalar = (value) => value && typeof value === 'object' && 'formula' in value
131
158
  ? value.result
132
159
  : value;
160
+ function hexArgb(color) {
161
+ const match = /^#([\da-f]{3}|[\da-f]{6})$/i.exec(color?.trim() ?? '');
162
+ if (!match)
163
+ return undefined;
164
+ const hex = match[1].length === 3
165
+ ? [...match[1]].map((channel) => channel + channel).join('')
166
+ : match[1];
167
+ return `FF${hex.toUpperCase()}`;
168
+ }
133
169
  /** Finalize a branded table after widths and data have been assigned. */
134
170
  function finishMapaExcelTable(sheet, request) {
135
171
  const columns = request.columns;
@@ -249,25 +285,40 @@ function finishMapaExcelTable(sheet, request) {
249
285
  columns.forEach((column, index) => {
250
286
  if (request.rows.length && column.status?.length) {
251
287
  const letter = sheet.getColumn(index + 1).letter;
252
- sheet.addConditionalFormatting({
253
- ref: range(index),
254
- rules: column.status.map((status, priority) => {
255
- const tone = MAPA_EXCEL_STATUS_COLORS[status.tone];
256
- return {
288
+ const rules = column.status.flatMap((status, priority) => {
289
+ const tone = status.tone
290
+ ? MAPA_EXCEL_STATUS_COLORS[status.tone]
291
+ : undefined;
292
+ const background = tone?.background ?? hexArgb(status.backgroundColor);
293
+ if (!background)
294
+ return [];
295
+ return [
296
+ {
257
297
  type: 'expression',
258
298
  priority: priority + 1,
259
299
  formulae: [`${letter}10=${quote(status.value)}`],
260
300
  style: {
261
- font: { bold: true, color: { argb: tone.text } },
301
+ font: {
302
+ ...(tone ? { bold: true } : {}),
303
+ color: {
304
+ argb: tone?.text ?? hexArgb(status.textColor) ?? MAPA_EXCEL_COLORS.text,
305
+ },
306
+ },
262
307
  fill: {
263
308
  type: 'pattern',
264
309
  pattern: 'solid',
265
- bgColor: { argb: tone.background },
266
- fgColor: { argb: tone.background },
310
+ bgColor: { argb: background },
311
+ fgColor: { argb: background },
267
312
  },
268
313
  },
269
- };
270
- }),
314
+ },
315
+ ];
316
+ });
317
+ if (!rules.length)
318
+ return;
319
+ sheet.addConditionalFormatting({
320
+ ref: range(index),
321
+ rules,
271
322
  });
272
323
  }
273
324
  });
@@ -313,6 +364,111 @@ function finishMapaExcelTable(sheet, request) {
313
364
  }
314
365
  }
315
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
+
316
472
  function resolveWorkbookConstructor(module) {
317
473
  const constructor = module.default?.Workbook ?? module.Workbook;
318
474
  if (typeof constructor !== 'function')
@@ -362,9 +518,19 @@ async function addExcelTable(book, request, options = {}) {
362
518
  if ((request.metadata?.length ?? 0) > 3)
363
519
  throw new Error('Informe no máximo três linhas de metadados.');
364
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
+ }
365
528
  if (request.rows.length + headerRow > 1048576)
366
529
  throw new Error('Quantidade de linhas excede o limite do Excel.');
367
530
  request.columns.forEach((column) => {
531
+ validateExcelAutoWidth({ ...request.autoWidth, ...column.autoWidth });
532
+ validateExcelCellStyle(column.style);
533
+ validateExcelCellStyle(column.headerStyle);
368
534
  if (!column.value && !column.key)
369
535
  throw new Error('A coluna deve ter uma chave ou um extrator.');
370
536
  if (column.width !== undefined &&
@@ -387,13 +553,27 @@ async function addExcelTable(book, request, options = {}) {
387
553
  const count = branded
388
554
  ? Math.max(request.columns.length, 2)
389
555
  : request.columns.length;
390
- sheet.getRow(headerRow).values = request.columns.map((column) => branded ? column.label.toLocaleUpperCase() : column.label);
391
- 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);
392
559
  if (branded) {
393
- 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
+ });
394
567
  sheet.getRow(headerRow).height = 30;
395
568
  sheet.pageSetup.printTitlesRow = '9:9';
396
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
+ });
397
577
  let lastYield = performance.now();
398
578
  for (let index = 0; index < request.rows.length; index++) {
399
579
  checkCancelled(isCancelled);
@@ -424,6 +604,8 @@ async function addExcelTable(book, request, options = {}) {
424
604
  cell.numFmt = 'dd/mm/yyyy hh:mm';
425
605
  else if (branded && typeof value === 'number')
426
606
  cell.numFmt = Number.isInteger(value) ? '#,##0' : '#,##0.###############';
607
+ applyExcelCellStyle(cell, request.style);
608
+ applyExcelCellStyle(cell, column.style);
427
609
  widths[columnIndex] = Math.max(widths[columnIndex], value instanceof Date ? 16 : String(value ?? '').length);
428
610
  });
429
611
  // Let cancellation and the UI run between batches; ZIP serialization may still require a worker.
@@ -434,8 +616,21 @@ async function addExcelTable(book, request, options = {}) {
434
616
  }
435
617
  }
436
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);
437
631
  sheet.getColumn(index + 1).width =
438
- 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));
439
634
  });
440
635
  if (branded && request.columns.length === 1)
441
636
  sheet.getColumn(2).width = 28;
@@ -786,5 +981,5 @@ function getExcelWorkerConstructor() {
786
981
  * Generated bundle index. Do not edit.
787
982
  */
788
983
 
789
- 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 };
790
985
  //# sourceMappingURL=mapa-library-ui-src-lib-core-excel-export.mjs.map