@praxisui/core 10.0.0-rc.5 → 10.0.0-rc.51

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,3 +1,5 @@
1
+ import { InjectionToken } from '@angular/core';
2
+
1
3
  function normalizeFieldAccessMetadata(value) {
2
4
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
3
5
  return undefined;
@@ -111,6 +113,10 @@ const VISUALIZATION_TONES = new Set([
111
113
  'danger',
112
114
  'critical',
113
115
  ]);
116
+ const VISUALIZATION_SCALE_SCOPES = new Set([
117
+ 'row',
118
+ 'page',
119
+ ]);
114
120
  const TABLE_SAFE_KINDS = new Set([
115
121
  'line',
116
122
  'area',
@@ -163,8 +169,8 @@ function resolvePraxisMicroVisualizationTone(value, thresholds, fallbackTone) {
163
169
  if (value === undefined || value === null || !Array.isArray(thresholds) || thresholds.length === 0) {
164
170
  return fallbackTone ? { tone: fallbackTone } : undefined;
165
171
  }
166
- const num = typeof value === 'number' ? value : Number(value);
167
- const isNum = Number.isFinite(num);
172
+ const num = toFiniteNumber(value);
173
+ const isNum = num !== undefined;
168
174
  // 1. Pass 1: Correspondencia discreta (equals) tem prioridade maxima
169
175
  for (const t of thresholds) {
170
176
  if (!t || !t.tone || t.equals === undefined) {
@@ -173,7 +179,8 @@ function resolvePraxisMicroVisualizationTone(value, thresholds, fallbackTone) {
173
179
  if (t.equals === value || String(t.equals) === String(value)) {
174
180
  return { tone: t.tone, label: t.label, matchedThreshold: t };
175
181
  }
176
- if (isNum && Number.isFinite(Number(t.equals)) && Number(t.equals) === num) {
182
+ const eqNum = toFiniteNumber(t.equals);
183
+ if (isNum && eqNum !== undefined && eqNum === num) {
177
184
  return { tone: t.tone, label: t.label, matchedThreshold: t };
178
185
  }
179
186
  }
@@ -207,6 +214,266 @@ function resolvePraxisMicroVisualizationTone(value, thresholds, fallbackTone) {
207
214
  }
208
215
  return fallbackTone ? { tone: fallbackTone } : undefined;
209
216
  }
217
+ const STACKED_BAR_TONE_PAINT = {
218
+ info: 'var(--prx-micro-tone-info, var(--p-table-state-info-fg, var(--md-sys-color-primary, #0a6eb4)))',
219
+ success: 'var(--prx-micro-tone-success, var(--p-table-state-success-fg, #1b7a43))',
220
+ warning: 'var(--prx-micro-tone-warning, var(--p-table-state-warning-fg, #d97706))',
221
+ danger: 'var(--prx-micro-tone-danger, var(--p-table-state-danger-fg, var(--md-sys-color-error, #c62828)))',
222
+ critical: 'var(--prx-micro-tone-critical, var(--prx-micro-tone-danger, var(--p-table-state-danger-fg, var(--md-sys-color-error, #9f1239))))',
223
+ neutral: 'var(--prx-micro-tone-neutral, var(--md-sys-color-secondary, #5c6b73))',
224
+ };
225
+ function normalizePraxisHexColor(value) {
226
+ if (typeof value !== 'string') {
227
+ return undefined;
228
+ }
229
+ const trimmed = value.trim();
230
+ const match = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(trimmed);
231
+ if (!match) {
232
+ return undefined;
233
+ }
234
+ const raw = match[1].toLowerCase();
235
+ if (raw.length === 3) {
236
+ return `#${raw[0]}${raw[0]}${raw[1]}${raw[1]}${raw[2]}${raw[2]}`;
237
+ }
238
+ return `#${raw}`;
239
+ }
240
+ function getPraxisStackedBarPaintStyle(segment, fallbackTone = 'neutral') {
241
+ const hex = normalizePraxisHexColor(segment?.color);
242
+ const resolvedTone = normalizeEnum$1(segment?.tone, VISUALIZATION_TONES) ??
243
+ normalizeEnum$1(fallbackTone, VISUALIZATION_TONES) ??
244
+ 'neutral';
245
+ const paint = hex ?? STACKED_BAR_TONE_PAINT[resolvedTone];
246
+ return {
247
+ '--prx-micro-category-color': paint,
248
+ color: paint,
249
+ };
250
+ }
251
+ function resolvePraxisStackedBarSegments(visualization) {
252
+ if (!visualization || visualization.kind !== 'stackedBar') {
253
+ return [];
254
+ }
255
+ if (Array.isArray(visualization.segments) && visualization.segments.length > 0) {
256
+ return visualization.segments;
257
+ }
258
+ if (Array.isArray(visualization.items) && visualization.items.length > 0) {
259
+ const mapped = [];
260
+ for (let i = 0; i < visualization.items.length; i++) {
261
+ if (!Object.prototype.hasOwnProperty.call(visualization.items, i)) {
262
+ return [];
263
+ }
264
+ const item = visualization.items[i];
265
+ if (!item || typeof item.value !== 'number' || !Number.isFinite(item.value) || item.value < 0) {
266
+ return [];
267
+ }
268
+ const hex = normalizePraxisHexColor(item.color);
269
+ mapped.push({
270
+ value: item.value,
271
+ ...(item.label ? { label: item.label } : {}),
272
+ ...(item.tone ? { tone: item.tone } : {}),
273
+ ...(hex ? { color: hex } : {}),
274
+ });
275
+ }
276
+ return mapped;
277
+ }
278
+ return [];
279
+ }
280
+ function resolvePraxisStackedBarTotal(segments, explicitTotal) {
281
+ if (typeof explicitTotal === 'number' && Number.isFinite(explicitTotal) && explicitTotal >= 0) {
282
+ return explicitTotal;
283
+ }
284
+ return compensatedSum(segments.map((segment) => segment.value));
285
+ }
286
+ function computePraxisStackedBarSegmentWidthPct(value, resolvedTotal) {
287
+ if (!Number.isFinite(value) || value <= 0 || !Number.isFinite(resolvedTotal) || resolvedTotal <= 0) {
288
+ return 0;
289
+ }
290
+ return Math.max(0, Math.min(100, (value / resolvedTotal) * 100));
291
+ }
292
+ function formatPraxisStackedBarPercentage(value, resolvedTotal, locale) {
293
+ const pct = computePraxisStackedBarSegmentWidthPct(value, resolvedTotal);
294
+ const maximumFractionDigits = pct === 0 ? 0 : pct < 0.1 ? 3 : pct < 1 ? 2 : 1;
295
+ return `${new Intl.NumberFormat(locale || undefined, { maximumFractionDigits }).format(pct)}%`;
296
+ }
297
+ function resolvePraxisStackedBarAriaLabel(visualization, segments, resolvedTotal, locale) {
298
+ if (visualization.ariaLabel) {
299
+ return visualization.ariaLabel;
300
+ }
301
+ if (segments.length > 0 &&
302
+ segments.every((segment) => typeof segment.label === 'string' && segment.label.trim().length > 0)) {
303
+ const prefix = visualization.title || visualization.fallbackText;
304
+ const summary = segments
305
+ .map((segment) => `${segment.label} ${formatPraxisStackedBarPercentage(segment.value, resolvedTotal, locale)}`)
306
+ .join(', ');
307
+ return `${prefix}: ${summary}`;
308
+ }
309
+ return visualization.fallbackText;
310
+ }
311
+ function compensatedSum(values) {
312
+ let sum = 0;
313
+ let compensation = 0;
314
+ for (let i = 0; i < values.length; i++) {
315
+ const value = values[i];
316
+ const next = sum + value;
317
+ if (Math.abs(sum) >= Math.abs(value)) {
318
+ compensation += (sum - next) + value;
319
+ }
320
+ else {
321
+ compensation += (value - next) + sum;
322
+ }
323
+ sum = next;
324
+ }
325
+ return sum + compensation;
326
+ }
327
+ function normalizeStackedBarDistribution(value, surface) {
328
+ const isTableCell = surface === 'table-cell';
329
+ const hasSegmentsProp = value.segments !== undefined;
330
+ const hasItemsProp = value.items !== undefined;
331
+ const hasExplicitTotalProp = Object.prototype.hasOwnProperty.call(value, 'total') &&
332
+ value.total !== undefined &&
333
+ value.total !== null;
334
+ const hasDeferredExpr = Boolean(normalizeExpression(value.segmentsExpr, 'segmentsExpr') ||
335
+ normalizeExpression(value.itemsExpr, 'itemsExpr'));
336
+ const rawTitle = isTableCell ? undefined : normalizeText$1(value.title);
337
+ if (!hasSegmentsProp && !hasItemsProp) {
338
+ const explicitTotal = hasExplicitTotalProp ? toFiniteNumber(value.total) : undefined;
339
+ const validDeferredTotal = !hasExplicitTotalProp || (explicitTotal !== undefined && explicitTotal >= 0);
340
+ if (!validDeferredTotal) {
341
+ return {
342
+ valid: false,
343
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
344
+ };
345
+ }
346
+ if (!isTableCell && value.legend === true && !hasDeferredExpr) {
347
+ return {
348
+ valid: false,
349
+ legend: false,
350
+ };
351
+ }
352
+ return {
353
+ valid: hasDeferredExpr,
354
+ ...(explicitTotal !== undefined ? { total: explicitTotal } : {}),
355
+ ...(rawTitle && hasDeferredExpr ? { title: rawTitle } : {}),
356
+ ...(typeof value.legend === 'boolean'
357
+ ? { legend: isTableCell ? false : value.legend }
358
+ : {}),
359
+ };
360
+ }
361
+ const rawEntries = hasSegmentsProp ? value.segments : value.items;
362
+ if (!Array.isArray(rawEntries) || rawEntries.length === 0) {
363
+ return {
364
+ valid: false,
365
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
366
+ };
367
+ }
368
+ const parsedSegments = [];
369
+ const parsedItems = [];
370
+ for (let i = 0; i < rawEntries.length; i++) {
371
+ if (!Object.prototype.hasOwnProperty.call(rawEntries, i)) {
372
+ return {
373
+ valid: false,
374
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
375
+ };
376
+ }
377
+ const rawEntry = rawEntries[i];
378
+ if (typeof rawEntry === 'number' || typeof rawEntry === 'string') {
379
+ const num = toFiniteNumber(rawEntry);
380
+ if (num === undefined || num < 0) {
381
+ return {
382
+ valid: false,
383
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
384
+ };
385
+ }
386
+ parsedSegments.push({ value: num });
387
+ parsedItems.push({ value: num });
388
+ continue;
389
+ }
390
+ if (!rawEntry || typeof rawEntry !== 'object') {
391
+ return {
392
+ valid: false,
393
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
394
+ };
395
+ }
396
+ const entryObj = rawEntry;
397
+ const num = toFiniteNumber(entryObj.value);
398
+ if (num === undefined || num < 0) {
399
+ return {
400
+ valid: false,
401
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
402
+ };
403
+ }
404
+ const label = normalizeText$1(entryObj.label);
405
+ const entryTone = normalizeEnum$1(entryObj.tone, VISUALIZATION_TONES);
406
+ const entryColor = normalizePraxisHexColor(entryObj.color);
407
+ const id = normalizeText$1(entryObj.id);
408
+ const icon = normalizeText$1(entryObj.icon);
409
+ const state = normalizeText$1(entryObj.state);
410
+ parsedSegments.push({
411
+ value: num,
412
+ ...(label ? { label } : {}),
413
+ ...(entryTone ? { tone: entryTone } : {}),
414
+ ...(entryColor ? { color: entryColor } : {}),
415
+ });
416
+ parsedItems.push({
417
+ value: num,
418
+ ...(id ? { id } : {}),
419
+ ...(label ? { label } : {}),
420
+ ...(icon ? { icon } : {}),
421
+ ...(state ? { state } : {}),
422
+ ...(entryTone ? { tone: entryTone } : {}),
423
+ ...(entryColor ? { color: entryColor } : {}),
424
+ });
425
+ }
426
+ const sum = compensatedSum(parsedSegments.map((entry) => entry.value));
427
+ if (!Number.isFinite(sum) || sum < 0) {
428
+ return {
429
+ valid: false,
430
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
431
+ };
432
+ }
433
+ let validatedTotal;
434
+ if (hasExplicitTotalProp) {
435
+ const explicitTotal = toFiniteNumber(value.total);
436
+ if (explicitTotal === undefined || !Number.isFinite(explicitTotal) || explicitTotal < 0) {
437
+ return {
438
+ valid: false,
439
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
440
+ };
441
+ }
442
+ if (explicitTotal === 0 && sum > 0) {
443
+ return {
444
+ valid: false,
445
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
446
+ };
447
+ }
448
+ if (explicitTotal > 0) {
449
+ const tolerance = Math.max(4, parsedSegments.length) * Number.EPSILON * Math.max(sum, explicitTotal);
450
+ if (sum - explicitTotal > tolerance) {
451
+ return {
452
+ valid: false,
453
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
454
+ };
455
+ }
456
+ }
457
+ validatedTotal = explicitTotal;
458
+ }
459
+ const normalizedLegend = typeof value.legend === 'boolean' ? (isTableCell ? false : value.legend) : undefined;
460
+ if (!isTableCell && normalizedLegend === true) {
461
+ const allLabeled = parsedSegments.every((entry) => typeof entry.label === 'string' && entry.label.length > 0);
462
+ if (!allLabeled) {
463
+ return {
464
+ valid: false,
465
+ legend: false,
466
+ };
467
+ }
468
+ }
469
+ return {
470
+ valid: true,
471
+ ...(hasSegmentsProp ? { segments: parsedSegments } : { items: parsedItems }),
472
+ ...(validatedTotal !== undefined ? { total: validatedTotal } : {}),
473
+ ...(rawTitle ? { title: rawTitle } : {}),
474
+ ...(normalizedLegend !== undefined ? { legend: normalizedLegend } : {}),
475
+ };
476
+ }
210
477
  function normalizePraxisPresentationVisualization(value) {
211
478
  if (!value || typeof value !== 'object') {
212
479
  return undefined;
@@ -218,17 +485,23 @@ function normalizePraxisPresentationVisualization(value) {
218
485
  }
219
486
  const surface = normalizeEnum$1(value.surface, VISUALIZATION_SURFACES);
220
487
  const size = normalizeEnum$1(value.size, VISUALIZATION_SIZES);
488
+ const scaleScope = normalizeEnum$1(value.scaleScope, VISUALIZATION_SCALE_SCOPES);
221
489
  const tone = normalizeEnum$1(value.tone, VISUALIZATION_TONES);
222
490
  const ariaLabel = normalizeText$1(value.ariaLabel);
223
491
  const valueSuffix = normalizeText$1(value.valueSuffix);
492
+ const normalizedTargetLabel = normalizeText$1(value.targetLabel);
224
493
  const thresholdsObj = normalizeThresholds(value.thresholds);
494
+ const isTableCell = surface === 'table-cell';
225
495
  let resolvedTone = tone;
226
496
  let resolvedAriaLabel = ariaLabel;
227
497
  if (!resolvedTone && thresholdsObj?.thresholds?.length) {
228
498
  let evalVal = value.value;
229
499
  if (evalVal === undefined && Array.isArray(value.points) && value.points.length > 0) {
230
500
  const last = value.points[value.points.length - 1];
231
- if (last && typeof last === 'object' && Number.isFinite(last.value)) {
501
+ if (typeof last === 'number' && Number.isFinite(last)) {
502
+ evalVal = last;
503
+ }
504
+ else if (last && typeof last === 'object' && Number.isFinite(last.value)) {
232
505
  evalVal = last.value;
233
506
  }
234
507
  }
@@ -246,11 +519,66 @@ function normalizePraxisPresentationVisualization(value) {
246
519
  }
247
520
  }
248
521
  }
522
+ if (kind === 'stackedBar') {
523
+ const stacked = normalizeStackedBarDistribution(value, surface);
524
+ return {
525
+ kind,
526
+ fallbackText,
527
+ ...(surface ? { surface } : {}),
528
+ ...(size ? { size } : {}),
529
+ ...(scaleScope ? { scaleScope } : {}),
530
+ ...(stacked.title ? { title: stacked.title } : {}),
531
+ ...(normalizeExpression(value.titleExpr, 'titleExpr') ?? {}),
532
+ ...(stacked.legend !== undefined ? { legend: stacked.legend } : {}),
533
+ ...(resolvedTone ? { tone: resolvedTone } : {}),
534
+ ...(resolvedAriaLabel ? { ariaLabel: resolvedAriaLabel } : {}),
535
+ ...(valueSuffix ? { valueSuffix } : {}),
536
+ ...(typeof value.compactValue === 'boolean' ? { compactValue: value.compactValue } : {}),
537
+ ...(Object.prototype.hasOwnProperty.call(value, 'value') ? { value: value.value } : {}),
538
+ ...(normalizeExpression(value.valueExpr, 'valueExpr') ?? {}),
539
+ ...(normalizeExpression(value.valueSuffixExpr, 'valueSuffixExpr') ?? {}),
540
+ ...(normalizeNumber(value.min, 'min') ?? {}),
541
+ ...(normalizeExpression(value.minExpr, 'minExpr') ?? {}),
542
+ ...(normalizeNumber(value.max, 'max') ?? {}),
543
+ ...(normalizeExpression(value.maxExpr, 'maxExpr') ?? {}),
544
+ ...(stacked.total !== undefined ? { total: stacked.total } : {}),
545
+ ...(normalizeExpression(value.totalExpr, 'totalExpr') ?? {}),
546
+ ...(normalizeNumber(value.target, 'target') ?? {}),
547
+ ...(normalizeExpression(value.targetExpr, 'targetExpr') ?? {}),
548
+ ...(normalizedTargetLabel ? { targetLabel: normalizedTargetLabel } : {}),
549
+ ...(normalizeExpression(value.targetLabelExpr, 'targetLabelExpr') ?? {}),
550
+ ...(normalizeNumber(value.baseline, 'baseline') ?? {}),
551
+ ...(normalizeExpression(value.baselineExpr, 'baselineExpr') ?? {}),
552
+ ...(normalizePoints(value.points) ?? {}),
553
+ ...(normalizeExpression(value.pointsExpr, 'pointsExpr') ?? {}),
554
+ ...(stacked.segments ? { segments: stacked.segments } : {}),
555
+ ...(normalizeExpression(value.segmentsExpr, 'segmentsExpr') ?? {}),
556
+ ...(normalizeThresholds(value.thresholds) ?? {}),
557
+ ...(normalizeExpression(value.thresholdsExpr, 'thresholdsExpr') ?? {}),
558
+ ...(stacked.items ? { items: stacked.items } : {}),
559
+ ...(normalizeExpression(value.itemsExpr, 'itemsExpr') ?? {}),
560
+ ...(normalizeExpression(value.toneExpr, 'toneExpr') ?? {}),
561
+ ...(value.stepLabelWidth !== undefined && (typeof value.stepLabelWidth === 'number' || typeof value.stepLabelWidth === 'string')
562
+ ? { stepLabelWidth: value.stepLabelWidth }
563
+ : {}),
564
+ ...(typeof value.stepLabelLineClamp === 'number' && Number.isFinite(value.stepLabelLineClamp)
565
+ ? { stepLabelLineClamp: value.stepLabelLineClamp }
566
+ : {}),
567
+ ...(normalizeExpression(value.ariaLabelExpr, 'ariaLabelExpr') ?? {}),
568
+ ...(normalizeExpression(value.fallbackTextExpr, 'fallbackTextExpr') ?? {}),
569
+ };
570
+ }
571
+ const normalizedTitle = isTableCell ? undefined : normalizeText$1(value.title);
572
+ const normalizedLegend = typeof value.legend === 'boolean' ? (isTableCell ? false : value.legend) : undefined;
249
573
  return {
250
574
  kind,
251
575
  fallbackText,
252
576
  ...(surface ? { surface } : {}),
253
577
  ...(size ? { size } : {}),
578
+ ...(scaleScope ? { scaleScope } : {}),
579
+ ...(normalizedTitle ? { title: normalizedTitle } : {}),
580
+ ...(normalizeExpression(value.titleExpr, 'titleExpr') ?? {}),
581
+ ...(normalizedLegend !== undefined ? { legend: normalizedLegend } : {}),
254
582
  ...(resolvedTone ? { tone: resolvedTone } : {}),
255
583
  ...(resolvedAriaLabel ? { ariaLabel: resolvedAriaLabel } : {}),
256
584
  ...(valueSuffix ? { valueSuffix } : {}),
@@ -258,10 +586,16 @@ function normalizePraxisPresentationVisualization(value) {
258
586
  ...(Object.prototype.hasOwnProperty.call(value, 'value') ? { value: value.value } : {}),
259
587
  ...(normalizeExpression(value.valueExpr, 'valueExpr') ?? {}),
260
588
  ...(normalizeExpression(value.valueSuffixExpr, 'valueSuffixExpr') ?? {}),
589
+ ...(normalizeNumber(value.min, 'min') ?? {}),
590
+ ...(normalizeExpression(value.minExpr, 'minExpr') ?? {}),
591
+ ...(normalizeNumber(value.max, 'max') ?? {}),
592
+ ...(normalizeExpression(value.maxExpr, 'maxExpr') ?? {}),
261
593
  ...(normalizeNumber(value.total, 'total') ?? {}),
262
594
  ...(normalizeExpression(value.totalExpr, 'totalExpr') ?? {}),
263
595
  ...(normalizeNumber(value.target, 'target') ?? {}),
264
596
  ...(normalizeExpression(value.targetExpr, 'targetExpr') ?? {}),
597
+ ...(normalizedTargetLabel ? { targetLabel: normalizedTargetLabel } : {}),
598
+ ...(normalizeExpression(value.targetLabelExpr, 'targetLabelExpr') ?? {}),
265
599
  ...(normalizeNumber(value.baseline, 'baseline') ?? {}),
266
600
  ...(normalizeExpression(value.baselineExpr, 'baselineExpr') ?? {}),
267
601
  ...(normalizePoints(value.points) ?? {}),
@@ -287,6 +621,55 @@ function isPraxisPresentationVisualizationTableSafe(value) {
287
621
  const normalized = normalizePraxisPresentationVisualization(value);
288
622
  return !!normalized && TABLE_SAFE_KINDS.has(normalized.kind);
289
623
  }
624
+ function computeMicroSvgIdSuffix(visualization, options) {
625
+ const ptsKey = visualization.points
626
+ ?.map((p) => `${p.label ?? ''}:${p.value}:${p.tone ?? ''}`)
627
+ .join(',') ?? '';
628
+ const seed = [
629
+ options.idPrefix ?? '',
630
+ visualization.kind,
631
+ visualization.surface ?? '',
632
+ visualization.tone ?? '',
633
+ String(visualization.value ?? ''),
634
+ String(visualization.total ?? ''),
635
+ String(visualization.target ?? ''),
636
+ visualization.fallbackText,
637
+ visualization.title ?? '',
638
+ ptsKey,
639
+ ].join('|');
640
+ let hash = 0x811c9dc5;
641
+ for (let i = 0; i < seed.length; i++) {
642
+ hash ^= seed.charCodeAt(i);
643
+ hash = Math.imul(hash, 0x01000193);
644
+ }
645
+ return (hash >>> 0).toString(36);
646
+ }
647
+ function resolveTargetReferenceLabel(visualization, options) {
648
+ if (visualization.targetLabel) {
649
+ return visualization.targetLabel;
650
+ }
651
+ return options.locale?.toLowerCase().startsWith('pt') ? 'Meta' : 'Target';
652
+ }
653
+ /**
654
+ * Returns a luminous 3-stop directional color ramp (`[highlight, mid, deep]`)
655
+ * for radial arcs, sector dials, and precision micro-visualizations.
656
+ */
657
+ function getPraxisMicroToneGradientStops(tone) {
658
+ switch (tone) {
659
+ case 'success':
660
+ return ['#bef264', '#22c55e', '#15803d'];
661
+ case 'info':
662
+ return ['#93c5fd', '#3b82f6', '#3730a3'];
663
+ case 'warning':
664
+ return ['#fde047', '#f59e0b', '#b45309'];
665
+ case 'danger':
666
+ case 'critical':
667
+ return ['#fda4af', '#f43f5e', '#be123c'];
668
+ case 'neutral':
669
+ default:
670
+ return ['#cbd5e1', '#64748b', '#334155'];
671
+ }
672
+ }
290
673
  function renderPraxisPresentationVisualizationHtml(value, options = {}) {
291
674
  const visualization = normalizePraxisPresentationVisualization(value);
292
675
  if (!visualization) {
@@ -318,51 +701,97 @@ function renderPraxisPresentationVisualizationHtml(value, options = {}) {
318
701
  }
319
702
  }
320
703
  function renderComparisonVisualizationHtml(visualization, options) {
321
- const points = visualization.points ?? [];
704
+ let points = visualization.points ?? [];
705
+ if (points.length === 0) {
706
+ const primaryValue = toFiniteNumber(visualization.value);
707
+ const referenceValue = toFiniteNumber(visualization.baseline) ?? toFiniteNumber(visualization.target);
708
+ if (primaryValue !== undefined) {
709
+ points = [
710
+ { value: primaryValue, tone: visualization.tone ?? 'info' },
711
+ ...(referenceValue !== undefined
712
+ ? [{ value: referenceValue, tone: 'neutral' }]
713
+ : []),
714
+ ];
715
+ }
716
+ }
322
717
  if (points.length === 0) {
323
718
  return renderFallbackVisualizationHtml(visualization, visualization.tone ?? 'neutral');
324
719
  }
325
- const max = Math.max(1, ...points.map((point) => Math.max(0, point.value)));
720
+ const explicitCeiling = Math.max(toFiniteNumber(visualization.max) ?? 0, toFiniteNumber(visualization.total) ?? 0);
721
+ const max = Math.max(1, explicitCeiling, ...points.map((point) => Math.max(0, point.value)));
722
+ const suffix = visualization.valueSuffix ?? '';
723
+ const useCompact = visualization.compactValue === true;
326
724
  const rows = points
327
725
  .map((point) => {
328
726
  const width = percent(point.value, max);
727
+ const formattedVal = formatVisualizationMetricValue(point.value, options, useCompact, suffix);
728
+ const alreadyPercent = (suffix.trim() === '%' || formattedVal.trim().endsWith('%')) && max === 100;
729
+ const readout = alreadyPercent
730
+ ? `${point.label ? `${point.label}: ` : ''}${formattedVal}`
731
+ : `${point.label ? `${point.label}: ` : ''}${formattedVal} (${Math.round(Number(width))}%)`;
329
732
  return `
330
- <span class="pfx-micro-viz__row" data-tone="${escapeHtml(point.tone ?? visualization.tone ?? 'info')}">
733
+ <span class="pfx-micro-viz__row" data-tone="${escapeHtml(point.tone ?? visualization.tone ?? 'info')}" data-micro-readout="${escapeHtml(readout)}">
331
734
  <span class="pfx-micro-viz__label">${escapeHtml(point.label ?? '')}</span>
332
735
  <span class="pfx-micro-viz__track">
333
736
  <span class="pfx-micro-viz__bar" style="width:${width}%"></span>
334
737
  </span>
335
- <span class="pfx-micro-viz__value">${escapeHtml(formatMicroNumber(point.value, options.locale))}</span>
738
+ <span class="pfx-micro-viz__value">${escapeHtml(formattedVal)}</span>
336
739
  </span>`;
337
740
  })
338
741
  .join('');
339
- return `<span class="pfx-micro-viz" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">${rows}</span>`;
742
+ return `<span class="pfx-micro-viz pfx-micro-viz__comparison" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">${rows}</span>`;
340
743
  }
341
744
  function renderStackedBarVisualizationHtml(visualization, options) {
342
- const segments = visualization.segments ?? [];
745
+ const segments = resolvePraxisStackedBarSegments(visualization);
343
746
  if (segments.length === 0) {
344
747
  return renderFallbackVisualizationHtml(visualization, visualization.tone ?? 'neutral');
345
748
  }
346
- const total = visualization.total && visualization.total > 0
347
- ? visualization.total
348
- : Math.max(1, segments.reduce((sum, segment) => sum + Math.max(0, segment.value), 0));
749
+ const isTable = visualization.surface === 'table-cell';
750
+ const resolvedTotal = resolvePraxisStackedBarTotal(segments, visualization.total);
751
+ const suffix = visualization.valueSuffix ?? '';
752
+ const useCompact = visualization.compactValue === true;
753
+ const fallbackTone = visualization.tone ?? 'neutral';
754
+ const aria = resolvePraxisStackedBarAriaLabel(visualization, segments, resolvedTotal, options.locale);
755
+ const buildSegmentReadout = (segment) => {
756
+ const formattedVal = formatVisualizationMetricValue(segment.value, options, useCompact, suffix);
757
+ const pctText = formatPraxisStackedBarPercentage(segment.value, resolvedTotal, options.locale);
758
+ const alreadyPercent = suffix.trim() === '%' || formattedVal.trim().endsWith('%');
759
+ const metricPart = alreadyPercent ? formattedVal : `${formattedVal} (${pctText})`;
760
+ return segment.label ? `${segment.label}: ${metricPart}` : metricPart;
761
+ };
349
762
  const bars = segments
350
- .map((segment) => `
763
+ .map((segment) => {
764
+ const widthPct = computePraxisStackedBarSegmentWidthPct(segment.value, resolvedTotal);
765
+ const isZero = segment.value === 0 || widthPct === 0;
766
+ const paint = getPraxisStackedBarPaintStyle(segment, fallbackTone);
767
+ const paintCss = `--prx-micro-category-color:${paint['--prx-micro-category-color']};color:${paint['color']}`;
768
+ const readout = buildSegmentReadout(segment);
769
+ return `
351
770
  <span
352
771
  class="pfx-micro-viz__segment"
353
- data-tone="${escapeHtml(segment.tone ?? visualization.tone ?? 'info')}"
354
- style="width:${percent(segment.value, total)}%"
355
- title="${escapeHtml(`${segment.label ?? ''} ${formatMicroNumber(segment.value, options.locale)}`.trim())}"
356
- ></span>`)
357
- .join('');
358
- const meta = segments
359
- .slice(0, 3)
360
- .map((segment) => `<span>${escapeHtml(segment.label ?? '')}: ${escapeHtml(formatMicroNumber(segment.value, options.locale))}</span>`)
772
+ data-tone="${escapeHtml(segment.tone ?? fallbackTone)}"${isZero ? '\n data-zero="true"' : ''}
773
+ data-micro-readout="${escapeHtml(readout)}"
774
+ style="width:${widthPct}%;${escapeHtml(paintCss)}"
775
+ ></span>`;
776
+ })
361
777
  .join('');
778
+ const titleHtml = !isTable && visualization.title
779
+ ? `\n <span class="pfx-micro-viz__title">${escapeHtml(visualization.title)}</span>`
780
+ : '';
781
+ const legendHtml = !isTable && visualization.legend === true
782
+ ? `\n <span class="pfx-micro-viz__legend" role="list">${segments
783
+ .map((segment) => {
784
+ const paint = getPraxisStackedBarPaintStyle(segment, fallbackTone);
785
+ const paintCss = `--prx-micro-category-color:${paint['--prx-micro-category-color']};color:${paint['color']}`;
786
+ const pctText = formatPraxisStackedBarPercentage(segment.value, resolvedTotal, options.locale);
787
+ const readout = buildSegmentReadout(segment);
788
+ return `<span class="pfx-micro-viz__legend-item" role="listitem" data-micro-readout="${escapeHtml(readout)}"><span class="pfx-micro-viz__legend-swatch" style="${escapeHtml(paintCss)}" aria-hidden="true"></span><span class="pfx-micro-viz__legend-label">${escapeHtml(segment.label ?? '')}</span><span class="pfx-micro-viz__legend-value">${escapeHtml(pctText)}</span></span>`;
789
+ })
790
+ .join('')}</span>`
791
+ : '';
362
792
  return `
363
- <span class="pfx-micro-viz" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">
364
- <span class="pfx-micro-viz__segments">${bars}</span>
365
- <span class="pfx-micro-viz__meta">${meta}</span>
793
+ <span class="pfx-micro-viz pfx-micro-viz__stacked" role="img" aria-label="${escapeHtml(aria)}">${titleHtml}
794
+ <span class="pfx-micro-viz__segments">${bars}</span>${legendHtml}
366
795
  </span>`;
367
796
  }
368
797
  function resolveBulletMax(visualization) {
@@ -374,9 +803,15 @@ function resolveBulletMax(visualization) {
374
803
  toFiniteNumber(visualization.value) ?? 0,
375
804
  visualization.target ?? 0,
376
805
  visualization.total ?? 0,
806
+ visualization.max ?? 0,
377
807
  ...thresholdValues
378
808
  ].filter((v) => Number.isFinite(v) && v > 0);
379
- return Math.max(...values, 100);
809
+ const fallbackCeiling = visualization.total && visualization.total > 0
810
+ ? visualization.total
811
+ : visualization.max && visualization.max > 0
812
+ ? visualization.max
813
+ : 100;
814
+ return Math.max(...values, fallbackCeiling);
380
815
  }
381
816
  function renderBulletVisualizationHtml(visualization, options) {
382
817
  const currentValue = toFiniteNumber(visualization.value);
@@ -387,6 +822,7 @@ function renderBulletVisualizationHtml(visualization, options) {
387
822
  const target = toFiniteNumber(visualization.target);
388
823
  const targetLeft = target === undefined ? null : percent(target, max);
389
824
  const isTable = visualization.surface === 'table-cell';
825
+ const suffix = visualization.valueSuffix ?? '';
390
826
  // thresholds: sort ascending by boundary value so bands draw continuously regardless of declaration order
391
827
  const thresholds = visualization.thresholds ?? [];
392
828
  const sortedThresholds = [...thresholds].sort((a, b) => {
@@ -404,28 +840,46 @@ function renderBulletVisualizationHtml(visualization, options) {
404
840
  return { left, width, tone: t.tone ?? 'info' };
405
841
  }).filter(b => parseFloat(b.width) > 0);
406
842
  const bandsHtml = bands.map(b => `<span class="pfx-micro-bullet__range" data-tone="${escapeHtml(b.tone)}" style="left: ${b.left}%; width: ${b.width}%;"></span>`).join('');
843
+ const bandsLayerHtml = bandsHtml
844
+ ? `<span class="pfx-micro-bullet__bands">${bandsHtml}</span>`
845
+ : '';
846
+ const targetLabel = resolveTargetReferenceLabel(visualization, options);
847
+ const topMetricHtml = visualization.compactValue === false
848
+ ? target === undefined
849
+ ? ''
850
+ : `<span class="pfx-micro-bullet__target-val">${escapeHtml(targetLabel)}: ${escapeHtml(formatVisualizationMetricValue(target, options, false, suffix))}</span>`
851
+ : `<span class="pfx-micro-bullet__value">
852
+ ${escapeHtml(formatVisualizationMetricValue(currentValue, options, false, suffix))}
853
+ ${target === undefined ? '' : `<span class="pfx-micro-bullet__target-val">/ ${escapeHtml(targetLabel)}: ${escapeHtml(formatVisualizationMetricValue(target, options, false, suffix))}</span>`}
854
+ </span>`;
407
855
  const topHtml = isTable ? '' : `
408
856
  <div class="pfx-micro-bullet__top">
409
- <span class="pfx-micro-bullet__label">${escapeHtml(visualization.fallbackText)}</span>
410
- <span class="pfx-micro-bullet__value">
411
- ${escapeHtml(formatMicroNumber(currentValue, options.locale))}
412
- ${target === undefined ? '' : `<span class="pfx-micro-bullet__target-val">/ Target: ${escapeHtml(formatMicroNumber(target, options.locale))}</span>`}
413
- </span>
857
+ <span class="pfx-micro-bullet__label">${escapeHtml(visualization.title || visualization.fallbackText)}</span>
858
+ ${topMetricHtml}
414
859
  </div>`;
415
860
  const bottomHtml = isTable ? '' : `
416
861
  <div class="pfx-micro-bullet__bottom">
417
- <span>${escapeHtml(formatMicroNumber(visualization.baseline ?? 0, options.locale))}</span>
418
- <span>${escapeHtml(formatMicroNumber(max, options.locale))}</span>
862
+ <span>${escapeHtml(formatVisualizationMetricValue(visualization.baseline ?? 0, options, false, suffix))}</span>
863
+ <span>${escapeHtml(formatVisualizationMetricValue(max, options, false, suffix))}</span>
419
864
  </div>`;
420
865
  const showCompactValue = isTable && visualization.compactValue !== false;
866
+ const useCompactNotation = visualization.compactValue === true;
421
867
  const compactValueHtml = showCompactValue
422
- ? `<span class="pfx-micro-bullet__compact-value">${escapeHtml(formatMicroNumber(currentValue, options.locale))}${escapeHtml(visualization.valueSuffix ?? '')}</span>`
868
+ ? `<span class="pfx-micro-bullet__compact-value">${escapeHtml(formatVisualizationMetricValue(currentValue, options, useCompactNotation, suffix))}</span>`
423
869
  : '';
870
+ const currentStr = formatVisualizationMetricValue(currentValue, options, false, suffix);
871
+ const diff = target !== undefined ? currentValue - target : undefined;
872
+ const diffSign = diff !== undefined && diff > 0 ? '+' : '';
873
+ const bulletReadout = target !== undefined && diff !== undefined
874
+ ? `${currentStr} / ${targetLabel} ${formatVisualizationMetricValue(target, options, false, suffix)} (${diffSign}${formatVisualizationMetricValue(diff, options, false, suffix)})`
875
+ : `${currentStr} / ${formatVisualizationMetricValue(max, options, false, suffix)}`;
876
+ const suppressTabIndex = isTable || options.interactiveContainer === true;
877
+ const tabIndexAttr = suppressTabIndex ? '' : ' tabindex="0"';
424
878
  return `
425
- <span class="pfx-micro-viz pfx-micro-viz__bullet" data-tone="${escapeHtml(visualization.tone ?? 'info')}" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">
879
+ <span class="pfx-micro-viz pfx-micro-viz__bullet"${tabIndexAttr} data-tone="${escapeHtml(visualization.tone ?? 'info')}" data-micro-readout="${escapeHtml(bulletReadout)}" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">
426
880
  ${topHtml}
427
881
  <span class="pfx-micro-bullet__track">
428
- ${bandsHtml}
882
+ ${bandsLayerHtml}
429
883
  <span class="pfx-micro-bullet__actual" data-tone="${escapeHtml(visualization.tone ?? 'info')}" style="width: ${percent(currentValue, max)}%;"></span>
430
884
  ${targetLeft === null ? '' : `<span class="pfx-micro-bullet__target" style="left: ${targetLeft}%;"></span>`}
431
885
  </span>
@@ -448,15 +902,28 @@ function renderDeltaVisualizationHtml(visualization, options) {
448
902
  const valueSuffix = visualization.valueSuffix ?? '';
449
903
  const text = value === undefined
450
904
  ? visualization.fallbackText
451
- : `${formatMicroNumber(Math.abs(value), options.locale)}${valueSuffix}`;
905
+ : formatVisualizationMetricValue(Math.abs(value), options, visualization.compactValue === true, valueSuffix);
452
906
  const directionLabel = direction === 'up'
453
907
  ? 'up'
454
908
  : direction === 'down'
455
909
  ? 'down'
456
910
  : 'stable';
457
911
  const aria = visualization.ariaLabel ?? `${visualization.fallbackText}: ${directionLabel} ${text}`;
912
+ const target = toFiniteNumber(visualization.target);
913
+ const baseline = toFiniteNumber(visualization.baseline);
914
+ const isTable = visualization.surface === 'table-cell';
915
+ const suppressTabIndex = isTable || options.interactiveContainer === true;
916
+ const targetLabel = resolveTargetReferenceLabel(visualization, options);
917
+ const deltaReadout = target !== undefined
918
+ ? `${targetLabel} ${formatVisualizationMetricValue(target, options, false, valueSuffix)}`
919
+ : baseline !== undefined
920
+ ? `Base ${formatVisualizationMetricValue(baseline, options, false, valueSuffix)}`
921
+ : null;
922
+ const readoutAttr = deltaReadout
923
+ ? `${suppressTabIndex ? '' : ' tabindex="0"'} data-micro-readout="${escapeHtml(deltaReadout)}"`
924
+ : '';
458
925
  return `
459
- <span class="pfx-micro-viz pfx-micro-viz__delta" data-tone="${escapeHtml(tone)}" data-direction="${escapeHtml(direction)}" role="img" aria-label="${escapeHtml(aria)}">
926
+ <span class="pfx-micro-viz pfx-micro-viz__delta" data-tone="${escapeHtml(tone)}" data-direction="${escapeHtml(direction)}"${readoutAttr} role="img" aria-label="${escapeHtml(aria)}">
460
927
  <span class="pfx-micro-viz__delta-symbol" aria-hidden="true">${symbol}</span>
461
928
  <span>${escapeHtml(text)}</span>
462
929
  </span>`;
@@ -468,11 +935,40 @@ function percent(value, total) {
468
935
  return Math.max(0, Math.min(100, (value / total) * 100)).toFixed(2);
469
936
  }
470
937
  function toFiniteNumber(value) {
471
- return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
938
+ if (typeof value === 'number') {
939
+ return Number.isFinite(value) ? value : undefined;
940
+ }
941
+ if (typeof value === 'string') {
942
+ const trimmed = value.trim();
943
+ if (!trimmed) {
944
+ return undefined;
945
+ }
946
+ const parsed = Number(trimmed);
947
+ return Number.isFinite(parsed) ? parsed : undefined;
948
+ }
949
+ return undefined;
950
+ }
951
+ function formatVisualizationMetricValue(value, options, compactValue = false, suffix = '') {
952
+ if (typeof options.formatValue === 'function') {
953
+ const custom = options.formatValue(value, compactValue);
954
+ if (typeof custom === 'string' && custom.trim().length > 0) {
955
+ return suffix && !custom.endsWith(suffix) ? `${custom}${suffix}` : custom;
956
+ }
957
+ }
958
+ return `${formatMicroNumber(value, options.locale, compactValue)}${suffix}`;
472
959
  }
473
- function formatMicroNumber(value, locale) {
960
+ function formatMicroNumber(value, locale, compactValue = false) {
961
+ if (compactValue && Math.abs(value) >= 1000) {
962
+ return new Intl.NumberFormat(locale || undefined, {
963
+ notation: 'compact',
964
+ compactDisplay: 'short',
965
+ maximumFractionDigits: 1,
966
+ }).format(value);
967
+ }
968
+ const abs = Math.abs(value);
969
+ const hasFraction = Math.abs(value - Math.trunc(value)) > 1e-6;
474
970
  return new Intl.NumberFormat(locale || undefined, {
475
- maximumFractionDigits: Math.abs(value) < 10 ? 2 : 0,
971
+ maximumFractionDigits: abs < 10 ? 2 : hasFraction && abs < 1000 ? 1 : 0,
476
972
  }).format(value);
477
973
  }
478
974
  function escapeHtml(value) {
@@ -545,15 +1041,25 @@ function normalizeNumericEntries(value) {
545
1041
  }
546
1042
  return value
547
1043
  .map((item) => {
548
- if (!item || typeof item !== 'object' || !Number.isFinite(item.value)) {
1044
+ if (typeof item === 'number' || typeof item === 'string') {
1045
+ const num = toFiniteNumber(item);
1046
+ return num !== undefined ? { value: num } : null;
1047
+ }
1048
+ if (!item || typeof item !== 'object') {
1049
+ return null;
1050
+ }
1051
+ const num = toFiniteNumber(item.value);
1052
+ if (num === undefined) {
549
1053
  return null;
550
1054
  }
551
1055
  const label = normalizeText$1(item.label);
552
1056
  const tone = normalizeEnum$1(item.tone, VISUALIZATION_TONES);
1057
+ const color = normalizePraxisHexColor(item.color);
553
1058
  return {
554
- value: item.value,
1059
+ value: num,
555
1060
  ...(label ? { label } : {}),
556
1061
  ...(tone ? { tone } : {}),
1062
+ ...(color ? { color } : {}),
557
1063
  };
558
1064
  })
559
1065
  .filter((item) => !!item);
@@ -567,8 +1073,9 @@ function normalizeVisualizationItem(item) {
567
1073
  const icon = normalizeText$1(item.icon);
568
1074
  const state = normalizeText$1(item.state);
569
1075
  const tone = normalizeEnum$1(item.tone, VISUALIZATION_TONES);
570
- const normalizedValue = Number.isFinite(item.value) ? item.value : undefined;
571
- if (!id && !label && normalizedValue === undefined && !icon && !state && !tone) {
1076
+ const color = normalizePraxisHexColor(item.color);
1077
+ const normalizedValue = toFiniteNumber(item.value);
1078
+ if (!id && !label && normalizedValue === undefined && !icon && !state && !tone && !color) {
572
1079
  return null;
573
1080
  }
574
1081
  return {
@@ -578,10 +1085,12 @@ function normalizeVisualizationItem(item) {
578
1085
  ...(icon ? { icon } : {}),
579
1086
  ...(state ? { state } : {}),
580
1087
  ...(tone ? { tone } : {}),
1088
+ ...(color ? { color } : {}),
581
1089
  };
582
1090
  }
583
1091
  function normalizeNumber(value, key) {
584
- return Number.isFinite(value) ? { [key]: value } : undefined;
1092
+ const num = toFiniteNumber(value);
1093
+ return num !== undefined ? { [key]: num } : undefined;
585
1094
  }
586
1095
  function normalizeEnum$1(value, allowed) {
587
1096
  if (typeof value !== 'string') {
@@ -603,23 +1112,62 @@ function renderRadialVisualizationHtml(visualization, options) {
603
1112
  return renderFallbackVisualizationHtml(visualization, visualization.tone ?? 'neutral');
604
1113
  }
605
1114
  const total = visualization.total && visualization.total > 0 ? visualization.total : 100;
606
- const pct = Math.max(0, Math.min(100, (value / total) * 100));
1115
+ const rawPct = Math.max(0, (value / total) * 100);
1116
+ const arcPct = Math.min(100, rawPct);
607
1117
  const tone = visualization.tone ?? 'info';
608
- const dashArray = `${pct.toFixed(1)}, 100`;
609
- const pctText = `${Math.round(pct)}%`;
1118
+ const suffix = visualization.valueSuffix ?? '';
1119
+ const dashArray = `${arcPct.toFixed(1)}, 100`;
1120
+ const hasFractionalPct = rawPct < 100 && Math.abs(rawPct - Math.round(rawPct)) >= 0.05;
1121
+ const displayPctNum = hasFractionalPct ? Number(rawPct.toFixed(1)) : Math.round(rawPct);
1122
+ const radialNumStr = formatMicroNumber(displayPctNum, options.locale, false);
1123
+ const pctText = `${radialNumStr}%`;
610
1124
  const aria = visualization.ariaLabel ?? `${visualization.fallbackText} (${pctText})`;
611
1125
  const isTable = visualization.surface === 'table-cell';
1126
+ const isZero = rawPct <= 0;
1127
+ const svgSuffix = computeMicroSvgIdSuffix(visualization, options);
1128
+ const gradId = `pfx-rad-grad-${tone}-${svgSuffix}`;
1129
+ const [stop0, stop1, stop2] = getPraxisMicroToneGradientStops(tone);
1130
+ const targetVal = toFiniteNumber(visualization.target);
1131
+ const targetPct = targetVal !== undefined && targetVal > 0
1132
+ ? Math.max(0, Math.min(100, (targetVal / total) * 100))
1133
+ : null;
1134
+ const targetArcHtml = targetPct !== null
1135
+ ? `<circle class="pfx-micro-radial-svg__target-arc" cx="18" cy="18" r="13.5" pathLength="100" stroke-dasharray="${targetPct.toFixed(1)}, 100" transform="rotate(-90 18 18)" />`
1136
+ : '';
1137
+ const digitTierAttr = radialNumStr.length >= 4
1138
+ ? ' data-digits="4"'
1139
+ : radialNumStr.length === 3
1140
+ ? ' data-digits="3"'
1141
+ : '';
612
1142
  const svgText = isTable
613
1143
  ? ''
614
- : `<text x="18" y="21" class="pfx-micro-radial-svg__text">${escapeHtml(pctText)}</text>`;
1144
+ : `<text x="18" y="20.6" class="pfx-micro-radial-svg__text"${digitTierAttr}><tspan class="pfx-micro-radial-svg__num">${escapeHtml(radialNumStr)}</tspan><tspan class="pfx-micro-radial-svg__unit">%</tspan></text>`;
615
1145
  const externalText = isTable
616
1146
  ? `<span class="pfx-micro-radial-value">${escapeHtml(pctText)}</span>`
617
1147
  : '';
1148
+ const formattedVal = formatVisualizationMetricValue(value, options, false, suffix);
1149
+ const formattedTotal = formatVisualizationMetricValue(total, options, false, suffix);
1150
+ const alreadyPercent = (suffix.trim() === '%' || formattedVal.trim().endsWith('%')) && total === 100;
1151
+ const radialReadout = alreadyPercent
1152
+ ? formattedVal
1153
+ : `${formattedVal} / ${formattedTotal} (${pctText})`;
1154
+ const suppressTabIndex = isTable || options.interactiveContainer === true;
1155
+ const tabIndexAttr = suppressTabIndex ? '' : ' tabindex="0"';
618
1156
  return `
619
- <span class="pfx-micro-viz pfx-micro-viz__radial" data-tone="${escapeHtml(tone)}" role="img" aria-label="${escapeHtml(aria)}">
1157
+ <span class="pfx-micro-viz pfx-micro-viz__radial"${tabIndexAttr} data-tone="${escapeHtml(tone)}" data-micro-readout="${escapeHtml(radialReadout)}" role="img" aria-label="${escapeHtml(aria)}">
620
1158
  <svg class="pfx-micro-radial-svg" viewBox="0 0 36 36">
621
- <circle class="pfx-micro-radial-svg__track" cx="18" cy="18" r="15.9155" />
622
- <circle class="pfx-micro-radial-svg__bar" cx="18" cy="18" r="15.9155" stroke-dasharray="${dashArray}" transform="rotate(-90 18 18)" />
1159
+ <defs>
1160
+ <linearGradient id="${escapeHtml(gradId)}" x1="100%" y1="55%" x2="10%" y2="15%">
1161
+ <stop offset="0%" stop-color="${stop0}" />
1162
+ <stop offset="52%" stop-color="${stop1}" />
1163
+ <stop offset="100%" stop-color="${stop2}" />
1164
+ </linearGradient>
1165
+ </defs>
1166
+ <circle class="pfx-micro-radial-svg__bezel" cx="18" cy="18" r="17" />
1167
+ <circle class="pfx-micro-radial-svg__track" cx="18" cy="18" r="13.5" pathLength="100" />
1168
+ ${targetArcHtml}
1169
+ <circle class="pfx-micro-radial-svg__bar" cx="18" cy="18" r="13.5" pathLength="100"${isZero ? ' data-zero="true"' : ''} stroke="url(#${escapeHtml(gradId)})" stroke-dasharray="${dashArray}" transform="rotate(-90 18 18)" />
1170
+ <circle class="pfx-micro-radial-svg__medallion" cx="18" cy="18" r="9.8" />
623
1171
  ${svgText}
624
1172
  </svg>
625
1173
  ${externalText}
@@ -631,37 +1179,100 @@ function renderHarveyBallVisualizationHtml(visualization, options) {
631
1179
  return renderFallbackVisualizationHtml(visualization, visualization.tone ?? 'neutral');
632
1180
  }
633
1181
  const total = visualization.total && visualization.total > 0 ? visualization.total : 100;
634
- const pct = Math.max(0, Math.min(100, (value / total) * 100));
1182
+ const rawPct = Math.max(0, (value / total) * 100);
1183
+ const arcPct = Math.min(100, rawPct);
635
1184
  const tone = visualization.tone ?? 'info';
636
- const strokeLength = pct * 0.50265;
637
- const dashArray = `${strokeLength.toFixed(3)} 50.265`;
638
- const aria = visualization.ariaLabel ?? `${visualization.fallbackText} (${Math.round(pct)}%)`;
1185
+ const isTable = visualization.surface === 'table-cell';
1186
+ const suppressTabIndex = isTable || options.interactiveContainer === true;
1187
+ const tabIndexAttr = suppressTabIndex ? '' : ' tabindex="0"';
1188
+ const suffix = visualization.valueSuffix ?? '';
1189
+ const isZero = rawPct <= 0;
1190
+ const svgSuffix = computeMicroSvgIdSuffix(visualization, options);
1191
+ const gradId = `pfx-harvey-grad-${tone}-${svgSuffix}`;
1192
+ const [stop0, stop1, stop2] = getPraxisMicroToneGradientStops(tone);
1193
+ const dashArray = `${arcPct.toFixed(2)} 100`;
1194
+ const roundedPct = Math.round(rawPct);
1195
+ const aria = visualization.ariaLabel ?? `${visualization.fallbackText} (${roundedPct}%)`;
1196
+ const formattedValue = formatVisualizationMetricValue(value, options, false, suffix);
1197
+ const formattedTotal = formatVisualizationMetricValue(total, options, false, suffix);
1198
+ const harveyReadout = `${formattedValue}/${formattedTotal} (${roundedPct}%)`;
1199
+ const pctBadgeHtml = isTable
1200
+ ? ''
1201
+ : `<span class="pfx-micro-harvey-pct">${roundedPct}%</span>`;
639
1202
  return `
640
- <span class="pfx-micro-viz pfx-micro-viz__harvey" data-tone="${escapeHtml(tone)}" role="img" aria-label="${escapeHtml(aria)}">
1203
+ <span class="pfx-micro-viz pfx-micro-viz__harvey"${tabIndexAttr} data-tone="${escapeHtml(tone)}" data-micro-readout="${escapeHtml(harveyReadout)}" role="img" aria-label="${escapeHtml(aria)}">
641
1204
  <svg class="pfx-micro-harvey-svg" viewBox="0 0 36 36">
642
- <circle class="pfx-micro-harvey-svg__track" cx="18" cy="18" r="16" />
643
- <circle class="pfx-micro-harvey-svg__bar" cx="18" cy="18" r="8" stroke-dasharray="${dashArray}" transform="rotate(-90 18 18)" />
1205
+ <defs>
1206
+ <linearGradient id="${escapeHtml(gradId)}" x1="15%" y1="10%" x2="85%" y2="90%">
1207
+ <stop offset="0%" stop-color="${stop0}" />
1208
+ <stop offset="52%" stop-color="${stop1}" />
1209
+ <stop offset="100%" stop-color="${stop2}" />
1210
+ </linearGradient>
1211
+ </defs>
1212
+ <circle class="pfx-micro-harvey-svg__bezel" cx="18" cy="18" r="16.8" />
1213
+ <circle class="pfx-micro-harvey-svg__track" cx="18" cy="18" r="14" />
1214
+ <circle class="pfx-micro-harvey-svg__bar" cx="18" cy="18" r="7" pathLength="100"${isZero ? ' data-zero="true"' : ''} stroke="url(#${escapeHtml(gradId)})" stroke-dasharray="${dashArray}" transform="rotate(-90 18 18)" />
1215
+ <circle class="pfx-micro-harvey-svg__pin" cx="18" cy="18" r="1.8" />
644
1216
  </svg>
645
1217
  <span class="pfx-micro-harvey-fraction">
646
- <strong>${escapeHtml(formatMicroNumber(value, options.locale))}</strong>
1218
+ <strong>${escapeHtml(formattedValue)}</strong>
647
1219
  <span class="pfx-separator">/</span>
648
- <span class="pfx-total">${escapeHtml(formatMicroNumber(total, options.locale))}</span>
1220
+ <span class="pfx-total">${escapeHtml(formattedTotal)}</span>
649
1221
  </span>
1222
+ ${pctBadgeHtml}
650
1223
  </span>`;
651
1224
  }
652
- function getPointsCoordinates(points, width, height, padding) {
1225
+ function resolveTrendBounds(points, visualization, anchorZero = false) {
1226
+ const values = points.map((p) => p.value);
1227
+ const refValue = toFiniteNumber(visualization?.target) ?? toFiniteNumber(visualization?.baseline);
1228
+ const explicitMin = toFiniteNumber(visualization?.min);
1229
+ const explicitMax = toFiniteNumber(visualization?.max);
1230
+ const baseCandidates = anchorZero ? [...values, 0] : [...values];
1231
+ if (refValue !== undefined) {
1232
+ baseCandidates.push(refValue);
1233
+ }
1234
+ const minVal = explicitMin !== undefined ? Math.min(explicitMin, ...baseCandidates) : Math.min(...baseCandidates);
1235
+ const maxVal = explicitMax !== undefined ? Math.max(explicitMax, ...baseCandidates) : Math.max(...baseCandidates);
1236
+ const valRange = maxVal - minVal === 0 ? 1 : maxVal - minVal;
1237
+ return { minVal, maxVal, valRange, refValue };
1238
+ }
1239
+ function getPointsCoordinates(points, width, height, padding, visualization) {
653
1240
  if (points.length < 2)
654
1241
  return [];
655
- const values = points.map(p => p.value);
656
- const minVal = Math.min(...values);
657
- const maxVal = Math.max(...values);
658
- const valRange = maxVal - minVal === 0 ? 1 : maxVal - minVal;
1242
+ const { minVal, valRange } = resolveTrendBounds(points, visualization, false);
659
1243
  return points.map((p, index) => {
660
1244
  const x = padding + (index / (points.length - 1)) * (width - 2 * padding);
661
1245
  const y = height - padding - ((p.value - minVal) / valRange) * (height - 2 * padding);
662
1246
  return { x, y };
663
1247
  });
664
1248
  }
1249
+ function renderTrendReferenceLineHtml(points, width, height, padding, visualization, anchorZero = false) {
1250
+ const { minVal, valRange, refValue } = resolveTrendBounds(points, visualization, anchorZero);
1251
+ if (refValue === undefined) {
1252
+ return '';
1253
+ }
1254
+ const refY = height - padding - ((refValue - minVal) / valRange) * (height - 2 * padding);
1255
+ return `<line class="pfx-micro-trend__ref-line" x1="${padding}" y1="${refY.toFixed(1)}" x2="${width - padding}" y2="${refY.toFixed(1)}" stroke="currentColor" stroke-opacity="0.38" stroke-width="1" stroke-dasharray="2 2" />`;
1256
+ }
1257
+ function renderTrendScrubLayerHtml(points, coords, width, height, visualization, options) {
1258
+ const defaultTone = visualization.tone ?? 'info';
1259
+ const suffix = visualization.valueSuffix ?? '';
1260
+ const slicesHtml = points
1261
+ .map((point, index) => {
1262
+ const coord = coords[index] ?? { x: 50, y: 15 };
1263
+ const xPct = ((coord.x / width) * 100).toFixed(1);
1264
+ const yPct = ((coord.y / height) * 100).toFixed(1);
1265
+ const pointTone = point.tone ??
1266
+ (visualization.thresholds?.length
1267
+ ? resolvePraxisMicroVisualizationTone(point.value, visualization.thresholds)?.tone ?? defaultTone
1268
+ : defaultTone);
1269
+ const labelPrefix = point.label ? `${point.label}: ` : `#${index + 1}: `;
1270
+ const readout = `${labelPrefix}${formatVisualizationMetricValue(point.value, options, visualization.compactValue === true, suffix)}`;
1271
+ return `<span class="pfx-micro-trend__scrub-slice" data-tone="${escapeHtml(pointTone)}" data-micro-readout="${escapeHtml(readout)}" style="--pfx-scrub-x:${xPct}%;--pfx-scrub-y:${yPct}%;"></span>`;
1272
+ })
1273
+ .join('');
1274
+ return `<span class="pfx-micro-trend__scrub-layer" aria-hidden="true">${slicesHtml}</span>`;
1275
+ }
665
1276
  function renderLineVisualizationHtml(visualization, options) {
666
1277
  const points = visualization.points ?? [];
667
1278
  const tone = visualization.tone ?? 'info';
@@ -671,8 +1282,14 @@ function renderLineVisualizationHtml(visualization, options) {
671
1282
  const width = 100;
672
1283
  const height = 30;
673
1284
  const padding = 4;
674
- const coords = getPointsCoordinates(points, width, height, padding);
1285
+ const coords = getPointsCoordinates(points, width, height, padding, visualization);
675
1286
  const pathD = coords.map((c, i) => `${i === 0 ? 'M' : 'L'} ${c.x.toFixed(1)} ${c.y.toFixed(1)}`).join(' ');
1287
+ const firstX = coords[0].x.toFixed(1);
1288
+ const lastCoord = coords[coords.length - 1];
1289
+ const lastX = lastCoord.x.toFixed(1);
1290
+ const glowAreaD = `${pathD} L ${lastX} ${height} L ${firstX} ${height} Z`;
1291
+ const glowGradId = `pfx-line-glow-${tone}-${computeMicroSvgIdSuffix(visualization, options)}`;
1292
+ const refLineHtml = renderTrendReferenceLineHtml(points, width, height, padding, visualization, false);
676
1293
  // Highlight extreme/boundary values
677
1294
  let minIdx = 0;
678
1295
  let maxIdx = 0;
@@ -682,9 +1299,10 @@ function renderLineVisualizationHtml(visualization, options) {
682
1299
  if (points[i].value > points[maxIdx].value)
683
1300
  maxIdx = i;
684
1301
  }
1302
+ const lastTone = points[points.length - 1].tone ?? tone;
685
1303
  const markers = [
686
1304
  { x: coords[0].x, y: coords[0].y, tone: points[0].tone ?? tone },
687
- { x: coords[coords.length - 1].x, y: coords[coords.length - 1].y, tone: points[points.length - 1].tone ?? tone }
1305
+ { x: lastCoord.x, y: lastCoord.y, tone: lastTone }
688
1306
  ];
689
1307
  if (minIdx !== 0 && minIdx !== coords.length - 1) {
690
1308
  markers.push({ x: coords[minIdx].x, y: coords[minIdx].y, tone: points[minIdx].tone ?? 'danger' });
@@ -692,18 +1310,21 @@ function renderLineVisualizationHtml(visualization, options) {
692
1310
  if (maxIdx !== 0 && maxIdx !== coords.length - 1) {
693
1311
  markers.push({ x: coords[maxIdx].x, y: coords[maxIdx].y, tone: points[maxIdx].tone ?? 'success' });
694
1312
  }
1313
+ const endpointHaloHtml = `<circle cx="${lastCoord.x.toFixed(1)}" cy="${lastCoord.y.toFixed(1)}" r="5" class="pfx-micro-trend__endpoint-halo" data-tone="${escapeHtml(lastTone)}" />`;
695
1314
  const circlesHtml = markers.map(c => `<circle cx="${c.x.toFixed(1)}" cy="${c.y.toFixed(1)}" r="2.5" class="pfx-micro-trend__marker" data-tone="${escapeHtml(c.tone)}" />`).join('');
1315
+ const scrubLayerHtml = renderTrendScrubLayerHtml(points, coords, width, height, visualization, options);
696
1316
  const isTable = visualization.surface === 'table-cell';
697
1317
  const firstPoint = points[0];
698
1318
  const lastPoint = points[points.length - 1];
1319
+ const suffix = visualization.valueSuffix ?? '';
699
1320
  const leftHtml = isTable ? '' : `
700
1321
  <div class="pfx-micro-trend__label-col pfx-micro-trend__label-col--start">
701
- <span class="pfx-micro-trend__value">${escapeHtml(formatMicroNumber(firstPoint.value, options.locale))}</span>
1322
+ <span class="pfx-micro-trend__value">${escapeHtml(formatVisualizationMetricValue(firstPoint.value, options, visualization.compactValue === true, suffix))}</span>
702
1323
  ${firstPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(firstPoint.label)}</span>` : ''}
703
1324
  </div>`;
704
1325
  const rightHtml = isTable ? '' : `
705
1326
  <div class="pfx-micro-trend__label-col pfx-micro-trend__label-col--end">
706
- <span class="pfx-micro-trend__value">${escapeHtml(formatMicroNumber(lastPoint.value, options.locale))}</span>
1327
+ <span class="pfx-micro-trend__value">${escapeHtml(formatVisualizationMetricValue(lastPoint.value, options, visualization.compactValue === true, suffix))}</span>
707
1328
  ${lastPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(lastPoint.label)}</span>` : ''}
708
1329
  </div>`;
709
1330
  return `
@@ -711,9 +1332,19 @@ function renderLineVisualizationHtml(visualization, options) {
711
1332
  ${leftHtml}
712
1333
  <span class="pfx-micro-viz pfx-micro-viz__line" data-tone="${escapeHtml(tone)}" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">
713
1334
  <svg class="pfx-micro-line__svg" viewBox="0 0 100 30">
714
- <path class="pfx-micro-line__path" d="${pathD}" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
1335
+ <defs>
1336
+ <linearGradient id="${escapeHtml(glowGradId)}" x1="0%" y1="0%" x2="0%" y2="100%">
1337
+ <stop offset="0%" stop-color="currentColor" stop-opacity="0.16" />
1338
+ <stop offset="100%" stop-color="currentColor" stop-opacity="0" />
1339
+ </linearGradient>
1340
+ </defs>
1341
+ ${refLineHtml}
1342
+ <path class="pfx-micro-line__glow" d="${glowAreaD}" fill="url(#${escapeHtml(glowGradId)})" />
1343
+ <path class="pfx-micro-line__path" d="${pathD}" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" />
1344
+ ${endpointHaloHtml}
715
1345
  ${circlesHtml}
716
1346
  </svg>
1347
+ ${scrubLayerHtml}
717
1348
  </span>
718
1349
  ${rightHtml}
719
1350
  </span>`;
@@ -727,11 +1358,14 @@ function renderAreaVisualizationHtml(visualization, options) {
727
1358
  const width = 100;
728
1359
  const height = 30;
729
1360
  const padding = 4;
730
- const coords = getPointsCoordinates(points, width, height, padding);
1361
+ const coords = getPointsCoordinates(points, width, height, padding, visualization);
731
1362
  const lineD = coords.map((c, i) => `${i === 0 ? 'M' : 'L'} ${c.x.toFixed(1)} ${c.y.toFixed(1)}`).join(' ');
1363
+ const refLineHtml = renderTrendReferenceLineHtml(points, width, height, padding, visualization, false);
732
1364
  const firstX = coords[0].x.toFixed(1);
733
- const lastX = coords[coords.length - 1].x.toFixed(1);
1365
+ const lastCoord = coords[coords.length - 1];
1366
+ const lastX = lastCoord.x.toFixed(1);
734
1367
  const areaD = `${lineD} L ${lastX} ${height} L ${firstX} ${height} Z`;
1368
+ const areaGradId = `pfx-area-grad-${tone}-${computeMicroSvgIdSuffix(visualization, options)}`;
735
1369
  // Highlight extreme/boundary values
736
1370
  let minIdx = 0;
737
1371
  let maxIdx = 0;
@@ -741,9 +1375,10 @@ function renderAreaVisualizationHtml(visualization, options) {
741
1375
  if (points[i].value > points[maxIdx].value)
742
1376
  maxIdx = i;
743
1377
  }
1378
+ const lastTone = points[points.length - 1].tone ?? tone;
744
1379
  const markers = [
745
1380
  { x: coords[0].x, y: coords[0].y, tone: points[0].tone ?? tone },
746
- { x: coords[coords.length - 1].x, y: coords[coords.length - 1].y, tone: points[points.length - 1].tone ?? tone }
1381
+ { x: lastCoord.x, y: lastCoord.y, tone: lastTone }
747
1382
  ];
748
1383
  if (minIdx !== 0 && minIdx !== coords.length - 1) {
749
1384
  markers.push({ x: coords[minIdx].x, y: coords[minIdx].y, tone: points[minIdx].tone ?? 'danger' });
@@ -751,18 +1386,21 @@ function renderAreaVisualizationHtml(visualization, options) {
751
1386
  if (maxIdx !== 0 && maxIdx !== coords.length - 1) {
752
1387
  markers.push({ x: coords[maxIdx].x, y: coords[maxIdx].y, tone: points[maxIdx].tone ?? 'success' });
753
1388
  }
1389
+ const endpointHaloHtml = `<circle cx="${lastCoord.x.toFixed(1)}" cy="${lastCoord.y.toFixed(1)}" r="5" class="pfx-micro-trend__endpoint-halo" data-tone="${escapeHtml(lastTone)}" />`;
754
1390
  const circlesHtml = markers.map(c => `<circle cx="${c.x.toFixed(1)}" cy="${c.y.toFixed(1)}" r="2.5" class="pfx-micro-trend__marker" data-tone="${escapeHtml(c.tone)}" />`).join('');
1391
+ const scrubLayerHtml = renderTrendScrubLayerHtml(points, coords, width, height, visualization, options);
755
1392
  const isTable = visualization.surface === 'table-cell';
756
1393
  const firstPoint = points[0];
757
1394
  const lastPoint = points[points.length - 1];
1395
+ const suffix = visualization.valueSuffix ?? '';
758
1396
  const leftHtml = isTable ? '' : `
759
1397
  <div class="pfx-micro-trend__label-col pfx-micro-trend__label-col--start">
760
- <span class="pfx-micro-trend__value">${escapeHtml(formatMicroNumber(firstPoint.value, options.locale))}</span>
1398
+ <span class="pfx-micro-trend__value">${escapeHtml(formatVisualizationMetricValue(firstPoint.value, options, visualization.compactValue === true, suffix))}</span>
761
1399
  ${firstPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(firstPoint.label)}</span>` : ''}
762
1400
  </div>`;
763
1401
  const rightHtml = isTable ? '' : `
764
1402
  <div class="pfx-micro-trend__label-col pfx-micro-trend__label-col--end">
765
- <span class="pfx-micro-trend__value">${escapeHtml(formatMicroNumber(lastPoint.value, options.locale))}</span>
1403
+ <span class="pfx-micro-trend__value">${escapeHtml(formatVisualizationMetricValue(lastPoint.value, options, visualization.compactValue === true, suffix))}</span>
766
1404
  ${lastPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(lastPoint.label)}</span>` : ''}
767
1405
  </div>`;
768
1406
  return `
@@ -770,10 +1408,19 @@ function renderAreaVisualizationHtml(visualization, options) {
770
1408
  ${leftHtml}
771
1409
  <span class="pfx-micro-viz pfx-micro-viz__area" data-tone="${escapeHtml(tone)}" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">
772
1410
  <svg class="pfx-micro-area__svg" viewBox="0 0 100 30">
773
- <path class="pfx-micro-area__fill" d="${areaD}" fill="currentColor" fill-opacity="0.15" />
774
- <path class="pfx-micro-area__path" d="${lineD}" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
1411
+ <defs>
1412
+ <linearGradient id="${escapeHtml(areaGradId)}" x1="0%" y1="0%" x2="0%" y2="100%">
1413
+ <stop offset="0%" stop-color="currentColor" stop-opacity="0.32" />
1414
+ <stop offset="100%" stop-color="currentColor" stop-opacity="0.02" />
1415
+ </linearGradient>
1416
+ </defs>
1417
+ ${refLineHtml}
1418
+ <path class="pfx-micro-area__fill" d="${areaD}" fill="url(#${escapeHtml(areaGradId)})" />
1419
+ <path class="pfx-micro-area__path" d="${lineD}" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" />
1420
+ ${endpointHaloHtml}
775
1421
  ${circlesHtml}
776
1422
  </svg>
1423
+ ${scrubLayerHtml}
777
1424
  </span>
778
1425
  ${rightHtml}
779
1426
  </span>`;
@@ -787,32 +1434,35 @@ function renderColumnVisualizationHtml(visualization, options) {
787
1434
  const width = 100;
788
1435
  const height = 30;
789
1436
  const padding = 4;
790
- const values = points.map(p => p.value);
791
- const maxVal = Math.max(...values, 0);
792
- const minVal = Math.min(...values, 0);
793
- const valRange = maxVal - minVal === 0 ? 1 : maxVal - minVal;
1437
+ const { minVal, valRange } = resolveTrendBounds(points, visualization, true);
1438
+ const refLineHtml = renderTrendReferenceLineHtml(points, width, height, padding, visualization, true);
794
1439
  const colWidth = Math.max(2, (width - 2 * padding) / points.length - 2);
1440
+ const colCoords = [];
795
1441
  const columnsHtml = points.map((p, i) => {
796
1442
  const x = padding + i * ((width - 2 * padding) / points.length) + 1;
797
1443
  const rectHeight = Math.max(2, ((p.value - minVal) / valRange) * (height - 2 * padding));
798
1444
  const rectY = height - padding - rectHeight;
1445
+ colCoords.push({ x: x + colWidth / 2, y: rectY });
799
1446
  const itemTone = p.tone ??
800
1447
  (visualization.thresholds?.length
801
1448
  ? resolvePraxisMicroVisualizationTone(p.value, visualization.thresholds)?.tone ?? tone
802
1449
  : tone);
803
- return `<rect class="pfx-micro-column__bar" x="${x.toFixed(1)}" y="${rectY.toFixed(1)}" width="${colWidth.toFixed(1)}" height="${rectHeight.toFixed(1)}" fill="currentColor" data-tone="${escapeHtml(itemTone)}" />`;
1450
+ const latestAttr = i === points.length - 1 ? ' data-latest="true"' : '';
1451
+ return `<rect class="pfx-micro-column__bar" x="${x.toFixed(1)}" y="${rectY.toFixed(1)}" width="${colWidth.toFixed(1)}" height="${rectHeight.toFixed(1)}" rx="2" fill="currentColor" data-tone="${escapeHtml(itemTone)}"${latestAttr} />`;
804
1452
  }).join('');
1453
+ const scrubLayerHtml = renderTrendScrubLayerHtml(points, colCoords, width, height, visualization, options);
805
1454
  const isTable = visualization.surface === 'table-cell';
806
1455
  const firstPoint = points[0];
807
1456
  const lastPoint = points[points.length - 1];
1457
+ const suffix = visualization.valueSuffix ?? '';
808
1458
  const leftHtml = isTable ? '' : `
809
1459
  <div class="pfx-micro-trend__label-col pfx-micro-trend__label-col--start">
810
- <span class="pfx-micro-trend__value">${escapeHtml(formatMicroNumber(firstPoint.value, options.locale))}</span>
1460
+ <span class="pfx-micro-trend__value">${escapeHtml(formatVisualizationMetricValue(firstPoint.value, options, visualization.compactValue === true, suffix))}</span>
811
1461
  ${firstPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(firstPoint.label)}</span>` : ''}
812
1462
  </div>`;
813
1463
  const rightHtml = isTable ? '' : `
814
1464
  <div class="pfx-micro-trend__label-col pfx-micro-trend__label-col--end">
815
- <span class="pfx-micro-trend__value">${escapeHtml(formatMicroNumber(lastPoint.value, options.locale))}</span>
1465
+ <span class="pfx-micro-trend__value">${escapeHtml(formatVisualizationMetricValue(lastPoint.value, options, visualization.compactValue === true, suffix))}</span>
816
1466
  ${lastPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(lastPoint.label)}</span>` : ''}
817
1467
  </div>`;
818
1468
  return `
@@ -821,7 +1471,9 @@ function renderColumnVisualizationHtml(visualization, options) {
821
1471
  <span class="pfx-micro-viz pfx-micro-viz__column" data-tone="${escapeHtml(tone)}" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">
822
1472
  <svg class="pfx-micro-column__svg" viewBox="0 0 100 30">
823
1473
  ${columnsHtml}
1474
+ ${refLineHtml}
824
1475
  </svg>
1476
+ ${scrubLayerHtml}
825
1477
  </span>
826
1478
  ${rightHtml}
827
1479
  </span>`;
@@ -850,15 +1502,25 @@ function renderProcessFlowVisualizationHtml(visualization, options) {
850
1502
  const itemState = item.state ?? '';
851
1503
  const isLast = index === items.length - 1;
852
1504
  const itemLabel = stepLabels[index];
1505
+ const normalizedIcon = item.icon ? item.icon.replace(/-/g, '_') : undefined;
853
1506
  const label = !isTable && item.label ? `<span class="pfx-micro-step__label"${labelInlineStyle}>${escapeHtml(item.label)}</span>` : '';
1507
+ const isActiveStep = itemState === 'active' ||
1508
+ itemState === 'current' ||
1509
+ itemState === 'in_progress' ||
1510
+ normalizedIcon === 'sync' ||
1511
+ normalizedIcon === 'pending' ||
1512
+ normalizedIcon === 'pending_actions' ||
1513
+ normalizedIcon === 'schedule' ||
1514
+ (!itemState && itemTone === 'warning');
1515
+ const stepReadout = `${index + 1}/${items.length} · ${itemLabel}`;
854
1516
  const connector = !isLast ? `<span class="pfx-micro-step__connector" data-tone="${escapeHtml(itemTone)}"></span>` : '';
855
1517
  const stepCircle = `
856
- <span class="pfx-micro-step__node" data-tone="${escapeHtml(itemTone)}" aria-hidden="true">
857
- ${item.icon ? `<span class="material-icons pfx-micro-step__icon" aria-hidden="true">${escapeHtml(item.icon)}</span>` : `${index + 1}`}
1518
+ <span class="pfx-micro-step__node" data-tone="${escapeHtml(itemTone)}"${isActiveStep ? ' data-active="true"' : ''} aria-hidden="true">
1519
+ ${normalizedIcon ? `<span class="material-icons pfx-micro-step__icon" aria-hidden="true">${escapeHtml(normalizedIcon)}</span>` : `${index + 1}`}
858
1520
  </span>`;
859
1521
  return `
860
1522
  <div class="pfx-micro-step" data-state="${escapeHtml(itemState)}" data-tone="${escapeHtml(itemTone)}">
861
- <div class="pfx-micro-step__node-wrapper" title="${escapeHtml(itemLabel)}">
1523
+ <div class="pfx-micro-step__node-wrapper" data-micro-readout="${escapeHtml(stepReadout)}" title="${escapeHtml(itemLabel)}">
862
1524
  ${stepCircle}
863
1525
  ${label}
864
1526
  </div>
@@ -880,6 +1542,475 @@ function renderFallbackVisualizationHtml(visualization, tone) {
880
1542
  >${escapeHtml(visualization.fallbackText)}</span>`;
881
1543
  }
882
1544
 
1545
+ const PRAXIS_QUICK_VIEW_PRESENTER = new InjectionToken('PRAXIS_QUICK_VIEW_PRESENTER');
1546
+ const PRAXIS_QUICK_VIEW_BODY_RENDERER = new InjectionToken('PRAXIS_QUICK_VIEW_BODY_RENDERER');
1547
+ const FORBIDDEN_BINDING_KEYS = new Set([
1548
+ 'element',
1549
+ 'nativeElement',
1550
+ 'anchor',
1551
+ 'hostElement',
1552
+ 'focusOrigin',
1553
+ 'getViewportRect',
1554
+ 'nodes',
1555
+ 'document',
1556
+ 'action',
1557
+ 'actions',
1558
+ 'ctaAction',
1559
+ 'overrideAction',
1560
+ 'route',
1561
+ 'href',
1562
+ 'payload',
1563
+ 'hostCapabilities',
1564
+ ]);
1565
+ const RESOURCE_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
1566
+ /**
1567
+ * Detecta se um valor candidato à serialização contém referências efêmeras de DOM ou funções.
1568
+ */
1569
+ function containsEphemeralQuickViewRuntimeValue(value, visited = new Set()) {
1570
+ if (!value || typeof value !== 'object') {
1571
+ return typeof value === 'function';
1572
+ }
1573
+ if (visited.has(value)) {
1574
+ return false;
1575
+ }
1576
+ visited.add(value);
1577
+ if (typeof Element !== 'undefined' && value instanceof Element) {
1578
+ return true;
1579
+ }
1580
+ if (typeof value.nodeType === 'number' &&
1581
+ typeof value.nodeName === 'string') {
1582
+ return true;
1583
+ }
1584
+ if (Array.isArray(value)) {
1585
+ return value.some((item) => containsEphemeralQuickViewRuntimeValue(item, visited));
1586
+ }
1587
+ for (const [key, entry] of Object.entries(value)) {
1588
+ if (key === 'element' ||
1589
+ key === 'nativeElement' ||
1590
+ key === 'hostElement' ||
1591
+ key === 'focusOrigin' ||
1592
+ typeof entry === 'function') {
1593
+ return true;
1594
+ }
1595
+ if (containsEphemeralQuickViewRuntimeValue(entry, visited)) {
1596
+ return true;
1597
+ }
1598
+ }
1599
+ return false;
1600
+ }
1601
+ function normalizeResourceRecordOpenReference(candidate) {
1602
+ if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {
1603
+ return null;
1604
+ }
1605
+ const record = candidate;
1606
+ const target = record['target'] && typeof record['target'] === 'object' && !Array.isArray(record['target'])
1607
+ ? record['target']
1608
+ : null;
1609
+ const sourceIdentityField = typeof record['sourceIdentityField'] === 'string'
1610
+ ? record['sourceIdentityField'].trim()
1611
+ : '';
1612
+ const resourceKey = typeof target?.['resourceKey'] === 'string'
1613
+ ? target['resourceKey'].trim()
1614
+ : '';
1615
+ const surfaceId = typeof target?.['surfaceId'] === 'string'
1616
+ ? target['surfaceId'].trim()
1617
+ : '';
1618
+ if (!sourceIdentityField ||
1619
+ sourceIdentityField.length > 200 ||
1620
+ !RESOURCE_KEY_PATTERN.test(resourceKey) ||
1621
+ !surfaceId ||
1622
+ surfaceId.length > 200) {
1623
+ return null;
1624
+ }
1625
+ return {
1626
+ sourceIdentityField,
1627
+ target: {
1628
+ resourceKey,
1629
+ surfaceId,
1630
+ },
1631
+ };
1632
+ }
1633
+ /**
1634
+ * Valida e normaliza um `ResourceQuickViewBinding` de forma fail-closed.
1635
+ */
1636
+ function validateResourceQuickViewBinding(value) {
1637
+ const diagnostics = [];
1638
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
1639
+ return {
1640
+ valid: false,
1641
+ binding: null,
1642
+ diagnostics: ['Quick View binding must be a non-null object.'],
1643
+ };
1644
+ }
1645
+ const record = value;
1646
+ for (const forbiddenKey of FORBIDDEN_BINDING_KEYS) {
1647
+ if (forbiddenKey in record && record[forbiddenKey] !== undefined) {
1648
+ diagnostics.push(`Quick View binding cannot contain runtime, inline document or action override property "${forbiddenKey}".`);
1649
+ }
1650
+ }
1651
+ if (containsEphemeralQuickViewRuntimeValue(record)) {
1652
+ diagnostics.push('Quick View binding cannot contain DOM elements or functions.');
1653
+ }
1654
+ const rawRecordOpen = record['recordOpen'];
1655
+ if (!rawRecordOpen || typeof rawRecordOpen !== 'object' || Array.isArray(rawRecordOpen)) {
1656
+ diagnostics.push('Quick View binding requires a valid "recordOpen" object.');
1657
+ }
1658
+ else {
1659
+ const recordOpenObj = rawRecordOpen;
1660
+ for (const forbiddenKey of FORBIDDEN_BINDING_KEYS) {
1661
+ if (forbiddenKey in recordOpenObj && recordOpenObj[forbiddenKey] !== undefined) {
1662
+ diagnostics.push(`Quick View recordOpen cannot contain override property "${forbiddenKey}".`);
1663
+ }
1664
+ }
1665
+ if ('presentation' in recordOpenObj && recordOpenObj['presentation'] === 'popover') {
1666
+ diagnostics.push('Quick View recordOpen cannot declare "popover" presentation.');
1667
+ }
1668
+ }
1669
+ let previewSurfaceId;
1670
+ const rawPreviewSurfaceId = record['previewSurfaceId'];
1671
+ if (rawPreviewSurfaceId !== undefined && rawPreviewSurfaceId !== null) {
1672
+ if (typeof rawPreviewSurfaceId === 'string' &&
1673
+ rawPreviewSurfaceId.trim().length > 0 &&
1674
+ rawPreviewSurfaceId.trim().length <= 200) {
1675
+ previewSurfaceId = rawPreviewSurfaceId.trim();
1676
+ }
1677
+ else {
1678
+ diagnostics.push('Quick View previewSurfaceId must be a non-empty string up to 200 characters.');
1679
+ }
1680
+ }
1681
+ let detailPresentation;
1682
+ const rawDetailPresentation = record['detailPresentation'];
1683
+ if (rawDetailPresentation !== undefined && rawDetailPresentation !== null) {
1684
+ if (rawDetailPresentation === 'drawer' || rawDetailPresentation === 'modal') {
1685
+ detailPresentation = rawDetailPresentation;
1686
+ }
1687
+ else {
1688
+ diagnostics.push(`Quick View detailPresentation must be "drawer" or "modal"; received "${String(rawDetailPresentation)}".`);
1689
+ }
1690
+ }
1691
+ const normalizedRecordOpen = normalizeResourceRecordOpenReference(rawRecordOpen);
1692
+ if (!normalizedRecordOpen) {
1693
+ diagnostics.push('Quick View recordOpen must declare non-empty sourceIdentityField and target.{resourceKey, surfaceId}.');
1694
+ }
1695
+ let normalizedContentRef;
1696
+ const rawContentRef = record['contentRef'];
1697
+ if (rawContentRef !== undefined && rawContentRef !== null) {
1698
+ if (typeof rawContentRef !== 'object' || Array.isArray(rawContentRef)) {
1699
+ diagnostics.push('Quick View contentRef must be an object reference to a rich-block preset.');
1700
+ }
1701
+ else {
1702
+ const refObj = rawContentRef;
1703
+ const kind = typeof refObj['kind'] === 'string' ? refObj['kind'].trim() : '';
1704
+ const namespace = typeof refObj['namespace'] === 'string' ? refObj['namespace'].trim() : '';
1705
+ const presetId = typeof refObj['presetId'] === 'string' ? refObj['presetId'].trim() : '';
1706
+ const version = typeof refObj['version'] === 'string' ? refObj['version'].trim() : '';
1707
+ if (kind !== 'rich-block') {
1708
+ diagnostics.push(`Quick View contentRef.kind must be "rich-block"; received "${kind || 'empty'}".`);
1709
+ }
1710
+ if (!namespace) {
1711
+ diagnostics.push('Quick View contentRef.namespace must be a non-empty string.');
1712
+ }
1713
+ if (!presetId) {
1714
+ diagnostics.push('Quick View contentRef.presetId must be a non-empty string.');
1715
+ }
1716
+ if (!version) {
1717
+ diagnostics.push('Quick View contentRef.version must be explicitly declared.');
1718
+ }
1719
+ if ('nodes' in refObj || 'inputs' in refObj || 'action' in refObj) {
1720
+ diagnostics.push('Quick View contentRef cannot embed inline nodes, inputs or actions.');
1721
+ }
1722
+ if (kind === 'rich-block' &&
1723
+ namespace &&
1724
+ presetId &&
1725
+ version &&
1726
+ !('nodes' in refObj || 'inputs' in refObj || 'action' in refObj)) {
1727
+ normalizedContentRef = {
1728
+ kind: 'rich-block',
1729
+ namespace,
1730
+ presetId,
1731
+ version,
1732
+ };
1733
+ }
1734
+ }
1735
+ }
1736
+ if (diagnostics.length > 0 || !normalizedRecordOpen) {
1737
+ return {
1738
+ valid: false,
1739
+ binding: null,
1740
+ diagnostics,
1741
+ };
1742
+ }
1743
+ return {
1744
+ valid: true,
1745
+ binding: {
1746
+ recordOpen: normalizedRecordOpen,
1747
+ ...(previewSurfaceId ? { previewSurfaceId } : {}),
1748
+ ...(normalizedContentRef ? { contentRef: normalizedContentRef } : {}),
1749
+ ...(detailPresentation ? { detailPresentation } : {}),
1750
+ },
1751
+ diagnostics: [],
1752
+ };
1753
+ }
1754
+ function normalizeResourceQuickViewBinding(value) {
1755
+ return validateResourceQuickViewBinding(value).binding;
1756
+ }
1757
+ /**
1758
+ * Resolve ou sintetiza de forma determinística o `ResourceQuickViewBinding` de um campo
1759
+ * (`FieldDefinition` ou `FieldMetadata`), priorizando:
1760
+ * 1. `field.quickView` explícito;
1761
+ * 2. `field.presentation.interactions.quickView` explícito;
1762
+ * 3. síntese automática a partir de `field.resourceReference` ou `field.optionSource.detail`.
1763
+ *
1764
+ * Protege contra colisão de `valueField`/`optionSource.valuePropertyPath` (`'id'` da opção)
1765
+ * com o identificador da própria entidade pai quando o campo de origem possui outro nome
1766
+ * (ex.: `cargoId`, `fornecedorId`).
1767
+ */
1768
+ function resolveFieldQuickViewBinding(candidate) {
1769
+ if (!candidate || typeof candidate !== 'object') {
1770
+ return null;
1771
+ }
1772
+ const explicitQuickView = normalizeResourceQuickViewBinding(candidate.quickView);
1773
+ if (explicitQuickView) {
1774
+ return explicitQuickView;
1775
+ }
1776
+ const presentationQuickView = normalizeResourceQuickViewBinding(candidate.presentation?.interactions?.quickView);
1777
+ if (presentationQuickView) {
1778
+ return presentationQuickView;
1779
+ }
1780
+ const fieldName = typeof candidate.name === 'string' ? candidate.name.trim() : '';
1781
+ const rawValueField = typeof candidate.valueField === 'string' ? candidate.valueField.trim() : '';
1782
+ const optionValueProperty = typeof candidate.optionSource?.valuePropertyPath === 'string' &&
1783
+ candidate.optionSource.valuePropertyPath.trim().length > 0
1784
+ ? candidate.optionSource.valuePropertyPath.trim()
1785
+ : 'id';
1786
+ // Quando o campo possui optionSource e seu nome não coincide com rawValueField, um valueField
1787
+ // igual a 'id'/'value'/'key' ou a optionValueProperty (ex.: 'numero', 'codigo') refere-se à
1788
+ // chave do OptionDTO e nunca ao campo irmão 'id' do registro pai.
1789
+ const isOptionKeyAlias = rawValueField === 'id' ||
1790
+ rawValueField === 'value' ||
1791
+ rawValueField === 'key' ||
1792
+ rawValueField === optionValueProperty;
1793
+ const effectiveSiblingValueField = rawValueField &&
1794
+ (!candidate.optionSource ||
1795
+ fieldName === rawValueField ||
1796
+ !isOptionKeyAlias)
1797
+ ? rawValueField
1798
+ : '';
1799
+ const refCandidate = candidate.resourceReference?.resourceKey
1800
+ ? {
1801
+ resourceKey: candidate.resourceReference.resourceKey,
1802
+ sourceIdentityField: (typeof candidate.resourceReference.valueField === 'string'
1803
+ ? candidate.resourceReference.valueField.trim()
1804
+ : '') ||
1805
+ effectiveSiblingValueField ||
1806
+ fieldName,
1807
+ surfaceId: candidate.resourceReference.surfaceId || 'detail',
1808
+ previewSurfaceId: candidate.resourceReference.previewSurfaceId,
1809
+ detailPresentation: candidate.resourceReference.detailPresentation === 'drawer' ||
1810
+ candidate.resourceReference.detailPresentation === 'modal'
1811
+ ? candidate.resourceReference.detailPresentation
1812
+ : undefined,
1813
+ }
1814
+ : candidate.optionSource?.detail?.resourceKey
1815
+ ? {
1816
+ resourceKey: candidate.optionSource.detail.resourceKey,
1817
+ sourceIdentityField: effectiveSiblingValueField || fieldName,
1818
+ surfaceId: candidate.optionSource.detail.surfaceId || 'detail',
1819
+ previewSurfaceId: candidate.optionSource.detail.previewSurfaceId,
1820
+ detailPresentation: candidate.optionSource.detail.presentation === 'drawer' ||
1821
+ candidate.optionSource.detail.presentation === 'modal'
1822
+ ? candidate.optionSource.detail.presentation
1823
+ : undefined,
1824
+ }
1825
+ : undefined;
1826
+ if (!refCandidate || !refCandidate.sourceIdentityField) {
1827
+ return null;
1828
+ }
1829
+ return normalizeResourceQuickViewBinding({
1830
+ recordOpen: {
1831
+ sourceIdentityField: refCandidate.sourceIdentityField,
1832
+ target: {
1833
+ resourceKey: refCandidate.resourceKey,
1834
+ surfaceId: refCandidate.surfaceId || 'detail',
1835
+ },
1836
+ },
1837
+ ...(refCandidate.previewSurfaceId
1838
+ ? { previewSurfaceId: refCandidate.previewSurfaceId }
1839
+ : {}),
1840
+ ...(refCandidate.detailPresentation
1841
+ ? { detailPresentation: refCandidate.detailPresentation }
1842
+ : {}),
1843
+ });
1844
+ }
1845
+ /**
1846
+ * Reconcilia o `ResourceQuickViewBinding` entre a definição base do servidor e uma
1847
+ * customização local persistida:
1848
+ * - Um `local` indefinido, nulo ou inválido nunca apaga o binding canônico do servidor (`base`).
1849
+ * - Quando o campo possui binding canônico do servidor (`base`), `base.recordOpen`
1850
+ * (recurso de destino, `surfaceId` e `sourceIdentityField`) permanece autoritativo
1851
+ * do servidor, permitindo que o `local` customize apenas preferências visuais de UX
1852
+ * (`trigger`, `previewSurfaceId`, `detailPresentation`).
1853
+ */
1854
+ function reconcileFieldQuickViewBinding(base, local) {
1855
+ const normalizedBase = normalizeResourceQuickViewBinding(base);
1856
+ const normalizedLocal = normalizeResourceQuickViewBinding(local);
1857
+ if (normalizedBase && normalizedLocal) {
1858
+ return {
1859
+ ...normalizedBase,
1860
+ ...normalizedLocal,
1861
+ recordOpen: normalizedBase.recordOpen,
1862
+ };
1863
+ }
1864
+ return normalizedLocal ?? normalizedBase ?? undefined;
1865
+ }
1866
+ function readQuickViewFieldOrPath(target, path) {
1867
+ if (Object.prototype.hasOwnProperty.call(target, path)) {
1868
+ return target[path];
1869
+ }
1870
+ if (!path.includes('.')) {
1871
+ return undefined;
1872
+ }
1873
+ return path.split('.').reduce((acc, segment) => {
1874
+ if (!acc || typeof acc !== 'object' || Array.isArray(acc)) {
1875
+ return undefined;
1876
+ }
1877
+ return Object.prototype.hasOwnProperty.call(acc, segment)
1878
+ ? acc[segment]
1879
+ : undefined;
1880
+ }, target);
1881
+ }
1882
+ /**
1883
+ * Resolve de forma determinística o alvo (`resourceKey`, `surfaceId`, `previewSurfaceId`, `identity`)
1884
+ * a partir de um `ResourceQuickViewBinding` e de um registro candidato (`sourceRecord`).
1885
+ */
1886
+ function resolveResourceQuickViewTarget(binding, sourceRecord) {
1887
+ const normalized = normalizeResourceQuickViewBinding(binding);
1888
+ if (!normalized ||
1889
+ !sourceRecord ||
1890
+ typeof sourceRecord !== 'object' ||
1891
+ Array.isArray(sourceRecord)) {
1892
+ return null;
1893
+ }
1894
+ const record = sourceRecord;
1895
+ const sourceField = normalized.recordOpen.sourceIdentityField;
1896
+ let candidate = readQuickViewFieldOrPath(record, sourceField);
1897
+ if (candidate === undefined) {
1898
+ for (const envelopeKey of ['row', 'item', 'values']) {
1899
+ const nested = record[envelopeKey];
1900
+ if (nested && typeof nested === 'object' && !Array.isArray(nested)) {
1901
+ candidate = readQuickViewFieldOrPath(nested, sourceField);
1902
+ if (candidate !== undefined) {
1903
+ break;
1904
+ }
1905
+ }
1906
+ }
1907
+ }
1908
+ if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
1909
+ const candidateObj = candidate;
1910
+ candidate =
1911
+ candidateObj['id'] ?? candidateObj['value'] ?? candidateObj['key'];
1912
+ }
1913
+ if (typeof candidate === 'number' && Number.isFinite(candidate)) {
1914
+ return {
1915
+ resourceKey: normalized.recordOpen.target.resourceKey,
1916
+ surfaceId: normalized.recordOpen.target.surfaceId,
1917
+ previewSurfaceId: normalized.previewSurfaceId || normalized.recordOpen.target.surfaceId,
1918
+ identity: candidate,
1919
+ };
1920
+ }
1921
+ if (typeof candidate === 'string' && candidate.trim().length > 0) {
1922
+ return {
1923
+ resourceKey: normalized.recordOpen.target.resourceKey,
1924
+ surfaceId: normalized.recordOpen.target.surfaceId,
1925
+ previewSurfaceId: normalized.previewSurfaceId || normalized.recordOpen.target.surfaceId,
1926
+ identity: candidate.trim(),
1927
+ };
1928
+ }
1929
+ return null;
1930
+ }
1931
+ /**
1932
+ * Verifica se a âncora efêmera de runtime permanece conectada e visível na viewport.
1933
+ */
1934
+ function isResourceQuickViewAnchorValid(anchor) {
1935
+ if (!anchor || typeof anchor !== 'object') {
1936
+ return false;
1937
+ }
1938
+ if (typeof anchor.isValid === 'function' && !anchor.isValid()) {
1939
+ return false;
1940
+ }
1941
+ const viewportWidth = typeof window !== 'undefined' && Number.isFinite(window.innerWidth) && window.innerWidth > 0
1942
+ ? window.innerWidth
1943
+ : 1920;
1944
+ const viewportHeight = typeof window !== 'undefined' && Number.isFinite(window.innerHeight) && window.innerHeight > 0
1945
+ ? window.innerHeight
1946
+ : 1080;
1947
+ if (anchor.kind === 'element') {
1948
+ const el = anchor.element;
1949
+ if (!el || typeof el.getBoundingClientRect !== 'function' || el.isConnected === false) {
1950
+ return false;
1951
+ }
1952
+ const rect = el.getBoundingClientRect();
1953
+ if (!Number.isFinite(rect.left) || !Number.isFinite(rect.top)) {
1954
+ return false;
1955
+ }
1956
+ if (rect.width === 0 && rect.height === 0) {
1957
+ return false;
1958
+ }
1959
+ return (rect.bottom >= 0 &&
1960
+ rect.right >= 0 &&
1961
+ rect.top <= viewportHeight &&
1962
+ rect.left <= viewportWidth);
1963
+ }
1964
+ if (anchor.kind === 'virtual-rect') {
1965
+ if (!anchor.anchorKey || !anchor.anchorKey.trim()) {
1966
+ return false;
1967
+ }
1968
+ if (anchor.hostElement && anchor.hostElement.isConnected === false) {
1969
+ return false;
1970
+ }
1971
+ if (typeof anchor.getViewportRect !== 'function') {
1972
+ return false;
1973
+ }
1974
+ const rect = anchor.getViewportRect();
1975
+ if (!rect ||
1976
+ !Number.isFinite(rect.x) ||
1977
+ !Number.isFinite(rect.y) ||
1978
+ !Number.isFinite(rect.width) ||
1979
+ !Number.isFinite(rect.height) ||
1980
+ rect.width < 0 ||
1981
+ rect.height < 0) {
1982
+ return false;
1983
+ }
1984
+ const right = rect.right ?? rect.x + rect.width;
1985
+ const bottom = rect.bottom ?? rect.y + rect.height;
1986
+ const left = rect.left ?? rect.x;
1987
+ const top = rect.top ?? rect.y;
1988
+ return (bottom >= 0 &&
1989
+ right >= 0 &&
1990
+ top <= viewportHeight &&
1991
+ left <= viewportWidth);
1992
+ }
1993
+ return false;
1994
+ }
1995
+ function resolveQuickViewAnchorKey(anchor) {
1996
+ if (anchor.kind === 'virtual-rect') {
1997
+ return anchor.anchorKey.trim();
1998
+ }
1999
+ const explicit = anchor.anchorKey?.trim();
2000
+ if (explicit) {
2001
+ return explicit;
2002
+ }
2003
+ const focusKey = anchor.element?.getAttribute?.('data-praxis-focus-key')?.trim();
2004
+ if (focusKey) {
2005
+ return focusKey;
2006
+ }
2007
+ const id = anchor.element?.id?.trim();
2008
+ if (id) {
2009
+ return `element:${id}`;
2010
+ }
2011
+ return 'element:anonymous';
2012
+ }
2013
+
883
2014
  const TONES = new Set([
884
2015
  'neutral',
885
2016
  'info',
@@ -1006,14 +2137,113 @@ function normalizeText(value) {
1006
2137
  return trimmed.length ? trimmed : undefined;
1007
2138
  }
1008
2139
  function normalizeInteractions(value) {
2140
+ const quickView = normalizeResourceQuickViewBinding(value.quickView);
1009
2141
  return {
1010
2142
  ...(value.copy === true ? { copy: true } : {}),
1011
2143
  ...(value.details === true ? { details: true } : {}),
1012
2144
  ...(value.expand === true ? { expand: true } : {}),
1013
2145
  ...(value.link === true ? { link: true } : {}),
2146
+ ...(quickView ? { quickView } : {}),
1014
2147
  };
1015
2148
  }
1016
2149
 
2150
+ /** Converts UI tokens only under declared scalar items; invalid input is never dropped or partially converted. */
2151
+ function normalizeScalarArrayValue(value, items) {
2152
+ if (items.enum !== undefined && !isScalarEnum(items.enum))
2153
+ return { valid: false, invalidIndices: [-1] };
2154
+ if (value == null)
2155
+ return { valid: true, value };
2156
+ if (!Array.isArray(value))
2157
+ return { valid: false, invalidIndices: [-1] };
2158
+ const converted = [];
2159
+ const invalidIndices = [];
2160
+ for (let index = 0; index < value.length; index += 1) {
2161
+ const item = normalizeItem(value[index], items);
2162
+ if (item === undefined || items.enum && !items.enum.some(candidate => candidate === item))
2163
+ invalidIndices.push(index);
2164
+ else
2165
+ converted.push(item);
2166
+ }
2167
+ return invalidIndices.length ? { valid: false, invalidIndices } : { valid: true, value: converted };
2168
+ }
2169
+ function normalizeItem(value, items) {
2170
+ if (value == null)
2171
+ return undefined;
2172
+ if (items.type === 'boolean') {
2173
+ if (typeof value === 'boolean')
2174
+ return value;
2175
+ return value === 'true' ? true : value === 'false' ? false : undefined;
2176
+ }
2177
+ if (items.type === 'integer' || items.type === 'number') {
2178
+ const number = typeof value === 'number' ? value : typeof value === 'string' &&
2179
+ /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(value) ? Number(value) : NaN;
2180
+ if (!Number.isFinite(number) || items.type === 'integer' && !Number.isSafeInteger(number))
2181
+ return undefined;
2182
+ return number;
2183
+ }
2184
+ if (items.type !== 'string')
2185
+ return undefined;
2186
+ if (items.format === 'date') {
2187
+ if (value instanceof Date) {
2188
+ if (Number.isNaN(value.getTime()))
2189
+ return undefined;
2190
+ const date = `${String(value.getFullYear()).padStart(4, '0')}-${String(value.getMonth() + 1).padStart(2, '0')}-${String(value.getDate()).padStart(2, '0')}`;
2191
+ return isIsoDate(date) ? date : undefined;
2192
+ }
2193
+ return typeof value === 'string' && isIsoDate(value) ? value : undefined;
2194
+ }
2195
+ if (items.format === 'date-time') {
2196
+ if (value instanceof Date)
2197
+ return Number.isNaN(value.getTime()) ? undefined : value.toISOString();
2198
+ return typeof value === 'string' && isIsoDateTime(value) ? value : undefined;
2199
+ }
2200
+ return typeof value === 'string' ? value : undefined;
2201
+ }
2202
+ function isIsoDate(value) {
2203
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
2204
+ if (!match)
2205
+ return false;
2206
+ const year = Number(match[1]), month = Number(match[2]), day = Number(match[3]);
2207
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
2208
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
2209
+ return month >= 1 && month <= 12 && day >= 1 && day <= days[month - 1];
2210
+ }
2211
+ function isIsoDateTime(value) {
2212
+ const match = /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,9}))?)?(?:Z|([+-])(\d{2}):(\d{2}))?$/.exec(value);
2213
+ if (!match || !isIsoDate(match[1]))
2214
+ return false;
2215
+ if (Number(match[2]) > 23 || Number(match[3]) > 59 || Number(match[4] ?? 0) > 59)
2216
+ return false;
2217
+ const offsetHours = Number(match[7] ?? 0), offsetMinutes = Number(match[8] ?? 0);
2218
+ return offsetHours <= 18 && offsetMinutes <= 59 && (offsetHours !== 18 || offsetMinutes === 0);
2219
+ }
2220
+ /** Internal admission of the scalar subset already published in JSON Schema items. */
2221
+ function normalizeScalarItemsSchema(value) {
2222
+ if (!value || typeof value !== 'object' || Array.isArray(value))
2223
+ return undefined;
2224
+ const record = value;
2225
+ if (typeof record['type'] !== 'string' || !['string', 'integer', 'number', 'boolean'].includes(record['type']))
2226
+ return undefined;
2227
+ const result = { type: record['type'] };
2228
+ if (typeof record['format'] === 'string')
2229
+ result.format = record['format'];
2230
+ if (record['enum'] !== undefined) {
2231
+ if (!isScalarEnum(record['enum']))
2232
+ throw new TypeError('Scalar items enum must contain JSON scalar values.');
2233
+ result.enum = [...record['enum']];
2234
+ }
2235
+ return result;
2236
+ }
2237
+ function isScalarEnum(value) {
2238
+ return Array.isArray(value) && value.length > 0 && value.every(item => item === null || typeof item === 'string' || typeof item === 'boolean' || typeof item === 'number' && Number.isFinite(item));
2239
+ }
2240
+
2241
+ // Mirrors the backend custom-field key policy. Ordinary static field names are
2242
+ // outside this boundary; custom keys must be safe across all runtime consumers.
2243
+ const RESERVED_CUSTOM_FIELD_KEYS = new Set([
2244
+ 'constructor', 'prototype', 'hasOwnProperty', 'isPrototypeOf',
2245
+ 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf',
2246
+ ]);
1017
2247
  const VALUE_PRESENTATION_TYPES = new Set([
1018
2248
  'string',
1019
2249
  'number',
@@ -1262,6 +2492,33 @@ class SchemaNormalizationKernel {
1262
2492
  }
1263
2493
  return false;
1264
2494
  }
2495
+ parseOptionalBoolean(value) {
2496
+ if (typeof value === 'boolean') {
2497
+ return value;
2498
+ }
2499
+ if (typeof value === 'string') {
2500
+ const normalized = value.trim().toLowerCase();
2501
+ if (normalized === 'true') {
2502
+ return true;
2503
+ }
2504
+ if (normalized === 'false') {
2505
+ return false;
2506
+ }
2507
+ }
2508
+ return undefined;
2509
+ }
2510
+ parseOptionalFiniteNumber(value) {
2511
+ if (typeof value === 'number' && Number.isFinite(value)) {
2512
+ return value;
2513
+ }
2514
+ if (typeof value === 'string' && value.trim().length > 0) {
2515
+ const parsed = Number(value);
2516
+ if (Number.isFinite(parsed)) {
2517
+ return parsed;
2518
+ }
2519
+ }
2520
+ return undefined;
2521
+ }
1265
2522
  /** Ensure an array of strings from various inputs. */
1266
2523
  parseStringArray(value) {
1267
2524
  if (Array.isArray(value)) {
@@ -1365,9 +2622,15 @@ class SchemaNormalizationKernel {
1365
2622
  if (value.kind !== undefined) {
1366
2623
  detail.kind = String(value.kind);
1367
2624
  }
2625
+ if (value.resourceKey !== undefined && String(value.resourceKey).trim().length > 0) {
2626
+ detail.resourceKey = String(value.resourceKey).trim();
2627
+ }
1368
2628
  if (value.surfaceId !== undefined) {
1369
2629
  detail.surfaceId = String(value.surfaceId);
1370
2630
  }
2631
+ if (value.previewSurfaceId !== undefined && String(value.previewSurfaceId).trim().length > 0) {
2632
+ detail.previewSurfaceId = String(value.previewSurfaceId).trim();
2633
+ }
1371
2634
  if (value.presentation !== undefined) {
1372
2635
  detail.presentation = String(value.presentation);
1373
2636
  }
@@ -1392,6 +2655,11 @@ class SchemaNormalizationKernel {
1392
2655
  'resultLayout',
1393
2656
  'primaryPropertyPath',
1394
2657
  'avatarPropertyPath',
2658
+ 'detailActionLabel',
2659
+ 'quickViewActionLabel',
2660
+ 'copyCodeActionLabel',
2661
+ 'copyIdActionLabel',
2662
+ 'createActionLabel',
1395
2663
  ];
1396
2664
  stringKeys.forEach((key) => {
1397
2665
  if (value[key] !== undefined) {
@@ -1429,6 +2697,10 @@ class SchemaNormalizationKernel {
1429
2697
  if (value.maxVisibleBadges !== undefined && !Number.isNaN(Number(value.maxVisibleBadges))) {
1430
2698
  display.maxVisibleBadges = Number(value.maxVisibleBadges);
1431
2699
  }
2700
+ const actions = this.parseLookupActions(value.actions);
2701
+ if (actions) {
2702
+ display.actions = actions;
2703
+ }
1432
2704
  return Object.keys(display).length ? display : undefined;
1433
2705
  }
1434
2706
  parseLookupDisplayField(value) {
@@ -1443,6 +2715,28 @@ class SchemaNormalizationKernel {
1443
2715
  });
1444
2716
  return Object.keys(field).length ? field : undefined;
1445
2717
  }
2718
+ parseLookupActions(value) {
2719
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
2720
+ return undefined;
2721
+ }
2722
+ const actions = {};
2723
+ if (value.showDetail !== undefined) {
2724
+ actions.showDetail = this.parseBoolean(value.showDetail);
2725
+ }
2726
+ if (value.showQuickView !== undefined) {
2727
+ actions.showQuickView = this.parseBoolean(value.showQuickView);
2728
+ }
2729
+ if (value.showCopyCode !== undefined) {
2730
+ actions.showCopyCode = this.parseBoolean(value.showCopyCode);
2731
+ }
2732
+ if (value.showCopyId !== undefined) {
2733
+ actions.showCopyId = this.parseBoolean(value.showCopyId);
2734
+ }
2735
+ if (value.showCreate !== undefined) {
2736
+ actions.showCreate = this.parseBoolean(value.showCreate);
2737
+ }
2738
+ return Object.keys(actions).length ? actions : undefined;
2739
+ }
1446
2740
  parseLookupCreate(value) {
1447
2741
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
1448
2742
  return undefined;
@@ -1898,6 +3192,34 @@ class SchemaNormalizationKernel {
1898
3192
  const normalized = String(value ?? '').trim();
1899
3193
  return OPTION_SOURCE_INVALID_SORT_POLICIES.has(normalized) ? normalized : undefined;
1900
3194
  }
3195
+ parseResourceReference(value) {
3196
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
3197
+ return undefined;
3198
+ }
3199
+ const raw = value;
3200
+ const resourceKey = String(raw['resourceKey'] ?? '').trim();
3201
+ if (!resourceKey) {
3202
+ return undefined;
3203
+ }
3204
+ const ref = { resourceKey };
3205
+ const valueField = String(raw['valueField'] ?? '').trim();
3206
+ if (valueField) {
3207
+ ref.valueField = valueField;
3208
+ }
3209
+ const surfaceId = String(raw['surfaceId'] ?? '').trim();
3210
+ if (surfaceId) {
3211
+ ref.surfaceId = surfaceId;
3212
+ }
3213
+ const previewSurfaceId = String(raw['previewSurfaceId'] ?? '').trim();
3214
+ if (previewSurfaceId) {
3215
+ ref.previewSurfaceId = previewSurfaceId;
3216
+ }
3217
+ const detailPresentation = String(raw['detailPresentation'] ?? '').trim();
3218
+ if (detailPresentation === 'drawer' || detailPresentation === 'modal') {
3219
+ ref.detailPresentation = detailPresentation;
3220
+ }
3221
+ return ref;
3222
+ }
1901
3223
  parseLookupOpenDetailMode(value) {
1902
3224
  const normalized = String(value ?? '').trim();
1903
3225
  return LOOKUP_OPEN_DETAIL_MODES.has(normalized) ? normalized : undefined;
@@ -2015,10 +3337,14 @@ class SchemaNormalizationKernel {
2015
3337
  out.maxLength = Number(ui.maxLength);
2016
3338
  if (ui.maxLengthMessage !== undefined)
2017
3339
  out.maxLengthMessage = ui.maxLengthMessage;
2018
- if (ui.min !== undefined)
2019
- out.min = Number(ui.min);
2020
- if (ui.max !== undefined)
2021
- out.max = Number(ui.max);
3340
+ if (ui.min !== undefined) {
3341
+ const parsedMin = Number(ui.min);
3342
+ out.min = Number.isFinite(parsedMin) ? parsedMin : String(ui.min).trim();
3343
+ }
3344
+ if (ui.max !== undefined) {
3345
+ const parsedMax = Number(ui.max);
3346
+ out.max = Number.isFinite(parsedMax) ? parsedMax : String(ui.max).trim();
3347
+ }
2022
3348
  if (ui.minMessage !== undefined)
2023
3349
  out.minMessage = ui.minMessage;
2024
3350
  if (ui.maxMessage !== undefined)
@@ -2155,14 +3481,25 @@ class SchemaNormalizationKernel {
2155
3481
  return ['number', 'integer', 'int', 'float', 'double', 'decimal'].includes(token);
2156
3482
  }
2157
3483
  resolveNumericFormatToken(prop, ui, resolvedType) {
3484
+ if (ui?.numberFormat?.percentage === true || ui?.['numberFormat.percentage'] === true) {
3485
+ return 'percent';
3486
+ }
3487
+ const explicitUiFormat = this.resolveNonEmptyStringToken(ui?.numericFormat, ui?.numberFormat?.style, ui?.['numberFormat.style']);
3488
+ if (explicitUiFormat) {
3489
+ return explicitUiFormat;
3490
+ }
2158
3491
  const typeToken = resolvedType ?? prop?.type;
2159
3492
  if (!this.isNumericSchemaType(typeToken)) {
2160
3493
  return undefined;
2161
3494
  }
2162
- if (ui?.numberFormat?.percentage === true || ui?.['numberFormat.percentage'] === true) {
2163
- return 'percent';
3495
+ const explicitFormat = this.resolveNonEmptyStringToken(ui?.format, prop?.format);
3496
+ if (explicitFormat) {
3497
+ return explicitFormat;
2164
3498
  }
2165
- return this.resolveNonEmptyStringToken(ui?.numericFormat, ui?.format, ui?.numberFormat?.style, ui?.['numberFormat.style'], prop?.format);
3499
+ if (String(prop?.type ?? '').trim().toLowerCase() === 'integer') {
3500
+ return 'integer';
3501
+ }
3502
+ return undefined;
2166
3503
  }
2167
3504
  /**
2168
3505
  * Converte o schema bruto do backend (OpenAPI + x-ui) em FieldDefinition[] tipado.
@@ -2177,6 +3514,151 @@ class SchemaNormalizationKernel {
2177
3514
  normalizeSchema(schema) {
2178
3515
  return this.normalizeSchemaWithRoot(schema, schema);
2179
3516
  }
3517
+ /**
3518
+ * Extrai metadados estruturais de nível raiz (`x-ui` no objeto schema),
3519
+ * cobrindo `formLayout`, `progression`, `timeline`, `schedule`, `hierarchy`,
3520
+ * `calculationMemory`, `contextBinding` e `resourceState`.
3521
+ */
3522
+ extractRootUiMetadata(schema) {
3523
+ const ui = schema &&
3524
+ typeof schema === 'object' &&
3525
+ !Array.isArray(schema) &&
3526
+ schema['x-ui'] &&
3527
+ typeof schema['x-ui'] === 'object' &&
3528
+ !Array.isArray(schema['x-ui'])
3529
+ ? schema['x-ui']
3530
+ : undefined;
3531
+ if (!ui) {
3532
+ return null;
3533
+ }
3534
+ const out = {};
3535
+ const formLayout = this.parseSchemaFormLayout(ui['formLayout']);
3536
+ if (formLayout)
3537
+ out.formLayout = formLayout;
3538
+ if (ui['progression'] && typeof ui['progression'] === 'object' && !Array.isArray(ui['progression'])) {
3539
+ out.progression = this.clonePlain(ui['progression']);
3540
+ }
3541
+ if (ui['timeline'] && typeof ui['timeline'] === 'object' && !Array.isArray(ui['timeline'])) {
3542
+ out.timeline = this.clonePlain(ui['timeline']);
3543
+ }
3544
+ if (ui['schedule'] && typeof ui['schedule'] === 'object' && !Array.isArray(ui['schedule'])) {
3545
+ out.schedule = this.clonePlain(ui['schedule']);
3546
+ }
3547
+ if (ui['hierarchy'] && typeof ui['hierarchy'] === 'object' && !Array.isArray(ui['hierarchy'])) {
3548
+ out.hierarchy = this.clonePlain(ui['hierarchy']);
3549
+ }
3550
+ if (ui['calculationMemory'] && typeof ui['calculationMemory'] === 'object' && !Array.isArray(ui['calculationMemory'])) {
3551
+ out.calculationMemory = this.clonePlain(ui['calculationMemory']);
3552
+ }
3553
+ const contextBinding = this.parseContextBinding(ui['contextBinding']);
3554
+ if (contextBinding)
3555
+ out.contextBinding = contextBinding;
3556
+ const resourceState = this.parseResourceState(ui['resourceState']);
3557
+ if (resourceState)
3558
+ out.resourceState = resourceState;
3559
+ return Object.keys(out).length > 0 ? out : null;
3560
+ }
3561
+ parseSchemaFormLayout(raw) {
3562
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
3563
+ return undefined;
3564
+ }
3565
+ const record = raw;
3566
+ const rawMode = String(record['mode'] ?? 'flat').trim().toLowerCase();
3567
+ const mode = rawMode === 'tabs' || rawMode === 'accordion' || rawMode === 'stepper' || rawMode === 'flat'
3568
+ ? rawMode
3569
+ : 'flat';
3570
+ const rawSections = Array.isArray(record['sections']) ? record['sections'] : [];
3571
+ const sections = [];
3572
+ for (let idx = 0; idx < rawSections.length; idx++) {
3573
+ const entry = rawSections[idx];
3574
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
3575
+ continue;
3576
+ const item = entry;
3577
+ const id = String(item['id'] ?? '').trim();
3578
+ const title = String(item['title'] ?? '').trim();
3579
+ if (!id || !title)
3580
+ continue;
3581
+ const orderNum = Number(item['order']);
3582
+ const subtitle = typeof item['subtitle'] === 'string' && item['subtitle'].trim() ? item['subtitle'].trim() : undefined;
3583
+ const icon = typeof item['icon'] === 'string' && item['icon'].trim() ? item['icon'].trim() : undefined;
3584
+ const groups = this.parseNonBlankStringArray(item['groups']);
3585
+ sections.push({
3586
+ id,
3587
+ title,
3588
+ ...(subtitle ? { subtitle } : {}),
3589
+ ...(icon ? { icon } : {}),
3590
+ order: Number.isFinite(orderNum) ? orderNum : idx,
3591
+ ...(groups.length ? { groups } : {}),
3592
+ });
3593
+ }
3594
+ sections.sort((a, b) => a.order - b.order);
3595
+ return {
3596
+ mode,
3597
+ ...(sections.length ? { sections } : {}),
3598
+ };
3599
+ }
3600
+ parseContextBinding(raw) {
3601
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
3602
+ return undefined;
3603
+ }
3604
+ const record = raw;
3605
+ const dim = String(record['dimension'] ?? '').trim().toLowerCase();
3606
+ if (dim !== 'organization' &&
3607
+ dim !== 'company_group' &&
3608
+ dim !== 'unit' &&
3609
+ dim !== 'person' &&
3610
+ dim !== 'bond' &&
3611
+ dim !== 'contract') {
3612
+ return undefined;
3613
+ }
3614
+ const targetField = typeof record['targetField'] === 'string' && record['targetField'].trim()
3615
+ ? record['targetField'].trim()
3616
+ : undefined;
3617
+ return {
3618
+ dimension: dim,
3619
+ lockWhenActive: this.parseBoolean(record['lockWhenActive']),
3620
+ ...(targetField ? { targetField } : {}),
3621
+ };
3622
+ }
3623
+ parseResourceState(raw) {
3624
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
3625
+ return undefined;
3626
+ }
3627
+ const record = raw;
3628
+ const initialStates = this.parseNonBlankStringArray(record['initialStates']);
3629
+ const putMutableStates = this.parseNonBlankStringArray(record['putMutableStates']);
3630
+ if (!initialStates.length && !putMutableStates.length) {
3631
+ return undefined;
3632
+ }
3633
+ return {
3634
+ ...(initialStates.length ? { initialStates } : {}),
3635
+ ...(putMutableStates.length ? { putMutableStates } : {}),
3636
+ };
3637
+ }
3638
+ parseMicroVisualization(raw) {
3639
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
3640
+ return undefined;
3641
+ }
3642
+ const normalized = normalizePraxisPresentationVisualization(raw);
3643
+ if (normalized) {
3644
+ return normalized;
3645
+ }
3646
+ const clone = this.clonePlain(raw);
3647
+ if (typeof clone['kind'] === 'string' && clone['kind'].trim()) {
3648
+ const rawKind = clone['kind'].trim();
3649
+ const upper = rawKind.toUpperCase();
3650
+ if (upper === 'HARVEY_BALL')
3651
+ clone['kind'] = 'harveyBall';
3652
+ else if (upper === 'STACKED_BAR')
3653
+ clone['kind'] = 'stackedBar';
3654
+ else if (upper === 'PROCESS_FLOW')
3655
+ clone['kind'] = 'processFlow';
3656
+ else if (upper === upper && /^[A-Z_]+$/.test(rawKind))
3657
+ clone['kind'] = rawKind.toLowerCase();
3658
+ return clone;
3659
+ }
3660
+ return undefined;
3661
+ }
2180
3662
  normalizeSchemaWithRoot(schema, rootSchema) {
2181
3663
  if (!schema || typeof schema !== 'object') {
2182
3664
  return [];
@@ -2195,16 +3677,62 @@ class SchemaNormalizationKernel {
2195
3677
  !Array.isArray(prop['x-ui'])
2196
3678
  ? prop['x-ui']
2197
3679
  : undefined;
3680
+ const hasChildProperties = prop?.properties &&
3681
+ typeof prop.properties === 'object' &&
3682
+ !Array.isArray(prop.properties);
3683
+ const isCustomFieldsContainer = ui?.customFieldsContainer === true ||
3684
+ (name === 'customFields' && prop?.type === 'object' && hasChildProperties);
3685
+ if (isCustomFieldsContainer) {
3686
+ if (hasChildProperties) {
3687
+ for (const key of Object.keys(prop.properties)) {
3688
+ if (RESERVED_CUSTOM_FIELD_KEYS.has(key)) {
3689
+ throw new Error(`Unsupported custom field key "${name}.${key}". Publish a key admitted by the canonical backend custom-field policy.`);
3690
+ }
3691
+ }
3692
+ const parentAccess = normalizeFieldAccessMetadata(ui?.fieldAccess);
3693
+ for (const childField of this.normalizeSchemaWithRoot(prop, rootSchema)) {
3694
+ const originalKey = childField.name;
3695
+ if (parentAccess && childField.fieldAccess &&
3696
+ !this.haveEquivalentFieldAccess(parentAccess, childField.fieldAccess)) {
3697
+ throw new Error(`Conflicting fieldAccess on custom-field container "${name}" and child "${originalKey}". Publish the effective access policy on each leaf field.`);
3698
+ }
3699
+ fields.push({
3700
+ ...childField,
3701
+ name: `${name}.${originalKey}`,
3702
+ customField: true,
3703
+ customFieldKey: childField.customFieldKey ?? originalKey,
3704
+ customFieldScope: childField.customFieldScope ?? 'tenant',
3705
+ ...(ui?.disabled !== undefined && this.parseBoolean(ui.disabled) ? { disabled: true } : {}),
3706
+ ...(ui?.readOnly !== undefined && this.parseBoolean(ui.readOnly) ? { readOnly: true } : {}),
3707
+ ...(ui?.formHidden !== undefined && this.parseBoolean(ui.formHidden) ? { formHidden: true } : {}),
3708
+ ...(parentAccess && !childField.fieldAccess ? { fieldAccess: normalizeFieldAccessMetadata(parentAccess) } : {}),
3709
+ });
3710
+ }
3711
+ }
3712
+ // The container is wire structure, never an independent field control.
3713
+ continue;
3714
+ }
2198
3715
  // Skip properties without x-ui metadata
2199
3716
  if (!ui || Object.keys(ui).length === 0) {
2200
3717
  continue;
2201
3718
  }
2202
3719
  const field = { name };
3720
+ if (ui.customField !== undefined) {
3721
+ field.customField = this.parseBoolean(ui.customField);
3722
+ }
3723
+ if (ui.customFieldKey != null) {
3724
+ field.customFieldKey = String(ui.customFieldKey);
3725
+ }
3726
+ if (ui.customFieldScope != null) {
3727
+ field.customFieldScope = String(ui.customFieldScope);
3728
+ }
2203
3729
  // -------------------------------------------------------------------
2204
3730
  // Basic information
2205
3731
  // -------------------------------------------------------------------
2206
3732
  field.label = ui.label ?? prop.title ?? name;
2207
3733
  field.type = this.resolveFieldType(prop, ui);
3734
+ if (field.type === 'array')
3735
+ field.items = normalizeScalarItemsSchema(prop?.items);
2208
3736
  const numericFormat = this.resolveNumericFormatToken(prop, ui, field.type);
2209
3737
  if (numericFormat) {
2210
3738
  field.numericFormat = numericFormat;
@@ -2314,6 +3842,40 @@ class SchemaNormalizationKernel {
2314
3842
  if (condRequired !== undefined) {
2315
3843
  field.conditionalRequired = condRequired;
2316
3844
  }
3845
+ if (ui.conditionalReadOnly !== undefined && ui.conditionalReadOnly !== null) {
3846
+ if (typeof ui.conditionalReadOnly === 'string') {
3847
+ const trimmed = ui.conditionalReadOnly.trim();
3848
+ if (trimmed) {
3849
+ field.conditionalReadOnly = trimmed;
3850
+ }
3851
+ }
3852
+ else {
3853
+ const condReadOnly = this.parseJsonLogicExpression(ui.conditionalReadOnly, name, 'x-ui.conditionalReadOnly');
3854
+ if (condReadOnly !== undefined) {
3855
+ field.conditionalReadOnly = condReadOnly;
3856
+ }
3857
+ }
3858
+ }
3859
+ if (ui.colSpan !== undefined) {
3860
+ const parsedSpan = this.parseOptionalFiniteNumber(ui.colSpan);
3861
+ if (parsedSpan !== undefined) {
3862
+ field.colSpan = Math.min(12, Math.max(1, Math.trunc(parsedSpan)));
3863
+ }
3864
+ }
3865
+ const contextBinding = this.parseContextBinding(ui.contextBinding);
3866
+ if (contextBinding) {
3867
+ field.contextBinding = contextBinding;
3868
+ }
3869
+ if (ui.draftCleared !== undefined) {
3870
+ const parsedDraftCleared = this.parseOptionalBoolean(ui.draftCleared);
3871
+ if (parsedDraftCleared !== undefined) {
3872
+ field.draftCleared = parsedDraftCleared;
3873
+ }
3874
+ }
3875
+ const resourceState = this.parseResourceState(ui.resourceState);
3876
+ if (resourceState) {
3877
+ field.resourceState = resourceState;
3878
+ }
2317
3879
  const transformFn = this.parseTransformFunction(ui.transformValueFunction);
2318
3880
  if (transformFn) {
2319
3881
  field.transformValueFunction = transformFn;
@@ -2328,9 +3890,45 @@ class SchemaNormalizationKernel {
2328
3890
  if (ui.tableHidden !== undefined) {
2329
3891
  field.tableHidden = this.parseBoolean(ui.tableHidden);
2330
3892
  }
3893
+ if (ui.tableOrder !== undefined) {
3894
+ const parsedTableOrder = this.parseOptionalFiniteNumber(ui.tableOrder);
3895
+ if (parsedTableOrder !== undefined) {
3896
+ field.tableOrder = parsedTableOrder;
3897
+ }
3898
+ }
3899
+ if (ui.pinned !== undefined && typeof ui.pinned === 'string') {
3900
+ const pinned = ui.pinned.trim().toLowerCase();
3901
+ if (pinned === 'start' || pinned === 'end') {
3902
+ field.pinned = pinned;
3903
+ }
3904
+ }
3905
+ if (ui.primarySearch !== undefined) {
3906
+ const primarySearch = this.parseOptionalBoolean(ui.primarySearch);
3907
+ if (primarySearch !== undefined) {
3908
+ field.primarySearch = primarySearch;
3909
+ }
3910
+ }
3911
+ if (ui.microVisualization !== undefined) {
3912
+ const microVisualization = this.parseMicroVisualization(ui.microVisualization);
3913
+ if (microVisualization) {
3914
+ field.microVisualization = microVisualization;
3915
+ }
3916
+ }
2331
3917
  if (ui.formHidden !== undefined) {
2332
3918
  field.formHidden = this.parseBoolean(ui.formHidden);
2333
3919
  }
3920
+ if (ui.quickViewVisible !== undefined) {
3921
+ const quickViewVisible = this.parseOptionalBoolean(ui.quickViewVisible);
3922
+ if (quickViewVisible !== undefined) {
3923
+ field.quickViewVisible = quickViewVisible;
3924
+ }
3925
+ }
3926
+ if (ui.quickViewOrder !== undefined) {
3927
+ const quickViewOrder = this.parseOptionalFiniteNumber(ui.quickViewOrder);
3928
+ if (quickViewOrder !== undefined) {
3929
+ field.quickViewOrder = quickViewOrder;
3930
+ }
3931
+ }
2334
3932
  if (ui.width !== undefined) {
2335
3933
  field.width = ui.width;
2336
3934
  }
@@ -2414,6 +4012,9 @@ class SchemaNormalizationKernel {
2414
4012
  if (ui.options !== undefined) {
2415
4013
  field.options = this.parseOptions(ui.options);
2416
4014
  }
4015
+ if (Array.isArray(prop?.enum) && prop.enum.length > 0 && field.enumValues === undefined) {
4016
+ field.enumValues = [...prop.enum];
4017
+ }
2417
4018
  if (ui.optionGroups !== undefined) {
2418
4019
  field.optionGroups = this.parseOptions(ui.optionGroups);
2419
4020
  }
@@ -2452,6 +4053,24 @@ class SchemaNormalizationKernel {
2452
4053
  if (ui.filterField !== undefined) {
2453
4054
  field.filterField = ui.filterField;
2454
4055
  }
4056
+ if (ui.resourceReference !== undefined) {
4057
+ const resourceReference = this.parseResourceReference(ui.resourceReference);
4058
+ if (resourceReference) {
4059
+ field.resourceReference = resourceReference;
4060
+ }
4061
+ }
4062
+ if (ui.quickView !== undefined) {
4063
+ const explicitQuickView = normalizeResourceQuickViewBinding(ui.quickView);
4064
+ if (explicitQuickView) {
4065
+ field.quickView = explicitQuickView;
4066
+ }
4067
+ }
4068
+ if (!field.quickView) {
4069
+ const synthesized = resolveFieldQuickViewBinding(field);
4070
+ if (synthesized) {
4071
+ field.quickView = synthesized;
4072
+ }
4073
+ }
2455
4074
  if (ui.multiple !== undefined) {
2456
4075
  field.multiple = this.parseBoolean(ui.multiple);
2457
4076
  }
@@ -2476,6 +4095,12 @@ class SchemaNormalizationKernel {
2476
4095
  field.detailActionLabel = detailActionLabel;
2477
4096
  }
2478
4097
  }
4098
+ if (ui.quickViewActionLabel !== undefined) {
4099
+ const quickViewActionLabel = String(ui.quickViewActionLabel).trim();
4100
+ if (quickViewActionLabel) {
4101
+ field.quickViewActionLabel = quickViewActionLabel;
4102
+ }
4103
+ }
2479
4104
  if (ui.copyCodeActionLabel !== undefined) {
2480
4105
  const copyCodeActionLabel = String(ui.copyCodeActionLabel).trim();
2481
4106
  if (copyCodeActionLabel) {
@@ -2499,6 +4124,9 @@ class SchemaNormalizationKernel {
2499
4124
  if (ui.actions.showDetail !== undefined) {
2500
4125
  actions.showDetail = this.parseBoolean(ui.actions.showDetail);
2501
4126
  }
4127
+ if (ui.actions.showQuickView !== undefined) {
4128
+ actions.showQuickView = this.parseBoolean(ui.actions.showQuickView);
4129
+ }
2502
4130
  if (ui.actions.showCopyCode !== undefined) {
2503
4131
  actions.showCopyCode = this.parseBoolean(ui.actions.showCopyCode);
2504
4132
  }
@@ -2530,10 +4158,22 @@ class SchemaNormalizationKernel {
2530
4158
  field.numericStep = Number(ui.numericStep);
2531
4159
  }
2532
4160
  if (ui.numericMin !== undefined) {
2533
- field.numericMin = Number(ui.numericMin);
4161
+ const parsedMin = Number(ui.numericMin);
4162
+ if (Number.isFinite(parsedMin)) {
4163
+ field.numericMin = parsedMin;
4164
+ }
4165
+ else if (field.min === undefined && String(ui.numericMin).trim().length > 0) {
4166
+ field.min = String(ui.numericMin).trim();
4167
+ }
2534
4168
  }
2535
4169
  if (ui.numericMax !== undefined) {
2536
- field.numericMax = Number(ui.numericMax);
4170
+ const parsedMax = Number(ui.numericMax);
4171
+ if (Number.isFinite(parsedMax)) {
4172
+ field.numericMax = parsedMax;
4173
+ }
4174
+ else if (field.max === undefined && String(ui.numericMax).trim().length > 0) {
4175
+ field.max = String(ui.numericMax).trim();
4176
+ }
2537
4177
  }
2538
4178
  if (ui.numericMaxLength !== undefined) {
2539
4179
  field.numericMaxLength = Number(ui.numericMaxLength);
@@ -2541,8 +4181,224 @@ class SchemaNormalizationKernel {
2541
4181
  if (ui.buttons !== undefined) {
2542
4182
  field.buttons = this.parseButtons(ui.buttons);
2543
4183
  }
4184
+ if (ui.valueLabelDisplay !== undefined) {
4185
+ const normalizedValueLabelDisplay = typeof ui.valueLabelDisplay === 'string'
4186
+ ? ui.valueLabelDisplay.trim().toLowerCase()
4187
+ : '';
4188
+ if (normalizedValueLabelDisplay === 'off' ||
4189
+ normalizedValueLabelDisplay === 'auto' ||
4190
+ normalizedValueLabelDisplay === 'on') {
4191
+ field.valueLabelDisplay = normalizedValueLabelDisplay;
4192
+ }
4193
+ }
4194
+ const sliderBooleanKeys = [
4195
+ 'thumbLabel',
4196
+ 'discrete',
4197
+ 'showInputs',
4198
+ 'disableThumbSwap',
4199
+ 'vertical',
4200
+ 'invert',
4201
+ ];
4202
+ for (const key of sliderBooleanKeys) {
4203
+ if (ui[key] !== undefined) {
4204
+ const parsed = this.parseOptionalBoolean(ui[key]);
4205
+ if (parsed !== undefined) {
4206
+ field[key] = parsed;
4207
+ }
4208
+ }
4209
+ }
4210
+ if (ui.showTicks !== undefined) {
4211
+ const parsedTicks = this.parseOptionalBoolean(ui.showTicks);
4212
+ if (parsedTicks !== undefined) {
4213
+ field.showTicks = parsedTicks;
4214
+ }
4215
+ else if (typeof ui.showTicks === 'string' &&
4216
+ ui.showTicks.trim().toLowerCase() === 'auto') {
4217
+ field.showTicks = 'auto';
4218
+ }
4219
+ }
4220
+ const sliderNumberKeys = [
4221
+ 'shiftStep',
4222
+ 'minDistance',
4223
+ 'maxDistance',
4224
+ ];
4225
+ for (const key of sliderNumberKeys) {
4226
+ if (ui[key] !== undefined) {
4227
+ const parsed = this.parseOptionalFiniteNumber(ui[key]);
4228
+ if (parsed !== undefined) {
4229
+ field[key] = parsed;
4230
+ }
4231
+ }
4232
+ }
4233
+ // -------------------------------------------------------------------
4234
+ // Inline filter and specialized control metadata (x-ui)
4235
+ // -------------------------------------------------------------------
4236
+ const inlinePassThroughKeys = [
4237
+ 'prefixIcon',
4238
+ 'suffixIcon',
4239
+ 'prefixIconColor',
4240
+ 'suffixIconColor',
4241
+ 'chipLeadingIcon',
4242
+ 'chipTrailingIcon',
4243
+ 'chipLeadingIconColor',
4244
+ 'chipTrailingIconColor',
4245
+ 'clearIcon',
4246
+ 'clearIconColor',
4247
+ 'showQuickClear',
4248
+ 'clearable',
4249
+ 'inlineAutoSize',
4250
+ 'inlineAutoSizeMaxPx',
4251
+ 'inlineAutoSizeMaxVw',
4252
+ 'inlineOverlay',
4253
+ 'inlineChipDisplay',
4254
+ 'inlineChipSummaryTemplate',
4255
+ 'inlineChipUnitLabel',
4256
+ 'inlinePanelTitle',
4257
+ 'inlineQuickPresets',
4258
+ 'inlineQuickPresetsApplyMode',
4259
+ 'inlineTexts',
4260
+ 'shortcuts',
4261
+ 'showShortcuts',
4262
+ 'quickPresets',
4263
+ 'quickPresetsAuto',
4264
+ 'quickPresetsLabels',
4265
+ 'granularity',
4266
+ 'defaultGranularity',
4267
+ 'selectionGrid',
4268
+ 'showSlider',
4269
+ 'minPeriod',
4270
+ 'maxPeriod',
4271
+ 'minYear',
4272
+ 'maxYear',
4273
+ 'minTime',
4274
+ 'maxTime',
4275
+ 'stepMinutes',
4276
+ 'startField',
4277
+ 'endField',
4278
+ 'startLabel',
4279
+ 'endLabel',
4280
+ 'startPlaceholder',
4281
+ 'endPlaceholder',
4282
+ 'inputMinLabel',
4283
+ 'inputMaxLabel',
4284
+ 'maxVisibleChips',
4285
+ 'maxVisibleBadges',
4286
+ 'showSelectAll',
4287
+ 'selectAllLabel',
4288
+ 'clearSelectionLabel',
4289
+ 'searchPlaceholder',
4290
+ 'noResultsText',
4291
+ 'allowSelectAll',
4292
+ 'governedPaletteRef',
4293
+ 'palette',
4294
+ 'paletteColors',
4295
+ 'paletteSettings',
4296
+ 'documentType',
4297
+ 'version',
4298
+ 'nodes',
4299
+ 'nodeIdField',
4300
+ 'parentIdField',
4301
+ 'childrenField',
4302
+ 'lazyLoad',
4303
+ 'marks',
4304
+ 'semanticBands',
4305
+ 'distribution',
4306
+ 'inlineDistribution',
4307
+ 'track',
4308
+ 'trueLabel',
4309
+ 'falseLabel',
4310
+ 'labelTrue',
4311
+ 'labelFalse',
4312
+ 'iconTrue',
4313
+ 'iconFalse',
4314
+ 'tone',
4315
+ 'toneTrue',
4316
+ 'toneFalse',
4317
+ 'booleanFormat',
4318
+ 'displayFormat',
4319
+ 'currency',
4320
+ 'currencyCode',
4321
+ 'locale',
4322
+ 'precision',
4323
+ 'decimalPlaces',
4324
+ 'initialsField',
4325
+ 'optionLabelKey',
4326
+ 'optionValueKey',
4327
+ 'extraProperties',
4328
+ 'rangeMode',
4329
+ 'maxRating',
4330
+ 'allowHalf',
4331
+ 'ratingIcon',
4332
+ 'ratingEmptyIcon',
4333
+ 'ratingHalfIcon',
4334
+ 'ratingTone',
4335
+ 'ratingToneColors',
4336
+ 'ratingLabels',
4337
+ 'distanceUnit',
4338
+ 'distanceBaseUnit',
4339
+ 'distanceUnits',
4340
+ 'distanceAllowUnitToggle',
4341
+ 'distanceUnitLabels',
4342
+ 'distanceDisplayDecimals',
4343
+ 'distanceDecimalsKm',
4344
+ 'distanceDecimalsMi',
4345
+ 'distancePresets',
4346
+ 'distanceSubtitle',
4347
+ 'distanceRadialRings',
4348
+ 'distanceAccentColor',
4349
+ 'distanceRingColor',
4350
+ 'distanceTrackColor',
4351
+ 'distanceGlowColor',
4352
+ 'distanceGradientLowColor',
4353
+ 'distanceGradientMidColor',
4354
+ 'distanceGradientHighColor',
4355
+ 'distanceRangeBandOpacity',
4356
+ 'pipelineOptions',
4357
+ 'pipelineColors',
4358
+ 'pipelineTexts',
4359
+ 'scoreBands',
4360
+ 'priorityBands',
4361
+ 'severityBands',
4362
+ 'scorePalette',
4363
+ 'scoreTexts',
4364
+ 'relativePeriodOptions',
4365
+ 'relativePeriodPresets',
4366
+ 'relativePeriodTexts',
4367
+ 'sentimentOptions',
4368
+ 'sentimentPalette',
4369
+ 'sentimentTexts',
4370
+ 'colorLabelOptions',
4371
+ 'colorLabelPalette',
4372
+ 'colorLabelTexts',
4373
+ 'timeOptions',
4374
+ 'inlineTimeQuickPresets',
4375
+ 'inlineVisualStyle',
4376
+ 'percentPresets',
4377
+ 'numberFormat',
4378
+ 'valueLabelFormat',
4379
+ 'scale',
4380
+ ];
4381
+ for (const key of inlinePassThroughKeys) {
4382
+ if (ui[key] !== undefined && field[key] === undefined) {
4383
+ field[key] = ui[key];
4384
+ }
4385
+ }
2544
4386
  fields.push(field);
2545
4387
  }
4388
+ if (fields.length === 0 &&
4389
+ properties['parameters'] &&
4390
+ typeof properties['parameters'] === 'object' &&
4391
+ !Array.isArray(properties['parameters'])) {
4392
+ const parametersProp = properties['parameters'];
4393
+ const resolvedParametersSchema = this.resolveSchemaRef(parametersProp.$ref, rootSchema) ?? parametersProp;
4394
+ if (resolvedParametersSchema &&
4395
+ typeof resolvedParametersSchema === 'object' &&
4396
+ resolvedParametersSchema !== schema &&
4397
+ resolvedParametersSchema.properties &&
4398
+ typeof resolvedParametersSchema.properties === 'object') {
4399
+ return this.normalizeObjectSchema(resolvedParametersSchema, rootSchema);
4400
+ }
4401
+ }
2546
4402
  // Order by the optional 'order' property when present
2547
4403
  fields.sort((a, b) => {
2548
4404
  const orderA = a.order ?? Number.MAX_SAFE_INTEGER;
@@ -2551,6 +4407,13 @@ class SchemaNormalizationKernel {
2551
4407
  });
2552
4408
  return fields;
2553
4409
  }
4410
+ haveEquivalentFieldAccess(left, right) {
4411
+ const identity = (access) => JSON.stringify([
4412
+ [...(access.visibleForAuthorities ?? [])].sort(),
4413
+ [...(access.editableForAuthorities ?? [])].sort(),
4414
+ ]);
4415
+ return identity(left) === identity(right);
4416
+ }
2554
4417
  resolveFieldType(prop, ui) {
2555
4418
  if (ui?.type !== undefined && ui?.type !== null && String(ui.type).trim() !== '') {
2556
4419
  return String(ui.type);
@@ -2558,6 +4421,10 @@ class SchemaNormalizationKernel {
2558
4421
  if (String(ui?.controlType ?? '').trim() === 'array') {
2559
4422
  return 'array';
2560
4423
  }
4424
+ if (Array.isArray(prop?.type)) {
4425
+ const types = [...new Set(prop.type.filter((type) => typeof type === 'string' && type !== 'null'))];
4426
+ return types.length === 1 ? types[0] : undefined;
4427
+ }
2561
4428
  if (prop?.type) {
2562
4429
  return String(prop.type);
2563
4430
  }
@@ -2573,7 +4440,21 @@ class SchemaNormalizationKernel {
2573
4440
  }
2574
4441
  // Compatibilidade para schemas de range publicados como oneOf(array|object).
2575
4442
  const controlToken = String(ui?.controlType || '').trim().toLowerCase().replace(/[^a-z0-9]/g, '');
2576
- const isRangeControl = ['daterange', 'datetimerange', 'rangeslider', 'pricerange'].includes(controlToken);
4443
+ const isRangeControl = [
4444
+ 'daterange',
4445
+ 'datetimerange',
4446
+ 'rangeslider',
4447
+ 'pricerange',
4448
+ 'inlinerange',
4449
+ 'inlinecurrencyrange',
4450
+ 'inlinedaterange',
4451
+ 'inlineperiodrange',
4452
+ 'inlineyearrange',
4453
+ 'inlinemonthrange',
4454
+ 'inlinetimerange',
4455
+ 'inlinedistanceradius',
4456
+ 'inlinescorepriority',
4457
+ ].includes(controlToken);
2577
4458
  if (isRangeControl && nonNullTypes.includes('array')) {
2578
4459
  return 'array';
2579
4460
  }
@@ -2589,6 +4470,10 @@ class SchemaNormalizationKernel {
2589
4470
  function normalizeSchemaFields(schema) {
2590
4471
  return new SchemaNormalizationKernel().normalizeSchema(schema);
2591
4472
  }
4473
+ /** Extracts root-level `x-ui` metadata blocks (`formLayout`, `progression`, `timeline`, `schedule`, `hierarchy`, `calculationMemory`). */
4474
+ function extractSchemaRootUiMetadata(schema) {
4475
+ return new SchemaNormalizationKernel().extractRootUiMetadata(schema);
4476
+ }
2592
4477
 
2593
4478
  function isObject(value) {
2594
4479
  return value != null && typeof value === 'object' && !Array.isArray(value);
@@ -2667,8 +4552,18 @@ function clone(v) {
2667
4552
 
2668
4553
  function buildBaseColumnFromDef(def) {
2669
4554
  const type = resolveColumnTypeFromFieldDefinition(def);
2670
- const format = type === 'string' ? resolveTextMaskFormatFromFieldDefinition(def) : undefined;
2671
- const renderer = resolveRendererFromFieldPresentation(def);
4555
+ const format = resolveFormatFromFieldDefinition(def, type);
4556
+ const valueMapping = resolveSchemaValueMappingFromFieldDefinition(def);
4557
+ const renderer = resolveRendererFromFieldDefinition(def);
4558
+ const quickView = resolveQuickViewFromFieldDefinition(def);
4559
+ const isAvatar = renderer?.type === 'avatar';
4560
+ const explicitWidth = firstNonEmptyString(def.width);
4561
+ const resolvedOrder = typeof def.tableOrder === 'number'
4562
+ ? def.tableOrder
4563
+ : typeof def.order === 'number'
4564
+ ? def.order
4565
+ : undefined;
4566
+ const sticky = def.pinned ?? def.sticky;
2672
4567
  return {
2673
4568
  field: def.name,
2674
4569
  header: def.label || def.name,
@@ -2677,9 +4572,14 @@ function buildBaseColumnFromDef(def) {
2677
4572
  sortable: def.sortable !== false,
2678
4573
  filterable: def.filterable === true,
2679
4574
  resizable: true,
2680
- order: typeof def.order === 'number' ? def.order : undefined,
4575
+ ...(sticky !== undefined ? { sticky } : {}),
4576
+ order: resolvedOrder,
4577
+ ...(explicitWidth ? { width: explicitWidth } : isAvatar ? { width: '56px' } : {}),
4578
+ ...(isAvatar ? { align: 'center' } : {}),
2681
4579
  ...(format ? { format } : {}),
4580
+ ...(valueMapping ? { valueMapping } : {}),
2682
4581
  ...(renderer ? { renderer } : {}),
4582
+ ...(quickView ? { quickView } : {}),
2683
4583
  };
2684
4584
  }
2685
4585
  function applyLocalCustomizations(baseCol, localCol) {
@@ -2706,11 +4606,18 @@ function applyLocalCustomizations(baseCol, localCol) {
2706
4606
  result.headerStyle = localCol.headerStyle ?? baseCol.headerStyle;
2707
4607
  result.cssClass = localCol.cssClass ?? baseCol.cssClass;
2708
4608
  result.headerCssClass = localCol.headerCssClass ?? baseCol.headerCssClass;
4609
+ const resolvedQuickView = reconcileFieldQuickViewBinding(baseCol.quickView, localCol.quickView);
4610
+ if (resolvedQuickView) {
4611
+ result.quickView = resolvedQuickView;
4612
+ }
4613
+ else {
4614
+ delete result.quickView;
4615
+ }
2709
4616
  // If server type changed, drop potentially incompatible formatting/renderers.
2710
4617
  if (!typeChanged) {
2711
4618
  result.format = localCol.format ?? baseCol.format;
2712
4619
  result.valueMapping = localCol.valueMapping ?? baseCol.valueMapping;
2713
- result.renderer = localCol.renderer ?? baseCol.renderer;
4620
+ result.renderer = normalizeColumnRendererQuickView(localCol.renderer ?? baseCol.renderer);
2714
4621
  }
2715
4622
  else {
2716
4623
  // Drop local presentation that may be incompatible with the new server type,
@@ -2729,6 +4636,10 @@ function reconcileTableConfig(layout, serverDefs) {
2729
4636
  const localCol = localByField.get(base.field);
2730
4637
  return localCol ? applyLocalCustomizations(base, localCol) : base;
2731
4638
  });
4639
+ if (serverDefs.some((d) => typeof d.tableOrder === 'number')) {
4640
+ mergedColumns.sort((a, b) => (a.order ?? Number.MAX_SAFE_INTEGER) -
4641
+ (b.order ?? Number.MAX_SAFE_INTEGER));
4642
+ }
2732
4643
  const serverFields = new Set(serverDefs.map((d) => d.name));
2733
4644
  const orphans = (local.columns || []).filter((c) => !serverFields.has(c.field));
2734
4645
  const hiddenOrphans = orphans.map((c) => ({ ...c, visible: false }));
@@ -2773,8 +4684,11 @@ function resolveSemanticColumnTypeFromFieldDefinition(def) {
2773
4684
  return 'string';
2774
4685
  if (numericFormat === 'currency' || controlType === 'currency')
2775
4686
  return 'currency';
2776
- if (numericFormat === 'percent' || numericFormat === 'percentage')
4687
+ if (numericFormat === 'percent' ||
4688
+ numericFormat === 'percentage' ||
4689
+ numericFormat === 'fraction') {
2777
4690
  return 'percentage';
4691
+ }
2778
4692
  if (numericFormat === 'date' || numericFormat === 'datetime')
2779
4693
  return 'date';
2780
4694
  if (controlType === 'numerictextbox' || controlType === 'inlinenumber')
@@ -2831,21 +4745,293 @@ function resolveTextMaskFormat(value) {
2831
4745
  const hasInvalidMaskLetters = /[A-WYZa-wyz]/.test(format);
2832
4746
  return hasMaskTokens && !hasInvalidMaskLetters ? format : undefined;
2833
4747
  }
4748
+ function resolveFormatFromFieldDefinition(def, type) {
4749
+ if (type === 'string') {
4750
+ return resolveTextMaskFormatFromFieldDefinition(def);
4751
+ }
4752
+ if (type === 'currency') {
4753
+ return resolveSchemaCurrencyFormatFromFieldDefinition(def);
4754
+ }
4755
+ if (type === 'date') {
4756
+ return (firstNonEmptyString(def.displayFormat) ??
4757
+ firstNonEmptyString(def.extraProperties?.displayFormat));
4758
+ }
4759
+ if (type === 'boolean') {
4760
+ return resolveSchemaBooleanFormatFromFieldDefinition(def);
4761
+ }
4762
+ if (type === 'number') {
4763
+ const schemaDataType = normalizePresentationToken(def.type);
4764
+ const schemaFormat = normalizePresentationToken(def.format);
4765
+ const numericFormat = normalizePresentationToken(def.numericFormat ?? def.extraProperties?.numericFormat);
4766
+ if (schemaDataType === 'integer' ||
4767
+ schemaFormat === 'integer' ||
4768
+ schemaFormat === 'int32' ||
4769
+ schemaFormat === 'int64' ||
4770
+ numericFormat === 'integer' ||
4771
+ numericFormat === 'int32' ||
4772
+ numericFormat === 'int64') {
4773
+ return '1.0-0';
4774
+ }
4775
+ if (numericFormat === 'auto') {
4776
+ return undefined;
4777
+ }
4778
+ const explicitDecimals = firstFiniteNumber(def.decimalPlaces) ??
4779
+ firstFiniteNumber(def.extraProperties?.decimalPlaces);
4780
+ if (explicitDecimals !== undefined && explicitDecimals >= 0) {
4781
+ const decimals = Math.trunc(explicitDecimals);
4782
+ return `1.${decimals}-${decimals}`;
4783
+ }
4784
+ }
4785
+ return undefined;
4786
+ }
4787
+ function resolveSchemaCurrencyFormatFromFieldDefinition(def) {
4788
+ const currency = firstNonEmptyString(def.currency) ??
4789
+ firstNonEmptyString(def.extraProperties?.currency) ??
4790
+ 'BRL';
4791
+ const decimalPlaces = firstFiniteNumber(def.decimalPlaces) ??
4792
+ firstFiniteNumber(def.extraProperties?.decimalPlaces) ??
4793
+ 2;
4794
+ return `${currency}|symbol|${decimalPlaces}`;
4795
+ }
4796
+ function resolveSchemaBooleanFormatFromFieldDefinition(def) {
4797
+ const explicit = firstNonEmptyString(def.booleanFormat) ??
4798
+ firstNonEmptyString(def.extraProperties?.booleanFormat);
4799
+ if (explicit)
4800
+ return explicit;
4801
+ const trueLabel = firstNonEmptyString(def.trueLabel) ??
4802
+ firstNonEmptyString(def.labelTrue) ??
4803
+ firstNonEmptyString(def.extraProperties?.trueLabel) ??
4804
+ firstNonEmptyString(def.extraProperties?.labelTrue);
4805
+ const falseLabel = firstNonEmptyString(def.falseLabel) ??
4806
+ firstNonEmptyString(def.labelFalse) ??
4807
+ firstNonEmptyString(def.extraProperties?.falseLabel) ??
4808
+ firstNonEmptyString(def.extraProperties?.labelFalse);
4809
+ if (trueLabel && falseLabel) {
4810
+ const tNorm = normalizePresentationToken(trueLabel);
4811
+ const fNorm = normalizePresentationToken(falseLabel);
4812
+ if (tNorm === 'ativo' && fNorm === 'inativo')
4813
+ return 'active-inactive';
4814
+ if (tNorm === 'sim' && (fNorm === 'nao' || fNorm === 'não'))
4815
+ return 'yes-no';
4816
+ return `custom|${trueLabel}|${falseLabel}`;
4817
+ }
4818
+ const name = normalizePresentationToken(def.name);
4819
+ if (name === 'ativo' || name === 'active' || name.endsWith('ativo')) {
4820
+ return 'active-inactive';
4821
+ }
4822
+ return undefined;
4823
+ }
4824
+ function resolveSchemaValueMappingFromFieldDefinition(def) {
4825
+ const explicit = def.valueMapping;
4826
+ if (explicit && typeof explicit === 'object' && !Array.isArray(explicit)) {
4827
+ const normalized = Object.entries(explicit).reduce((acc, [key, value]) => {
4828
+ if (key && typeof value === 'string' && value.trim()) {
4829
+ acc[key] = value.trim();
4830
+ }
4831
+ return acc;
4832
+ }, {});
4833
+ if (Object.keys(normalized).length > 0)
4834
+ return normalized;
4835
+ }
4836
+ const options = Array.isArray(def.options) ? def.options : [];
4837
+ if (options.length > 0) {
4838
+ const valueKey = firstNonEmptyString(def.optionValueKey) ?? 'key';
4839
+ const labelKey = firstNonEmptyString(def.optionLabelKey) ?? 'value';
4840
+ const mapping = options.reduce((acc, option) => {
4841
+ if (!option || typeof option !== 'object')
4842
+ return acc;
4843
+ const record = option;
4844
+ const value = record[valueKey] ?? record.key ?? record.id ?? record.value;
4845
+ const label = record[labelKey] ?? record.label ?? record.value ?? record.name;
4846
+ if (value !== undefined && value !== null && label !== undefined && label !== null) {
4847
+ acc[String(value)] = String(label);
4848
+ }
4849
+ return acc;
4850
+ }, {});
4851
+ if (Object.keys(mapping).length > 0)
4852
+ return mapping;
4853
+ }
4854
+ const enumValues = Array.isArray(def.enumValues)
4855
+ ? def.enumValues
4856
+ .map((v) => (v != null ? String(v).trim() : ''))
4857
+ .filter((v) => v.length > 0)
4858
+ : [];
4859
+ if (enumValues.length > 0) {
4860
+ return enumValues.reduce((acc, value) => {
4861
+ acc[value] = humanizeSchemaEnumValue(value);
4862
+ return acc;
4863
+ }, {});
4864
+ }
4865
+ return undefined;
4866
+ }
4867
+ function humanizeSchemaEnumValue(value) {
4868
+ return value
4869
+ .toLowerCase()
4870
+ .split(/[_\-\s]+/)
4871
+ .filter(Boolean)
4872
+ .map((part, index) => (index === 0 ? `${part.charAt(0).toUpperCase()}${part.slice(1)}` : part))
4873
+ .join(' ');
4874
+ }
4875
+ function resolveQuickViewFromFieldDefinition(def) {
4876
+ return (resolveFieldQuickViewBinding(def) ??
4877
+ normalizeResourceQuickViewBinding(def['extraProperties'] && typeof def['extraProperties'] === 'object' ? def['extraProperties']['quickView'] : undefined) ??
4878
+ undefined);
4879
+ }
4880
+ function normalizeColumnRendererQuickView(renderer) {
4881
+ if (!renderer || typeof renderer !== 'object') {
4882
+ return renderer;
4883
+ }
4884
+ const next = { ...renderer };
4885
+ if (next.link && typeof next.link === 'object') {
4886
+ const qv = normalizeResourceQuickViewBinding(next.link.quickView);
4887
+ next.link = { ...next.link };
4888
+ if (qv) {
4889
+ next.link.quickView = qv;
4890
+ }
4891
+ else {
4892
+ delete next.link.quickView;
4893
+ }
4894
+ }
4895
+ if (next.badge && typeof next.badge === 'object') {
4896
+ const qv = normalizeResourceQuickViewBinding(next.badge.quickView);
4897
+ next.badge = { ...next.badge };
4898
+ if (qv) {
4899
+ next.badge.quickView = qv;
4900
+ }
4901
+ else {
4902
+ delete next.badge.quickView;
4903
+ }
4904
+ }
4905
+ if (next.chip && typeof next.chip === 'object') {
4906
+ const qv = normalizeResourceQuickViewBinding(next.chip.quickView);
4907
+ next.chip = { ...next.chip };
4908
+ if (qv) {
4909
+ next.chip.quickView = qv;
4910
+ }
4911
+ else {
4912
+ delete next.chip.quickView;
4913
+ }
4914
+ }
4915
+ if (next.icon && typeof next.icon === 'object') {
4916
+ const qv = normalizeResourceQuickViewBinding(next.icon.quickView);
4917
+ next.icon = { ...next.icon };
4918
+ if (qv) {
4919
+ next.icon.quickView = qv;
4920
+ }
4921
+ else {
4922
+ delete next.icon.quickView;
4923
+ }
4924
+ }
4925
+ if (next.compose && typeof next.compose === 'object' && Array.isArray(next.compose.items)) {
4926
+ next.compose = {
4927
+ ...next.compose,
4928
+ items: next.compose.items.map((item) => {
4929
+ if (!item || typeof item !== 'object')
4930
+ return item;
4931
+ if (item.type === 'value') {
4932
+ const qv = normalizeResourceQuickViewBinding(item.quickView);
4933
+ const cloned = { ...item };
4934
+ if (qv)
4935
+ cloned.quickView = qv;
4936
+ else
4937
+ delete cloned.quickView;
4938
+ return cloned;
4939
+ }
4940
+ if (item.type === 'link' && item.link) {
4941
+ const qv = normalizeResourceQuickViewBinding(item.link.quickView);
4942
+ const link = { ...item.link };
4943
+ if (qv)
4944
+ link.quickView = qv;
4945
+ else
4946
+ delete link.quickView;
4947
+ return { ...item, link };
4948
+ }
4949
+ if (item.type === 'badge' && item.badge) {
4950
+ const qv = normalizeResourceQuickViewBinding(item.badge.quickView);
4951
+ const badge = { ...item.badge };
4952
+ if (qv)
4953
+ badge.quickView = qv;
4954
+ else
4955
+ delete badge.quickView;
4956
+ return { ...item, badge };
4957
+ }
4958
+ if (item.type === 'chip' && item.chip) {
4959
+ const qv = normalizeResourceQuickViewBinding(item.chip.quickView);
4960
+ const chip = { ...item.chip };
4961
+ if (qv)
4962
+ chip.quickView = qv;
4963
+ else
4964
+ delete chip.quickView;
4965
+ return { ...item, chip };
4966
+ }
4967
+ if (item.type === 'icon' && item.icon) {
4968
+ const qv = normalizeResourceQuickViewBinding(item.icon.quickView);
4969
+ const icon = { ...item.icon };
4970
+ if (qv)
4971
+ icon.quickView = qv;
4972
+ else
4973
+ delete icon.quickView;
4974
+ return { ...item, icon };
4975
+ }
4976
+ return item;
4977
+ }),
4978
+ };
4979
+ }
4980
+ return next;
4981
+ }
4982
+ function resolveRendererFromFieldDefinition(def) {
4983
+ const presentationRenderer = resolveRendererFromFieldPresentation(def);
4984
+ if (presentationRenderer)
4985
+ return presentationRenderer;
4986
+ if (isPraxisPresentationVisualizationTableSafe(def.microVisualization)) {
4987
+ return {
4988
+ type: 'microVisualization',
4989
+ microVisualization: {
4990
+ visualization: def.microVisualization,
4991
+ },
4992
+ };
4993
+ }
4994
+ if (normalizePresentationToken(def.controlType) === 'avatar') {
4995
+ const initialsField = firstNonEmptyString(def.initialsField) ??
4996
+ firstNonEmptyString(def.extraProperties?.initialsField) ??
4997
+ 'nomeCompleto';
4998
+ return {
4999
+ type: 'avatar',
5000
+ avatar: {
5001
+ srcField: def.name,
5002
+ initialsField,
5003
+ shape: 'circle',
5004
+ size: 32,
5005
+ },
5006
+ };
5007
+ }
5008
+ return undefined;
5009
+ }
2834
5010
  function resolveRendererFromFieldPresentation(def) {
2835
5011
  const presentation = def.presentation;
2836
5012
  if (!presentation || typeof presentation !== 'object')
2837
5013
  return undefined;
5014
+ if (presentation.presenter === 'microVisualization' &&
5015
+ isPraxisPresentationVisualizationTableSafe(presentation.visualization)) {
5016
+ return {
5017
+ type: 'microVisualization',
5018
+ microVisualization: {
5019
+ visualization: presentation.visualization,
5020
+ },
5021
+ };
5022
+ }
2838
5023
  const presenter = normalizePresentationToken(presentation.presenter ?? presentation.variant);
2839
5024
  const color = resolveSemanticPresentationColor(presentation.tone);
2840
5025
  const variant = resolveSemanticPresentationVariant(presentation.appearance);
2841
5026
  const icon = firstNonEmptyString(presentation.icon);
2842
5027
  const tooltipText = firstNonEmptyString(presentation.tooltip);
2843
5028
  const tooltip = tooltipText ? { text: tooltipText } : undefined;
5029
+ const fixedText = firstNonEmptyString(presentation.label);
2844
5030
  if (presenter === 'chip') {
2845
5031
  return {
2846
5032
  type: 'chip',
2847
5033
  chip: {
2848
- textField: def.name,
5034
+ ...(fixedText ? { text: fixedText } : { textField: def.name }),
2849
5035
  ...(color ? { color } : {}),
2850
5036
  ...(variant ? { variant } : {}),
2851
5037
  ...(icon ? { icon } : {}),
@@ -2857,7 +5043,7 @@ function resolveRendererFromFieldPresentation(def) {
2857
5043
  return {
2858
5044
  type: 'badge',
2859
5045
  badge: {
2860
- textField: def.name,
5046
+ ...(fixedText ? { text: fixedText } : { textField: def.name }),
2861
5047
  ...(color ? { color } : {}),
2862
5048
  ...(variant ? { variant } : {}),
2863
5049
  ...(icon ? { icon } : {}),
@@ -2871,13 +5057,41 @@ function resolveRendererFromFieldPresentation(def) {
2871
5057
  const hasAffixes = !!(affixes.prefix || affixes.suffix);
2872
5058
  if (!rendererIcon && !hasAffixes)
2873
5059
  return undefined;
5060
+ if (affixes.prefix || affixes.suffix || tooltipText) {
5061
+ return {
5062
+ type: 'icon',
5063
+ icon: {
5064
+ ...(!hasAffixes && rendererIcon ? { name: rendererIcon } : {}),
5065
+ textField: def.name,
5066
+ ...(tooltipText ? { ariaLabel: tooltipText } : {}),
5067
+ ...affixes,
5068
+ },
5069
+ };
5070
+ }
5071
+ if (!rendererIcon)
5072
+ return undefined;
2874
5073
  return {
2875
- type: 'icon',
2876
- icon: {
2877
- ...(rendererIcon && !hasAffixes ? { name: rendererIcon } : {}),
2878
- textField: def.name,
2879
- ...(tooltipText ? { ariaLabel: tooltipText } : {}),
2880
- ...affixes,
5074
+ type: 'compose',
5075
+ compose: {
5076
+ items: [
5077
+ {
5078
+ type: 'icon',
5079
+ icon: {
5080
+ name: rendererIcon,
5081
+ ...(color ? { color } : {}),
5082
+ ...(def.label ? { ariaLabel: def.label } : {}),
5083
+ },
5084
+ },
5085
+ {
5086
+ type: 'value',
5087
+ field: def.name,
5088
+ },
5089
+ ],
5090
+ layout: {
5091
+ direction: 'row',
5092
+ gap: 6,
5093
+ align: 'center',
5094
+ },
2881
5095
  },
2882
5096
  };
2883
5097
  }
@@ -2885,13 +5099,20 @@ function resolveRendererFromFieldPresentation(def) {
2885
5099
  }
2886
5100
  function resolveSemanticPresentationColor(tone) {
2887
5101
  const normalized = normalizePresentationToken(tone);
2888
- if (!normalized || normalized === 'neutral')
5102
+ if (normalized === 'neutral')
5103
+ return 'basic';
5104
+ if (!normalized)
2889
5105
  return undefined;
2890
- return normalized === 'danger' ? 'warn' : normalized;
5106
+ if (normalized === 'danger' || normalized === 'warning')
5107
+ return 'warn';
5108
+ return normalized;
2891
5109
  }
2892
5110
  function resolveSemanticPresentationVariant(appearance) {
2893
5111
  const normalized = normalizePresentationToken(appearance);
2894
- return normalized === 'filled' || normalized === 'outlined' || normalized === 'soft'
5112
+ return normalized === 'filled' ||
5113
+ normalized === 'outlined' ||
5114
+ normalized === 'soft' ||
5115
+ normalized === 'plain'
2895
5116
  ? normalized
2896
5117
  : undefined;
2897
5118
  }
@@ -2909,6 +5130,12 @@ function firstNonEmptyString(value) {
2909
5130
  const trimmed = value.trim();
2910
5131
  return trimmed ? trimmed : undefined;
2911
5132
  }
5133
+ function firstFiniteNumber(value) {
5134
+ if (value === null || value === undefined || value === '')
5135
+ return undefined;
5136
+ const numeric = typeof value === 'number' ? value : Number(value);
5137
+ return Number.isFinite(numeric) ? numeric : undefined;
5138
+ }
2912
5139
  function normalizePresentationToken(value) {
2913
5140
  return String(value ?? '').trim().toLowerCase().replace(/[\s_-]+/g, '');
2914
5141
  }