@praxisui/core 10.0.0-rc.6 → 10.0.0-rc.60

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;
@@ -88,6 +90,14 @@ const VISUALIZATION_KINDS = new Set([
88
90
  'bullet',
89
91
  'delta',
90
92
  'processFlow',
93
+ 'waterfall',
94
+ ]);
95
+ const WATERFALL_ROLES = new Set([
96
+ 'start',
97
+ 'increase',
98
+ 'decrease',
99
+ 'subtotal',
100
+ 'total',
91
101
  ]);
92
102
  const VISUALIZATION_SURFACES = new Set([
93
103
  'table-cell',
@@ -111,6 +121,10 @@ const VISUALIZATION_TONES = new Set([
111
121
  'danger',
112
122
  'critical',
113
123
  ]);
124
+ const VISUALIZATION_SCALE_SCOPES = new Set([
125
+ 'row',
126
+ 'page',
127
+ ]);
114
128
  const TABLE_SAFE_KINDS = new Set([
115
129
  'line',
116
130
  'area',
@@ -122,6 +136,7 @@ const TABLE_SAFE_KINDS = new Set([
122
136
  'bullet',
123
137
  'delta',
124
138
  'processFlow',
139
+ 'waterfall',
125
140
  ]);
126
141
  const TABLE_CELL_RECOMMENDED_KINDS = new Set([
127
142
  'delta',
@@ -143,7 +158,7 @@ function getPraxisTableCellVisualizationConstraint(kind) {
143
158
  return 'row-density';
144
159
  if (kind === 'processFlow')
145
160
  return 'step-labels';
146
- if (kind === 'line' || kind === 'area' || kind === 'column') {
161
+ if (kind === 'line' || kind === 'area' || kind === 'column' || kind === 'waterfall') {
147
162
  return 'horizontal-space';
148
163
  }
149
164
  return null;
@@ -163,8 +178,8 @@ function resolvePraxisMicroVisualizationTone(value, thresholds, fallbackTone) {
163
178
  if (value === undefined || value === null || !Array.isArray(thresholds) || thresholds.length === 0) {
164
179
  return fallbackTone ? { tone: fallbackTone } : undefined;
165
180
  }
166
- const num = typeof value === 'number' ? value : Number(value);
167
- const isNum = Number.isFinite(num);
181
+ const num = toFiniteNumber(value);
182
+ const isNum = num !== undefined;
168
183
  // 1. Pass 1: Correspondencia discreta (equals) tem prioridade maxima
169
184
  for (const t of thresholds) {
170
185
  if (!t || !t.tone || t.equals === undefined) {
@@ -173,7 +188,8 @@ function resolvePraxisMicroVisualizationTone(value, thresholds, fallbackTone) {
173
188
  if (t.equals === value || String(t.equals) === String(value)) {
174
189
  return { tone: t.tone, label: t.label, matchedThreshold: t };
175
190
  }
176
- if (isNum && Number.isFinite(Number(t.equals)) && Number(t.equals) === num) {
191
+ const eqNum = toFiniteNumber(t.equals);
192
+ if (isNum && eqNum !== undefined && eqNum === num) {
177
193
  return { tone: t.tone, label: t.label, matchedThreshold: t };
178
194
  }
179
195
  }
@@ -207,6 +223,313 @@ function resolvePraxisMicroVisualizationTone(value, thresholds, fallbackTone) {
207
223
  }
208
224
  return fallbackTone ? { tone: fallbackTone } : undefined;
209
225
  }
226
+ const STACKED_BAR_TONE_PAINT = {
227
+ info: 'var(--prx-micro-tone-info, var(--p-table-state-info-fg, var(--md-sys-color-primary, #0a6eb4)))',
228
+ success: 'var(--prx-micro-tone-success, var(--p-table-state-success-fg, #1b7a43))',
229
+ warning: 'var(--prx-micro-tone-warning, var(--p-table-state-warning-fg, #d97706))',
230
+ danger: 'var(--prx-micro-tone-danger, var(--p-table-state-danger-fg, var(--md-sys-color-error, #c62828)))',
231
+ critical: 'var(--prx-micro-tone-critical, var(--prx-micro-tone-danger, var(--p-table-state-danger-fg, var(--md-sys-color-error, #9f1239))))',
232
+ neutral: 'var(--prx-micro-tone-neutral, var(--md-sys-color-secondary, #5c6b73))',
233
+ };
234
+ function normalizePraxisHexColor(value) {
235
+ if (typeof value !== 'string') {
236
+ return undefined;
237
+ }
238
+ const trimmed = value.trim();
239
+ const match = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(trimmed);
240
+ if (!match) {
241
+ return undefined;
242
+ }
243
+ const raw = match[1].toLowerCase();
244
+ if (raw.length === 3) {
245
+ return `#${raw[0]}${raw[0]}${raw[1]}${raw[1]}${raw[2]}${raw[2]}`;
246
+ }
247
+ return `#${raw}`;
248
+ }
249
+ function getPraxisStackedBarPaintStyle(segment, fallbackTone = 'neutral') {
250
+ const hex = normalizePraxisHexColor(segment?.color);
251
+ const resolvedTone = normalizeEnum$1(segment?.tone, VISUALIZATION_TONES) ??
252
+ normalizeEnum$1(fallbackTone, VISUALIZATION_TONES) ??
253
+ 'neutral';
254
+ const paint = hex ?? STACKED_BAR_TONE_PAINT[resolvedTone];
255
+ return {
256
+ '--prx-micro-category-color': paint,
257
+ color: paint,
258
+ };
259
+ }
260
+ function isVisualizationEntrySuppressed(entry) {
261
+ if (!entry || typeof entry !== 'object') {
262
+ return false;
263
+ }
264
+ const obj = entry;
265
+ return (obj.suppressed === true
266
+ || obj.privacySuppressed === true
267
+ || (obj.value === null && obj.state === 'suppressed'));
268
+ }
269
+ function countSuppressedEntries(entries) {
270
+ if (!Array.isArray(entries)) {
271
+ return 0;
272
+ }
273
+ let count = 0;
274
+ for (const entry of entries) {
275
+ if (isVisualizationEntrySuppressed(entry)) {
276
+ count += 1;
277
+ }
278
+ }
279
+ return count;
280
+ }
281
+ function resolvePreservedSuppressedCount(value) {
282
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
283
+ ? Math.trunc(value)
284
+ : 0;
285
+ }
286
+ function resolvePraxisStackedBarSegments(visualization) {
287
+ if (!visualization || visualization.kind !== 'stackedBar') {
288
+ return [];
289
+ }
290
+ if (Array.isArray(visualization.segments) && visualization.segments.length > 0) {
291
+ return visualization.segments.filter((seg) => !isVisualizationEntrySuppressed(seg));
292
+ }
293
+ if (Array.isArray(visualization.items) && visualization.items.length > 0) {
294
+ const mapped = [];
295
+ for (let i = 0; i < visualization.items.length; i++) {
296
+ if (!Object.prototype.hasOwnProperty.call(visualization.items, i)) {
297
+ return [];
298
+ }
299
+ const item = visualization.items[i];
300
+ if (!item) {
301
+ return [];
302
+ }
303
+ if (isVisualizationEntrySuppressed(item)) {
304
+ continue;
305
+ }
306
+ if (typeof item.value !== 'number' || !Number.isFinite(item.value) || item.value < 0) {
307
+ return [];
308
+ }
309
+ const hex = normalizePraxisHexColor(item.color);
310
+ mapped.push({
311
+ value: item.value,
312
+ ...(item.label ? { label: item.label } : {}),
313
+ ...(item.tone ? { tone: item.tone } : {}),
314
+ ...(hex ? { color: hex } : {}),
315
+ });
316
+ }
317
+ return mapped;
318
+ }
319
+ return [];
320
+ }
321
+ function resolvePraxisStackedBarTotal(segments, explicitTotal) {
322
+ if (typeof explicitTotal === 'number' && Number.isFinite(explicitTotal) && explicitTotal >= 0) {
323
+ return explicitTotal;
324
+ }
325
+ return compensatedSum(segments.map((segment) => segment.value));
326
+ }
327
+ function computePraxisStackedBarSegmentWidthPct(value, resolvedTotal) {
328
+ if (!Number.isFinite(value) || value <= 0 || !Number.isFinite(resolvedTotal) || resolvedTotal <= 0) {
329
+ return 0;
330
+ }
331
+ return Math.max(0, Math.min(100, (value / resolvedTotal) * 100));
332
+ }
333
+ function formatPraxisStackedBarPercentage(value, resolvedTotal, locale) {
334
+ const pct = computePraxisStackedBarSegmentWidthPct(value, resolvedTotal);
335
+ const maximumFractionDigits = pct === 0 ? 0 : pct < 0.1 ? 3 : pct < 1 ? 2 : 1;
336
+ return `${new Intl.NumberFormat(locale || undefined, { maximumFractionDigits }).format(pct)}%`;
337
+ }
338
+ function resolvePraxisStackedBarAriaLabel(visualization, segments, resolvedTotal, locale) {
339
+ if (visualization.ariaLabel) {
340
+ return visualization.ariaLabel;
341
+ }
342
+ if (segments.length > 0 &&
343
+ segments.every((segment) => typeof segment.label === 'string' && segment.label.trim().length > 0)) {
344
+ const prefix = visualization.title || visualization.fallbackText;
345
+ const summary = segments
346
+ .map((segment) => `${segment.label} ${formatPraxisStackedBarPercentage(segment.value, resolvedTotal, locale)}`)
347
+ .join(', ');
348
+ return `${prefix}: ${summary}`;
349
+ }
350
+ return visualization.fallbackText;
351
+ }
352
+ function compensatedSum(values) {
353
+ let sum = 0;
354
+ let compensation = 0;
355
+ for (let i = 0; i < values.length; i++) {
356
+ const value = values[i];
357
+ const next = sum + value;
358
+ if (Math.abs(sum) >= Math.abs(value)) {
359
+ compensation += (sum - next) + value;
360
+ }
361
+ else {
362
+ compensation += (value - next) + sum;
363
+ }
364
+ sum = next;
365
+ }
366
+ return sum + compensation;
367
+ }
368
+ function normalizeStackedBarDistribution(value, surface) {
369
+ const isTableCell = surface === 'table-cell';
370
+ const hasSegmentsProp = value.segments !== undefined;
371
+ const hasItemsProp = value.items !== undefined;
372
+ const hasExplicitTotalProp = Object.prototype.hasOwnProperty.call(value, 'total') &&
373
+ value.total !== undefined &&
374
+ value.total !== null;
375
+ const hasDeferredExpr = Boolean(normalizeExpression(value.segmentsExpr, 'segmentsExpr') ||
376
+ normalizeExpression(value.itemsExpr, 'itemsExpr'));
377
+ const rawTitle = isTableCell ? undefined : normalizeText$1(value.title);
378
+ if (!hasSegmentsProp && !hasItemsProp) {
379
+ const explicitTotal = hasExplicitTotalProp ? toFiniteNumber(value.total) : undefined;
380
+ const validDeferredTotal = !hasExplicitTotalProp || (explicitTotal !== undefined && explicitTotal >= 0);
381
+ if (!validDeferredTotal) {
382
+ return {
383
+ valid: false,
384
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
385
+ };
386
+ }
387
+ if (!isTableCell && value.legend === true && !hasDeferredExpr) {
388
+ return {
389
+ valid: false,
390
+ legend: false,
391
+ };
392
+ }
393
+ return {
394
+ valid: hasDeferredExpr,
395
+ ...(explicitTotal !== undefined ? { total: explicitTotal } : {}),
396
+ ...(rawTitle && hasDeferredExpr ? { title: rawTitle } : {}),
397
+ ...(typeof value.legend === 'boolean'
398
+ ? { legend: isTableCell ? false : value.legend }
399
+ : {}),
400
+ };
401
+ }
402
+ const rawEntries = hasSegmentsProp ? value.segments : value.items;
403
+ if (!Array.isArray(rawEntries) || rawEntries.length === 0) {
404
+ return {
405
+ valid: false,
406
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
407
+ };
408
+ }
409
+ const parsedSegments = [];
410
+ const parsedItems = [];
411
+ const preservedSuppressedCount = resolvePreservedSuppressedCount(value.suppressedCount);
412
+ let suppressedCount = 0;
413
+ for (let i = 0; i < rawEntries.length; i++) {
414
+ if (!Object.prototype.hasOwnProperty.call(rawEntries, i)) {
415
+ return {
416
+ valid: false,
417
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
418
+ };
419
+ }
420
+ const rawEntry = rawEntries[i];
421
+ if (typeof rawEntry === 'number' || typeof rawEntry === 'string') {
422
+ const num = toFiniteNumber(rawEntry);
423
+ if (num === undefined || num < 0) {
424
+ return {
425
+ valid: false,
426
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
427
+ };
428
+ }
429
+ parsedSegments.push({ value: num });
430
+ parsedItems.push({ value: num });
431
+ continue;
432
+ }
433
+ if (!rawEntry || typeof rawEntry !== 'object') {
434
+ return {
435
+ valid: false,
436
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
437
+ };
438
+ }
439
+ const entryObj = rawEntry;
440
+ if (isVisualizationEntrySuppressed(entryObj)) {
441
+ suppressedCount += 1;
442
+ continue;
443
+ }
444
+ const num = toFiniteNumber(entryObj.value);
445
+ if (num === undefined || num < 0) {
446
+ return {
447
+ valid: false,
448
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
449
+ };
450
+ }
451
+ const label = normalizeText$1(entryObj.label);
452
+ const entryTone = normalizeEnum$1(entryObj.tone, VISUALIZATION_TONES);
453
+ const entryColor = normalizePraxisHexColor(entryObj.color);
454
+ const id = normalizeText$1(entryObj.id);
455
+ const icon = normalizeText$1(entryObj.icon);
456
+ const state = normalizeText$1(entryObj.state);
457
+ parsedSegments.push({
458
+ value: num,
459
+ ...(label ? { label } : {}),
460
+ ...(entryTone ? { tone: entryTone } : {}),
461
+ ...(entryColor ? { color: entryColor } : {}),
462
+ });
463
+ parsedItems.push({
464
+ value: num,
465
+ ...(id ? { id } : {}),
466
+ ...(label ? { label } : {}),
467
+ ...(icon ? { icon } : {}),
468
+ ...(state ? { state } : {}),
469
+ ...(entryTone ? { tone: entryTone } : {}),
470
+ ...(entryColor ? { color: entryColor } : {}),
471
+ });
472
+ }
473
+ const effectiveSuppressedCount = Math.max(preservedSuppressedCount, suppressedCount);
474
+ if (parsedSegments.length === 0) {
475
+ return {
476
+ valid: false,
477
+ ...(effectiveSuppressedCount > 0 ? { suppressedCount: effectiveSuppressedCount } : {}),
478
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
479
+ };
480
+ }
481
+ const sum = compensatedSum(parsedSegments.map((entry) => entry.value));
482
+ if (!Number.isFinite(sum) || sum < 0) {
483
+ return {
484
+ valid: false,
485
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
486
+ };
487
+ }
488
+ let validatedTotal;
489
+ if (hasExplicitTotalProp) {
490
+ const explicitTotal = toFiniteNumber(value.total);
491
+ if (explicitTotal === undefined || !Number.isFinite(explicitTotal) || explicitTotal < 0) {
492
+ return {
493
+ valid: false,
494
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
495
+ };
496
+ }
497
+ if (explicitTotal === 0 && sum > 0) {
498
+ return {
499
+ valid: false,
500
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
501
+ };
502
+ }
503
+ if (explicitTotal > 0) {
504
+ const tolerance = Math.max(4, parsedSegments.length) * Number.EPSILON * Math.max(sum, explicitTotal);
505
+ if (sum - explicitTotal > tolerance) {
506
+ return {
507
+ valid: false,
508
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
509
+ };
510
+ }
511
+ }
512
+ validatedTotal = explicitTotal;
513
+ }
514
+ const normalizedLegend = typeof value.legend === 'boolean' ? (isTableCell ? false : value.legend) : undefined;
515
+ if (!isTableCell && normalizedLegend === true) {
516
+ const allLabeled = parsedSegments.every((entry) => typeof entry.label === 'string' && entry.label.length > 0);
517
+ if (!allLabeled) {
518
+ return {
519
+ valid: false,
520
+ legend: false,
521
+ };
522
+ }
523
+ }
524
+ return {
525
+ valid: true,
526
+ ...(hasSegmentsProp ? { segments: parsedSegments } : { items: parsedItems }),
527
+ ...(validatedTotal !== undefined ? { total: validatedTotal } : {}),
528
+ ...(effectiveSuppressedCount > 0 ? { suppressedCount: effectiveSuppressedCount } : {}),
529
+ ...(rawTitle ? { title: rawTitle } : {}),
530
+ ...(normalizedLegend !== undefined ? { legend: normalizedLegend } : {}),
531
+ };
532
+ }
210
533
  function normalizePraxisPresentationVisualization(value) {
211
534
  if (!value || typeof value !== 'object') {
212
535
  return undefined;
@@ -218,23 +541,30 @@ function normalizePraxisPresentationVisualization(value) {
218
541
  }
219
542
  const surface = normalizeEnum$1(value.surface, VISUALIZATION_SURFACES);
220
543
  const size = normalizeEnum$1(value.size, VISUALIZATION_SIZES);
544
+ const scaleScope = normalizeEnum$1(value.scaleScope, VISUALIZATION_SCALE_SCOPES);
221
545
  const tone = normalizeEnum$1(value.tone, VISUALIZATION_TONES);
222
546
  const ariaLabel = normalizeText$1(value.ariaLabel);
223
547
  const valueSuffix = normalizeText$1(value.valueSuffix);
548
+ const normalizedTargetLabel = normalizeText$1(value.targetLabel);
224
549
  const thresholdsObj = normalizeThresholds(value.thresholds);
550
+ const isTableCell = surface === 'table-cell';
551
+ const normalizedPointsObj = normalizePoints(value.points);
225
552
  let resolvedTone = tone;
226
553
  let resolvedAriaLabel = ariaLabel;
227
554
  if (!resolvedTone && thresholdsObj?.thresholds?.length) {
228
555
  let evalVal = value.value;
229
- if (evalVal === undefined && Array.isArray(value.points) && value.points.length > 0) {
230
- const last = value.points[value.points.length - 1];
231
- if (last && typeof last === 'object' && Number.isFinite(last.value)) {
232
- evalVal = last.value;
233
- }
556
+ if (evalVal === undefined && normalizedPointsObj?.points?.length) {
557
+ evalVal = normalizedPointsObj.points[normalizedPointsObj.points.length - 1].value;
234
558
  }
235
559
  else if (Array.isArray(evalVal) && evalVal.length > 0) {
236
- const last = evalVal[evalVal.length - 1];
237
- evalVal = typeof last === 'object' && last !== null && 'value' in last ? last.value : last;
560
+ const visibleVals = evalVal.filter((entry) => !isVisualizationEntrySuppressed(entry));
561
+ if (visibleVals.length > 0) {
562
+ const last = visibleVals[visibleVals.length - 1];
563
+ evalVal = typeof last === 'object' && last !== null && 'value' in last ? last.value : last;
564
+ }
565
+ else {
566
+ evalVal = undefined;
567
+ }
238
568
  }
239
569
  if (evalVal !== undefined && evalVal !== null) {
240
570
  const resolution = resolvePraxisMicroVisualizationTone(evalVal, thresholdsObj.thresholds);
@@ -246,11 +576,71 @@ function normalizePraxisPresentationVisualization(value) {
246
576
  }
247
577
  }
248
578
  }
579
+ if (kind === 'stackedBar') {
580
+ const stacked = normalizeStackedBarDistribution(value, surface);
581
+ const stackedSuppressedCount = Math.max(stacked.suppressedCount ?? 0, countSuppressedEntries(value.points));
582
+ return {
583
+ kind,
584
+ fallbackText,
585
+ ...(surface ? { surface } : {}),
586
+ ...(size ? { size } : {}),
587
+ ...(scaleScope ? { scaleScope } : {}),
588
+ ...(stacked.title ? { title: stacked.title } : {}),
589
+ ...(normalizeExpression(value.titleExpr, 'titleExpr') ?? {}),
590
+ ...(stacked.legend !== undefined ? { legend: stacked.legend } : {}),
591
+ ...(resolvedTone ? { tone: resolvedTone } : {}),
592
+ ...(resolvedAriaLabel ? { ariaLabel: resolvedAriaLabel } : {}),
593
+ ...(valueSuffix ? { valueSuffix } : {}),
594
+ ...(typeof value.compactValue === 'boolean' ? { compactValue: value.compactValue } : {}),
595
+ ...(Object.prototype.hasOwnProperty.call(value, 'value') ? { value: value.value } : {}),
596
+ ...(normalizeExpression(value.valueExpr, 'valueExpr') ?? {}),
597
+ ...(normalizeExpression(value.valueSuffixExpr, 'valueSuffixExpr') ?? {}),
598
+ ...(normalizeNumber(value.min, 'min') ?? {}),
599
+ ...(normalizeExpression(value.minExpr, 'minExpr') ?? {}),
600
+ ...(normalizeNumber(value.max, 'max') ?? {}),
601
+ ...(normalizeExpression(value.maxExpr, 'maxExpr') ?? {}),
602
+ ...(stacked.total !== undefined ? { total: stacked.total } : {}),
603
+ ...(normalizeExpression(value.totalExpr, 'totalExpr') ?? {}),
604
+ ...(normalizeNumber(value.target, 'target') ?? {}),
605
+ ...(normalizeExpression(value.targetExpr, 'targetExpr') ?? {}),
606
+ ...(normalizedTargetLabel ? { targetLabel: normalizedTargetLabel } : {}),
607
+ ...(normalizeExpression(value.targetLabelExpr, 'targetLabelExpr') ?? {}),
608
+ ...(normalizeNumber(value.baseline, 'baseline') ?? {}),
609
+ ...(normalizeExpression(value.baselineExpr, 'baselineExpr') ?? {}),
610
+ ...(normalizedPointsObj ?? {}),
611
+ ...(normalizeExpression(value.pointsExpr, 'pointsExpr') ?? {}),
612
+ ...(stacked.segments ? { segments: stacked.segments } : {}),
613
+ ...(normalizeExpression(value.segmentsExpr, 'segmentsExpr') ?? {}),
614
+ ...(normalizeThresholds(value.thresholds) ?? {}),
615
+ ...(normalizeExpression(value.thresholdsExpr, 'thresholdsExpr') ?? {}),
616
+ ...(stacked.items ? { items: stacked.items } : {}),
617
+ ...(stackedSuppressedCount > 0 ? { suppressedCount: stackedSuppressedCount } : {}),
618
+ ...(normalizeExpression(value.itemsExpr, 'itemsExpr') ?? {}),
619
+ ...(normalizeExpression(value.toneExpr, 'toneExpr') ?? {}),
620
+ ...(value.stepLabelWidth !== undefined && (typeof value.stepLabelWidth === 'number' || typeof value.stepLabelWidth === 'string')
621
+ ? { stepLabelWidth: value.stepLabelWidth }
622
+ : {}),
623
+ ...(typeof value.stepLabelLineClamp === 'number' && Number.isFinite(value.stepLabelLineClamp)
624
+ ? { stepLabelLineClamp: value.stepLabelLineClamp }
625
+ : {}),
626
+ ...(normalizeExpression(value.ariaLabelExpr, 'ariaLabelExpr') ?? {}),
627
+ ...(normalizeExpression(value.fallbackTextExpr, 'fallbackTextExpr') ?? {}),
628
+ };
629
+ }
630
+ const normalizedTitle = isTableCell ? undefined : normalizeText$1(value.title);
631
+ const normalizedLegend = typeof value.legend === 'boolean' ? (isTableCell ? false : value.legend) : undefined;
632
+ const suppressedCount = Math.max(resolvePreservedSuppressedCount(value.suppressedCount), countSuppressedEntries(value.points)
633
+ + countSuppressedEntries(value.items)
634
+ + countSuppressedEntries(value.segments));
249
635
  return {
250
636
  kind,
251
637
  fallbackText,
252
638
  ...(surface ? { surface } : {}),
253
639
  ...(size ? { size } : {}),
640
+ ...(scaleScope ? { scaleScope } : {}),
641
+ ...(normalizedTitle ? { title: normalizedTitle } : {}),
642
+ ...(normalizeExpression(value.titleExpr, 'titleExpr') ?? {}),
643
+ ...(normalizedLegend !== undefined ? { legend: normalizedLegend } : {}),
254
644
  ...(resolvedTone ? { tone: resolvedTone } : {}),
255
645
  ...(resolvedAriaLabel ? { ariaLabel: resolvedAriaLabel } : {}),
256
646
  ...(valueSuffix ? { valueSuffix } : {}),
@@ -258,19 +648,26 @@ function normalizePraxisPresentationVisualization(value) {
258
648
  ...(Object.prototype.hasOwnProperty.call(value, 'value') ? { value: value.value } : {}),
259
649
  ...(normalizeExpression(value.valueExpr, 'valueExpr') ?? {}),
260
650
  ...(normalizeExpression(value.valueSuffixExpr, 'valueSuffixExpr') ?? {}),
651
+ ...(normalizeNumber(value.min, 'min') ?? {}),
652
+ ...(normalizeExpression(value.minExpr, 'minExpr') ?? {}),
653
+ ...(normalizeNumber(value.max, 'max') ?? {}),
654
+ ...(normalizeExpression(value.maxExpr, 'maxExpr') ?? {}),
261
655
  ...(normalizeNumber(value.total, 'total') ?? {}),
262
656
  ...(normalizeExpression(value.totalExpr, 'totalExpr') ?? {}),
263
657
  ...(normalizeNumber(value.target, 'target') ?? {}),
264
658
  ...(normalizeExpression(value.targetExpr, 'targetExpr') ?? {}),
659
+ ...(normalizedTargetLabel ? { targetLabel: normalizedTargetLabel } : {}),
660
+ ...(normalizeExpression(value.targetLabelExpr, 'targetLabelExpr') ?? {}),
265
661
  ...(normalizeNumber(value.baseline, 'baseline') ?? {}),
266
662
  ...(normalizeExpression(value.baselineExpr, 'baselineExpr') ?? {}),
267
- ...(normalizePoints(value.points) ?? {}),
663
+ ...(normalizedPointsObj ?? {}),
268
664
  ...(normalizeExpression(value.pointsExpr, 'pointsExpr') ?? {}),
269
665
  ...(normalizeSegments(value.segments) ?? {}),
270
666
  ...(normalizeExpression(value.segmentsExpr, 'segmentsExpr') ?? {}),
271
667
  ...(normalizeThresholds(value.thresholds) ?? {}),
272
668
  ...(normalizeExpression(value.thresholdsExpr, 'thresholdsExpr') ?? {}),
273
669
  ...(normalizeItems(value.items) ?? {}),
670
+ ...(suppressedCount > 0 ? { suppressedCount } : {}),
274
671
  ...(normalizeExpression(value.itemsExpr, 'itemsExpr') ?? {}),
275
672
  ...(normalizeExpression(value.toneExpr, 'toneExpr') ?? {}),
276
673
  ...(value.stepLabelWidth !== undefined && (typeof value.stepLabelWidth === 'number' || typeof value.stepLabelWidth === 'string')
@@ -287,6 +684,55 @@ function isPraxisPresentationVisualizationTableSafe(value) {
287
684
  const normalized = normalizePraxisPresentationVisualization(value);
288
685
  return !!normalized && TABLE_SAFE_KINDS.has(normalized.kind);
289
686
  }
687
+ function computeMicroSvgIdSuffix(visualization, options) {
688
+ const ptsKey = visualization.points
689
+ ?.map((p) => `${p.label ?? ''}:${p.value}:${p.tone ?? ''}`)
690
+ .join(',') ?? '';
691
+ const seed = [
692
+ options.idPrefix ?? '',
693
+ visualization.kind,
694
+ visualization.surface ?? '',
695
+ visualization.tone ?? '',
696
+ String(visualization.value ?? ''),
697
+ String(visualization.total ?? ''),
698
+ String(visualization.target ?? ''),
699
+ visualization.fallbackText,
700
+ visualization.title ?? '',
701
+ ptsKey,
702
+ ].join('|');
703
+ let hash = 0x811c9dc5;
704
+ for (let i = 0; i < seed.length; i++) {
705
+ hash ^= seed.charCodeAt(i);
706
+ hash = Math.imul(hash, 0x01000193);
707
+ }
708
+ return (hash >>> 0).toString(36);
709
+ }
710
+ function resolveTargetReferenceLabel(visualization, options) {
711
+ if (visualization.targetLabel) {
712
+ return visualization.targetLabel;
713
+ }
714
+ return options.locale?.toLowerCase().startsWith('pt') ? 'Meta' : 'Target';
715
+ }
716
+ /**
717
+ * Returns a luminous 3-stop directional color ramp (`[highlight, mid, deep]`)
718
+ * for radial arcs, sector dials, and precision micro-visualizations.
719
+ */
720
+ function getPraxisMicroToneGradientStops(tone) {
721
+ switch (tone) {
722
+ case 'success':
723
+ return ['#bef264', '#22c55e', '#15803d'];
724
+ case 'info':
725
+ return ['#93c5fd', '#3b82f6', '#3730a3'];
726
+ case 'warning':
727
+ return ['#fde047', '#f59e0b', '#b45309'];
728
+ case 'danger':
729
+ case 'critical':
730
+ return ['#fda4af', '#f43f5e', '#be123c'];
731
+ case 'neutral':
732
+ default:
733
+ return ['#cbd5e1', '#64748b', '#334155'];
734
+ }
735
+ }
290
736
  function renderPraxisPresentationVisualizationHtml(value, options = {}) {
291
737
  const visualization = normalizePraxisPresentationVisualization(value);
292
738
  if (!visualization) {
@@ -313,56 +759,107 @@ function renderPraxisPresentationVisualizationHtml(value, options = {}) {
313
759
  return renderColumnVisualizationHtml(visualization, options);
314
760
  case 'processFlow':
315
761
  return renderProcessFlowVisualizationHtml(visualization, options);
762
+ case 'waterfall':
763
+ return renderWaterfallVisualizationHtml(visualization, options);
316
764
  default:
317
765
  return `<span class="pfx-micro-viz__fallback">${escapeHtml(visualization.fallbackText)}</span>`;
318
766
  }
319
767
  }
320
768
  function renderComparisonVisualizationHtml(visualization, options) {
321
- const points = visualization.points ?? [];
769
+ let points = visualization.points ?? [];
770
+ if (points.length === 0) {
771
+ const primaryValue = toFiniteNumber(visualization.value);
772
+ const referenceValue = toFiniteNumber(visualization.baseline) ?? toFiniteNumber(visualization.target);
773
+ if (primaryValue !== undefined) {
774
+ points = [
775
+ { value: primaryValue, tone: visualization.tone ?? 'info' },
776
+ ...(referenceValue !== undefined
777
+ ? [{ value: referenceValue, tone: 'neutral' }]
778
+ : []),
779
+ ];
780
+ }
781
+ }
322
782
  if (points.length === 0) {
323
783
  return renderFallbackVisualizationHtml(visualization, visualization.tone ?? 'neutral');
324
784
  }
325
- const max = Math.max(1, ...points.map((point) => Math.max(0, point.value)));
785
+ const explicitCeiling = Math.max(toFiniteNumber(visualization.max) ?? 0, toFiniteNumber(visualization.total) ?? 0);
786
+ const max = Math.max(1, explicitCeiling, ...points.map((point) => Math.max(0, point.value)));
787
+ const suffix = visualization.valueSuffix ?? '';
788
+ const useCompact = visualization.compactValue === true;
326
789
  const rows = points
327
790
  .map((point) => {
328
791
  const width = percent(point.value, max);
792
+ const formattedVal = formatVisualizationMetricValue(point.value, options, useCompact, suffix);
793
+ const alreadyPercent = (suffix.trim() === '%' || formattedVal.trim().endsWith('%')) && max === 100;
794
+ const readout = alreadyPercent
795
+ ? `${point.label ? `${point.label}: ` : ''}${formattedVal}`
796
+ : `${point.label ? `${point.label}: ` : ''}${formattedVal} (${Math.round(Number(width))}%)`;
329
797
  return `
330
- <span class="pfx-micro-viz__row" data-tone="${escapeHtml(point.tone ?? visualization.tone ?? 'info')}">
798
+ <span class="pfx-micro-viz__row" data-tone="${escapeHtml(point.tone ?? visualization.tone ?? 'info')}" data-micro-readout="${escapeHtml(readout)}">
331
799
  <span class="pfx-micro-viz__label">${escapeHtml(point.label ?? '')}</span>
332
800
  <span class="pfx-micro-viz__track">
333
801
  <span class="pfx-micro-viz__bar" style="width:${width}%"></span>
334
802
  </span>
335
- <span class="pfx-micro-viz__value">${escapeHtml(formatMicroNumber(point.value, options.locale))}</span>
803
+ <span class="pfx-micro-viz__value">${escapeHtml(formattedVal)}</span>
336
804
  </span>`;
337
805
  })
338
806
  .join('');
339
- return `<span class="pfx-micro-viz" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">${rows}</span>`;
807
+ return `<span class="pfx-micro-viz pfx-micro-viz__comparison" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">${rows}</span>`;
340
808
  }
341
809
  function renderStackedBarVisualizationHtml(visualization, options) {
342
- const segments = visualization.segments ?? [];
810
+ const segments = resolvePraxisStackedBarSegments(visualization);
343
811
  if (segments.length === 0) {
344
812
  return renderFallbackVisualizationHtml(visualization, visualization.tone ?? 'neutral');
345
813
  }
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));
814
+ const isTable = visualization.surface === 'table-cell';
815
+ const resolvedTotal = resolvePraxisStackedBarTotal(segments, visualization.total);
816
+ const suffix = visualization.valueSuffix ?? '';
817
+ const useCompact = visualization.compactValue === true;
818
+ const fallbackTone = visualization.tone ?? 'neutral';
819
+ const aria = resolvePraxisStackedBarAriaLabel(visualization, segments, resolvedTotal, options.locale);
820
+ const buildSegmentReadout = (segment) => {
821
+ const formattedVal = formatVisualizationMetricValue(segment.value, options, useCompact, suffix);
822
+ const pctText = formatPraxisStackedBarPercentage(segment.value, resolvedTotal, options.locale);
823
+ const alreadyPercent = suffix.trim() === '%' || formattedVal.trim().endsWith('%');
824
+ const metricPart = alreadyPercent ? formattedVal : `${formattedVal} (${pctText})`;
825
+ return segment.label ? `${segment.label}: ${metricPart}` : metricPart;
826
+ };
349
827
  const bars = segments
350
- .map((segment) => `
828
+ .map((segment) => {
829
+ const widthPct = computePraxisStackedBarSegmentWidthPct(segment.value, resolvedTotal);
830
+ const isZero = segment.value === 0 || widthPct === 0;
831
+ const paint = getPraxisStackedBarPaintStyle(segment, fallbackTone);
832
+ const paintCss = `--prx-micro-category-color:${paint['--prx-micro-category-color']};color:${paint['color']}`;
833
+ const readout = buildSegmentReadout(segment);
834
+ return `
351
835
  <span
352
836
  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>`)
837
+ data-tone="${escapeHtml(segment.tone ?? fallbackTone)}"${isZero ? '\n data-zero="true"' : ''}
838
+ data-micro-readout="${escapeHtml(readout)}"
839
+ style="width:${widthPct}%;${escapeHtml(paintCss)}"
840
+ ></span>`;
841
+ })
361
842
  .join('');
843
+ const titleHtml = !isTable && visualization.title
844
+ ? `\n <span class="pfx-micro-viz__title">${escapeHtml(visualization.title)}</span>`
845
+ : '';
846
+ const legendHtml = !isTable && visualization.legend === true
847
+ ? `\n <span class="pfx-micro-viz__legend" role="list">${segments
848
+ .map((segment) => {
849
+ const paint = getPraxisStackedBarPaintStyle(segment, fallbackTone);
850
+ const paintCss = `--prx-micro-category-color:${paint['--prx-micro-category-color']};color:${paint['color']}`;
851
+ const pctText = formatPraxisStackedBarPercentage(segment.value, resolvedTotal, options.locale);
852
+ const readout = buildSegmentReadout(segment);
853
+ 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>`;
854
+ })
855
+ .join('')}</span>`
856
+ : '';
857
+ const suppressedAttr = visualization.suppressedCount
858
+ ? ` data-suppressed-count="${visualization.suppressedCount}"`
859
+ : '';
362
860
  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>
861
+ <span class="pfx-micro-viz pfx-micro-viz__stacked" role="img" aria-label="${escapeHtml(aria)}"${suppressedAttr}>${titleHtml}
862
+ <span class="pfx-micro-viz__segments">${bars}</span>${legendHtml}
366
863
  </span>`;
367
864
  }
368
865
  function resolveBulletMax(visualization) {
@@ -374,9 +871,15 @@ function resolveBulletMax(visualization) {
374
871
  toFiniteNumber(visualization.value) ?? 0,
375
872
  visualization.target ?? 0,
376
873
  visualization.total ?? 0,
874
+ visualization.max ?? 0,
377
875
  ...thresholdValues
378
876
  ].filter((v) => Number.isFinite(v) && v > 0);
379
- return Math.max(...values, 100);
877
+ const fallbackCeiling = visualization.total && visualization.total > 0
878
+ ? visualization.total
879
+ : visualization.max && visualization.max > 0
880
+ ? visualization.max
881
+ : 100;
882
+ return Math.max(...values, fallbackCeiling);
380
883
  }
381
884
  function renderBulletVisualizationHtml(visualization, options) {
382
885
  const currentValue = toFiniteNumber(visualization.value);
@@ -387,6 +890,7 @@ function renderBulletVisualizationHtml(visualization, options) {
387
890
  const target = toFiniteNumber(visualization.target);
388
891
  const targetLeft = target === undefined ? null : percent(target, max);
389
892
  const isTable = visualization.surface === 'table-cell';
893
+ const suffix = visualization.valueSuffix ?? '';
390
894
  // thresholds: sort ascending by boundary value so bands draw continuously regardless of declaration order
391
895
  const thresholds = visualization.thresholds ?? [];
392
896
  const sortedThresholds = [...thresholds].sort((a, b) => {
@@ -404,28 +908,46 @@ function renderBulletVisualizationHtml(visualization, options) {
404
908
  return { left, width, tone: t.tone ?? 'info' };
405
909
  }).filter(b => parseFloat(b.width) > 0);
406
910
  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('');
911
+ const bandsLayerHtml = bandsHtml
912
+ ? `<span class="pfx-micro-bullet__bands">${bandsHtml}</span>`
913
+ : '';
914
+ const targetLabel = resolveTargetReferenceLabel(visualization, options);
915
+ const topMetricHtml = visualization.compactValue === false
916
+ ? target === undefined
917
+ ? ''
918
+ : `<span class="pfx-micro-bullet__target-val">${escapeHtml(targetLabel)}: ${escapeHtml(formatVisualizationMetricValue(target, options, false, suffix))}</span>`
919
+ : `<span class="pfx-micro-bullet__value">
920
+ ${escapeHtml(formatVisualizationMetricValue(currentValue, options, false, suffix))}
921
+ ${target === undefined ? '' : `<span class="pfx-micro-bullet__target-val">/ ${escapeHtml(targetLabel)}: ${escapeHtml(formatVisualizationMetricValue(target, options, false, suffix))}</span>`}
922
+ </span>`;
407
923
  const topHtml = isTable ? '' : `
408
924
  <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>
925
+ <span class="pfx-micro-bullet__label">${escapeHtml(visualization.title || visualization.fallbackText)}</span>
926
+ ${topMetricHtml}
414
927
  </div>`;
415
928
  const bottomHtml = isTable ? '' : `
416
929
  <div class="pfx-micro-bullet__bottom">
417
- <span>${escapeHtml(formatMicroNumber(visualization.baseline ?? 0, options.locale))}</span>
418
- <span>${escapeHtml(formatMicroNumber(max, options.locale))}</span>
930
+ <span>${escapeHtml(formatVisualizationMetricValue(visualization.baseline ?? 0, options, false, suffix))}</span>
931
+ <span>${escapeHtml(formatVisualizationMetricValue(max, options, false, suffix))}</span>
419
932
  </div>`;
420
933
  const showCompactValue = isTable && visualization.compactValue !== false;
934
+ const useCompactNotation = visualization.compactValue === true;
421
935
  const compactValueHtml = showCompactValue
422
- ? `<span class="pfx-micro-bullet__compact-value">${escapeHtml(formatMicroNumber(currentValue, options.locale))}${escapeHtml(visualization.valueSuffix ?? '')}</span>`
936
+ ? `<span class="pfx-micro-bullet__compact-value">${escapeHtml(formatVisualizationMetricValue(currentValue, options, useCompactNotation, suffix))}</span>`
423
937
  : '';
938
+ const currentStr = formatVisualizationMetricValue(currentValue, options, false, suffix);
939
+ const diff = target !== undefined ? currentValue - target : undefined;
940
+ const diffSign = diff !== undefined && diff > 0 ? '+' : '';
941
+ const bulletReadout = target !== undefined && diff !== undefined
942
+ ? `${currentStr} / ${targetLabel} ${formatVisualizationMetricValue(target, options, false, suffix)} (${diffSign}${formatVisualizationMetricValue(diff, options, false, suffix)})`
943
+ : `${currentStr} / ${formatVisualizationMetricValue(max, options, false, suffix)}`;
944
+ const suppressTabIndex = isTable || options.interactiveContainer === true;
945
+ const tabIndexAttr = suppressTabIndex ? '' : ' tabindex="0"';
424
946
  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)}">
947
+ <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
948
  ${topHtml}
427
949
  <span class="pfx-micro-bullet__track">
428
- ${bandsHtml}
950
+ ${bandsLayerHtml}
429
951
  <span class="pfx-micro-bullet__actual" data-tone="${escapeHtml(visualization.tone ?? 'info')}" style="width: ${percent(currentValue, max)}%;"></span>
430
952
  ${targetLeft === null ? '' : `<span class="pfx-micro-bullet__target" style="left: ${targetLeft}%;"></span>`}
431
953
  </span>
@@ -448,15 +970,28 @@ function renderDeltaVisualizationHtml(visualization, options) {
448
970
  const valueSuffix = visualization.valueSuffix ?? '';
449
971
  const text = value === undefined
450
972
  ? visualization.fallbackText
451
- : `${formatMicroNumber(Math.abs(value), options.locale)}${valueSuffix}`;
973
+ : formatVisualizationMetricValue(Math.abs(value), options, visualization.compactValue === true, valueSuffix);
452
974
  const directionLabel = direction === 'up'
453
975
  ? 'up'
454
976
  : direction === 'down'
455
977
  ? 'down'
456
978
  : 'stable';
457
979
  const aria = visualization.ariaLabel ?? `${visualization.fallbackText}: ${directionLabel} ${text}`;
980
+ const target = toFiniteNumber(visualization.target);
981
+ const baseline = toFiniteNumber(visualization.baseline);
982
+ const isTable = visualization.surface === 'table-cell';
983
+ const suppressTabIndex = isTable || options.interactiveContainer === true;
984
+ const targetLabel = resolveTargetReferenceLabel(visualization, options);
985
+ const deltaReadout = target !== undefined
986
+ ? `${targetLabel} ${formatVisualizationMetricValue(target, options, false, valueSuffix)}`
987
+ : baseline !== undefined
988
+ ? `Base ${formatVisualizationMetricValue(baseline, options, false, valueSuffix)}`
989
+ : null;
990
+ const readoutAttr = deltaReadout
991
+ ? `${suppressTabIndex ? '' : ' tabindex="0"'} data-micro-readout="${escapeHtml(deltaReadout)}"`
992
+ : '';
458
993
  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)}">
994
+ <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
995
  <span class="pfx-micro-viz__delta-symbol" aria-hidden="true">${symbol}</span>
461
996
  <span>${escapeHtml(text)}</span>
462
997
  </span>`;
@@ -468,11 +1003,40 @@ function percent(value, total) {
468
1003
  return Math.max(0, Math.min(100, (value / total) * 100)).toFixed(2);
469
1004
  }
470
1005
  function toFiniteNumber(value) {
471
- return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
1006
+ if (typeof value === 'number') {
1007
+ return Number.isFinite(value) ? value : undefined;
1008
+ }
1009
+ if (typeof value === 'string') {
1010
+ const trimmed = value.trim();
1011
+ if (!trimmed) {
1012
+ return undefined;
1013
+ }
1014
+ const parsed = Number(trimmed);
1015
+ return Number.isFinite(parsed) ? parsed : undefined;
1016
+ }
1017
+ return undefined;
1018
+ }
1019
+ function formatVisualizationMetricValue(value, options, compactValue = false, suffix = '') {
1020
+ if (typeof options.formatValue === 'function') {
1021
+ const custom = options.formatValue(value, compactValue);
1022
+ if (typeof custom === 'string' && custom.trim().length > 0) {
1023
+ return suffix && !custom.endsWith(suffix) ? `${custom}${suffix}` : custom;
1024
+ }
1025
+ }
1026
+ return `${formatMicroNumber(value, options.locale, compactValue)}${suffix}`;
472
1027
  }
473
- function formatMicroNumber(value, locale) {
1028
+ function formatMicroNumber(value, locale, compactValue = false) {
1029
+ if (compactValue && Math.abs(value) >= 1000) {
1030
+ return new Intl.NumberFormat(locale || undefined, {
1031
+ notation: 'compact',
1032
+ compactDisplay: 'short',
1033
+ maximumFractionDigits: 1,
1034
+ }).format(value);
1035
+ }
1036
+ const abs = Math.abs(value);
1037
+ const hasFraction = Math.abs(value - Math.trunc(value)) > 1e-6;
474
1038
  return new Intl.NumberFormat(locale || undefined, {
475
- maximumFractionDigits: Math.abs(value) < 10 ? 2 : 0,
1039
+ maximumFractionDigits: abs < 10 ? 2 : hasFraction && abs < 1000 ? 1 : 0,
476
1040
  }).format(value);
477
1041
  }
478
1042
  function escapeHtml(value) {
@@ -545,21 +1109,31 @@ function normalizeNumericEntries(value) {
545
1109
  }
546
1110
  return value
547
1111
  .map((item) => {
548
- if (!item || typeof item !== 'object' || !Number.isFinite(item.value)) {
1112
+ if (typeof item === 'number' || typeof item === 'string') {
1113
+ const num = toFiniteNumber(item);
1114
+ return num !== undefined ? { value: num } : null;
1115
+ }
1116
+ if (!item || typeof item !== 'object' || isVisualizationEntrySuppressed(item)) {
1117
+ return null;
1118
+ }
1119
+ const num = toFiniteNumber(item.value);
1120
+ if (num === undefined) {
549
1121
  return null;
550
1122
  }
551
1123
  const label = normalizeText$1(item.label);
552
1124
  const tone = normalizeEnum$1(item.tone, VISUALIZATION_TONES);
1125
+ const color = normalizePraxisHexColor(item.color);
553
1126
  return {
554
- value: item.value,
1127
+ value: num,
555
1128
  ...(label ? { label } : {}),
556
1129
  ...(tone ? { tone } : {}),
1130
+ ...(color ? { color } : {}),
557
1131
  };
558
1132
  })
559
1133
  .filter((item) => !!item);
560
1134
  }
561
1135
  function normalizeVisualizationItem(item) {
562
- if (!item || typeof item !== 'object') {
1136
+ if (!item || typeof item !== 'object' || isVisualizationEntrySuppressed(item)) {
563
1137
  return null;
564
1138
  }
565
1139
  const id = normalizeText$1(item.id);
@@ -567,8 +1141,10 @@ function normalizeVisualizationItem(item) {
567
1141
  const icon = normalizeText$1(item.icon);
568
1142
  const state = normalizeText$1(item.state);
569
1143
  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) {
1144
+ const role = normalizeEnum$1(item.role, WATERFALL_ROLES);
1145
+ const color = normalizePraxisHexColor(item.color);
1146
+ const normalizedValue = toFiniteNumber(item.value);
1147
+ if (!id && !label && normalizedValue === undefined && !icon && !state && !tone && !role && !color) {
572
1148
  return null;
573
1149
  }
574
1150
  return {
@@ -578,10 +1154,13 @@ function normalizeVisualizationItem(item) {
578
1154
  ...(icon ? { icon } : {}),
579
1155
  ...(state ? { state } : {}),
580
1156
  ...(tone ? { tone } : {}),
1157
+ ...(role ? { role } : {}),
1158
+ ...(color ? { color } : {}),
581
1159
  };
582
1160
  }
583
1161
  function normalizeNumber(value, key) {
584
- return Number.isFinite(value) ? { [key]: value } : undefined;
1162
+ const num = toFiniteNumber(value);
1163
+ return num !== undefined ? { [key]: num } : undefined;
585
1164
  }
586
1165
  function normalizeEnum$1(value, allowed) {
587
1166
  if (typeof value !== 'string') {
@@ -603,23 +1182,62 @@ function renderRadialVisualizationHtml(visualization, options) {
603
1182
  return renderFallbackVisualizationHtml(visualization, visualization.tone ?? 'neutral');
604
1183
  }
605
1184
  const total = visualization.total && visualization.total > 0 ? visualization.total : 100;
606
- const pct = Math.max(0, Math.min(100, (value / total) * 100));
1185
+ const rawPct = Math.max(0, (value / total) * 100);
1186
+ const arcPct = Math.min(100, rawPct);
607
1187
  const tone = visualization.tone ?? 'info';
608
- const dashArray = `${pct.toFixed(1)}, 100`;
609
- const pctText = `${Math.round(pct)}%`;
1188
+ const suffix = visualization.valueSuffix ?? '';
1189
+ const dashArray = `${arcPct.toFixed(1)}, 100`;
1190
+ const hasFractionalPct = rawPct < 100 && Math.abs(rawPct - Math.round(rawPct)) >= 0.05;
1191
+ const displayPctNum = hasFractionalPct ? Number(rawPct.toFixed(1)) : Math.round(rawPct);
1192
+ const radialNumStr = formatMicroNumber(displayPctNum, options.locale, false);
1193
+ const pctText = `${radialNumStr}%`;
610
1194
  const aria = visualization.ariaLabel ?? `${visualization.fallbackText} (${pctText})`;
611
1195
  const isTable = visualization.surface === 'table-cell';
1196
+ const isZero = rawPct <= 0;
1197
+ const svgSuffix = computeMicroSvgIdSuffix(visualization, options);
1198
+ const gradId = `pfx-rad-grad-${tone}-${svgSuffix}`;
1199
+ const [stop0, stop1, stop2] = getPraxisMicroToneGradientStops(tone);
1200
+ const targetVal = toFiniteNumber(visualization.target);
1201
+ const targetPct = targetVal !== undefined && targetVal > 0
1202
+ ? Math.max(0, Math.min(100, (targetVal / total) * 100))
1203
+ : null;
1204
+ const targetArcHtml = targetPct !== null
1205
+ ? `<circle class="pfx-micro-radial-svg__target-arc" cx="18" cy="18" r="13.8" pathLength="100" stroke-dasharray="${targetPct.toFixed(1)}, 100" transform="rotate(-90 18 18)" />`
1206
+ : '';
1207
+ const digitTierAttr = radialNumStr.length >= 4
1208
+ ? ' data-digits="4"'
1209
+ : radialNumStr.length === 3
1210
+ ? ' data-digits="3"'
1211
+ : '';
612
1212
  const svgText = isTable
613
1213
  ? ''
614
- : `<text x="18" y="21" class="pfx-micro-radial-svg__text">${escapeHtml(pctText)}</text>`;
1214
+ : `<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
1215
  const externalText = isTable
616
1216
  ? `<span class="pfx-micro-radial-value">${escapeHtml(pctText)}</span>`
617
1217
  : '';
1218
+ const formattedVal = formatVisualizationMetricValue(value, options, false, suffix);
1219
+ const formattedTotal = formatVisualizationMetricValue(total, options, false, suffix);
1220
+ const alreadyPercent = (suffix.trim() === '%' || formattedVal.trim().endsWith('%')) && total === 100;
1221
+ const radialReadout = alreadyPercent
1222
+ ? formattedVal
1223
+ : `${formattedVal} / ${formattedTotal} (${pctText})`;
1224
+ const suppressTabIndex = isTable || options.interactiveContainer === true;
1225
+ const tabIndexAttr = suppressTabIndex ? '' : ' tabindex="0"';
618
1226
  return `
619
- <span class="pfx-micro-viz pfx-micro-viz__radial" data-tone="${escapeHtml(tone)}" role="img" aria-label="${escapeHtml(aria)}">
1227
+ <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
1228
  <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)" />
1229
+ <defs>
1230
+ <linearGradient id="${escapeHtml(gradId)}" x1="100%" y1="55%" x2="10%" y2="15%">
1231
+ <stop offset="0%" stop-color="${stop0}" />
1232
+ <stop offset="52%" stop-color="${stop1}" />
1233
+ <stop offset="100%" stop-color="${stop2}" />
1234
+ </linearGradient>
1235
+ </defs>
1236
+ <circle class="pfx-micro-radial-svg__bezel" cx="18" cy="18" r="17" />
1237
+ <circle class="pfx-micro-radial-svg__track" cx="18" cy="18" r="13.8" pathLength="100" />
1238
+ ${targetArcHtml}
1239
+ <circle class="pfx-micro-radial-svg__bar" cx="18" cy="18" r="13.8" pathLength="100"${isZero ? ' data-zero="true"' : ''} stroke="url(#${escapeHtml(gradId)})" stroke-dasharray="${dashArray}" transform="rotate(-90 18 18)" />
1240
+ <circle class="pfx-micro-radial-svg__medallion" cx="18" cy="18" r="10.9" />
623
1241
  ${svgText}
624
1242
  </svg>
625
1243
  ${externalText}
@@ -631,37 +1249,100 @@ function renderHarveyBallVisualizationHtml(visualization, options) {
631
1249
  return renderFallbackVisualizationHtml(visualization, visualization.tone ?? 'neutral');
632
1250
  }
633
1251
  const total = visualization.total && visualization.total > 0 ? visualization.total : 100;
634
- const pct = Math.max(0, Math.min(100, (value / total) * 100));
1252
+ const rawPct = Math.max(0, (value / total) * 100);
1253
+ const arcPct = Math.min(100, rawPct);
635
1254
  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)}%)`;
1255
+ const isTable = visualization.surface === 'table-cell';
1256
+ const suppressTabIndex = isTable || options.interactiveContainer === true;
1257
+ const tabIndexAttr = suppressTabIndex ? '' : ' tabindex="0"';
1258
+ const suffix = visualization.valueSuffix ?? '';
1259
+ const isZero = rawPct <= 0;
1260
+ const svgSuffix = computeMicroSvgIdSuffix(visualization, options);
1261
+ const gradId = `pfx-harvey-grad-${tone}-${svgSuffix}`;
1262
+ const [stop0, stop1, stop2] = getPraxisMicroToneGradientStops(tone);
1263
+ const dashArray = `${arcPct.toFixed(2)} 100`;
1264
+ const roundedPct = Math.round(rawPct);
1265
+ const aria = visualization.ariaLabel ?? `${visualization.fallbackText} (${roundedPct}%)`;
1266
+ const formattedValue = formatVisualizationMetricValue(value, options, false, suffix);
1267
+ const formattedTotal = formatVisualizationMetricValue(total, options, false, suffix);
1268
+ const harveyReadout = `${formattedValue}/${formattedTotal} (${roundedPct}%)`;
1269
+ const pctBadgeHtml = isTable
1270
+ ? ''
1271
+ : `<span class="pfx-micro-harvey-pct">${roundedPct}%</span>`;
639
1272
  return `
640
- <span class="pfx-micro-viz pfx-micro-viz__harvey" data-tone="${escapeHtml(tone)}" role="img" aria-label="${escapeHtml(aria)}">
1273
+ <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
1274
  <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)" />
1275
+ <defs>
1276
+ <linearGradient id="${escapeHtml(gradId)}" x1="15%" y1="10%" x2="85%" y2="90%">
1277
+ <stop offset="0%" stop-color="${stop0}" />
1278
+ <stop offset="52%" stop-color="${stop1}" />
1279
+ <stop offset="100%" stop-color="${stop2}" />
1280
+ </linearGradient>
1281
+ </defs>
1282
+ <circle class="pfx-micro-harvey-svg__bezel" cx="18" cy="18" r="16.8" />
1283
+ <circle class="pfx-micro-harvey-svg__track" cx="18" cy="18" r="14" />
1284
+ <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)" />
1285
+ <circle class="pfx-micro-harvey-svg__pin" cx="18" cy="18" r="1.8" />
644
1286
  </svg>
645
1287
  <span class="pfx-micro-harvey-fraction">
646
- <strong>${escapeHtml(formatMicroNumber(value, options.locale))}</strong>
1288
+ <strong>${escapeHtml(formattedValue)}</strong>
647
1289
  <span class="pfx-separator">/</span>
648
- <span class="pfx-total">${escapeHtml(formatMicroNumber(total, options.locale))}</span>
1290
+ <span class="pfx-total">${escapeHtml(formattedTotal)}</span>
649
1291
  </span>
1292
+ ${pctBadgeHtml}
650
1293
  </span>`;
651
1294
  }
652
- function getPointsCoordinates(points, width, height, padding) {
1295
+ function resolveTrendBounds(points, visualization, anchorZero = false) {
1296
+ const values = points.map((p) => p.value);
1297
+ const refValue = toFiniteNumber(visualization?.target) ?? toFiniteNumber(visualization?.baseline);
1298
+ const explicitMin = toFiniteNumber(visualization?.min);
1299
+ const explicitMax = toFiniteNumber(visualization?.max);
1300
+ const baseCandidates = anchorZero ? [...values, 0] : [...values];
1301
+ if (refValue !== undefined) {
1302
+ baseCandidates.push(refValue);
1303
+ }
1304
+ const minVal = explicitMin !== undefined ? Math.min(explicitMin, ...baseCandidates) : Math.min(...baseCandidates);
1305
+ const maxVal = explicitMax !== undefined ? Math.max(explicitMax, ...baseCandidates) : Math.max(...baseCandidates);
1306
+ const valRange = maxVal - minVal === 0 ? 1 : maxVal - minVal;
1307
+ return { minVal, maxVal, valRange, refValue };
1308
+ }
1309
+ function getPointsCoordinates(points, width, height, padding, visualization) {
653
1310
  if (points.length < 2)
654
1311
  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;
1312
+ const { minVal, valRange } = resolveTrendBounds(points, visualization, false);
659
1313
  return points.map((p, index) => {
660
1314
  const x = padding + (index / (points.length - 1)) * (width - 2 * padding);
661
1315
  const y = height - padding - ((p.value - minVal) / valRange) * (height - 2 * padding);
662
1316
  return { x, y };
663
1317
  });
664
1318
  }
1319
+ function renderTrendReferenceLineHtml(points, width, height, padding, visualization, anchorZero = false) {
1320
+ const { minVal, valRange, refValue } = resolveTrendBounds(points, visualization, anchorZero);
1321
+ if (refValue === undefined) {
1322
+ return '';
1323
+ }
1324
+ const refY = height - padding - ((refValue - minVal) / valRange) * (height - 2 * padding);
1325
+ 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" />`;
1326
+ }
1327
+ function renderTrendScrubLayerHtml(points, coords, width, height, visualization, options) {
1328
+ const defaultTone = visualization.tone ?? 'info';
1329
+ const suffix = visualization.valueSuffix ?? '';
1330
+ const slicesHtml = points
1331
+ .map((point, index) => {
1332
+ const coord = coords[index] ?? { x: 50, y: 15 };
1333
+ const xPct = ((coord.x / width) * 100).toFixed(1);
1334
+ const yPct = ((coord.y / height) * 100).toFixed(1);
1335
+ const pointTone = point.tone ??
1336
+ (visualization.thresholds?.length
1337
+ ? resolvePraxisMicroVisualizationTone(point.value, visualization.thresholds)?.tone ?? defaultTone
1338
+ : defaultTone);
1339
+ const labelPrefix = point.label ? `${point.label}: ` : `#${index + 1}: `;
1340
+ const readout = `${labelPrefix}${formatVisualizationMetricValue(point.value, options, visualization.compactValue === true, suffix)}`;
1341
+ 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>`;
1342
+ })
1343
+ .join('');
1344
+ return `<span class="pfx-micro-trend__scrub-layer" aria-hidden="true">${slicesHtml}</span>`;
1345
+ }
665
1346
  function renderLineVisualizationHtml(visualization, options) {
666
1347
  const points = visualization.points ?? [];
667
1348
  const tone = visualization.tone ?? 'info';
@@ -671,8 +1352,14 @@ function renderLineVisualizationHtml(visualization, options) {
671
1352
  const width = 100;
672
1353
  const height = 30;
673
1354
  const padding = 4;
674
- const coords = getPointsCoordinates(points, width, height, padding);
1355
+ const coords = getPointsCoordinates(points, width, height, padding, visualization);
675
1356
  const pathD = coords.map((c, i) => `${i === 0 ? 'M' : 'L'} ${c.x.toFixed(1)} ${c.y.toFixed(1)}`).join(' ');
1357
+ const firstX = coords[0].x.toFixed(1);
1358
+ const lastCoord = coords[coords.length - 1];
1359
+ const lastX = lastCoord.x.toFixed(1);
1360
+ const glowAreaD = `${pathD} L ${lastX} ${height} L ${firstX} ${height} Z`;
1361
+ const glowGradId = `pfx-line-glow-${tone}-${computeMicroSvgIdSuffix(visualization, options)}`;
1362
+ const refLineHtml = renderTrendReferenceLineHtml(points, width, height, padding, visualization, false);
676
1363
  // Highlight extreme/boundary values
677
1364
  let minIdx = 0;
678
1365
  let maxIdx = 0;
@@ -682,9 +1369,10 @@ function renderLineVisualizationHtml(visualization, options) {
682
1369
  if (points[i].value > points[maxIdx].value)
683
1370
  maxIdx = i;
684
1371
  }
1372
+ const lastTone = points[points.length - 1].tone ?? tone;
685
1373
  const markers = [
686
1374
  { 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 }
1375
+ { x: lastCoord.x, y: lastCoord.y, tone: lastTone }
688
1376
  ];
689
1377
  if (minIdx !== 0 && minIdx !== coords.length - 1) {
690
1378
  markers.push({ x: coords[minIdx].x, y: coords[minIdx].y, tone: points[minIdx].tone ?? 'danger' });
@@ -692,18 +1380,21 @@ function renderLineVisualizationHtml(visualization, options) {
692
1380
  if (maxIdx !== 0 && maxIdx !== coords.length - 1) {
693
1381
  markers.push({ x: coords[maxIdx].x, y: coords[maxIdx].y, tone: points[maxIdx].tone ?? 'success' });
694
1382
  }
1383
+ 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
1384
  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('');
1385
+ const scrubLayerHtml = renderTrendScrubLayerHtml(points, coords, width, height, visualization, options);
696
1386
  const isTable = visualization.surface === 'table-cell';
697
1387
  const firstPoint = points[0];
698
1388
  const lastPoint = points[points.length - 1];
1389
+ const suffix = visualization.valueSuffix ?? '';
699
1390
  const leftHtml = isTable ? '' : `
700
1391
  <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>
1392
+ <span class="pfx-micro-trend__value">${escapeHtml(formatVisualizationMetricValue(firstPoint.value, options, visualization.compactValue === true, suffix))}</span>
702
1393
  ${firstPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(firstPoint.label)}</span>` : ''}
703
1394
  </div>`;
704
1395
  const rightHtml = isTable ? '' : `
705
1396
  <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>
1397
+ <span class="pfx-micro-trend__value">${escapeHtml(formatVisualizationMetricValue(lastPoint.value, options, visualization.compactValue === true, suffix))}</span>
707
1398
  ${lastPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(lastPoint.label)}</span>` : ''}
708
1399
  </div>`;
709
1400
  return `
@@ -711,9 +1402,12 @@ function renderLineVisualizationHtml(visualization, options) {
711
1402
  ${leftHtml}
712
1403
  <span class="pfx-micro-viz pfx-micro-viz__line" data-tone="${escapeHtml(tone)}" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">
713
1404
  <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" />
1405
+ ${refLineHtml}
1406
+ <path class="pfx-micro-line__path" d="${pathD}" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" />
1407
+ ${endpointHaloHtml}
715
1408
  ${circlesHtml}
716
1409
  </svg>
1410
+ ${scrubLayerHtml}
717
1411
  </span>
718
1412
  ${rightHtml}
719
1413
  </span>`;
@@ -727,11 +1421,14 @@ function renderAreaVisualizationHtml(visualization, options) {
727
1421
  const width = 100;
728
1422
  const height = 30;
729
1423
  const padding = 4;
730
- const coords = getPointsCoordinates(points, width, height, padding);
1424
+ const coords = getPointsCoordinates(points, width, height, padding, visualization);
731
1425
  const lineD = coords.map((c, i) => `${i === 0 ? 'M' : 'L'} ${c.x.toFixed(1)} ${c.y.toFixed(1)}`).join(' ');
1426
+ const refLineHtml = renderTrendReferenceLineHtml(points, width, height, padding, visualization, false);
732
1427
  const firstX = coords[0].x.toFixed(1);
733
- const lastX = coords[coords.length - 1].x.toFixed(1);
1428
+ const lastCoord = coords[coords.length - 1];
1429
+ const lastX = lastCoord.x.toFixed(1);
734
1430
  const areaD = `${lineD} L ${lastX} ${height} L ${firstX} ${height} Z`;
1431
+ const areaGradId = `pfx-area-grad-${tone}-${computeMicroSvgIdSuffix(visualization, options)}`;
735
1432
  // Highlight extreme/boundary values
736
1433
  let minIdx = 0;
737
1434
  let maxIdx = 0;
@@ -741,9 +1438,10 @@ function renderAreaVisualizationHtml(visualization, options) {
741
1438
  if (points[i].value > points[maxIdx].value)
742
1439
  maxIdx = i;
743
1440
  }
1441
+ const lastTone = points[points.length - 1].tone ?? tone;
744
1442
  const markers = [
745
1443
  { 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 }
1444
+ { x: lastCoord.x, y: lastCoord.y, tone: lastTone }
747
1445
  ];
748
1446
  if (minIdx !== 0 && minIdx !== coords.length - 1) {
749
1447
  markers.push({ x: coords[minIdx].x, y: coords[minIdx].y, tone: points[minIdx].tone ?? 'danger' });
@@ -751,18 +1449,21 @@ function renderAreaVisualizationHtml(visualization, options) {
751
1449
  if (maxIdx !== 0 && maxIdx !== coords.length - 1) {
752
1450
  markers.push({ x: coords[maxIdx].x, y: coords[maxIdx].y, tone: points[maxIdx].tone ?? 'success' });
753
1451
  }
1452
+ 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
1453
  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('');
1454
+ const scrubLayerHtml = renderTrendScrubLayerHtml(points, coords, width, height, visualization, options);
755
1455
  const isTable = visualization.surface === 'table-cell';
756
1456
  const firstPoint = points[0];
757
1457
  const lastPoint = points[points.length - 1];
1458
+ const suffix = visualization.valueSuffix ?? '';
758
1459
  const leftHtml = isTable ? '' : `
759
1460
  <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>
1461
+ <span class="pfx-micro-trend__value">${escapeHtml(formatVisualizationMetricValue(firstPoint.value, options, visualization.compactValue === true, suffix))}</span>
761
1462
  ${firstPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(firstPoint.label)}</span>` : ''}
762
1463
  </div>`;
763
1464
  const rightHtml = isTable ? '' : `
764
1465
  <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>
1466
+ <span class="pfx-micro-trend__value">${escapeHtml(formatVisualizationMetricValue(lastPoint.value, options, visualization.compactValue === true, suffix))}</span>
766
1467
  ${lastPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(lastPoint.label)}</span>` : ''}
767
1468
  </div>`;
768
1469
  return `
@@ -770,10 +1471,19 @@ function renderAreaVisualizationHtml(visualization, options) {
770
1471
  ${leftHtml}
771
1472
  <span class="pfx-micro-viz pfx-micro-viz__area" data-tone="${escapeHtml(tone)}" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">
772
1473
  <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" />
1474
+ <defs>
1475
+ <linearGradient id="${escapeHtml(areaGradId)}" x1="0%" y1="0%" x2="0%" y2="100%">
1476
+ <stop offset="0%" stop-color="currentColor" stop-opacity="0.32" />
1477
+ <stop offset="100%" stop-color="currentColor" stop-opacity="0.02" />
1478
+ </linearGradient>
1479
+ </defs>
1480
+ ${refLineHtml}
1481
+ <path class="pfx-micro-area__fill" d="${areaD}" fill="url(#${escapeHtml(areaGradId)})" />
1482
+ <path class="pfx-micro-area__path" d="${lineD}" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" />
1483
+ ${endpointHaloHtml}
775
1484
  ${circlesHtml}
776
1485
  </svg>
1486
+ ${scrubLayerHtml}
777
1487
  </span>
778
1488
  ${rightHtml}
779
1489
  </span>`;
@@ -787,32 +1497,35 @@ function renderColumnVisualizationHtml(visualization, options) {
787
1497
  const width = 100;
788
1498
  const height = 30;
789
1499
  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;
1500
+ const { minVal, valRange } = resolveTrendBounds(points, visualization, true);
1501
+ const refLineHtml = renderTrendReferenceLineHtml(points, width, height, padding, visualization, true);
794
1502
  const colWidth = Math.max(2, (width - 2 * padding) / points.length - 2);
1503
+ const colCoords = [];
795
1504
  const columnsHtml = points.map((p, i) => {
796
1505
  const x = padding + i * ((width - 2 * padding) / points.length) + 1;
797
1506
  const rectHeight = Math.max(2, ((p.value - minVal) / valRange) * (height - 2 * padding));
798
1507
  const rectY = height - padding - rectHeight;
1508
+ colCoords.push({ x: x + colWidth / 2, y: rectY });
799
1509
  const itemTone = p.tone ??
800
1510
  (visualization.thresholds?.length
801
1511
  ? resolvePraxisMicroVisualizationTone(p.value, visualization.thresholds)?.tone ?? tone
802
1512
  : 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)}" />`;
1513
+ const latestAttr = i === points.length - 1 ? ' data-latest="true"' : '';
1514
+ 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
1515
  }).join('');
1516
+ const scrubLayerHtml = renderTrendScrubLayerHtml(points, colCoords, width, height, visualization, options);
805
1517
  const isTable = visualization.surface === 'table-cell';
806
1518
  const firstPoint = points[0];
807
1519
  const lastPoint = points[points.length - 1];
1520
+ const suffix = visualization.valueSuffix ?? '';
808
1521
  const leftHtml = isTable ? '' : `
809
1522
  <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>
1523
+ <span class="pfx-micro-trend__value">${escapeHtml(formatVisualizationMetricValue(firstPoint.value, options, visualization.compactValue === true, suffix))}</span>
811
1524
  ${firstPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(firstPoint.label)}</span>` : ''}
812
1525
  </div>`;
813
1526
  const rightHtml = isTable ? '' : `
814
1527
  <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>
1528
+ <span class="pfx-micro-trend__value">${escapeHtml(formatVisualizationMetricValue(lastPoint.value, options, visualization.compactValue === true, suffix))}</span>
816
1529
  ${lastPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(lastPoint.label)}</span>` : ''}
817
1530
  </div>`;
818
1531
  return `
@@ -821,7 +1534,9 @@ function renderColumnVisualizationHtml(visualization, options) {
821
1534
  <span class="pfx-micro-viz pfx-micro-viz__column" data-tone="${escapeHtml(tone)}" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">
822
1535
  <svg class="pfx-micro-column__svg" viewBox="0 0 100 30">
823
1536
  ${columnsHtml}
1537
+ ${refLineHtml}
824
1538
  </svg>
1539
+ ${scrubLayerHtml}
825
1540
  </span>
826
1541
  ${rightHtml}
827
1542
  </span>`;
@@ -850,15 +1565,25 @@ function renderProcessFlowVisualizationHtml(visualization, options) {
850
1565
  const itemState = item.state ?? '';
851
1566
  const isLast = index === items.length - 1;
852
1567
  const itemLabel = stepLabels[index];
1568
+ const normalizedIcon = item.icon ? item.icon.replace(/-/g, '_') : undefined;
853
1569
  const label = !isTable && item.label ? `<span class="pfx-micro-step__label"${labelInlineStyle}>${escapeHtml(item.label)}</span>` : '';
1570
+ const isActiveStep = itemState === 'active' ||
1571
+ itemState === 'current' ||
1572
+ itemState === 'in_progress' ||
1573
+ normalizedIcon === 'sync' ||
1574
+ normalizedIcon === 'pending' ||
1575
+ normalizedIcon === 'pending_actions' ||
1576
+ normalizedIcon === 'schedule' ||
1577
+ (!itemState && itemTone === 'warning');
1578
+ const stepReadout = `${index + 1}/${items.length} · ${itemLabel}`;
854
1579
  const connector = !isLast ? `<span class="pfx-micro-step__connector" data-tone="${escapeHtml(itemTone)}"></span>` : '';
855
1580
  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}`}
1581
+ <span class="pfx-micro-step__node" data-tone="${escapeHtml(itemTone)}"${isActiveStep ? ' data-active="true"' : ''} aria-hidden="true">
1582
+ ${normalizedIcon ? `<span class="material-icons pfx-micro-step__icon" aria-hidden="true">${escapeHtml(normalizedIcon)}</span>` : `${index + 1}`}
858
1583
  </span>`;
859
1584
  return `
860
1585
  <div class="pfx-micro-step" data-state="${escapeHtml(itemState)}" data-tone="${escapeHtml(itemTone)}">
861
- <div class="pfx-micro-step__node-wrapper" title="${escapeHtml(itemLabel)}">
1586
+ <div class="pfx-micro-step__node-wrapper" data-micro-readout="${escapeHtml(stepReadout)}" title="${escapeHtml(itemLabel)}">
862
1587
  ${stepCircle}
863
1588
  ${label}
864
1589
  </div>
@@ -870,6 +1595,209 @@ function renderProcessFlowVisualizationHtml(visualization, options) {
870
1595
  ${stepsHtml}
871
1596
  </span>`;
872
1597
  }
1598
+ function formatPraxisWaterfallSignedValue(value, role, options = {}, compactValue = false, suffix = '') {
1599
+ const absFormatted = formatVisualizationMetricValue(Math.abs(Number.isFinite(value) ? value : 0), options, compactValue, suffix);
1600
+ if (role === 'start' || role === 'subtotal' || role === 'total') {
1601
+ const negPrefix = value < 0 ? '-' : '';
1602
+ return `= ${negPrefix}${absFormatted}`;
1603
+ }
1604
+ if (value > 0) {
1605
+ return `+${absFormatted}`;
1606
+ }
1607
+ if (value < 0) {
1608
+ return `-${absFormatted}`;
1609
+ }
1610
+ return absFormatted;
1611
+ }
1612
+ function resolvePraxisMicroWaterfallSteps(visualization, options = {}) {
1613
+ const rawItems = Array.isArray(visualization.items) && visualization.items.length > 0
1614
+ ? visualization.items
1615
+ : Array.isArray(visualization.points)
1616
+ ? visualization.points.map((pt) => typeof pt === 'number'
1617
+ ? { value: pt }
1618
+ : {
1619
+ label: pt.label,
1620
+ value: pt.value,
1621
+ tone: pt.tone,
1622
+ ...(pt.suppressed !== undefined ? { suppressed: pt.suppressed } : {}),
1623
+ ...(pt.privacySuppressed !== undefined ? { privacySuppressed: pt.privacySuppressed } : {}),
1624
+ })
1625
+ : [];
1626
+ if (!rawItems.length) {
1627
+ return [];
1628
+ }
1629
+ const suffix = visualization.valueSuffix ?? '';
1630
+ const compactValue = visualization.compactValue === true;
1631
+ const fallbackAnchorTone = visualization.tone ?? 'info';
1632
+ const steps = [];
1633
+ let running = 0;
1634
+ let hasFiniteNumeric = false;
1635
+ let hadSuppressedItems = resolvePreservedSuppressedCount(visualization.suppressedCount) > 0;
1636
+ let visibleIncrementCount = 0;
1637
+ for (let i = 0; i < rawItems.length; i++) {
1638
+ const raw = rawItems[i];
1639
+ if (!raw || typeof raw !== 'object') {
1640
+ continue;
1641
+ }
1642
+ if (isVisualizationEntrySuppressed(raw)) {
1643
+ hadSuppressedItems = true;
1644
+ continue;
1645
+ }
1646
+ const rawNumeric = toFiniteNumber(raw.value);
1647
+ if (rawNumeric !== undefined) {
1648
+ hasFiniteNumeric = true;
1649
+ }
1650
+ const explicitRole = normalizeEnum$1(raw.role, WATERFALL_ROLES);
1651
+ const role = explicitRole
1652
+ ?? (steps.length === 0 ? 'start' : (rawNumeric ?? 0) < 0 ? 'decrease' : 'increase');
1653
+ if (rawNumeric === undefined && role !== 'subtotal' && role !== 'total') {
1654
+ continue;
1655
+ }
1656
+ if (role !== 'subtotal' && role !== 'total') {
1657
+ visibleIncrementCount += 1;
1658
+ }
1659
+ let start = running;
1660
+ let end = running;
1661
+ let delta = 0;
1662
+ let resolvedValue = rawNumeric ?? running;
1663
+ if (role === 'start') {
1664
+ start = 0;
1665
+ end = rawNumeric ?? 0;
1666
+ delta = end;
1667
+ running = end;
1668
+ resolvedValue = end;
1669
+ }
1670
+ else if (role === 'subtotal' || role === 'total') {
1671
+ const targetEnd = hadSuppressedItems ? running : (rawNumeric ?? running);
1672
+ start = 0;
1673
+ end = targetEnd;
1674
+ delta = targetEnd;
1675
+ running = targetEnd;
1676
+ resolvedValue = targetEnd;
1677
+ }
1678
+ else if (role === 'decrease') {
1679
+ delta = -Math.abs(rawNumeric ?? 0);
1680
+ start = running;
1681
+ end = running + delta;
1682
+ running = end;
1683
+ resolvedValue = delta;
1684
+ }
1685
+ else {
1686
+ delta = Math.abs(rawNumeric ?? 0);
1687
+ start = running;
1688
+ end = running + delta;
1689
+ running = end;
1690
+ resolvedValue = delta;
1691
+ }
1692
+ const defaultTone = role === 'increase'
1693
+ ? 'success'
1694
+ : role === 'decrease'
1695
+ ? 'danger'
1696
+ : role === 'start'
1697
+ ? 'neutral'
1698
+ : fallbackAnchorTone;
1699
+ const tone = normalizeEnum$1(raw.tone, VISUALIZATION_TONES) ?? defaultTone;
1700
+ const label = normalizeText$1(raw.label) ?? normalizeText$1(raw.id) ?? `#${steps.length + 1}`;
1701
+ const signedText = formatPraxisWaterfallSignedValue(role === 'start' || role === 'subtotal' || role === 'total' ? end : delta, role, options, compactValue, suffix);
1702
+ const endText = formatVisualizationMetricValue(Math.abs(end), options, compactValue, suffix);
1703
+ const signedEndText = `${end < 0 ? '-' : ''}${endText}`;
1704
+ const readout = role === 'start' || role === 'subtotal' || role === 'total'
1705
+ ? `${label}: ${signedText}`
1706
+ : `${label}: ${signedText} (=> ${signedEndText})`;
1707
+ steps.push({
1708
+ ...(raw.id ? { id: raw.id } : {}),
1709
+ label,
1710
+ value: resolvedValue,
1711
+ start,
1712
+ end,
1713
+ delta,
1714
+ role,
1715
+ tone,
1716
+ ...(raw.color ? { color: raw.color } : {}),
1717
+ signedText,
1718
+ readout,
1719
+ });
1720
+ }
1721
+ if (!hasFiniteNumeric || (hadSuppressedItems && visibleIncrementCount === 0)) {
1722
+ return [];
1723
+ }
1724
+ return steps;
1725
+ }
1726
+ function renderWaterfallVisualizationHtml(visualization, options) {
1727
+ const steps = resolvePraxisMicroWaterfallSteps(visualization, options);
1728
+ const fallbackTone = visualization.tone ?? 'info';
1729
+ if (steps.length === 0) {
1730
+ return renderFallbackVisualizationHtml(visualization, fallbackTone);
1731
+ }
1732
+ const width = 100;
1733
+ const height = 32;
1734
+ const xPad = 4;
1735
+ const yPad = 4;
1736
+ const plotHeight = height - 2 * yPad;
1737
+ const minVal = Math.min(0, ...steps.flatMap((s) => [s.start, s.end]));
1738
+ const maxVal = Math.max(0, ...steps.flatMap((s) => [s.start, s.end]));
1739
+ const span = Math.max(1e-6, maxVal - minVal);
1740
+ const yFor = (val) => yPad + (1 - (val - minVal) / span) * plotHeight;
1741
+ const slotW = (width - 2 * xPad) / steps.length;
1742
+ const barW = Math.max(3, Math.min(18, slotW * 0.64));
1743
+ const barOffset = (slotW - barW) / 2;
1744
+ const barsHtml = [];
1745
+ const connectorsHtml = [];
1746
+ const scrubSlicesHtml = [];
1747
+ for (let i = 0; i < steps.length; i++) {
1748
+ const step = steps[i];
1749
+ const x = xPad + i * slotW + barOffset;
1750
+ const yStart = yFor(step.start);
1751
+ const yEnd = yFor(step.end);
1752
+ const topY = Math.min(yStart, yEnd);
1753
+ const rectH = Math.max(2, Math.abs(yEnd - yStart));
1754
+ const clampedY = Math.min(height - yPad - 2, topY);
1755
+ const styleAttr = step.color ? ` style="color:${escapeHtml(step.color)}"` : '';
1756
+ barsHtml.push(`<rect class="pfx-micro-waterfall__bar" x="${x.toFixed(1)}" y="${clampedY.toFixed(1)}" width="${barW.toFixed(1)}" height="${rectH.toFixed(1)}" rx="1.5" fill="currentColor" data-role="${escapeHtml(step.role)}" data-tone="${escapeHtml(step.tone)}"${styleAttr} />`);
1757
+ if (i < steps.length - 1) {
1758
+ const nextX = xPad + (i + 1) * slotW + barOffset;
1759
+ const connY = step.end > step.start
1760
+ ? clampedY
1761
+ : step.end < step.start
1762
+ ? clampedY + rectH
1763
+ : Math.min(height - yPad, Math.max(clampedY, Math.min(clampedY + rectH, yEnd)));
1764
+ connectorsHtml.push(`<line class="pfx-micro-waterfall__connector" x1="${(x + barW).toFixed(1)}" y1="${connY.toFixed(1)}" x2="${nextX.toFixed(1)}" y2="${connY.toFixed(1)}" />`);
1765
+ }
1766
+ scrubSlicesHtml.push(`<span class="pfx-micro-waterfall__scrub-slice" data-tone="${escapeHtml(step.tone)}" data-role="${escapeHtml(step.role)}" data-micro-readout="${escapeHtml(step.readout)}" title="${escapeHtml(step.readout)}"></span>`);
1767
+ }
1768
+ const zeroY = yFor(0);
1769
+ const baselineHtml = `<line class="pfx-micro-waterfall__baseline" x1="2" y1="${zeroY.toFixed(1)}" x2="${(width - 2).toFixed(1)}" y2="${zeroY.toFixed(1)}" />`;
1770
+ const isTable = visualization.surface === 'table-cell';
1771
+ const firstStep = steps[0];
1772
+ const lastStep = steps[steps.length - 1];
1773
+ const aria = visualization.ariaLabel
1774
+ ?? `${visualization.fallbackText}: ${steps.map((s) => s.readout).join('; ')}`;
1775
+ const startSummaryHtml = !isTable && firstStep
1776
+ ? `<div class="pfx-micro-trend__label-col pfx-micro-trend__label-col--start">
1777
+ <span class="pfx-micro-trend__value">${escapeHtml(firstStep.signedText)}</span>
1778
+ <span class="pfx-micro-trend__label">${escapeHtml(firstStep.label)}</span>
1779
+ </div>`
1780
+ : '';
1781
+ const endSummaryHtml = !isTable && lastStep && steps.length > 1
1782
+ ? `<div class="pfx-micro-trend__label-col pfx-micro-trend__label-col--end">
1783
+ <span class="pfx-micro-trend__value">${escapeHtml(lastStep.signedText)}</span>
1784
+ <span class="pfx-micro-trend__label">${escapeHtml(lastStep.label)}</span>
1785
+ </div>`
1786
+ : '';
1787
+ return `
1788
+ <span class="pfx-micro-viz-container">
1789
+ ${startSummaryHtml}
1790
+ <span class="pfx-micro-viz pfx-micro-viz__waterfall" data-tone="${escapeHtml(fallbackTone)}" role="img" aria-label="${escapeHtml(aria)}">
1791
+ <svg class="pfx-micro-waterfall__svg" viewBox="0 0 ${width} ${height}" preserveAspectRatio="none">
1792
+ ${baselineHtml}
1793
+ ${connectorsHtml.join('')}
1794
+ ${barsHtml.join('')}
1795
+ </svg>
1796
+ <span class="pfx-micro-waterfall__scrub-layer">${scrubSlicesHtml.join('')}</span>
1797
+ </span>
1798
+ ${endSummaryHtml}
1799
+ </span>`;
1800
+ }
873
1801
  function renderFallbackVisualizationHtml(visualization, tone) {
874
1802
  return `
875
1803
  <span
@@ -880,74 +1808,544 @@ function renderFallbackVisualizationHtml(visualization, tone) {
880
1808
  >${escapeHtml(visualization.fallbackText)}</span>`;
881
1809
  }
882
1810
 
883
- const TONES = new Set([
884
- 'neutral',
885
- 'info',
886
- 'success',
887
- 'warning',
888
- 'danger',
889
- ]);
890
- const APPEARANCES = new Set([
891
- 'plain',
892
- 'soft',
893
- 'outlined',
894
- 'filled',
895
- ]);
896
- const PRESENTERS = new Set([
897
- 'text',
898
- 'badge',
899
- 'chip',
900
- 'status',
901
- 'iconValue',
902
- 'progress',
903
- 'rating',
904
- 'microVisualization',
1811
+ const PRAXIS_QUICK_VIEW_PRESENTER = new InjectionToken('PRAXIS_QUICK_VIEW_PRESENTER');
1812
+ const PRAXIS_QUICK_VIEW_BODY_RENDERER = new InjectionToken('PRAXIS_QUICK_VIEW_BODY_RENDERER');
1813
+ const FORBIDDEN_BINDING_KEYS = new Set([
1814
+ 'element',
1815
+ 'nativeElement',
1816
+ 'anchor',
1817
+ 'hostElement',
1818
+ 'focusOrigin',
1819
+ 'getViewportRect',
1820
+ 'nodes',
1821
+ 'document',
1822
+ 'action',
1823
+ 'actions',
1824
+ 'ctaAction',
1825
+ 'overrideAction',
1826
+ 'route',
1827
+ 'href',
1828
+ 'payload',
1829
+ 'hostCapabilities',
905
1830
  ]);
1831
+ const RESOURCE_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
906
1832
  /**
907
- * Resolves readonly field presentation from a base semantic config plus ordered
908
- * Json Logic rules. Later matching rules override earlier presentation values.
1833
+ * Detecta se um valor candidato à serialização contém referências efêmeras de DOM ou funções.
909
1834
  */
910
- function resolveFieldPresentation(base, rules, context = {}, options = {}) {
911
- let resolved = normalizeFieldPresentation(base);
912
- let matchedRule = false;
913
- if (!Array.isArray(rules) || !options.jsonLogic) {
914
- return resolved;
1835
+ function containsEphemeralQuickViewRuntimeValue(value, visited = new Set()) {
1836
+ if (!value || typeof value !== 'object') {
1837
+ return typeof value === 'function';
915
1838
  }
916
- for (const rule of rules) {
917
- if (!rule?.when || !matchesPresentationRule(rule, context, options.jsonLogic)) {
918
- continue;
1839
+ if (visited.has(value)) {
1840
+ return false;
1841
+ }
1842
+ visited.add(value);
1843
+ if (typeof Element !== 'undefined' && value instanceof Element) {
1844
+ return true;
1845
+ }
1846
+ if (typeof value.nodeType === 'number' &&
1847
+ typeof value.nodeName === 'string') {
1848
+ return true;
1849
+ }
1850
+ if (Array.isArray(value)) {
1851
+ return value.some((item) => containsEphemeralQuickViewRuntimeValue(item, visited));
1852
+ }
1853
+ for (const [key, entry] of Object.entries(value)) {
1854
+ if (key === 'element' ||
1855
+ key === 'nativeElement' ||
1856
+ key === 'hostElement' ||
1857
+ key === 'focusOrigin' ||
1858
+ typeof entry === 'function') {
1859
+ return true;
1860
+ }
1861
+ if (containsEphemeralQuickViewRuntimeValue(entry, visited)) {
1862
+ return true;
919
1863
  }
920
- const effect = normalizeFieldPresentation(rule.set ?? rule.effect);
921
- resolved = {
922
- ...resolved,
923
- ...effect,
924
- };
925
- matchedRule = true;
926
1864
  }
927
- return matchedRule ? { ...resolved, matchedRule } : resolved;
1865
+ return false;
928
1866
  }
929
- function normalizeFieldPresentation(value) {
930
- if (!value || typeof value !== 'object') {
931
- return {};
1867
+ function normalizeResourceRecordOpenReference(candidate) {
1868
+ if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {
1869
+ return null;
1870
+ }
1871
+ const record = candidate;
1872
+ const target = record['target'] && typeof record['target'] === 'object' && !Array.isArray(record['target'])
1873
+ ? record['target']
1874
+ : null;
1875
+ const sourceIdentityField = typeof record['sourceIdentityField'] === 'string'
1876
+ ? record['sourceIdentityField'].trim()
1877
+ : '';
1878
+ const resourceKey = typeof target?.['resourceKey'] === 'string'
1879
+ ? target['resourceKey'].trim()
1880
+ : '';
1881
+ const surfaceId = typeof target?.['surfaceId'] === 'string'
1882
+ ? target['surfaceId'].trim()
1883
+ : '';
1884
+ if (!sourceIdentityField ||
1885
+ sourceIdentityField.length > 200 ||
1886
+ !RESOURCE_KEY_PATTERN.test(resourceKey) ||
1887
+ !surfaceId ||
1888
+ surfaceId.length > 200) {
1889
+ return null;
932
1890
  }
933
- const presenter = normalizePresenter(value.presenter ?? value.variant);
934
- const tone = normalizeTone(value.tone);
935
- const appearance = normalizeAppearance(value.appearance);
936
- const icon = normalizeText(value.icon);
937
- const label = normalizeText(value.label);
938
- const badge = normalizeText(value.badge);
939
- const tooltip = normalizeText(value.tooltip);
940
- const prefix = normalizeText(value.prefix);
941
- const suffix = normalizeText(value.suffix);
942
- const iconTrue = normalizeText(value.iconTrue);
943
- const iconFalse = normalizeText(value.iconFalse);
944
- const toneTrue = normalizeTone(value.toneTrue);
945
- const toneFalse = normalizeTone(value.toneFalse);
946
- const labelTrue = normalizeText(value.labelTrue);
947
- const labelFalse = normalizeText(value.labelFalse);
948
- const visualization = normalizePraxisPresentationVisualization(value.visualization);
949
1891
  return {
950
- ...(presenter ? { presenter } : {}),
1892
+ sourceIdentityField,
1893
+ target: {
1894
+ resourceKey,
1895
+ surfaceId,
1896
+ },
1897
+ };
1898
+ }
1899
+ /**
1900
+ * Valida e normaliza um `ResourceQuickViewBinding` de forma fail-closed.
1901
+ */
1902
+ function validateResourceQuickViewBinding(value) {
1903
+ const diagnostics = [];
1904
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
1905
+ return {
1906
+ valid: false,
1907
+ binding: null,
1908
+ diagnostics: ['Quick View binding must be a non-null object.'],
1909
+ };
1910
+ }
1911
+ const record = value;
1912
+ for (const forbiddenKey of FORBIDDEN_BINDING_KEYS) {
1913
+ if (forbiddenKey in record && record[forbiddenKey] !== undefined) {
1914
+ diagnostics.push(`Quick View binding cannot contain runtime, inline document or action override property "${forbiddenKey}".`);
1915
+ }
1916
+ }
1917
+ if (containsEphemeralQuickViewRuntimeValue(record)) {
1918
+ diagnostics.push('Quick View binding cannot contain DOM elements or functions.');
1919
+ }
1920
+ const rawRecordOpen = record['recordOpen'];
1921
+ if (!rawRecordOpen || typeof rawRecordOpen !== 'object' || Array.isArray(rawRecordOpen)) {
1922
+ diagnostics.push('Quick View binding requires a valid "recordOpen" object.');
1923
+ }
1924
+ else {
1925
+ const recordOpenObj = rawRecordOpen;
1926
+ for (const forbiddenKey of FORBIDDEN_BINDING_KEYS) {
1927
+ if (forbiddenKey in recordOpenObj && recordOpenObj[forbiddenKey] !== undefined) {
1928
+ diagnostics.push(`Quick View recordOpen cannot contain override property "${forbiddenKey}".`);
1929
+ }
1930
+ }
1931
+ if ('presentation' in recordOpenObj && recordOpenObj['presentation'] === 'popover') {
1932
+ diagnostics.push('Quick View recordOpen cannot declare "popover" presentation.');
1933
+ }
1934
+ }
1935
+ let previewSurfaceId;
1936
+ const rawPreviewSurfaceId = record['previewSurfaceId'];
1937
+ if (rawPreviewSurfaceId !== undefined && rawPreviewSurfaceId !== null) {
1938
+ if (typeof rawPreviewSurfaceId === 'string' &&
1939
+ rawPreviewSurfaceId.trim().length > 0 &&
1940
+ rawPreviewSurfaceId.trim().length <= 200) {
1941
+ previewSurfaceId = rawPreviewSurfaceId.trim();
1942
+ }
1943
+ else {
1944
+ diagnostics.push('Quick View previewSurfaceId must be a non-empty string up to 200 characters.');
1945
+ }
1946
+ }
1947
+ let detailPresentation;
1948
+ const rawDetailPresentation = record['detailPresentation'];
1949
+ if (rawDetailPresentation !== undefined && rawDetailPresentation !== null) {
1950
+ if (rawDetailPresentation === 'drawer' || rawDetailPresentation === 'modal') {
1951
+ detailPresentation = rawDetailPresentation;
1952
+ }
1953
+ else {
1954
+ diagnostics.push(`Quick View detailPresentation must be "drawer" or "modal"; received "${String(rawDetailPresentation)}".`);
1955
+ }
1956
+ }
1957
+ const normalizedRecordOpen = normalizeResourceRecordOpenReference(rawRecordOpen);
1958
+ if (!normalizedRecordOpen) {
1959
+ diagnostics.push('Quick View recordOpen must declare non-empty sourceIdentityField and target.{resourceKey, surfaceId}.');
1960
+ }
1961
+ let normalizedContentRef;
1962
+ const rawContentRef = record['contentRef'];
1963
+ if (rawContentRef !== undefined && rawContentRef !== null) {
1964
+ if (typeof rawContentRef !== 'object' || Array.isArray(rawContentRef)) {
1965
+ diagnostics.push('Quick View contentRef must be an object reference to a rich-block preset.');
1966
+ }
1967
+ else {
1968
+ const refObj = rawContentRef;
1969
+ const kind = typeof refObj['kind'] === 'string' ? refObj['kind'].trim() : '';
1970
+ const namespace = typeof refObj['namespace'] === 'string' ? refObj['namespace'].trim() : '';
1971
+ const presetId = typeof refObj['presetId'] === 'string' ? refObj['presetId'].trim() : '';
1972
+ const version = typeof refObj['version'] === 'string' ? refObj['version'].trim() : '';
1973
+ if (kind !== 'rich-block') {
1974
+ diagnostics.push(`Quick View contentRef.kind must be "rich-block"; received "${kind || 'empty'}".`);
1975
+ }
1976
+ if (!namespace) {
1977
+ diagnostics.push('Quick View contentRef.namespace must be a non-empty string.');
1978
+ }
1979
+ if (!presetId) {
1980
+ diagnostics.push('Quick View contentRef.presetId must be a non-empty string.');
1981
+ }
1982
+ if (!version) {
1983
+ diagnostics.push('Quick View contentRef.version must be explicitly declared.');
1984
+ }
1985
+ if ('nodes' in refObj || 'inputs' in refObj || 'action' in refObj) {
1986
+ diagnostics.push('Quick View contentRef cannot embed inline nodes, inputs or actions.');
1987
+ }
1988
+ if (kind === 'rich-block' &&
1989
+ namespace &&
1990
+ presetId &&
1991
+ version &&
1992
+ !('nodes' in refObj || 'inputs' in refObj || 'action' in refObj)) {
1993
+ normalizedContentRef = {
1994
+ kind: 'rich-block',
1995
+ namespace,
1996
+ presetId,
1997
+ version,
1998
+ };
1999
+ }
2000
+ }
2001
+ }
2002
+ if (diagnostics.length > 0 || !normalizedRecordOpen) {
2003
+ return {
2004
+ valid: false,
2005
+ binding: null,
2006
+ diagnostics,
2007
+ };
2008
+ }
2009
+ return {
2010
+ valid: true,
2011
+ binding: {
2012
+ recordOpen: normalizedRecordOpen,
2013
+ ...(previewSurfaceId ? { previewSurfaceId } : {}),
2014
+ ...(normalizedContentRef ? { contentRef: normalizedContentRef } : {}),
2015
+ ...(detailPresentation ? { detailPresentation } : {}),
2016
+ },
2017
+ diagnostics: [],
2018
+ };
2019
+ }
2020
+ function normalizeResourceQuickViewBinding(value) {
2021
+ return validateResourceQuickViewBinding(value).binding;
2022
+ }
2023
+ /**
2024
+ * Resolve ou sintetiza de forma determinística o `ResourceQuickViewBinding` de um campo
2025
+ * (`FieldDefinition` ou `FieldMetadata`), priorizando:
2026
+ * 1. `field.quickView` explícito;
2027
+ * 2. `field.presentation.interactions.quickView` explícito;
2028
+ * 3. síntese automática a partir de `field.resourceReference` ou `field.optionSource.detail`.
2029
+ *
2030
+ * Protege contra colisão de `valueField`/`optionSource.valuePropertyPath` (`'id'` da opção)
2031
+ * com o identificador da própria entidade pai quando o campo de origem possui outro nome
2032
+ * (ex.: `cargoId`, `fornecedorId`).
2033
+ */
2034
+ function resolveFieldQuickViewBinding(candidate) {
2035
+ if (!candidate || typeof candidate !== 'object') {
2036
+ return null;
2037
+ }
2038
+ const explicitQuickView = normalizeResourceQuickViewBinding(candidate.quickView);
2039
+ if (explicitQuickView) {
2040
+ return explicitQuickView;
2041
+ }
2042
+ const presentationQuickView = normalizeResourceQuickViewBinding(candidate.presentation?.interactions?.quickView);
2043
+ if (presentationQuickView) {
2044
+ return presentationQuickView;
2045
+ }
2046
+ const fieldName = typeof candidate.name === 'string' ? candidate.name.trim() : '';
2047
+ const rawValueField = typeof candidate.valueField === 'string' ? candidate.valueField.trim() : '';
2048
+ const optionValueProperty = typeof candidate.optionSource?.valuePropertyPath === 'string' &&
2049
+ candidate.optionSource.valuePropertyPath.trim().length > 0
2050
+ ? candidate.optionSource.valuePropertyPath.trim()
2051
+ : 'id';
2052
+ // Quando o campo possui optionSource e seu nome não coincide com rawValueField, um valueField
2053
+ // igual a 'id'/'value'/'key' ou a optionValueProperty (ex.: 'numero', 'codigo') refere-se à
2054
+ // chave do OptionDTO e nunca ao campo irmão 'id' do registro pai.
2055
+ const isOptionKeyAlias = rawValueField === 'id' ||
2056
+ rawValueField === 'value' ||
2057
+ rawValueField === 'key' ||
2058
+ rawValueField === optionValueProperty;
2059
+ const effectiveSiblingValueField = rawValueField &&
2060
+ (!candidate.optionSource ||
2061
+ fieldName === rawValueField ||
2062
+ !isOptionKeyAlias)
2063
+ ? rawValueField
2064
+ : '';
2065
+ const refCandidate = candidate.resourceReference?.resourceKey
2066
+ ? {
2067
+ resourceKey: candidate.resourceReference.resourceKey,
2068
+ sourceIdentityField: (typeof candidate.resourceReference.valueField === 'string'
2069
+ ? candidate.resourceReference.valueField.trim()
2070
+ : '') ||
2071
+ effectiveSiblingValueField ||
2072
+ fieldName,
2073
+ surfaceId: candidate.resourceReference.surfaceId || 'detail',
2074
+ previewSurfaceId: candidate.resourceReference.previewSurfaceId,
2075
+ detailPresentation: candidate.resourceReference.detailPresentation === 'drawer' ||
2076
+ candidate.resourceReference.detailPresentation === 'modal'
2077
+ ? candidate.resourceReference.detailPresentation
2078
+ : undefined,
2079
+ }
2080
+ : candidate.optionSource?.detail?.resourceKey
2081
+ ? {
2082
+ resourceKey: candidate.optionSource.detail.resourceKey,
2083
+ sourceIdentityField: effectiveSiblingValueField || fieldName,
2084
+ surfaceId: candidate.optionSource.detail.surfaceId || 'detail',
2085
+ previewSurfaceId: candidate.optionSource.detail.previewSurfaceId,
2086
+ detailPresentation: candidate.optionSource.detail.presentation === 'drawer' ||
2087
+ candidate.optionSource.detail.presentation === 'modal'
2088
+ ? candidate.optionSource.detail.presentation
2089
+ : undefined,
2090
+ }
2091
+ : undefined;
2092
+ if (!refCandidate || !refCandidate.sourceIdentityField) {
2093
+ return null;
2094
+ }
2095
+ return normalizeResourceQuickViewBinding({
2096
+ recordOpen: {
2097
+ sourceIdentityField: refCandidate.sourceIdentityField,
2098
+ target: {
2099
+ resourceKey: refCandidate.resourceKey,
2100
+ surfaceId: refCandidate.surfaceId || 'detail',
2101
+ },
2102
+ },
2103
+ ...(refCandidate.previewSurfaceId
2104
+ ? { previewSurfaceId: refCandidate.previewSurfaceId }
2105
+ : {}),
2106
+ ...(refCandidate.detailPresentation
2107
+ ? { detailPresentation: refCandidate.detailPresentation }
2108
+ : {}),
2109
+ });
2110
+ }
2111
+ /**
2112
+ * Reconcilia o `ResourceQuickViewBinding` entre a definição base do servidor e uma
2113
+ * customização local persistida:
2114
+ * - Um `local` indefinido, nulo ou inválido nunca apaga o binding canônico do servidor (`base`).
2115
+ * - Quando o campo possui binding canônico do servidor (`base`), `base.recordOpen`
2116
+ * (recurso de destino, `surfaceId` e `sourceIdentityField`) permanece autoritativo
2117
+ * do servidor, permitindo que o `local` customize apenas preferências visuais de UX
2118
+ * (`trigger`, `previewSurfaceId`, `detailPresentation`).
2119
+ */
2120
+ function reconcileFieldQuickViewBinding(base, local) {
2121
+ const normalizedBase = normalizeResourceQuickViewBinding(base);
2122
+ const normalizedLocal = normalizeResourceQuickViewBinding(local);
2123
+ if (normalizedBase && normalizedLocal) {
2124
+ return {
2125
+ ...normalizedBase,
2126
+ ...normalizedLocal,
2127
+ recordOpen: normalizedBase.recordOpen,
2128
+ };
2129
+ }
2130
+ return normalizedLocal ?? normalizedBase ?? undefined;
2131
+ }
2132
+ function readQuickViewFieldOrPath(target, path) {
2133
+ if (Object.prototype.hasOwnProperty.call(target, path)) {
2134
+ return target[path];
2135
+ }
2136
+ if (!path.includes('.')) {
2137
+ return undefined;
2138
+ }
2139
+ return path.split('.').reduce((acc, segment) => {
2140
+ if (!acc || typeof acc !== 'object' || Array.isArray(acc)) {
2141
+ return undefined;
2142
+ }
2143
+ return Object.prototype.hasOwnProperty.call(acc, segment)
2144
+ ? acc[segment]
2145
+ : undefined;
2146
+ }, target);
2147
+ }
2148
+ /**
2149
+ * Resolve de forma determinística o alvo (`resourceKey`, `surfaceId`, `previewSurfaceId`, `identity`)
2150
+ * a partir de um `ResourceQuickViewBinding` e de um registro candidato (`sourceRecord`).
2151
+ */
2152
+ function resolveResourceQuickViewTarget(binding, sourceRecord) {
2153
+ const normalized = normalizeResourceQuickViewBinding(binding);
2154
+ if (!normalized ||
2155
+ !sourceRecord ||
2156
+ typeof sourceRecord !== 'object' ||
2157
+ Array.isArray(sourceRecord)) {
2158
+ return null;
2159
+ }
2160
+ const record = sourceRecord;
2161
+ const sourceField = normalized.recordOpen.sourceIdentityField;
2162
+ let candidate = readQuickViewFieldOrPath(record, sourceField);
2163
+ if (candidate === undefined) {
2164
+ for (const envelopeKey of ['row', 'item', 'values']) {
2165
+ const nested = record[envelopeKey];
2166
+ if (nested && typeof nested === 'object' && !Array.isArray(nested)) {
2167
+ candidate = readQuickViewFieldOrPath(nested, sourceField);
2168
+ if (candidate !== undefined) {
2169
+ break;
2170
+ }
2171
+ }
2172
+ }
2173
+ }
2174
+ if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
2175
+ const candidateObj = candidate;
2176
+ candidate =
2177
+ candidateObj['id'] ?? candidateObj['value'] ?? candidateObj['key'];
2178
+ }
2179
+ if (typeof candidate === 'number' && Number.isFinite(candidate)) {
2180
+ return {
2181
+ resourceKey: normalized.recordOpen.target.resourceKey,
2182
+ surfaceId: normalized.recordOpen.target.surfaceId,
2183
+ previewSurfaceId: normalized.previewSurfaceId || normalized.recordOpen.target.surfaceId,
2184
+ identity: candidate,
2185
+ };
2186
+ }
2187
+ if (typeof candidate === 'string' && candidate.trim().length > 0) {
2188
+ return {
2189
+ resourceKey: normalized.recordOpen.target.resourceKey,
2190
+ surfaceId: normalized.recordOpen.target.surfaceId,
2191
+ previewSurfaceId: normalized.previewSurfaceId || normalized.recordOpen.target.surfaceId,
2192
+ identity: candidate.trim(),
2193
+ };
2194
+ }
2195
+ return null;
2196
+ }
2197
+ /**
2198
+ * Verifica se a âncora efêmera de runtime permanece conectada e visível na viewport.
2199
+ */
2200
+ function isResourceQuickViewAnchorValid(anchor, trigger) {
2201
+ if (!anchor || typeof anchor !== 'object') {
2202
+ return false;
2203
+ }
2204
+ if (typeof anchor.isValid === 'function' && !anchor.isValid()) {
2205
+ return false;
2206
+ }
2207
+ const viewportWidth = typeof window !== 'undefined' && Number.isFinite(window.innerWidth) && window.innerWidth > 0
2208
+ ? window.innerWidth
2209
+ : 1920;
2210
+ const viewportHeight = typeof window !== 'undefined' && Number.isFinite(window.innerHeight) && window.innerHeight > 0
2211
+ ? window.innerHeight
2212
+ : 1080;
2213
+ if (anchor.kind === 'element') {
2214
+ const el = anchor.element;
2215
+ if (!el || typeof el.getBoundingClientRect !== 'function' || el.isConnected === false) {
2216
+ return false;
2217
+ }
2218
+ const rect = el.getBoundingClientRect();
2219
+ if (!Number.isFinite(rect.left) || !Number.isFinite(rect.top)) {
2220
+ return false;
2221
+ }
2222
+ if (rect.width === 0 && rect.height === 0) {
2223
+ return false;
2224
+ }
2225
+ const edgeTolerance = trigger === 'focus-shortcut' || trigger === 'explicit-button' ? 96 : 0;
2226
+ return (rect.bottom >= -edgeTolerance &&
2227
+ rect.right >= -edgeTolerance &&
2228
+ rect.top <= viewportHeight + edgeTolerance &&
2229
+ rect.left <= viewportWidth + edgeTolerance);
2230
+ }
2231
+ if (anchor.kind === 'virtual-rect') {
2232
+ if (!anchor.anchorKey || !anchor.anchorKey.trim()) {
2233
+ return false;
2234
+ }
2235
+ if (anchor.hostElement && anchor.hostElement.isConnected === false) {
2236
+ return false;
2237
+ }
2238
+ if (typeof anchor.getViewportRect !== 'function') {
2239
+ return false;
2240
+ }
2241
+ const rect = anchor.getViewportRect();
2242
+ if (!rect ||
2243
+ !Number.isFinite(rect.x) ||
2244
+ !Number.isFinite(rect.y) ||
2245
+ !Number.isFinite(rect.width) ||
2246
+ !Number.isFinite(rect.height) ||
2247
+ rect.width < 0 ||
2248
+ rect.height < 0) {
2249
+ return false;
2250
+ }
2251
+ const right = rect.right ?? rect.x + rect.width;
2252
+ const bottom = rect.bottom ?? rect.y + rect.height;
2253
+ const left = rect.left ?? rect.x;
2254
+ const top = rect.top ?? rect.y;
2255
+ return (bottom >= 0 &&
2256
+ right >= 0 &&
2257
+ top <= viewportHeight &&
2258
+ left <= viewportWidth);
2259
+ }
2260
+ return false;
2261
+ }
2262
+ function resolveQuickViewAnchorKey(anchor) {
2263
+ if (anchor.kind === 'virtual-rect') {
2264
+ return anchor.anchorKey.trim();
2265
+ }
2266
+ const explicit = anchor.anchorKey?.trim();
2267
+ if (explicit) {
2268
+ return explicit;
2269
+ }
2270
+ const focusKey = anchor.element?.getAttribute?.('data-praxis-focus-key')?.trim();
2271
+ if (focusKey) {
2272
+ return focusKey;
2273
+ }
2274
+ const id = anchor.element?.id?.trim();
2275
+ if (id) {
2276
+ return `element:${id}`;
2277
+ }
2278
+ return 'element:anonymous';
2279
+ }
2280
+
2281
+ const TONES = new Set([
2282
+ 'neutral',
2283
+ 'info',
2284
+ 'success',
2285
+ 'warning',
2286
+ 'danger',
2287
+ ]);
2288
+ const APPEARANCES = new Set([
2289
+ 'plain',
2290
+ 'soft',
2291
+ 'outlined',
2292
+ 'filled',
2293
+ ]);
2294
+ const PRESENTERS = new Set([
2295
+ 'text',
2296
+ 'badge',
2297
+ 'chip',
2298
+ 'status',
2299
+ 'iconValue',
2300
+ 'progress',
2301
+ 'rating',
2302
+ 'microVisualization',
2303
+ ]);
2304
+ /**
2305
+ * Resolves readonly field presentation from a base semantic config plus ordered
2306
+ * Json Logic rules. Later matching rules override earlier presentation values.
2307
+ */
2308
+ function resolveFieldPresentation(base, rules, context = {}, options = {}) {
2309
+ let resolved = normalizeFieldPresentation(base);
2310
+ let matchedRule = false;
2311
+ if (!Array.isArray(rules) || !options.jsonLogic) {
2312
+ return resolved;
2313
+ }
2314
+ for (const rule of rules) {
2315
+ if (!rule?.when || !matchesPresentationRule(rule, context, options.jsonLogic)) {
2316
+ continue;
2317
+ }
2318
+ const effect = normalizeFieldPresentation(rule.set ?? rule.effect);
2319
+ resolved = {
2320
+ ...resolved,
2321
+ ...effect,
2322
+ };
2323
+ matchedRule = true;
2324
+ }
2325
+ return matchedRule ? { ...resolved, matchedRule } : resolved;
2326
+ }
2327
+ function normalizeFieldPresentation(value) {
2328
+ if (!value || typeof value !== 'object') {
2329
+ return {};
2330
+ }
2331
+ const presenter = normalizePresenter(value.presenter ?? value.variant);
2332
+ const tone = normalizeTone(value.tone);
2333
+ const appearance = normalizeAppearance(value.appearance);
2334
+ const icon = normalizeText(value.icon);
2335
+ const label = normalizeText(value.label);
2336
+ const badge = normalizeText(value.badge);
2337
+ const tooltip = normalizeText(value.tooltip);
2338
+ const prefix = normalizeText(value.prefix);
2339
+ const suffix = normalizeText(value.suffix);
2340
+ const iconTrue = normalizeText(value.iconTrue);
2341
+ const iconFalse = normalizeText(value.iconFalse);
2342
+ const toneTrue = normalizeTone(value.toneTrue);
2343
+ const toneFalse = normalizeTone(value.toneFalse);
2344
+ const labelTrue = normalizeText(value.labelTrue);
2345
+ const labelFalse = normalizeText(value.labelFalse);
2346
+ const visualization = normalizePraxisPresentationVisualization(value.visualization);
2347
+ return {
2348
+ ...(presenter ? { presenter } : {}),
951
2349
  ...(tone ? { tone } : {}),
952
2350
  ...(appearance ? { appearance } : {}),
953
2351
  ...(icon ? { icon } : {}),
@@ -1006,14 +2404,475 @@ function normalizeText(value) {
1006
2404
  return trimmed.length ? trimmed : undefined;
1007
2405
  }
1008
2406
  function normalizeInteractions(value) {
2407
+ const quickView = normalizeResourceQuickViewBinding(value.quickView);
1009
2408
  return {
1010
2409
  ...(value.copy === true ? { copy: true } : {}),
1011
2410
  ...(value.details === true ? { details: true } : {}),
1012
2411
  ...(value.expand === true ? { expand: true } : {}),
1013
2412
  ...(value.link === true ? { link: true } : {}),
2413
+ ...(quickView ? { quickView } : {}),
1014
2414
  };
1015
2415
  }
1016
2416
 
2417
+ /** Converts UI tokens only under declared scalar items; invalid input is never dropped or partially converted. */
2418
+ function normalizeScalarArrayValue(value, items) {
2419
+ if (items.enum !== undefined && !isScalarEnum(items.enum))
2420
+ return { valid: false, invalidIndices: [-1] };
2421
+ if (value == null)
2422
+ return { valid: true, value };
2423
+ if (!Array.isArray(value))
2424
+ return { valid: false, invalidIndices: [-1] };
2425
+ const converted = [];
2426
+ const invalidIndices = [];
2427
+ for (let index = 0; index < value.length; index += 1) {
2428
+ const item = normalizeItem(value[index], items);
2429
+ if (item === undefined || items.enum && !items.enum.some(candidate => candidate === item))
2430
+ invalidIndices.push(index);
2431
+ else
2432
+ converted.push(item);
2433
+ }
2434
+ return invalidIndices.length ? { valid: false, invalidIndices } : { valid: true, value: converted };
2435
+ }
2436
+ function normalizeItem(value, items) {
2437
+ if (value == null)
2438
+ return undefined;
2439
+ if (items.type === 'boolean') {
2440
+ if (typeof value === 'boolean')
2441
+ return value;
2442
+ return value === 'true' ? true : value === 'false' ? false : undefined;
2443
+ }
2444
+ if (items.type === 'integer' || items.type === 'number') {
2445
+ const number = typeof value === 'number' ? value : typeof value === 'string' &&
2446
+ /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(value) ? Number(value) : NaN;
2447
+ if (!Number.isFinite(number) || items.type === 'integer' && !Number.isSafeInteger(number))
2448
+ return undefined;
2449
+ return number;
2450
+ }
2451
+ if (items.type !== 'string')
2452
+ return undefined;
2453
+ if (items.format === 'date') {
2454
+ if (value instanceof Date) {
2455
+ if (Number.isNaN(value.getTime()))
2456
+ return undefined;
2457
+ const date = `${String(value.getFullYear()).padStart(4, '0')}-${String(value.getMonth() + 1).padStart(2, '0')}-${String(value.getDate()).padStart(2, '0')}`;
2458
+ return isIsoDate(date) ? date : undefined;
2459
+ }
2460
+ return typeof value === 'string' && isIsoDate(value) ? value : undefined;
2461
+ }
2462
+ if (items.format === 'date-time') {
2463
+ if (value instanceof Date)
2464
+ return Number.isNaN(value.getTime()) ? undefined : value.toISOString();
2465
+ return typeof value === 'string' && isIsoDateTime(value) ? value : undefined;
2466
+ }
2467
+ return typeof value === 'string' ? value : undefined;
2468
+ }
2469
+ function isIsoDate(value) {
2470
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
2471
+ if (!match)
2472
+ return false;
2473
+ const year = Number(match[1]), month = Number(match[2]), day = Number(match[3]);
2474
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
2475
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
2476
+ return month >= 1 && month <= 12 && day >= 1 && day <= days[month - 1];
2477
+ }
2478
+ function isIsoDateTime(value) {
2479
+ 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);
2480
+ if (!match || !isIsoDate(match[1]))
2481
+ return false;
2482
+ if (Number(match[2]) > 23 || Number(match[3]) > 59 || Number(match[4] ?? 0) > 59)
2483
+ return false;
2484
+ const offsetHours = Number(match[7] ?? 0), offsetMinutes = Number(match[8] ?? 0);
2485
+ return offsetHours <= 18 && offsetMinutes <= 59 && (offsetHours !== 18 || offsetMinutes === 0);
2486
+ }
2487
+ /** Internal admission of the scalar subset already published in JSON Schema items. */
2488
+ function normalizeScalarItemsSchema(value) {
2489
+ if (!value || typeof value !== 'object' || Array.isArray(value))
2490
+ return undefined;
2491
+ const record = value;
2492
+ if (typeof record['type'] !== 'string' || !['string', 'integer', 'number', 'boolean'].includes(record['type']))
2493
+ return undefined;
2494
+ const result = { type: record['type'] };
2495
+ if (typeof record['format'] === 'string')
2496
+ result.format = record['format'];
2497
+ if (record['enum'] !== undefined) {
2498
+ if (!isScalarEnum(record['enum']))
2499
+ throw new TypeError('Scalar items enum must contain JSON scalar values.');
2500
+ result.enum = [...record['enum']];
2501
+ }
2502
+ return result;
2503
+ }
2504
+ function isScalarEnum(value) {
2505
+ return Array.isArray(value) && value.length > 0 && value.every(item => item === null || typeof item === 'string' || typeof item === 'boolean' || typeof item === 'number' && Number.isFinite(item));
2506
+ }
2507
+
2508
+ /**
2509
+ * Enum que define os tipos de controle (`CONTROL_TYPE`) disponíveis para a apresentação dos campos de formulário.
2510
+ *
2511
+ * O `CONTROL_TYPE` especifica o tipo de elemento de UI (User Interface) que será usado para capturar ou exibir dados do campo.
2512
+ * Essa configuração permite que a camada de apresentação saiba como renderizar o campo e oferecer a interação adequada ao usuário.
2513
+ * Em casos onde o `CONTROL_TYPE` não é especificado, a camada de apresentação pode usar o valor de `TYPE` (definido em `FieldDataType`)
2514
+ * para decidir o controle mais adequado de forma automática.
2515
+ */
2516
+ const FieldControlType = {
2517
+ AI_PROMPT: 'aiPrompt',
2518
+ APP_BAR: 'appBar',
2519
+ ARC_GAUGE: 'arcGauge',
2520
+ ARRAY_INPUT: 'array',
2521
+ ASYNC_SELECT: 'async-select',
2522
+ AUTO_COMPLETE: 'autoComplete',
2523
+ AVATAR: 'avatar',
2524
+ BARCODE_GENERATOR: 'barcodeGenerator',
2525
+ BOTTOM_NAVIGATION: 'bottomNavigation',
2526
+ BREADCRUMB: 'breadcrumb',
2527
+ BUTTON: 'button',
2528
+ BUTTON_TOGGLE: 'buttonToggle',
2529
+ CALENDAR: 'calendar',
2530
+ CARD: 'card',
2531
+ CHECKBOX: 'checkbox',
2532
+ CHIP_INPUT: 'chipInput',
2533
+ CHIP_LIST: 'chipList',
2534
+ CIRCULAR_GAUGE: 'circularGauge',
2535
+ COLOR_GRADIENT: 'colorGradient',
2536
+ CPF_CNPJ_INPUT: 'cpfCnpjInput',
2537
+ COLOR_PALETTE: 'colorPalette',
2538
+ COLOR_PICKER: 'colorPicker',
2539
+ COLOR_INPUT: 'color',
2540
+ CRON_BUILDER: 'cronBuilder',
2541
+ CONTEXT_MENU: 'contextMenu',
2542
+ CONVERSATIONAL_UI: 'conversationalUI',
2543
+ CURRENCY_INPUT: 'currency',
2544
+ DATE_INPUT: 'dateInput',
2545
+ DATE_PICKER: 'date',
2546
+ DATE_RANGE: 'dateRange',
2547
+ DATE_TIME_PICKER: 'dateTime',
2548
+ DATE_TIME_RANGE: 'dateTimeRange',
2549
+ DATETIME_LOCAL_INPUT: 'dateTimeLocal',
2550
+ DIALOG: 'dialog',
2551
+ DRAWER: 'drawer',
2552
+ DROP_DOWN_TREE: 'dropDownTree',
2553
+ EMAIL_INPUT: 'email',
2554
+ ENTITY_LOOKUP: 'entityLookup',
2555
+ EXPANSION_PANEL: 'expansionPanel',
2556
+ FILE_SAVER: 'fileSaver',
2557
+ FILE_SELECT: 'fileSelect',
2558
+ FILE_UPLOAD: 'upload',
2559
+ FILTER: 'filter',
2560
+ FLOATING_LABEL: 'floatingLabel',
2561
+ FLOATING_ACTION_BUTTON: 'floatingActionButton',
2562
+ GRID: 'grid',
2563
+ GRID_LAYOUT: 'gridLayout',
2564
+ INPUT: 'input',
2565
+ INLINE_SELECT: 'inlineSelect',
2566
+ INLINE_SEARCHABLE_SELECT: 'inlineSearchableSelect',
2567
+ INLINE_ASYNC_SELECT: 'inlineAsyncSelect',
2568
+ INLINE_ENTITY_LOOKUP: 'inlineEntityLookup',
2569
+ INLINE_AUTOCOMPLETE: 'inlineAutocomplete',
2570
+ INLINE_INPUT: 'inlineInput',
2571
+ INLINE_PHONE: 'inlinePhone',
2572
+ INLINE_NUMBER: 'inlineNumber',
2573
+ INLINE_CURRENCY: 'inlineCurrency',
2574
+ INLINE_CURRENCY_RANGE: 'inlineCurrencyRange',
2575
+ INLINE_MULTISELECT: 'inlineMultiSelect',
2576
+ INLINE_TOGGLE: 'inlineToggle',
2577
+ INLINE_RANGE: 'inlineRange',
2578
+ INLINE_PERIOD_RANGE: 'inlinePeriodRange',
2579
+ INLINE_YEAR_RANGE: 'inlineYearRange',
2580
+ INLINE_MONTH_RANGE: 'inlineMonthRange',
2581
+ INLINE_DATE: 'inlineDate',
2582
+ INLINE_DATE_RANGE: 'inlineDateRange',
2583
+ INLINE_TIME: 'inlineTime',
2584
+ INLINE_TIME_RANGE: 'inlineTimeRange',
2585
+ INLINE_TREE_SELECT: 'inlineTreeSelect',
2586
+ INLINE_RATING: 'inlineRating',
2587
+ INLINE_DISTANCE_RADIUS: 'inlineDistanceRadius',
2588
+ INLINE_PIPELINE_STATUS: 'inlinePipelineStatus',
2589
+ INLINE_SCORE_PRIORITY: 'inlineScorePriority',
2590
+ INLINE_RELATIVE_PERIOD: 'inlineRelativePeriod',
2591
+ INLINE_SENTIMENT: 'inlineSentiment',
2592
+ INLINE_COLOR_LABEL: 'inlineColorLabel',
2593
+ LINEAR_GAUGE: 'linearGauge',
2594
+ LIST_VIEW: 'listView',
2595
+ MAP: 'map',
2596
+ MASKED_TEXT_BOX: 'maskedTextBox',
2597
+ MONTH_INPUT: 'month',
2598
+ MULTI_COLUMN_COMBO_BOX: 'multiColumnComboBox',
2599
+ MULTI_SELECT: 'multiSelect',
2600
+ MULTI_SELECT_TREE: 'multiSelectTree',
2601
+ TRANSFER_LIST: 'transferList',
2602
+ NOTIFICATION: 'notification',
2603
+ NUMERIC_TEXT_BOX: 'numericTextBox',
2604
+ PAGER: 'pager',
2605
+ PAGINATOR: 'paginator',
2606
+ PASSWORD: 'password',
2607
+ PDF_VIEWER: 'pdfViewer',
2608
+ PHONE: 'phone',
2609
+ PIVOT_GRID: 'pivotGrid',
2610
+ POPUP: 'popup',
2611
+ PROGRESS_BAR: 'progressBar',
2612
+ PROGRESS_SPINNER: 'progressSpinner',
2613
+ QR_CODE: 'qrCode',
2614
+ RADIO: 'radio',
2615
+ RADIAL_GAUGE: 'radialGauge',
2616
+ RANGE_SLIDER: 'rangeSlider',
2617
+ PRICE_RANGE: 'priceRange',
2618
+ RATING: 'rating',
2619
+ RICH_TEXT_EDITOR: 'richTextEditor',
2620
+ RIPPLE: 'ripple',
2621
+ SCROLL_VIEW: 'scrollView',
2622
+ SEARCH_INPUT: 'search',
2623
+ SEARCHABLE_SELECT: 'searchable-select',
2624
+ SELECTION_LIST: 'selectionList',
2625
+ SELECT: 'select',
2626
+ SIGNATURE: 'signature',
2627
+ SLIDER: 'slider',
2628
+ SORTABLE: 'sortable',
2629
+ SORTABLE_TABLE: 'sortableTable',
2630
+ SPLITTER: 'splitter',
2631
+ SPREADSHEET: 'spreadsheet',
2632
+ STACK_LAYOUT: 'stackLayout',
2633
+ STEP_BAR: 'stepBar',
2634
+ STEPPER: 'stepper',
2635
+ SVG_ICON: 'svgIcon',
2636
+ TABS: 'tabs',
2637
+ TEXTAREA: 'textarea',
2638
+ TIME_INPUT: 'time',
2639
+ TIME_PICKER: 'timePicker',
2640
+ TIME_RANGE: 'timeRange',
2641
+ TIMELINE: 'timeline',
2642
+ TOGGLE: 'toggle',
2643
+ TOOLBAR: 'toolbar',
2644
+ TOOLTIP: 'tooltip',
2645
+ TREE_VIEW: 'treeView',
2646
+ TREE_SELECT: 'treeSelect',
2647
+ TYPOGRAPHY: 'typography',
2648
+ URL_INPUT: 'url',
2649
+ WEEK_INPUT: 'week',
2650
+ WINDOW: 'window',
2651
+ YEAR_INPUT: 'year',
2652
+ };
2653
+
2654
+ const INLINE_FILTER_CONTROL_TYPES = Object.freeze({
2655
+ SELECT: FieldControlType.INLINE_SELECT,
2656
+ SEARCHABLE_SELECT: FieldControlType.INLINE_SEARCHABLE_SELECT,
2657
+ ASYNC_SELECT: FieldControlType.INLINE_ASYNC_SELECT,
2658
+ ENTITY_LOOKUP: FieldControlType.INLINE_ENTITY_LOOKUP,
2659
+ AUTOCOMPLETE: FieldControlType.INLINE_AUTOCOMPLETE,
2660
+ NUMBER: FieldControlType.INLINE_NUMBER,
2661
+ CURRENCY: FieldControlType.INLINE_CURRENCY,
2662
+ CURRENCY_RANGE: FieldControlType.INLINE_CURRENCY_RANGE,
2663
+ MULTI_SELECT: FieldControlType.INLINE_MULTISELECT,
2664
+ INPUT: FieldControlType.INLINE_INPUT,
2665
+ PHONE: FieldControlType.INLINE_PHONE,
2666
+ TOGGLE: FieldControlType.INLINE_TOGGLE,
2667
+ RANGE: FieldControlType.INLINE_RANGE,
2668
+ PERIOD_RANGE: FieldControlType.INLINE_PERIOD_RANGE,
2669
+ YEAR_RANGE: FieldControlType.INLINE_YEAR_RANGE,
2670
+ MONTH_RANGE: FieldControlType.INLINE_MONTH_RANGE,
2671
+ DATE: FieldControlType.INLINE_DATE,
2672
+ DATE_RANGE: FieldControlType.INLINE_DATE_RANGE,
2673
+ TIME: FieldControlType.INLINE_TIME,
2674
+ TIME_RANGE: FieldControlType.INLINE_TIME_RANGE,
2675
+ TREE_SELECT: FieldControlType.INLINE_TREE_SELECT,
2676
+ RATING: FieldControlType.INLINE_RATING,
2677
+ DISTANCE_RADIUS: FieldControlType.INLINE_DISTANCE_RADIUS,
2678
+ PIPELINE_STATUS: FieldControlType.INLINE_PIPELINE_STATUS,
2679
+ SCORE_PRIORITY: FieldControlType.INLINE_SCORE_PRIORITY,
2680
+ RELATIVE_PERIOD: FieldControlType.INLINE_RELATIVE_PERIOD,
2681
+ SENTIMENT: FieldControlType.INLINE_SENTIMENT,
2682
+ COLOR_LABEL: FieldControlType.INLINE_COLOR_LABEL,
2683
+ });
2684
+ const INLINE_FILTER_CONTROL_TYPE_VALUES = Object.freeze(Object.values(INLINE_FILTER_CONTROL_TYPES));
2685
+ const INLINE_FILTER_CONTROL_TYPE_SET = new Set(INLINE_FILTER_CONTROL_TYPE_VALUES);
2686
+ function normalizeInlineControlTypeToken(value) {
2687
+ return String(value || '')
2688
+ .trim()
2689
+ .toLowerCase()
2690
+ .replace(/[-_\s]/g, '');
2691
+ }
2692
+ const INLINE_FILTER_CANONICAL_TOKEN_TO_CONTROL_TYPE_MAP = {
2693
+ inlineselect: INLINE_FILTER_CONTROL_TYPES.SELECT,
2694
+ inlinesearchableselect: INLINE_FILTER_CONTROL_TYPES.SEARCHABLE_SELECT,
2695
+ inlineasyncselect: INLINE_FILTER_CONTROL_TYPES.ASYNC_SELECT,
2696
+ inlineentitylookup: INLINE_FILTER_CONTROL_TYPES.ENTITY_LOOKUP,
2697
+ inlineautocomplete: INLINE_FILTER_CONTROL_TYPES.AUTOCOMPLETE,
2698
+ inlinenumber: INLINE_FILTER_CONTROL_TYPES.NUMBER,
2699
+ inlinecurrency: INLINE_FILTER_CONTROL_TYPES.CURRENCY,
2700
+ inlinecurrencyrange: INLINE_FILTER_CONTROL_TYPES.CURRENCY_RANGE,
2701
+ inlinemultiselect: INLINE_FILTER_CONTROL_TYPES.MULTI_SELECT,
2702
+ inlineinput: INLINE_FILTER_CONTROL_TYPES.INPUT,
2703
+ inlinephone: INLINE_FILTER_CONTROL_TYPES.PHONE,
2704
+ inlinetoggle: INLINE_FILTER_CONTROL_TYPES.TOGGLE,
2705
+ inlinerange: INLINE_FILTER_CONTROL_TYPES.RANGE,
2706
+ inlineperiodrange: INLINE_FILTER_CONTROL_TYPES.PERIOD_RANGE,
2707
+ inlineyearrange: INLINE_FILTER_CONTROL_TYPES.YEAR_RANGE,
2708
+ inlinemonthrange: INLINE_FILTER_CONTROL_TYPES.MONTH_RANGE,
2709
+ inlinedate: INLINE_FILTER_CONTROL_TYPES.DATE,
2710
+ inlinedaterange: INLINE_FILTER_CONTROL_TYPES.DATE_RANGE,
2711
+ inlinetime: INLINE_FILTER_CONTROL_TYPES.TIME,
2712
+ inlinetimerange: INLINE_FILTER_CONTROL_TYPES.TIME_RANGE,
2713
+ inlinetreeselect: INLINE_FILTER_CONTROL_TYPES.TREE_SELECT,
2714
+ inlinerating: INLINE_FILTER_CONTROL_TYPES.RATING,
2715
+ inlinedistanceradius: INLINE_FILTER_CONTROL_TYPES.DISTANCE_RADIUS,
2716
+ inlinepipelinestatus: INLINE_FILTER_CONTROL_TYPES.PIPELINE_STATUS,
2717
+ inlinescorepriority: INLINE_FILTER_CONTROL_TYPES.SCORE_PRIORITY,
2718
+ inlinerelativeperiod: INLINE_FILTER_CONTROL_TYPES.RELATIVE_PERIOD,
2719
+ inlinesentiment: INLINE_FILTER_CONTROL_TYPES.SENTIMENT,
2720
+ inlinecolorlabel: INLINE_FILTER_CONTROL_TYPES.COLOR_LABEL,
2721
+ };
2722
+ const INLINE_FILTER_ALIAS_TOKEN_MAP = {};
2723
+ for (const [token, controlType] of Object.entries(INLINE_FILTER_CANONICAL_TOKEN_TO_CONTROL_TYPE_MAP)) {
2724
+ INLINE_FILTER_ALIAS_TOKEN_MAP[`filter${token}`] = controlType;
2725
+ INLINE_FILTER_ALIAS_TOKEN_MAP[`pdxfilter${token}`] = controlType;
2726
+ }
2727
+ const INLINE_FILTER_TOKEN_TO_CONTROL_TYPE = Object.freeze({
2728
+ ...INLINE_FILTER_CANONICAL_TOKEN_TO_CONTROL_TYPE_MAP,
2729
+ ...INLINE_FILTER_ALIAS_TOKEN_MAP,
2730
+ });
2731
+ const INLINE_FILTER_ALIAS_TOKENS = Object.freeze(Object.keys(INLINE_FILTER_ALIAS_TOKEN_MAP));
2732
+ const INLINE_FILTER_CANONICAL_TOKEN_TO_BASE_CONTROL_TYPE_MAP = {
2733
+ inlineselect: FieldControlType.SELECT,
2734
+ inlinesearchableselect: FieldControlType.SEARCHABLE_SELECT,
2735
+ inlineasyncselect: FieldControlType.ASYNC_SELECT,
2736
+ inlineentitylookup: FieldControlType.ENTITY_LOOKUP,
2737
+ inlineautocomplete: FieldControlType.AUTO_COMPLETE,
2738
+ inlinenumber: FieldControlType.NUMERIC_TEXT_BOX,
2739
+ inlinecurrency: FieldControlType.CURRENCY_INPUT,
2740
+ inlinecurrencyrange: FieldControlType.PRICE_RANGE,
2741
+ inlinemultiselect: FieldControlType.MULTI_SELECT,
2742
+ inlineinput: FieldControlType.INPUT,
2743
+ inlinephone: FieldControlType.PHONE,
2744
+ inlinetoggle: FieldControlType.TOGGLE,
2745
+ inlinerange: FieldControlType.RANGE_SLIDER,
2746
+ inlineperiodrange: FieldControlType.RANGE_SLIDER,
2747
+ inlineyearrange: FieldControlType.YEAR_INPUT,
2748
+ inlinemonthrange: FieldControlType.MONTH_INPUT,
2749
+ inlinedate: FieldControlType.DATE_PICKER,
2750
+ inlinedaterange: FieldControlType.DATE_RANGE,
2751
+ inlinetime: FieldControlType.TIME_PICKER,
2752
+ inlinetimerange: FieldControlType.TIME_RANGE,
2753
+ inlinetreeselect: FieldControlType.TREE_SELECT,
2754
+ inlinerating: FieldControlType.RATING,
2755
+ inlinedistanceradius: FieldControlType.INLINE_DISTANCE_RADIUS,
2756
+ inlinepipelinestatus: FieldControlType.INLINE_PIPELINE_STATUS,
2757
+ inlinescorepriority: FieldControlType.INLINE_SCORE_PRIORITY,
2758
+ inlinerelativeperiod: FieldControlType.INLINE_RELATIVE_PERIOD,
2759
+ inlinesentiment: FieldControlType.INLINE_SENTIMENT,
2760
+ inlinecolorlabel: FieldControlType.INLINE_COLOR_LABEL,
2761
+ };
2762
+ const INLINE_FILTER_ALIAS_TOKEN_TO_BASE_CONTROL_TYPE_MAP = {};
2763
+ for (const [aliasToken, controlType] of Object.entries(INLINE_FILTER_ALIAS_TOKEN_MAP)) {
2764
+ const canonicalToken = aliasToken.startsWith('pdxfilter')
2765
+ ? aliasToken.replace(/^pdxfilter/, '')
2766
+ : aliasToken.replace(/^filter/, '');
2767
+ const baseControlType = INLINE_FILTER_CANONICAL_TOKEN_TO_BASE_CONTROL_TYPE_MAP[canonicalToken];
2768
+ if (baseControlType) {
2769
+ INLINE_FILTER_ALIAS_TOKEN_TO_BASE_CONTROL_TYPE_MAP[aliasToken] = baseControlType;
2770
+ }
2771
+ }
2772
+ const INLINE_FILTER_TOKEN_TO_BASE_CONTROL_TYPE = Object.freeze({
2773
+ ...INLINE_FILTER_CANONICAL_TOKEN_TO_BASE_CONTROL_TYPE_MAP,
2774
+ ...INLINE_FILTER_ALIAS_TOKEN_TO_BASE_CONTROL_TYPE_MAP,
2775
+ });
2776
+ function resolveInlineFilterControlType(value) {
2777
+ const token = normalizeInlineControlTypeToken(value);
2778
+ if (!token)
2779
+ return undefined;
2780
+ return INLINE_FILTER_TOKEN_TO_CONTROL_TYPE[token];
2781
+ }
2782
+ function resolveInlineFilterControlTypeToBaseControlType(value) {
2783
+ const token = normalizeInlineControlTypeToken(value);
2784
+ if (!token)
2785
+ return undefined;
2786
+ return INLINE_FILTER_TOKEN_TO_BASE_CONTROL_TYPE[token];
2787
+ }
2788
+ function isInlineFilterControlType(value) {
2789
+ return INLINE_FILTER_CONTROL_TYPE_SET.has(String(value || '').trim());
2790
+ }
2791
+
2792
+ function toUpperSnakeCase(raw) {
2793
+ return raw
2794
+ .trim()
2795
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
2796
+ .replace(/[-\s]+/g, '_')
2797
+ .replace(/__+/g, '_')
2798
+ .toUpperCase();
2799
+ }
2800
+ function normalizeControlTypeToken(value) {
2801
+ return String(value || '')
2802
+ .trim()
2803
+ .toLowerCase()
2804
+ .replace(/[-_\s]/g, '');
2805
+ }
2806
+ const CONTROL_TYPE_TOKEN_TO_KEY = Object.entries(FieldControlType).reduce((acc, [key, controlTypeValue]) => {
2807
+ acc[normalizeControlTypeToken(key)] = key;
2808
+ acc[normalizeControlTypeToken(controlTypeValue)] = key;
2809
+ return acc;
2810
+ }, {});
2811
+ const ALIAS_TOKEN_TO_CONTROL_TYPE = {
2812
+ // Legacy/common synonyms
2813
+ searchable: FieldControlType.SEARCHABLE_SELECT,
2814
+ searchableinput: FieldControlType.SEARCHABLE_SELECT,
2815
+ searchableselect: FieldControlType.SEARCHABLE_SELECT,
2816
+ materialsearchableselect: FieldControlType.SEARCHABLE_SELECT,
2817
+ asyncselect: FieldControlType.ASYNC_SELECT,
2818
+ materialasyncselect: FieldControlType.ASYNC_SELECT,
2819
+ entitylookup: FieldControlType.ENTITY_LOOKUP,
2820
+ materialentitylookup: FieldControlType.ENTITY_LOOKUP,
2821
+ autocomplete: FieldControlType.AUTO_COMPLETE,
2822
+ multiselect: FieldControlType.MULTI_SELECT,
2823
+ multiselecttree: FieldControlType.MULTI_SELECT_TREE,
2824
+ treeselect: FieldControlType.TREE_SELECT,
2825
+ datepicker: FieldControlType.DATE_PICKER,
2826
+ daterange: FieldControlType.DATE_RANGE,
2827
+ datetime: FieldControlType.DATETIME_LOCAL_INPUT,
2828
+ timepicker: FieldControlType.TIME_PICKER,
2829
+ timerange: FieldControlType.TIME_RANGE,
2830
+ pricerange: FieldControlType.PRICE_RANGE,
2831
+ rangeslider: FieldControlType.RANGE_SLIDER,
2832
+ number: FieldControlType.NUMERIC_TEXT_BOX,
2833
+ numeric: FieldControlType.NUMERIC_TEXT_BOX,
2834
+ currencyinput: FieldControlType.CURRENCY_INPUT,
2835
+ switch: FieldControlType.TOGGLE,
2836
+ radiogroup: FieldControlType.RADIO,
2837
+ checkboxgroup: FieldControlType.CHECKBOX,
2838
+ chiplist: FieldControlType.CHIP_LIST,
2839
+ chipinput: FieldControlType.CHIP_INPUT,
2840
+ searchinput: FieldControlType.SEARCH_INPUT,
2841
+ };
2842
+ function normalizeControlTypeKey(value) {
2843
+ const token = normalizeControlTypeToken(value);
2844
+ if (!token)
2845
+ return '';
2846
+ const resolvedKey = CONTROL_TYPE_TOKEN_TO_KEY[token];
2847
+ if (resolvedKey)
2848
+ return resolvedKey;
2849
+ return toUpperSnakeCase(String(value || ''));
2850
+ }
2851
+ function resolveControlTypeAlias(value, fallback = FieldControlType.INPUT) {
2852
+ const raw = String(value || '').trim();
2853
+ if (!raw)
2854
+ return fallback;
2855
+ const token = normalizeControlTypeToken(raw);
2856
+ const inlineAliased = INLINE_FILTER_TOKEN_TO_BASE_CONTROL_TYPE[token];
2857
+ if (inlineAliased)
2858
+ return inlineAliased;
2859
+ const aliased = ALIAS_TOKEN_TO_CONTROL_TYPE[token];
2860
+ if (aliased)
2861
+ return aliased;
2862
+ const resolvedKey = CONTROL_TYPE_TOKEN_TO_KEY[token];
2863
+ if (resolvedKey) {
2864
+ return FieldControlType[resolvedKey];
2865
+ }
2866
+ return raw;
2867
+ }
2868
+
2869
+ const MAX_OPTION_SOURCE_DEPTH = 3;
2870
+ // Mirrors the backend custom-field key policy. Ordinary static field names are
2871
+ // outside this boundary; custom keys must be safe across all runtime consumers.
2872
+ const RESERVED_CUSTOM_FIELD_KEYS = new Set([
2873
+ 'constructor', 'prototype', 'hasOwnProperty', 'isPrototypeOf',
2874
+ 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf',
2875
+ ]);
1017
2876
  const VALUE_PRESENTATION_TYPES = new Set([
1018
2877
  'string',
1019
2878
  'number',
@@ -1262,6 +3121,33 @@ class SchemaNormalizationKernel {
1262
3121
  }
1263
3122
  return false;
1264
3123
  }
3124
+ parseOptionalBoolean(value) {
3125
+ if (typeof value === 'boolean') {
3126
+ return value;
3127
+ }
3128
+ if (typeof value === 'string') {
3129
+ const normalized = value.trim().toLowerCase();
3130
+ if (normalized === 'true') {
3131
+ return true;
3132
+ }
3133
+ if (normalized === 'false') {
3134
+ return false;
3135
+ }
3136
+ }
3137
+ return undefined;
3138
+ }
3139
+ parseOptionalFiniteNumber(value) {
3140
+ if (typeof value === 'number' && Number.isFinite(value)) {
3141
+ return value;
3142
+ }
3143
+ if (typeof value === 'string' && value.trim().length > 0) {
3144
+ const parsed = Number(value);
3145
+ if (Number.isFinite(parsed)) {
3146
+ return parsed;
3147
+ }
3148
+ }
3149
+ return undefined;
3150
+ }
1265
3151
  /** Ensure an array of strings from various inputs. */
1266
3152
  parseStringArray(value) {
1267
3153
  if (Array.isArray(value)) {
@@ -1278,6 +3164,41 @@ class SchemaNormalizationKernel {
1278
3164
  .filter((v) => v.length > 0);
1279
3165
  return normalized.filter((v, index) => normalized.indexOf(v) === index);
1280
3166
  }
3167
+ parseDependsOn(value) {
3168
+ const rawItems = Array.isArray(value)
3169
+ ? value
3170
+ : typeof value === 'string'
3171
+ ? value.split(',')
3172
+ : [];
3173
+ const normalized = rawItems
3174
+ .map((item) => (typeof item === 'string' ? item.trim() : ''))
3175
+ .filter((item) => item.length > 0);
3176
+ return normalized.filter((item, index) => normalized.indexOf(item) === index);
3177
+ }
3178
+ parseStrictStringRecord(value) {
3179
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
3180
+ return undefined;
3181
+ }
3182
+ const normalized = Object.entries(value)
3183
+ .reduce((acc, [key, mapValue]) => {
3184
+ if (typeof mapValue !== 'string') {
3185
+ return acc;
3186
+ }
3187
+ const normalizedKey = String(key).trim();
3188
+ if (!normalizedKey ||
3189
+ normalizedKey === '__proto__' ||
3190
+ normalizedKey === 'constructor' ||
3191
+ normalizedKey === 'prototype') {
3192
+ return acc;
3193
+ }
3194
+ const normalizedValue = mapValue.trim();
3195
+ if (normalizedValue) {
3196
+ acc[normalizedKey] = normalizedValue;
3197
+ }
3198
+ return acc;
3199
+ }, {});
3200
+ return Object.keys(normalized).length ? normalized : undefined;
3201
+ }
1281
3202
  parseStringRecord(value) {
1282
3203
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
1283
3204
  return undefined;
@@ -1365,9 +3286,15 @@ class SchemaNormalizationKernel {
1365
3286
  if (value.kind !== undefined) {
1366
3287
  detail.kind = String(value.kind);
1367
3288
  }
3289
+ if (value.resourceKey !== undefined && String(value.resourceKey).trim().length > 0) {
3290
+ detail.resourceKey = String(value.resourceKey).trim();
3291
+ }
1368
3292
  if (value.surfaceId !== undefined) {
1369
3293
  detail.surfaceId = String(value.surfaceId);
1370
3294
  }
3295
+ if (value.previewSurfaceId !== undefined && String(value.previewSurfaceId).trim().length > 0) {
3296
+ detail.previewSurfaceId = String(value.previewSurfaceId).trim();
3297
+ }
1371
3298
  if (value.presentation !== undefined) {
1372
3299
  detail.presentation = String(value.presentation);
1373
3300
  }
@@ -1392,6 +3319,11 @@ class SchemaNormalizationKernel {
1392
3319
  'resultLayout',
1393
3320
  'primaryPropertyPath',
1394
3321
  'avatarPropertyPath',
3322
+ 'detailActionLabel',
3323
+ 'quickViewActionLabel',
3324
+ 'copyCodeActionLabel',
3325
+ 'copyIdActionLabel',
3326
+ 'createActionLabel',
1395
3327
  ];
1396
3328
  stringKeys.forEach((key) => {
1397
3329
  if (value[key] !== undefined) {
@@ -1429,6 +3361,10 @@ class SchemaNormalizationKernel {
1429
3361
  if (value.maxVisibleBadges !== undefined && !Number.isNaN(Number(value.maxVisibleBadges))) {
1430
3362
  display.maxVisibleBadges = Number(value.maxVisibleBadges);
1431
3363
  }
3364
+ const actions = this.parseLookupActions(value.actions);
3365
+ if (actions) {
3366
+ display.actions = actions;
3367
+ }
1432
3368
  return Object.keys(display).length ? display : undefined;
1433
3369
  }
1434
3370
  parseLookupDisplayField(value) {
@@ -1443,6 +3379,28 @@ class SchemaNormalizationKernel {
1443
3379
  });
1444
3380
  return Object.keys(field).length ? field : undefined;
1445
3381
  }
3382
+ parseLookupActions(value) {
3383
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
3384
+ return undefined;
3385
+ }
3386
+ const actions = {};
3387
+ if (value.showDetail !== undefined) {
3388
+ actions.showDetail = this.parseBoolean(value.showDetail);
3389
+ }
3390
+ if (value.showQuickView !== undefined) {
3391
+ actions.showQuickView = this.parseBoolean(value.showQuickView);
3392
+ }
3393
+ if (value.showCopyCode !== undefined) {
3394
+ actions.showCopyCode = this.parseBoolean(value.showCopyCode);
3395
+ }
3396
+ if (value.showCopyId !== undefined) {
3397
+ actions.showCopyId = this.parseBoolean(value.showCopyId);
3398
+ }
3399
+ if (value.showCreate !== undefined) {
3400
+ actions.showCreate = this.parseBoolean(value.showCreate);
3401
+ }
3402
+ return Object.keys(actions).length ? actions : undefined;
3403
+ }
1446
3404
  parseLookupCreate(value) {
1447
3405
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
1448
3406
  return undefined;
@@ -1498,10 +3456,13 @@ class SchemaNormalizationKernel {
1498
3456
  }
1499
3457
  const dialog = {};
1500
3458
  if (value.enabled !== undefined) {
1501
- dialog.enabled = this.parseBoolean(value.enabled);
3459
+ const enabled = this.parseOptionalBoolean(value.enabled);
3460
+ if (enabled !== undefined) {
3461
+ dialog.enabled = enabled;
3462
+ }
1502
3463
  }
1503
- if (value.title !== undefined) {
1504
- const title = String(value.title).trim();
3464
+ if (typeof value.title === 'string') {
3465
+ const title = value.title.trim();
1505
3466
  if (title) {
1506
3467
  dialog.title = title;
1507
3468
  }
@@ -1513,13 +3474,22 @@ class SchemaNormalizationKernel {
1513
3474
  }
1514
3475
  }
1515
3476
  if (value.previewPanel !== undefined) {
1516
- dialog.previewPanel = this.parseBoolean(value.previewPanel);
3477
+ const previewPanel = this.parseOptionalBoolean(value.previewPanel);
3478
+ if (previewPanel !== undefined) {
3479
+ dialog.previewPanel = previewPanel;
3480
+ }
1517
3481
  }
1518
3482
  if (value.allowColumnChooser !== undefined) {
1519
- dialog.allowColumnChooser = this.parseBoolean(value.allowColumnChooser);
3483
+ const allowColumnChooser = this.parseOptionalBoolean(value.allowColumnChooser);
3484
+ if (allowColumnChooser !== undefined) {
3485
+ dialog.allowColumnChooser = allowColumnChooser;
3486
+ }
1520
3487
  }
1521
3488
  if (value.allowSavedViews !== undefined) {
1522
- dialog.allowSavedViews = this.parseBoolean(value.allowSavedViews);
3489
+ const allowSavedViews = this.parseOptionalBoolean(value.allowSavedViews);
3490
+ if (allowSavedViews !== undefined) {
3491
+ dialog.allowSavedViews = allowSavedViews;
3492
+ }
1523
3493
  }
1524
3494
  if (Array.isArray(value.resultColumns)) {
1525
3495
  const resultColumns = value.resultColumns
@@ -1529,20 +3499,20 @@ class SchemaNormalizationKernel {
1529
3499
  dialog.resultColumns = resultColumns;
1530
3500
  }
1531
3501
  }
1532
- if (value.openActionLabel !== undefined) {
1533
- const openActionLabel = String(value.openActionLabel).trim();
3502
+ if (typeof value.openActionLabel === 'string') {
3503
+ const openActionLabel = value.openActionLabel.trim();
1534
3504
  if (openActionLabel) {
1535
3505
  dialog.openActionLabel = openActionLabel;
1536
3506
  }
1537
3507
  }
1538
- if (value.applyActionLabel !== undefined) {
1539
- const applyActionLabel = String(value.applyActionLabel).trim();
3508
+ if (typeof value.applyActionLabel === 'string') {
3509
+ const applyActionLabel = value.applyActionLabel.trim();
1540
3510
  if (applyActionLabel) {
1541
3511
  dialog.applyActionLabel = applyActionLabel;
1542
3512
  }
1543
3513
  }
1544
- if (value.cancelActionLabel !== undefined) {
1545
- const cancelActionLabel = String(value.cancelActionLabel).trim();
3514
+ if (typeof value.cancelActionLabel === 'string') {
3515
+ const cancelActionLabel = value.cancelActionLabel.trim();
1546
3516
  if (cancelActionLabel) {
1547
3517
  dialog.cancelActionLabel = cancelActionLabel;
1548
3518
  }
@@ -1553,19 +3523,19 @@ class SchemaNormalizationKernel {
1553
3523
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
1554
3524
  return undefined;
1555
3525
  }
1556
- const field = String(value.field ?? '').trim();
3526
+ const field = typeof value.field === 'string' ? value.field.trim() : '';
1557
3527
  if (!field) {
1558
3528
  return undefined;
1559
3529
  }
1560
3530
  const column = { field };
1561
- if (value.label !== undefined) {
1562
- const label = String(value.label).trim();
3531
+ if (typeof value.label === 'string') {
3532
+ const label = value.label.trim();
1563
3533
  if (label) {
1564
3534
  column.label = label;
1565
3535
  }
1566
3536
  }
1567
- if (value.kind !== undefined) {
1568
- const kind = String(value.kind).trim();
3537
+ if (typeof value.kind === 'string') {
3538
+ const kind = value.kind.trim();
1569
3539
  if (kind === 'code' ||
1570
3540
  kind === 'label' ||
1571
3541
  kind === 'description' ||
@@ -1575,15 +3545,137 @@ class SchemaNormalizationKernel {
1575
3545
  column.kind = kind;
1576
3546
  }
1577
3547
  }
1578
- if (value.width !== undefined) {
1579
- const width = String(value.width).trim();
3548
+ if (typeof value.width === 'string') {
3549
+ const width = value.width.trim();
1580
3550
  if (width) {
1581
3551
  column.width = width;
1582
3552
  }
1583
3553
  }
1584
3554
  return column;
1585
3555
  }
1586
- parseLookupFilterDefinition(value) {
3556
+ mergeLookupDialog(base, override) {
3557
+ const merged = {
3558
+ ...(this.parseLookupDialog(base) ?? {}),
3559
+ ...(this.parseLookupDialog(override) ?? {}),
3560
+ };
3561
+ return Object.keys(merged).length ? merged : undefined;
3562
+ }
3563
+ parseLookupFilterOptions(value) {
3564
+ if (!Array.isArray(value)) {
3565
+ return undefined;
3566
+ }
3567
+ const options = [];
3568
+ const seen = new Set();
3569
+ for (const item of value) {
3570
+ if (typeof item === 'string' ||
3571
+ typeof item === 'number' ||
3572
+ typeof item === 'boolean') {
3573
+ let parsedValue;
3574
+ if (typeof item === 'string') {
3575
+ const trimmed = item.trim();
3576
+ if (!trimmed) {
3577
+ continue;
3578
+ }
3579
+ parsedValue = trimmed;
3580
+ }
3581
+ else if (typeof item === 'number') {
3582
+ if (!Number.isFinite(item)) {
3583
+ continue;
3584
+ }
3585
+ parsedValue = item;
3586
+ }
3587
+ else {
3588
+ parsedValue = item;
3589
+ }
3590
+ const dedupeKey = `${typeof parsedValue}:${String(parsedValue)}`;
3591
+ if (seen.has(dedupeKey)) {
3592
+ continue;
3593
+ }
3594
+ seen.add(dedupeKey);
3595
+ options.push({
3596
+ value: parsedValue,
3597
+ label: String(parsedValue),
3598
+ });
3599
+ continue;
3600
+ }
3601
+ if (!item || typeof item !== 'object' || Array.isArray(item)) {
3602
+ continue;
3603
+ }
3604
+ const raw = item;
3605
+ const isLegacyKeyValue = raw['key'] !== undefined &&
3606
+ raw['key'] !== null &&
3607
+ raw['label'] === undefined &&
3608
+ raw['text'] === undefined &&
3609
+ typeof raw['value'] === 'string' &&
3610
+ raw['key'] !== raw['value'];
3611
+ const rawValue = isLegacyKeyValue
3612
+ ? raw['key']
3613
+ : raw['value'] !== undefined && raw['value'] !== null
3614
+ ? raw['value']
3615
+ : raw['key'];
3616
+ const rawLabel = isLegacyKeyValue
3617
+ ? raw['value']
3618
+ : raw['label'] ?? raw['text'];
3619
+ let parsedValue;
3620
+ if (typeof rawValue === 'string') {
3621
+ const trimmed = rawValue.trim();
3622
+ if (!trimmed) {
3623
+ continue;
3624
+ }
3625
+ parsedValue = trimmed;
3626
+ }
3627
+ else if (typeof rawValue === 'number') {
3628
+ if (!Number.isFinite(rawValue)) {
3629
+ continue;
3630
+ }
3631
+ parsedValue = rawValue;
3632
+ }
3633
+ else if (typeof rawValue === 'boolean') {
3634
+ parsedValue = rawValue;
3635
+ }
3636
+ else {
3637
+ continue;
3638
+ }
3639
+ const dedupeKey = `${typeof parsedValue}:${String(parsedValue)}`;
3640
+ if (seen.has(dedupeKey)) {
3641
+ continue;
3642
+ }
3643
+ seen.add(dedupeKey);
3644
+ let label;
3645
+ if (typeof rawLabel === 'string' && rawLabel.trim().length > 0) {
3646
+ label = rawLabel.trim();
3647
+ }
3648
+ else if ((typeof rawLabel === 'number' && Number.isFinite(rawLabel)) ||
3649
+ typeof rawLabel === 'boolean') {
3650
+ label = String(rawLabel);
3651
+ }
3652
+ else {
3653
+ label = String(parsedValue);
3654
+ }
3655
+ const option = {
3656
+ value: parsedValue,
3657
+ label,
3658
+ };
3659
+ if (typeof raw['icon'] === 'string' && raw['icon'].trim()) {
3660
+ option.icon = raw['icon'].trim();
3661
+ }
3662
+ if (typeof raw['tone'] === 'string' && raw['tone'].trim()) {
3663
+ option.tone = raw['tone'].trim();
3664
+ }
3665
+ if (typeof raw['description'] === 'string' && raw['description'].trim()) {
3666
+ option.description = raw['description'].trim();
3667
+ }
3668
+ if (raw['disabled'] !== undefined) {
3669
+ const disabled = this.parseOptionalBoolean(raw['disabled']);
3670
+ if (disabled !== undefined) {
3671
+ option.disabled = disabled;
3672
+ }
3673
+ }
3674
+ options.push(option);
3675
+ }
3676
+ return options.length ? options : undefined;
3677
+ }
3678
+ parseLookupFilterDefinition(value, optionSourceDepth = 0, visitedOptionSources = new Set()) {
1587
3679
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
1588
3680
  return undefined;
1589
3681
  }
@@ -1608,8 +3700,38 @@ class SchemaNormalizationKernel {
1608
3700
  if (defaultOperator && operators.includes(defaultOperator)) {
1609
3701
  definition.defaultOperator = defaultOperator;
1610
3702
  }
1611
- if (value.optionsSource !== undefined) {
1612
- const optionsSource = String(value.optionsSource).trim();
3703
+ if (value.options !== undefined) {
3704
+ const options = this.parseLookupFilterOptions(value.options);
3705
+ if (options) {
3706
+ definition.options = options;
3707
+ }
3708
+ }
3709
+ if (typeof value.optionSource === 'string') {
3710
+ const optionSource = value.optionSource.trim();
3711
+ if (optionSource) {
3712
+ definition.optionSource = optionSource;
3713
+ }
3714
+ }
3715
+ else if (value.optionSource &&
3716
+ typeof value.optionSource === 'object' &&
3717
+ !Array.isArray(value.optionSource)) {
3718
+ const optionSource = this.parseOptionSource(value.optionSource, optionSourceDepth + 1, visitedOptionSources);
3719
+ if (optionSource) {
3720
+ definition.optionSource = optionSource;
3721
+ }
3722
+ }
3723
+ if (value.dependsOn !== undefined) {
3724
+ const dependsOn = this.parseDependsOn(value.dependsOn);
3725
+ if (dependsOn.length) {
3726
+ definition.dependsOn = dependsOn;
3727
+ }
3728
+ }
3729
+ const dependencyFilterMap = this.parseStrictStringRecord(value.dependencyFilterMap);
3730
+ if (dependencyFilterMap) {
3731
+ definition.dependencyFilterMap = dependencyFilterMap;
3732
+ }
3733
+ if (typeof value.optionsSource === 'string') {
3734
+ const optionsSource = value.optionsSource.trim();
1613
3735
  if (optionsSource) {
1614
3736
  definition.optionsSource = optionsSource;
1615
3737
  }
@@ -1643,7 +3765,7 @@ class SchemaNormalizationKernel {
1643
3765
  }, {});
1644
3766
  return Object.keys(normalized).length ? normalized : undefined;
1645
3767
  }
1646
- parseLookupFiltering(value) {
3768
+ parseLookupFiltering(value, optionSourceDepth = 0, visitedOptionSources = new Set()) {
1647
3769
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
1648
3770
  return undefined;
1649
3771
  }
@@ -1651,7 +3773,7 @@ class SchemaNormalizationKernel {
1651
3773
  if (value.availableFilters !== undefined) {
1652
3774
  const availableFilters = Array.isArray(value.availableFilters)
1653
3775
  ? value.availableFilters
1654
- .map((item) => this.parseLookupFilterDefinition(item))
3776
+ .map((item) => this.parseLookupFilterDefinition(item, optionSourceDepth, visitedOptionSources))
1655
3777
  .filter((item) => !!item)
1656
3778
  : [];
1657
3779
  if (availableFilters.length) {
@@ -1737,6 +3859,12 @@ class SchemaNormalizationKernel {
1737
3859
  filtering.searchStrategies = searchStrategies;
1738
3860
  }
1739
3861
  }
3862
+ if (typeof value.defaultSearchStrategy === 'string') {
3863
+ const defaultSearchStrategy = value.defaultSearchStrategy.trim();
3864
+ if (defaultSearchStrategy) {
3865
+ filtering.defaultSearchStrategy = defaultSearchStrategy;
3866
+ }
3867
+ }
1740
3868
  return Object.keys(filtering).length ? filtering : undefined;
1741
3869
  }
1742
3870
  /** Parse option arrays into `{ key, value }` objects with label preservation. */
@@ -1767,16 +3895,23 @@ class SchemaNormalizationKernel {
1767
3895
  return { key: String(opt), value: String(opt) };
1768
3896
  });
1769
3897
  }
1770
- parseOptionSource(value) {
1771
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
3898
+ parseOptionSource(value, depth = 0, visited = new Set()) {
3899
+ if (!value ||
3900
+ typeof value !== 'object' ||
3901
+ Array.isArray(value) ||
3902
+ depth > MAX_OPTION_SOURCE_DEPTH ||
3903
+ visited.has(value)) {
1772
3904
  return undefined;
1773
3905
  }
1774
- const optionSource = {
1775
- key: String(value.key ?? '').trim(),
1776
- };
1777
- if (!optionSource.key) {
3906
+ const key = String(value.key ?? '').trim();
3907
+ if (!key) {
1778
3908
  return undefined;
1779
3909
  }
3910
+ const nextVisited = new Set(visited);
3911
+ nextVisited.add(value);
3912
+ const optionSource = {
3913
+ key,
3914
+ };
1780
3915
  if (value.type !== undefined) {
1781
3916
  const optionSourceType = this.parseOptionSourceType(value.type);
1782
3917
  if (optionSourceType) {
@@ -1820,12 +3955,12 @@ class SchemaNormalizationKernel {
1820
3955
  optionSource.searchPropertyPaths = this.parseStringArray(value.searchPropertyPaths);
1821
3956
  }
1822
3957
  if (value.dependsOn !== undefined) {
1823
- const dependsOn = this.parseNonBlankStringArray(value.dependsOn);
3958
+ const dependsOn = this.parseDependsOn(value.dependsOn);
1824
3959
  if (dependsOn.length) {
1825
3960
  optionSource.dependsOn = dependsOn;
1826
3961
  }
1827
3962
  }
1828
- const dependencyFilterMap = this.parseStringRecord(value.dependencyFilterMap);
3963
+ const dependencyFilterMap = this.parseStrictStringRecord(value.dependencyFilterMap);
1829
3964
  if (dependencyFilterMap) {
1830
3965
  optionSource.dependencyFilterMap = dependencyFilterMap;
1831
3966
  }
@@ -1849,10 +3984,14 @@ class SchemaNormalizationKernel {
1849
3984
  if (create) {
1850
3985
  optionSource.create = create;
1851
3986
  }
1852
- const filtering = this.parseLookupFiltering(value.filtering);
3987
+ const filtering = this.parseLookupFiltering(value.filtering, depth, nextVisited);
1853
3988
  if (filtering) {
1854
3989
  optionSource.filtering = filtering;
1855
3990
  }
3991
+ const dialog = this.parseLookupDialog(value.dialog);
3992
+ if (dialog) {
3993
+ optionSource.dialog = dialog;
3994
+ }
1856
3995
  if (value.excludeSelfField !== undefined) {
1857
3996
  optionSource.excludeSelfField = this.parseBoolean(value.excludeSelfField);
1858
3997
  }
@@ -1898,6 +4037,34 @@ class SchemaNormalizationKernel {
1898
4037
  const normalized = String(value ?? '').trim();
1899
4038
  return OPTION_SOURCE_INVALID_SORT_POLICIES.has(normalized) ? normalized : undefined;
1900
4039
  }
4040
+ parseResourceReference(value) {
4041
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
4042
+ return undefined;
4043
+ }
4044
+ const raw = value;
4045
+ const resourceKey = String(raw['resourceKey'] ?? '').trim();
4046
+ if (!resourceKey) {
4047
+ return undefined;
4048
+ }
4049
+ const ref = { resourceKey };
4050
+ const valueField = String(raw['valueField'] ?? '').trim();
4051
+ if (valueField) {
4052
+ ref.valueField = valueField;
4053
+ }
4054
+ const surfaceId = String(raw['surfaceId'] ?? '').trim();
4055
+ if (surfaceId) {
4056
+ ref.surfaceId = surfaceId;
4057
+ }
4058
+ const previewSurfaceId = String(raw['previewSurfaceId'] ?? '').trim();
4059
+ if (previewSurfaceId) {
4060
+ ref.previewSurfaceId = previewSurfaceId;
4061
+ }
4062
+ const detailPresentation = String(raw['detailPresentation'] ?? '').trim();
4063
+ if (detailPresentation === 'drawer' || detailPresentation === 'modal') {
4064
+ ref.detailPresentation = detailPresentation;
4065
+ }
4066
+ return ref;
4067
+ }
1901
4068
  parseLookupOpenDetailMode(value) {
1902
4069
  const normalized = String(value ?? '').trim();
1903
4070
  return LOOKUP_OPEN_DETAIL_MODES.has(normalized) ? normalized : undefined;
@@ -2015,10 +4182,14 @@ class SchemaNormalizationKernel {
2015
4182
  out.maxLength = Number(ui.maxLength);
2016
4183
  if (ui.maxLengthMessage !== undefined)
2017
4184
  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);
4185
+ if (ui.min !== undefined) {
4186
+ const parsedMin = Number(ui.min);
4187
+ out.min = Number.isFinite(parsedMin) ? parsedMin : String(ui.min).trim();
4188
+ }
4189
+ if (ui.max !== undefined) {
4190
+ const parsedMax = Number(ui.max);
4191
+ out.max = Number.isFinite(parsedMax) ? parsedMax : String(ui.max).trim();
4192
+ }
2022
4193
  if (ui.minMessage !== undefined)
2023
4194
  out.minMessage = ui.minMessage;
2024
4195
  if (ui.maxMessage !== undefined)
@@ -2155,14 +4326,25 @@ class SchemaNormalizationKernel {
2155
4326
  return ['number', 'integer', 'int', 'float', 'double', 'decimal'].includes(token);
2156
4327
  }
2157
4328
  resolveNumericFormatToken(prop, ui, resolvedType) {
4329
+ if (ui?.numberFormat?.percentage === true || ui?.['numberFormat.percentage'] === true) {
4330
+ return 'percent';
4331
+ }
4332
+ const explicitUiFormat = this.resolveNonEmptyStringToken(ui?.numericFormat, ui?.numberFormat?.style, ui?.['numberFormat.style']);
4333
+ if (explicitUiFormat) {
4334
+ return explicitUiFormat;
4335
+ }
2158
4336
  const typeToken = resolvedType ?? prop?.type;
2159
4337
  if (!this.isNumericSchemaType(typeToken)) {
2160
4338
  return undefined;
2161
4339
  }
2162
- if (ui?.numberFormat?.percentage === true || ui?.['numberFormat.percentage'] === true) {
2163
- return 'percent';
4340
+ const explicitFormat = this.resolveNonEmptyStringToken(ui?.format, prop?.format);
4341
+ if (explicitFormat) {
4342
+ return explicitFormat;
2164
4343
  }
2165
- return this.resolveNonEmptyStringToken(ui?.numericFormat, ui?.format, ui?.numberFormat?.style, ui?.['numberFormat.style'], prop?.format);
4344
+ if (String(prop?.type ?? '').trim().toLowerCase() === 'integer') {
4345
+ return 'integer';
4346
+ }
4347
+ return undefined;
2166
4348
  }
2167
4349
  /**
2168
4350
  * Converte o schema bruto do backend (OpenAPI + x-ui) em FieldDefinition[] tipado.
@@ -2177,6 +4359,232 @@ class SchemaNormalizationKernel {
2177
4359
  normalizeSchema(schema) {
2178
4360
  return this.normalizeSchemaWithRoot(schema, schema);
2179
4361
  }
4362
+ /**
4363
+ * Extrai metadados estruturais de nível raiz (`x-ui` no objeto schema),
4364
+ * cobrindo `formLayout`, `progression`, `timeline`, `schedule`, `hierarchy`,
4365
+ * `calculationMemory`, `contextBinding` e `resourceState`.
4366
+ */
4367
+ extractRootUiMetadata(schema) {
4368
+ const ui = schema &&
4369
+ typeof schema === 'object' &&
4370
+ !Array.isArray(schema) &&
4371
+ schema['x-ui'] &&
4372
+ typeof schema['x-ui'] === 'object' &&
4373
+ !Array.isArray(schema['x-ui'])
4374
+ ? schema['x-ui']
4375
+ : undefined;
4376
+ if (!ui) {
4377
+ return null;
4378
+ }
4379
+ const out = {};
4380
+ const formLayout = this.parseSchemaFormLayout(ui['formLayout']);
4381
+ if (formLayout)
4382
+ out.formLayout = formLayout;
4383
+ if (ui['progression'] && typeof ui['progression'] === 'object' && !Array.isArray(ui['progression'])) {
4384
+ out.progression = this.clonePlain(ui['progression']);
4385
+ }
4386
+ if (ui['timeline'] && typeof ui['timeline'] === 'object' && !Array.isArray(ui['timeline'])) {
4387
+ out.timeline = this.clonePlain(ui['timeline']);
4388
+ }
4389
+ if (ui['timelineLanes'] && typeof ui['timelineLanes'] === 'object' && !Array.isArray(ui['timelineLanes'])) {
4390
+ out.timelineLanes = this.clonePlain(ui['timelineLanes']);
4391
+ }
4392
+ if (ui['schedule'] && typeof ui['schedule'] === 'object' && !Array.isArray(ui['schedule'])) {
4393
+ out.schedule = this.clonePlain(ui['schedule']);
4394
+ }
4395
+ if (ui['hierarchy'] && typeof ui['hierarchy'] === 'object' && !Array.isArray(ui['hierarchy'])) {
4396
+ out.hierarchy = this.clonePlain(ui['hierarchy']);
4397
+ }
4398
+ if (ui['relationshipGraph'] && typeof ui['relationshipGraph'] === 'object' && !Array.isArray(ui['relationshipGraph'])) {
4399
+ out.relationshipGraph = this.clonePlain(ui['relationshipGraph']);
4400
+ }
4401
+ if (ui['calculationMemory'] && typeof ui['calculationMemory'] === 'object' && !Array.isArray(ui['calculationMemory'])) {
4402
+ out.calculationMemory = this.clonePlain(ui['calculationMemory']);
4403
+ }
4404
+ const contextBinding = this.parseContextBinding(ui['contextBinding']);
4405
+ if (contextBinding)
4406
+ out.contextBinding = contextBinding;
4407
+ const resourceState = this.parseResourceState(ui['resourceState']);
4408
+ if (resourceState)
4409
+ out.resourceState = resourceState;
4410
+ return Object.keys(out).length > 0 ? out : null;
4411
+ }
4412
+ parseSchemaFormLayout(raw) {
4413
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
4414
+ return undefined;
4415
+ }
4416
+ const record = raw;
4417
+ const rawMode = String(record['mode'] ?? 'flat').trim().toLowerCase();
4418
+ const mode = rawMode === 'tabs' || rawMode === 'accordion' || rawMode === 'stepper' || rawMode === 'flat'
4419
+ ? rawMode
4420
+ : rawMode === 'vertical'
4421
+ ? 'flat'
4422
+ : 'flat';
4423
+ const defaultTabId = typeof record['defaultTabId'] === 'string' && record['defaultTabId'].trim()
4424
+ ? record['defaultTabId'].trim()
4425
+ : undefined;
4426
+ const rawTabsAppearance = typeof record['tabsAppearance'] === 'string'
4427
+ ? record['tabsAppearance'].trim().toLowerCase()
4428
+ : '';
4429
+ const tabsAppearance = rawTabsAppearance === 'pills' ||
4430
+ rawTabsAppearance === 'underline' ||
4431
+ rawTabsAppearance === 'buttons'
4432
+ ? rawTabsAppearance
4433
+ : undefined;
4434
+ const accordionMulti = this.parseOptionalBoolean(record['accordionMulti']);
4435
+ const hideSectionHeaderInTabs = this.parseOptionalBoolean(record['hideSectionHeaderInTabs']);
4436
+ const hideSectionHeaderInStepper = this.parseOptionalBoolean(record['hideSectionHeaderInStepper']);
4437
+ const rawStepperInReadMode = typeof record['stepperInReadMode'] === 'string'
4438
+ ? record['stepperInReadMode'].trim().toLowerCase()
4439
+ : '';
4440
+ const stepperInReadMode = rawStepperInReadMode === 'presentation' ||
4441
+ rawStepperInReadMode === 'all' ||
4442
+ rawStepperInReadMode === 'none'
4443
+ ? rawStepperInReadMode
4444
+ : undefined;
4445
+ const stepperReviewStep = this.parseOptionalBoolean(record['stepperReviewStep']);
4446
+ const rawSections = Array.isArray(record['sections']) ? record['sections'] : [];
4447
+ const sections = [];
4448
+ for (let idx = 0; idx < rawSections.length; idx++) {
4449
+ const entry = rawSections[idx];
4450
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
4451
+ continue;
4452
+ const item = entry;
4453
+ const id = String(item['id'] ?? '').trim();
4454
+ const title = String(item['title'] ?? '').trim();
4455
+ if (!id || !title)
4456
+ continue;
4457
+ const orderNum = Number(item['order']);
4458
+ const subtitle = typeof item['subtitle'] === 'string' && item['subtitle'].trim() ? item['subtitle'].trim() : undefined;
4459
+ const icon = typeof item['icon'] === 'string' && item['icon'].trim() ? item['icon'].trim() : undefined;
4460
+ const groups = this.parseNonBlankStringArray(item['groups']);
4461
+ const optional = this.parseOptionalBoolean(item['optional']);
4462
+ sections.push({
4463
+ id,
4464
+ title,
4465
+ ...(subtitle ? { subtitle } : {}),
4466
+ ...(icon ? { icon } : {}),
4467
+ order: Number.isFinite(orderNum) ? orderNum : idx,
4468
+ ...(groups.length ? { groups } : {}),
4469
+ ...(optional !== undefined ? { optional } : {}),
4470
+ });
4471
+ }
4472
+ sections.sort((a, b) => a.order - b.order);
4473
+ const rawSteps = Array.isArray(record['steps']) ? record['steps'] : [];
4474
+ const steps = [];
4475
+ for (const entry of rawSteps) {
4476
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
4477
+ continue;
4478
+ const item = entry;
4479
+ const id = String(item['id'] ?? '').trim();
4480
+ const label = String(item['label'] ?? '').trim() || id;
4481
+ const sectionIds = this.parseNonBlankStringArray(item['sectionIds']);
4482
+ if (!id || !sectionIds.length)
4483
+ continue;
4484
+ const description = typeof item['description'] === 'string' && item['description'].trim()
4485
+ ? item['description'].trim()
4486
+ : undefined;
4487
+ const icon = typeof item['icon'] === 'string' && item['icon'].trim()
4488
+ ? item['icon'].trim()
4489
+ : undefined;
4490
+ const optional = this.parseOptionalBoolean(item['optional']);
4491
+ const disabled = this.parseOptionalBoolean(item['disabled']);
4492
+ const tooltip = typeof item['tooltip'] === 'string' && item['tooltip'].trim()
4493
+ ? item['tooltip'].trim()
4494
+ : undefined;
4495
+ const rawBadge = item['badge'];
4496
+ const badge = typeof rawBadge === 'string'
4497
+ ? (rawBadge.trim() ? rawBadge.trim() : undefined)
4498
+ : typeof rawBadge === 'number' && Number.isFinite(rawBadge)
4499
+ ? rawBadge
4500
+ : undefined;
4501
+ steps.push({
4502
+ id,
4503
+ label,
4504
+ ...(description ? { description } : {}),
4505
+ ...(icon ? { icon } : {}),
4506
+ sectionIds,
4507
+ ...(optional !== undefined ? { optional } : {}),
4508
+ ...(badge !== undefined ? { badge } : {}),
4509
+ ...(disabled !== undefined ? { disabled } : {}),
4510
+ ...(tooltip ? { tooltip } : {}),
4511
+ });
4512
+ }
4513
+ return {
4514
+ mode,
4515
+ ...(defaultTabId ? { defaultTabId } : {}),
4516
+ ...(tabsAppearance ? { tabsAppearance } : {}),
4517
+ ...(accordionMulti !== undefined ? { accordionMulti } : {}),
4518
+ ...(hideSectionHeaderInTabs !== undefined ? { hideSectionHeaderInTabs } : {}),
4519
+ ...(hideSectionHeaderInStepper !== undefined ? { hideSectionHeaderInStepper } : {}),
4520
+ ...(stepperInReadMode ? { stepperInReadMode } : {}),
4521
+ ...(stepperReviewStep !== undefined ? { stepperReviewStep } : {}),
4522
+ ...(sections.length ? { sections } : {}),
4523
+ ...(steps.length ? { steps } : {}),
4524
+ };
4525
+ }
4526
+ parseContextBinding(raw) {
4527
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
4528
+ return undefined;
4529
+ }
4530
+ const record = raw;
4531
+ const dim = String(record['dimension'] ?? '').trim().toLowerCase();
4532
+ if (dim !== 'organization' &&
4533
+ dim !== 'company_group' &&
4534
+ dim !== 'unit' &&
4535
+ dim !== 'person' &&
4536
+ dim !== 'bond' &&
4537
+ dim !== 'contract') {
4538
+ return undefined;
4539
+ }
4540
+ const targetField = typeof record['targetField'] === 'string' && record['targetField'].trim()
4541
+ ? record['targetField'].trim()
4542
+ : undefined;
4543
+ return {
4544
+ dimension: dim,
4545
+ lockWhenActive: this.parseBoolean(record['lockWhenActive']),
4546
+ ...(targetField ? { targetField } : {}),
4547
+ };
4548
+ }
4549
+ parseResourceState(raw) {
4550
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
4551
+ return undefined;
4552
+ }
4553
+ const record = raw;
4554
+ const initialStates = this.parseNonBlankStringArray(record['initialStates']);
4555
+ const putMutableStates = this.parseNonBlankStringArray(record['putMutableStates']);
4556
+ if (!initialStates.length && !putMutableStates.length) {
4557
+ return undefined;
4558
+ }
4559
+ return {
4560
+ ...(initialStates.length ? { initialStates } : {}),
4561
+ ...(putMutableStates.length ? { putMutableStates } : {}),
4562
+ };
4563
+ }
4564
+ parseMicroVisualization(raw) {
4565
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
4566
+ return undefined;
4567
+ }
4568
+ const normalized = normalizePraxisPresentationVisualization(raw);
4569
+ if (normalized) {
4570
+ return normalized;
4571
+ }
4572
+ const clone = this.clonePlain(raw);
4573
+ if (typeof clone['kind'] === 'string' && clone['kind'].trim()) {
4574
+ const rawKind = clone['kind'].trim();
4575
+ const upper = rawKind.toUpperCase();
4576
+ if (upper === 'HARVEY_BALL')
4577
+ clone['kind'] = 'harveyBall';
4578
+ else if (upper === 'STACKED_BAR')
4579
+ clone['kind'] = 'stackedBar';
4580
+ else if (upper === 'PROCESS_FLOW')
4581
+ clone['kind'] = 'processFlow';
4582
+ else if (upper === upper && /^[A-Z_]+$/.test(rawKind))
4583
+ clone['kind'] = rawKind.toLowerCase();
4584
+ return clone;
4585
+ }
4586
+ return undefined;
4587
+ }
2180
4588
  normalizeSchemaWithRoot(schema, rootSchema) {
2181
4589
  if (!schema || typeof schema !== 'object') {
2182
4590
  return [];
@@ -2195,16 +4603,62 @@ class SchemaNormalizationKernel {
2195
4603
  !Array.isArray(prop['x-ui'])
2196
4604
  ? prop['x-ui']
2197
4605
  : undefined;
4606
+ const hasChildProperties = prop?.properties &&
4607
+ typeof prop.properties === 'object' &&
4608
+ !Array.isArray(prop.properties);
4609
+ const isCustomFieldsContainer = ui?.customFieldsContainer === true ||
4610
+ (name === 'customFields' && prop?.type === 'object' && hasChildProperties);
4611
+ if (isCustomFieldsContainer) {
4612
+ if (hasChildProperties) {
4613
+ for (const key of Object.keys(prop.properties)) {
4614
+ if (RESERVED_CUSTOM_FIELD_KEYS.has(key)) {
4615
+ throw new Error(`Unsupported custom field key "${name}.${key}". Publish a key admitted by the canonical backend custom-field policy.`);
4616
+ }
4617
+ }
4618
+ const parentAccess = normalizeFieldAccessMetadata(ui?.fieldAccess);
4619
+ for (const childField of this.normalizeSchemaWithRoot(prop, rootSchema)) {
4620
+ const originalKey = childField.name;
4621
+ if (parentAccess && childField.fieldAccess &&
4622
+ !this.haveEquivalentFieldAccess(parentAccess, childField.fieldAccess)) {
4623
+ throw new Error(`Conflicting fieldAccess on custom-field container "${name}" and child "${originalKey}". Publish the effective access policy on each leaf field.`);
4624
+ }
4625
+ fields.push({
4626
+ ...childField,
4627
+ name: `${name}.${originalKey}`,
4628
+ customField: true,
4629
+ customFieldKey: childField.customFieldKey ?? originalKey,
4630
+ customFieldScope: childField.customFieldScope ?? 'tenant',
4631
+ ...(ui?.disabled !== undefined && this.parseBoolean(ui.disabled) ? { disabled: true } : {}),
4632
+ ...(ui?.readOnly !== undefined && this.parseBoolean(ui.readOnly) ? { readOnly: true } : {}),
4633
+ ...(ui?.formHidden !== undefined && this.parseBoolean(ui.formHidden) ? { formHidden: true } : {}),
4634
+ ...(parentAccess && !childField.fieldAccess ? { fieldAccess: normalizeFieldAccessMetadata(parentAccess) } : {}),
4635
+ });
4636
+ }
4637
+ }
4638
+ // The container is wire structure, never an independent field control.
4639
+ continue;
4640
+ }
2198
4641
  // Skip properties without x-ui metadata
2199
4642
  if (!ui || Object.keys(ui).length === 0) {
2200
4643
  continue;
2201
4644
  }
2202
4645
  const field = { name };
4646
+ if (ui.customField !== undefined) {
4647
+ field.customField = this.parseBoolean(ui.customField);
4648
+ }
4649
+ if (ui.customFieldKey != null) {
4650
+ field.customFieldKey = String(ui.customFieldKey);
4651
+ }
4652
+ if (ui.customFieldScope != null) {
4653
+ field.customFieldScope = String(ui.customFieldScope);
4654
+ }
2203
4655
  // -------------------------------------------------------------------
2204
4656
  // Basic information
2205
4657
  // -------------------------------------------------------------------
2206
4658
  field.label = ui.label ?? prop.title ?? name;
2207
- field.type = this.resolveFieldType(prop, ui);
4659
+ field.type = this.resolveFieldType(prop, ui, rootSchema);
4660
+ if (field.type === 'array')
4661
+ field.items = normalizeScalarItemsSchema(prop?.items);
2208
4662
  const numericFormat = this.resolveNumericFormatToken(prop, ui, field.type);
2209
4663
  if (numericFormat) {
2210
4664
  field.numericFormat = numericFormat;
@@ -2221,6 +4675,18 @@ class SchemaNormalizationKernel {
2221
4675
  if (ui.controlType) {
2222
4676
  field.controlType = ui.controlType;
2223
4677
  }
4678
+ if (this.isCanonicalMonetaryRangeUnion(prop, rootSchema)) {
4679
+ field.type = 'array';
4680
+ const controlToken = normalizeControlTypeToken(field.controlType);
4681
+ const isInlineCurrencyRange = controlToken === 'inlinecurrencyrange' ||
4682
+ resolveInlineFilterControlType(field.controlType) === 'inlineCurrencyRange';
4683
+ if (!isInlineCurrencyRange) {
4684
+ field.controlType = 'priceRange';
4685
+ }
4686
+ }
4687
+ if (this.inferRequireTwoBoundsFromUnion(prop, rootSchema)) {
4688
+ field.requireTwoBounds = true;
4689
+ }
2224
4690
  if (field.controlType === 'array' || ui.array !== undefined) {
2225
4691
  const arrayConfig = this.normalizeArrayConfig(ui, prop, rootSchema);
2226
4692
  if (arrayConfig) {
@@ -2314,6 +4780,40 @@ class SchemaNormalizationKernel {
2314
4780
  if (condRequired !== undefined) {
2315
4781
  field.conditionalRequired = condRequired;
2316
4782
  }
4783
+ if (ui.conditionalReadOnly !== undefined && ui.conditionalReadOnly !== null) {
4784
+ if (typeof ui.conditionalReadOnly === 'string') {
4785
+ const trimmed = ui.conditionalReadOnly.trim();
4786
+ if (trimmed) {
4787
+ field.conditionalReadOnly = trimmed;
4788
+ }
4789
+ }
4790
+ else {
4791
+ const condReadOnly = this.parseJsonLogicExpression(ui.conditionalReadOnly, name, 'x-ui.conditionalReadOnly');
4792
+ if (condReadOnly !== undefined) {
4793
+ field.conditionalReadOnly = condReadOnly;
4794
+ }
4795
+ }
4796
+ }
4797
+ if (ui.colSpan !== undefined) {
4798
+ const parsedSpan = this.parseOptionalFiniteNumber(ui.colSpan);
4799
+ if (parsedSpan !== undefined) {
4800
+ field.colSpan = Math.min(12, Math.max(1, Math.trunc(parsedSpan)));
4801
+ }
4802
+ }
4803
+ const contextBinding = this.parseContextBinding(ui.contextBinding);
4804
+ if (contextBinding) {
4805
+ field.contextBinding = contextBinding;
4806
+ }
4807
+ if (ui.draftCleared !== undefined) {
4808
+ const parsedDraftCleared = this.parseOptionalBoolean(ui.draftCleared);
4809
+ if (parsedDraftCleared !== undefined) {
4810
+ field.draftCleared = parsedDraftCleared;
4811
+ }
4812
+ }
4813
+ const resourceState = this.parseResourceState(ui.resourceState);
4814
+ if (resourceState) {
4815
+ field.resourceState = resourceState;
4816
+ }
2317
4817
  const transformFn = this.parseTransformFunction(ui.transformValueFunction);
2318
4818
  if (transformFn) {
2319
4819
  field.transformValueFunction = transformFn;
@@ -2328,9 +4828,57 @@ class SchemaNormalizationKernel {
2328
4828
  if (ui.tableHidden !== undefined) {
2329
4829
  field.tableHidden = this.parseBoolean(ui.tableHidden);
2330
4830
  }
4831
+ if (ui.tableOrder !== undefined) {
4832
+ const parsedTableOrder = this.parseOptionalFiniteNumber(ui.tableOrder);
4833
+ if (parsedTableOrder !== undefined) {
4834
+ field.tableOrder = parsedTableOrder;
4835
+ }
4836
+ }
4837
+ if (ui.pinned !== undefined && typeof ui.pinned === 'string') {
4838
+ const pinned = ui.pinned.trim().toLowerCase();
4839
+ if (pinned === 'start' || pinned === 'end') {
4840
+ field.pinned = pinned;
4841
+ }
4842
+ }
4843
+ if (ui.primarySearch !== undefined) {
4844
+ const primarySearch = this.parseOptionalBoolean(ui.primarySearch);
4845
+ if (primarySearch !== undefined) {
4846
+ field.primarySearch = primarySearch;
4847
+ }
4848
+ }
4849
+ if (ui.inlineFilter !== undefined) {
4850
+ const inlineFilter = this.parseOptionalBoolean(ui.inlineFilter);
4851
+ if (inlineFilter !== undefined) {
4852
+ field.inlineFilter = inlineFilter;
4853
+ }
4854
+ }
4855
+ if (ui.inline !== undefined) {
4856
+ const inline = this.parseOptionalBoolean(ui.inline);
4857
+ if (inline !== undefined) {
4858
+ field.inline = inline;
4859
+ }
4860
+ }
4861
+ if (ui.microVisualization !== undefined) {
4862
+ const microVisualization = this.parseMicroVisualization(ui.microVisualization);
4863
+ if (microVisualization) {
4864
+ field.microVisualization = microVisualization;
4865
+ }
4866
+ }
2331
4867
  if (ui.formHidden !== undefined) {
2332
4868
  field.formHidden = this.parseBoolean(ui.formHidden);
2333
4869
  }
4870
+ if (ui.quickViewVisible !== undefined) {
4871
+ const quickViewVisible = this.parseOptionalBoolean(ui.quickViewVisible);
4872
+ if (quickViewVisible !== undefined) {
4873
+ field.quickViewVisible = quickViewVisible;
4874
+ }
4875
+ }
4876
+ if (ui.quickViewOrder !== undefined) {
4877
+ const quickViewOrder = this.parseOptionalFiniteNumber(ui.quickViewOrder);
4878
+ if (quickViewOrder !== undefined) {
4879
+ field.quickViewOrder = quickViewOrder;
4880
+ }
4881
+ }
2334
4882
  if (ui.width !== undefined) {
2335
4883
  field.width = ui.width;
2336
4884
  }
@@ -2414,6 +4962,9 @@ class SchemaNormalizationKernel {
2414
4962
  if (ui.options !== undefined) {
2415
4963
  field.options = this.parseOptions(ui.options);
2416
4964
  }
4965
+ if (Array.isArray(prop?.enum) && prop.enum.length > 0 && field.enumValues === undefined) {
4966
+ field.enumValues = [...prop.enum];
4967
+ }
2417
4968
  if (ui.optionGroups !== undefined) {
2418
4969
  field.optionGroups = this.parseOptions(ui.optionGroups);
2419
4970
  }
@@ -2431,11 +4982,11 @@ class SchemaNormalizationKernel {
2431
4982
  if (optionSource) {
2432
4983
  // Java metadata publishes cascade context beside optionSource. Keep the
2433
4984
  // runtime contract canonical by materializing it inside optionSource.
2434
- const dependsOn = this.parseNonBlankStringArray(ui.dependsOn);
4985
+ const dependsOn = this.parseDependsOn(ui.dependsOn);
2435
4986
  if (!optionSource.dependsOn?.length && dependsOn.length) {
2436
4987
  optionSource.dependsOn = dependsOn;
2437
4988
  }
2438
- const dependencyFilterMap = this.parseStringRecord(ui.dependencyFilterMap);
4989
+ const dependencyFilterMap = this.parseStrictStringRecord(ui.dependencyFilterMap);
2439
4990
  if (!optionSource.dependencyFilterMap &&
2440
4991
  dependencyFilterMap) {
2441
4992
  optionSource.dependencyFilterMap = dependencyFilterMap;
@@ -2452,6 +5003,24 @@ class SchemaNormalizationKernel {
2452
5003
  if (ui.filterField !== undefined) {
2453
5004
  field.filterField = ui.filterField;
2454
5005
  }
5006
+ if (ui.resourceReference !== undefined) {
5007
+ const resourceReference = this.parseResourceReference(ui.resourceReference);
5008
+ if (resourceReference) {
5009
+ field.resourceReference = resourceReference;
5010
+ }
5011
+ }
5012
+ if (ui.quickView !== undefined) {
5013
+ const explicitQuickView = normalizeResourceQuickViewBinding(ui.quickView);
5014
+ if (explicitQuickView) {
5015
+ field.quickView = explicitQuickView;
5016
+ }
5017
+ }
5018
+ if (!field.quickView) {
5019
+ const synthesized = resolveFieldQuickViewBinding(field);
5020
+ if (synthesized) {
5021
+ field.quickView = synthesized;
5022
+ }
5023
+ }
2455
5024
  if (ui.multiple !== undefined) {
2456
5025
  field.multiple = this.parseBoolean(ui.multiple);
2457
5026
  }
@@ -2464,11 +5033,10 @@ class SchemaNormalizationKernel {
2464
5033
  if (ui.filter !== undefined) {
2465
5034
  field.filter = ui.filter;
2466
5035
  }
2467
- if (ui.dialog !== undefined) {
2468
- const dialog = this.parseLookupDialog(ui.dialog);
2469
- if (dialog) {
2470
- field.dialog = dialog;
2471
- }
5036
+ const explicitDialog = ui.dialog !== undefined ? this.parseLookupDialog(ui.dialog) : undefined;
5037
+ const resolvedDialog = this.mergeLookupDialog(field.optionSource?.dialog, explicitDialog);
5038
+ if (resolvedDialog) {
5039
+ field.dialog = resolvedDialog;
2472
5040
  }
2473
5041
  if (ui.detailActionLabel !== undefined) {
2474
5042
  const detailActionLabel = String(ui.detailActionLabel).trim();
@@ -2476,6 +5044,12 @@ class SchemaNormalizationKernel {
2476
5044
  field.detailActionLabel = detailActionLabel;
2477
5045
  }
2478
5046
  }
5047
+ if (ui.quickViewActionLabel !== undefined) {
5048
+ const quickViewActionLabel = String(ui.quickViewActionLabel).trim();
5049
+ if (quickViewActionLabel) {
5050
+ field.quickViewActionLabel = quickViewActionLabel;
5051
+ }
5052
+ }
2479
5053
  if (ui.copyCodeActionLabel !== undefined) {
2480
5054
  const copyCodeActionLabel = String(ui.copyCodeActionLabel).trim();
2481
5055
  if (copyCodeActionLabel) {
@@ -2499,6 +5073,9 @@ class SchemaNormalizationKernel {
2499
5073
  if (ui.actions.showDetail !== undefined) {
2500
5074
  actions.showDetail = this.parseBoolean(ui.actions.showDetail);
2501
5075
  }
5076
+ if (ui.actions.showQuickView !== undefined) {
5077
+ actions.showQuickView = this.parseBoolean(ui.actions.showQuickView);
5078
+ }
2502
5079
  if (ui.actions.showCopyCode !== undefined) {
2503
5080
  actions.showCopyCode = this.parseBoolean(ui.actions.showCopyCode);
2504
5081
  }
@@ -2530,10 +5107,22 @@ class SchemaNormalizationKernel {
2530
5107
  field.numericStep = Number(ui.numericStep);
2531
5108
  }
2532
5109
  if (ui.numericMin !== undefined) {
2533
- field.numericMin = Number(ui.numericMin);
5110
+ const parsedMin = Number(ui.numericMin);
5111
+ if (Number.isFinite(parsedMin)) {
5112
+ field.numericMin = parsedMin;
5113
+ }
5114
+ else if (field.min === undefined && String(ui.numericMin).trim().length > 0) {
5115
+ field.min = String(ui.numericMin).trim();
5116
+ }
2534
5117
  }
2535
5118
  if (ui.numericMax !== undefined) {
2536
- field.numericMax = Number(ui.numericMax);
5119
+ const parsedMax = Number(ui.numericMax);
5120
+ if (Number.isFinite(parsedMax)) {
5121
+ field.numericMax = parsedMax;
5122
+ }
5123
+ else if (field.max === undefined && String(ui.numericMax).trim().length > 0) {
5124
+ field.max = String(ui.numericMax).trim();
5125
+ }
2537
5126
  }
2538
5127
  if (ui.numericMaxLength !== undefined) {
2539
5128
  field.numericMaxLength = Number(ui.numericMaxLength);
@@ -2541,8 +5130,419 @@ class SchemaNormalizationKernel {
2541
5130
  if (ui.buttons !== undefined) {
2542
5131
  field.buttons = this.parseButtons(ui.buttons);
2543
5132
  }
5133
+ if (ui.valueLabelDisplay !== undefined) {
5134
+ const normalizedValueLabelDisplay = typeof ui.valueLabelDisplay === 'string'
5135
+ ? ui.valueLabelDisplay.trim().toLowerCase()
5136
+ : '';
5137
+ if (normalizedValueLabelDisplay === 'off' ||
5138
+ normalizedValueLabelDisplay === 'auto' ||
5139
+ normalizedValueLabelDisplay === 'on') {
5140
+ field.valueLabelDisplay = normalizedValueLabelDisplay;
5141
+ }
5142
+ }
5143
+ const sliderBooleanKeys = [
5144
+ 'thumbLabel',
5145
+ 'discrete',
5146
+ 'showInputs',
5147
+ 'showInlineInputs',
5148
+ 'showCurrencySymbol',
5149
+ 'disableThumbSwap',
5150
+ 'vertical',
5151
+ 'invert',
5152
+ ];
5153
+ for (const key of sliderBooleanKeys) {
5154
+ if (ui[key] !== undefined) {
5155
+ const parsed = this.parseOptionalBoolean(ui[key]);
5156
+ if (parsed !== undefined) {
5157
+ field[key] = parsed;
5158
+ }
5159
+ }
5160
+ }
5161
+ for (const guideKey of ['showTicks', 'showAnchors']) {
5162
+ const rawGuide = ui[guideKey];
5163
+ if (rawGuide !== undefined) {
5164
+ const parsedGuide = this.parseOptionalBoolean(rawGuide);
5165
+ if (parsedGuide !== undefined) {
5166
+ field[guideKey] = parsedGuide;
5167
+ }
5168
+ else if (typeof rawGuide === 'string' &&
5169
+ rawGuide.trim().toLowerCase() === 'auto') {
5170
+ field[guideKey] = 'auto';
5171
+ }
5172
+ }
5173
+ }
5174
+ const sliderNumberKeys = [
5175
+ 'sliderStep',
5176
+ 'shiftStep',
5177
+ 'minDistance',
5178
+ 'maxDistance',
5179
+ 'decimalPlaces',
5180
+ ];
5181
+ for (const key of sliderNumberKeys) {
5182
+ if (ui[key] !== undefined) {
5183
+ const parsed = this.parseOptionalFiniteNumber(ui[key]);
5184
+ if (parsed !== undefined) {
5185
+ field[key] = parsed;
5186
+ }
5187
+ }
5188
+ }
5189
+ // -------------------------------------------------------------------
5190
+ // Inline filter and specialized control metadata (x-ui)
5191
+ // -------------------------------------------------------------------
5192
+ const inlinePassThroughKeys = [
5193
+ 'prefixIcon',
5194
+ 'suffixIcon',
5195
+ 'prefixIconColor',
5196
+ 'suffixIconColor',
5197
+ 'chipLeadingIcon',
5198
+ 'chipTrailingIcon',
5199
+ 'chipLeadingIconColor',
5200
+ 'chipTrailingIconColor',
5201
+ 'clearIcon',
5202
+ 'clearIconColor',
5203
+ 'showQuickClear',
5204
+ 'clearable',
5205
+ 'inlineAutoSize',
5206
+ 'inlineAutoSizeMaxPx',
5207
+ 'inlineAutoSizeMaxVw',
5208
+ 'inlineOverlay',
5209
+ 'inlineChipDisplay',
5210
+ 'inlineChipSummaryTemplate',
5211
+ 'inlineChipUnitLabel',
5212
+ 'inlinePanelTitle',
5213
+ 'inlinePanelSubtitle',
5214
+ 'inlinePanelIcon',
5215
+ 'inlinePanelIconColor',
5216
+ 'inlineQuickPresets',
5217
+ 'inlineQuickPresetsApplyMode',
5218
+ 'inlineTexts',
5219
+ 'shortcuts',
5220
+ 'showShortcuts',
5221
+ 'quickPresets',
5222
+ 'quickPresetsAuto',
5223
+ 'quickPresetsLabels',
5224
+ 'granularity',
5225
+ 'defaultGranularity',
5226
+ 'selectionGrid',
5227
+ 'showSlider',
5228
+ 'minPeriod',
5229
+ 'maxPeriod',
5230
+ 'minYear',
5231
+ 'maxYear',
5232
+ 'minTime',
5233
+ 'maxTime',
5234
+ 'stepMinute',
5235
+ 'stepMinutes',
5236
+ 'interval',
5237
+ 'inlineTimeTrackShifts',
5238
+ 'inlineTrackShifts',
5239
+ 'trackShifts',
5240
+ 'minDistanceMinutes',
5241
+ 'maxDistanceMinutes',
5242
+ 'startField',
5243
+ 'endField',
5244
+ 'startLabel',
5245
+ 'endLabel',
5246
+ 'startPlaceholder',
5247
+ 'endPlaceholder',
5248
+ 'inputMinLabel',
5249
+ 'inputMaxLabel',
5250
+ 'inputExactLabel',
5251
+ 'startMin',
5252
+ 'startMax',
5253
+ 'endMin',
5254
+ 'endMax',
5255
+ 'startMinMessage',
5256
+ 'startMaxMessage',
5257
+ 'endMinMessage',
5258
+ 'endMaxMessage',
5259
+ 'endMinOffset',
5260
+ 'endMinOffsetMessage',
5261
+ 'startMaxOffset',
5262
+ 'startMaxOffsetMessage',
5263
+ 'maxVisibleChips',
5264
+ 'maxVisibleBadges',
5265
+ 'showSelectAll',
5266
+ 'selectAllLabel',
5267
+ 'clearSelectionLabel',
5268
+ 'searchPlaceholder',
5269
+ 'noResultsText',
5270
+ 'allowSelectAll',
5271
+ 'governedPaletteRef',
5272
+ 'palette',
5273
+ 'paletteColors',
5274
+ 'paletteSettings',
5275
+ 'documentType',
5276
+ 'version',
5277
+ 'nodes',
5278
+ 'nodeIdField',
5279
+ 'parentIdField',
5280
+ 'childrenField',
5281
+ 'lazyLoad',
5282
+ 'marks',
5283
+ 'semanticBands',
5284
+ 'distribution',
5285
+ 'inlineDistribution',
5286
+ 'track',
5287
+ 'trueLabel',
5288
+ 'falseLabel',
5289
+ 'labelTrue',
5290
+ 'labelFalse',
5291
+ 'iconTrue',
5292
+ 'iconFalse',
5293
+ 'tone',
5294
+ 'toneTrue',
5295
+ 'toneFalse',
5296
+ 'booleanFormat',
5297
+ 'displayFormat',
5298
+ 'currency',
5299
+ 'currencyCode',
5300
+ 'currencyPosition',
5301
+ 'thousandSeparator',
5302
+ 'thousandsSeparator',
5303
+ 'decimalSeparator',
5304
+ 'allowNegative',
5305
+ 'operatorModes',
5306
+ 'defaultOperatorMode',
5307
+ 'requireTwoBounds',
5308
+ 'locale',
5309
+ 'precision',
5310
+ 'initialsField',
5311
+ 'optionLabelKey',
5312
+ 'optionValueKey',
5313
+ 'extraProperties',
5314
+ 'rangeMode',
5315
+ 'maxRating',
5316
+ 'ratingMin',
5317
+ 'ratingMax',
5318
+ 'itemsCount',
5319
+ 'ratingStep',
5320
+ 'allowHalf',
5321
+ 'ratingAllowHalf',
5322
+ 'ratingPrecision',
5323
+ 'ratingIcon',
5324
+ 'ratingEmptyIcon',
5325
+ 'ratingHalfIcon',
5326
+ 'ratingActiveIcon',
5327
+ 'ratingInactiveIcon',
5328
+ 'ratingTone',
5329
+ 'ratingToneColors',
5330
+ 'ratingColors',
5331
+ 'starColors',
5332
+ 'ratingLowColor',
5333
+ 'ratingMidColor',
5334
+ 'ratingHighColor',
5335
+ 'ratingGradientLowColor',
5336
+ 'ratingGradientMidColor',
5337
+ 'ratingGradientHighColor',
5338
+ 'ratingToneLowColor',
5339
+ 'ratingToneMidColor',
5340
+ 'ratingToneHighColor',
5341
+ 'ratingBadgeColor',
5342
+ 'ratingBadgeIcon',
5343
+ 'ratingBadgeIconColor',
5344
+ 'ratingIndicatorColor',
5345
+ 'ratingLabels',
5346
+ 'distanceUnit',
5347
+ 'distanceBaseUnit',
5348
+ 'distanceUnits',
5349
+ 'distanceAllowUnitToggle',
5350
+ 'distanceUnitLabels',
5351
+ 'distanceDisplayDecimals',
5352
+ 'distanceDecimalsKm',
5353
+ 'distanceDecimalsMi',
5354
+ 'distancePresets',
5355
+ 'distanceSubtitle',
5356
+ 'distanceIcon',
5357
+ 'distanceStart',
5358
+ 'distanceEnd',
5359
+ 'radiusMin',
5360
+ 'radiusMax',
5361
+ 'radiusStep',
5362
+ 'radiusMode',
5363
+ 'distanceSliderStep',
5364
+ 'distanceRadialRings',
5365
+ 'distanceAccentColor',
5366
+ 'distanceRingColor',
5367
+ 'distanceTrackColor',
5368
+ 'distanceGlowColor',
5369
+ 'distanceGradientLowColor',
5370
+ 'distanceGradientMidColor',
5371
+ 'distanceGradientHighColor',
5372
+ 'distanceRangeBandOpacity',
5373
+ 'pipelineOptions',
5374
+ 'pipelineColors',
5375
+ 'pipelineTexts',
5376
+ 'scoreBands',
5377
+ 'priorityBands',
5378
+ 'severityBands',
5379
+ 'scorePalette',
5380
+ 'scoreTexts',
5381
+ 'scoreSubtitle',
5382
+ 'scoreUnit',
5383
+ 'scoreDisplayDecimals',
5384
+ 'scoreShowScaleLabels',
5385
+ 'scoreShowBandChips',
5386
+ 'scoreRangeSeparator',
5387
+ 'scoreGradientLowColor',
5388
+ 'scoreGradientMidColor',
5389
+ 'scoreGradientHighColor',
5390
+ 'scoreValueFallbackColor',
5391
+ 'scoreEmptyGradient',
5392
+ 'scoreIcon',
5393
+ 'scoreBandsAriaLabel',
5394
+ 'scoreBandAriaLabelTemplate',
5395
+ 'scoreMin',
5396
+ 'scoreMax',
5397
+ 'scoreStep',
5398
+ 'scoreMode',
5399
+ 'scoreSliderStep',
5400
+ 'relativePeriodOptions',
5401
+ 'relativePeriodPresets',
5402
+ 'relativePeriodTexts',
5403
+ 'sentimentOptions',
5404
+ 'sentimentPalette',
5405
+ 'sentimentTexts',
5406
+ 'colorLabelOptions',
5407
+ 'colorLabelPalette',
5408
+ 'colorLabelTexts',
5409
+ 'timeOptions',
5410
+ 'inlineTimeQuickPresets',
5411
+ 'inlineVisualStyle',
5412
+ 'percentPresets',
5413
+ 'numberFormat',
5414
+ 'valueLabelFormat',
5415
+ 'scale',
5416
+ 'optionSubtitleKey',
5417
+ 'optionWeightKey',
5418
+ 'optionColorKey',
5419
+ 'optionIconKey',
5420
+ 'optionEmojiKey',
5421
+ 'panelSearchIcon',
5422
+ 'panelSearchIconColor',
5423
+ 'panelResetIcon',
5424
+ 'panelResetIconColor',
5425
+ 'optionSelectedIcon',
5426
+ 'optionSelectedIconColor',
5427
+ 'columns',
5428
+ 'pipelineTitle',
5429
+ 'pipelineSubtitle',
5430
+ 'pipelineMode',
5431
+ 'pipelineMultiple',
5432
+ 'pipelineSearchable',
5433
+ 'pipelineSearchPlaceholder',
5434
+ 'pipelineOptionSubtitleKey',
5435
+ 'pipelineOptionWeightKey',
5436
+ 'pipelineOptionColorKey',
5437
+ 'pipelineShowBar',
5438
+ 'pipelineShowSelectionPills',
5439
+ 'pipelineShowSelectAll',
5440
+ 'pipelineSelectAllText',
5441
+ 'pipelineShowClearAction',
5442
+ 'pipelineClearActionText',
5443
+ 'pipelineChipMaxVisible',
5444
+ 'statusColors',
5445
+ 'pipelineGradientLowColor',
5446
+ 'pipelineGradientMidColor',
5447
+ 'pipelineGradientHighColor',
5448
+ 'pipelineEmptyStateText',
5449
+ 'pipelineSelectionActionsAriaLabel',
5450
+ 'pipelineOptionsGroupAriaLabelMultiple',
5451
+ 'pipelineOptionsGroupAriaLabelSingle',
5452
+ 'pipelineSelectionPillsAriaLabel',
5453
+ 'pipelineBarAriaLabelEmpty',
5454
+ 'pipelineBarAriaLabelSelected',
5455
+ 'pipelineIcon',
5456
+ 'pipelineSearchIcon',
5457
+ 'pipelineSearchIconColor',
5458
+ 'relativePeriodTitle',
5459
+ 'relativePeriodSubtitle',
5460
+ 'relativePeriodShowProgress',
5461
+ 'relativePeriodProgressGradientLowColor',
5462
+ 'relativePeriodProgressGradientMidColor',
5463
+ 'relativePeriodProgressGradientHighColor',
5464
+ 'relativePeriodColumns',
5465
+ 'relativePeriodCloseOnSelect',
5466
+ 'relativePeriodMultiple',
5467
+ 'relativePeriodSearchable',
5468
+ 'relativePeriodIcon',
5469
+ 'relativePeriodIconKey',
5470
+ 'relativePeriodSubtitleKey',
5471
+ 'relativePeriodSelectedIcon',
5472
+ 'relativePeriodSelectedIconColor',
5473
+ 'relativePeriodOptionsAriaLabel',
5474
+ 'relativePeriodProgressEmptyLabel',
5475
+ 'relativePeriodEmptyStateText',
5476
+ 'sentimentTitle',
5477
+ 'sentimentSubtitle',
5478
+ 'sentimentGradientLowColor',
5479
+ 'sentimentGradientMidColor',
5480
+ 'sentimentGradientHighColor',
5481
+ 'sentimentShowBar',
5482
+ 'sentimentAnimatedEmoji',
5483
+ 'sentimentCloseOnSelect',
5484
+ 'sentimentMultiple',
5485
+ 'sentimentShowSelectionPills',
5486
+ 'sentimentIcon',
5487
+ 'sentimentColorKey',
5488
+ 'sentimentEmojiKey',
5489
+ 'sentimentOptionsAriaLabel',
5490
+ 'sentimentSelectionPillsAriaLabel',
5491
+ 'sentimentEmptyStateText',
5492
+ 'colorLabelTitle',
5493
+ 'colorLabelSubtitle',
5494
+ 'colorLabelMultiple',
5495
+ 'colorLabelColumns',
5496
+ 'colorLabelShowSelectedBadges',
5497
+ 'colorLabelCloseOnSelect',
5498
+ 'colorLabelSelectionTitle',
5499
+ 'colorLabelIcon',
5500
+ 'colorLabelSelectedIcon',
5501
+ 'colorLabelSelectedIconColor',
5502
+ 'colorLabelBadgeRemoveIcon',
5503
+ 'colorLabelBadgeRemoveIconColor',
5504
+ 'colorLabelColorKey',
5505
+ 'colorLabelOptionsAriaLabel',
5506
+ 'colorLabelSelectionBadgesAriaLabel',
5507
+ 'colorLabelRemoveSelectionAriaLabel',
5508
+ 'colorLabelEmptyStateText',
5509
+ 'startAriaLabel',
5510
+ 'endAriaLabel',
5511
+ 'inlineQuickPresetsAriaLabel',
5512
+ 'inlineQuickPresetsCancelLabel',
5513
+ 'inlineQuickPresetsCancelAriaLabel',
5514
+ 'inlineQuickPresetsApplyLabel',
5515
+ 'inlineQuickPresetsApplyAriaLabel',
5516
+ 'shortcutsPosition',
5517
+ 'applyOnShortcutClick',
5518
+ 'i18nShortcuts',
5519
+ 'startView',
5520
+ 'startAt',
5521
+ 'touchUi',
5522
+ 'minDate',
5523
+ 'maxDate',
5524
+ ];
5525
+ for (const key of inlinePassThroughKeys) {
5526
+ if (ui[key] !== undefined && field[key] === undefined) {
5527
+ field[key] = ui[key];
5528
+ }
5529
+ }
2544
5530
  fields.push(field);
2545
5531
  }
5532
+ if (fields.length === 0 &&
5533
+ properties['parameters'] &&
5534
+ typeof properties['parameters'] === 'object' &&
5535
+ !Array.isArray(properties['parameters'])) {
5536
+ const parametersProp = properties['parameters'];
5537
+ const resolvedParametersSchema = this.resolveSchemaRef(parametersProp.$ref, rootSchema) ?? parametersProp;
5538
+ if (resolvedParametersSchema &&
5539
+ typeof resolvedParametersSchema === 'object' &&
5540
+ resolvedParametersSchema !== schema &&
5541
+ resolvedParametersSchema.properties &&
5542
+ typeof resolvedParametersSchema.properties === 'object') {
5543
+ return this.normalizeObjectSchema(resolvedParametersSchema, rootSchema);
5544
+ }
5545
+ }
2546
5546
  // Order by the optional 'order' property when present
2547
5547
  fields.sort((a, b) => {
2548
5548
  const orderA = a.order ?? Number.MAX_SAFE_INTEGER;
@@ -2551,29 +5551,177 @@ class SchemaNormalizationKernel {
2551
5551
  });
2552
5552
  return fields;
2553
5553
  }
2554
- resolveFieldType(prop, ui) {
5554
+ haveEquivalentFieldAccess(left, right) {
5555
+ const identity = (access) => JSON.stringify([
5556
+ [...(access.visibleForAuthorities ?? [])].sort(),
5557
+ [...(access.editableForAuthorities ?? [])].sort(),
5558
+ ]);
5559
+ return identity(left) === identity(right);
5560
+ }
5561
+ resolveSchemaNode(node, rootSchema, visited = new Set()) {
5562
+ if (!node || typeof node !== 'object' || Array.isArray(node)) {
5563
+ return node;
5564
+ }
5565
+ const ref = typeof node.$ref === 'string' ? node.$ref.trim() : '';
5566
+ if (!ref || visited.has(ref)) {
5567
+ return node;
5568
+ }
5569
+ const resolved = this.resolveSchemaRef(ref, rootSchema);
5570
+ if (!resolved || typeof resolved !== 'object' || Array.isArray(resolved)) {
5571
+ return node;
5572
+ }
5573
+ const nextVisited = new Set(visited);
5574
+ nextVisited.add(ref);
5575
+ const resolvedDeep = this.resolveSchemaNode(resolved, rootSchema, nextVisited);
5576
+ const { $ref: _ignoredRef, ...rest } = node;
5577
+ return {
5578
+ ...(resolvedDeep && typeof resolvedDeep === 'object' ? resolvedDeep : {}),
5579
+ ...rest,
5580
+ };
5581
+ }
5582
+ extractSchemaNonNullTypes(node) {
5583
+ if (!node || typeof node !== 'object') {
5584
+ return [];
5585
+ }
5586
+ const collected = [];
5587
+ const pushType = (raw) => {
5588
+ if (typeof raw !== 'string') {
5589
+ return;
5590
+ }
5591
+ const normalized = raw.trim().toLowerCase();
5592
+ if (normalized && normalized !== 'null' && !collected.includes(normalized)) {
5593
+ collected.push(normalized);
5594
+ }
5595
+ };
5596
+ const pushFrom = (raw) => {
5597
+ if (typeof raw === 'string') {
5598
+ pushType(raw);
5599
+ }
5600
+ else if (Array.isArray(raw)) {
5601
+ for (const item of raw) {
5602
+ pushType(item);
5603
+ }
5604
+ }
5605
+ else if (raw instanceof Set) {
5606
+ for (const item of raw) {
5607
+ pushType(item);
5608
+ }
5609
+ }
5610
+ };
5611
+ pushFrom(node.type);
5612
+ pushFrom(node.types);
5613
+ return collected;
5614
+ }
5615
+ extractUnionVariants(prop, rootSchema) {
5616
+ const resolvedProp = this.resolveSchemaNode(prop, rootSchema);
5617
+ if (!resolvedProp || typeof resolvedProp !== 'object' || Array.isArray(resolvedProp)) {
5618
+ return [];
5619
+ }
5620
+ const rawVariants = [
5621
+ ...(Array.isArray(resolvedProp.oneOf) ? resolvedProp.oneOf : []),
5622
+ ...(Array.isArray(resolvedProp.anyOf) ? resolvedProp.anyOf : []),
5623
+ ];
5624
+ return rawVariants
5625
+ .filter((variant) => variant && typeof variant === 'object' && !Array.isArray(variant))
5626
+ .map((variant) => this.resolveSchemaNode(variant, rootSchema));
5627
+ }
5628
+ isArrayVariant(variant) {
5629
+ return this.extractSchemaNonNullTypes(variant).includes('array');
5630
+ }
5631
+ isObjectVariant(variant) {
5632
+ const types = this.extractSchemaNonNullTypes(variant);
5633
+ return (types.includes('object') ||
5634
+ (types.length === 0 &&
5635
+ !!variant?.properties &&
5636
+ typeof variant.properties === 'object' &&
5637
+ !Array.isArray(variant.properties)));
5638
+ }
5639
+ isCanonicalMonetaryRangeUnion(prop, rootSchema) {
5640
+ const variants = this.extractUnionVariants(prop, rootSchema);
5641
+ if (variants.length === 0) {
5642
+ return false;
5643
+ }
5644
+ const hasArrayBranch = variants.some((variant) => this.isArrayVariant(variant));
5645
+ if (!hasArrayBranch) {
5646
+ return false;
5647
+ }
5648
+ return variants.some((variant) => {
5649
+ if (!this.isObjectVariant(variant)) {
5650
+ return false;
5651
+ }
5652
+ const props = variant?.properties;
5653
+ if (!props || typeof props !== 'object' || Array.isArray(props)) {
5654
+ return false;
5655
+ }
5656
+ return (Object.prototype.hasOwnProperty.call(props, 'minPrice') &&
5657
+ props.minPrice != null &&
5658
+ Object.prototype.hasOwnProperty.call(props, 'maxPrice') &&
5659
+ props.maxPrice != null);
5660
+ });
5661
+ }
5662
+ inferRequireTwoBoundsFromUnion(prop, rootSchema) {
5663
+ const variants = this.extractUnionVariants(prop, rootSchema);
5664
+ if (variants.length === 0) {
5665
+ return false;
5666
+ }
5667
+ const requiredPairs = [
5668
+ ['minPrice', 'maxPrice'],
5669
+ ['min', 'max'],
5670
+ ['startDate', 'endDate'],
5671
+ ];
5672
+ for (const variant of variants) {
5673
+ if (this.isArrayVariant(variant) && Number(variant?.minItems) === 2) {
5674
+ return true;
5675
+ }
5676
+ if (this.isObjectVariant(variant) && Array.isArray(variant?.required)) {
5677
+ const requiredSet = new Set(variant.required.filter((entry) => typeof entry === 'string'));
5678
+ if (requiredPairs.some(([lower, upper]) => requiredSet.has(lower) && requiredSet.has(upper))) {
5679
+ return true;
5680
+ }
5681
+ }
5682
+ }
5683
+ return false;
5684
+ }
5685
+ resolveFieldType(prop, ui, rootSchema) {
5686
+ if (this.isCanonicalMonetaryRangeUnion(prop, rootSchema)) {
5687
+ return 'array';
5688
+ }
2555
5689
  if (ui?.type !== undefined && ui?.type !== null && String(ui.type).trim() !== '') {
2556
5690
  return String(ui.type);
2557
5691
  }
2558
5692
  if (String(ui?.controlType ?? '').trim() === 'array') {
2559
5693
  return 'array';
2560
5694
  }
2561
- if (prop?.type) {
2562
- return String(prop.type);
5695
+ const resolvedProp = this.resolveSchemaNode(prop, rootSchema);
5696
+ const propTypes = this.extractSchemaNonNullTypes(resolvedProp);
5697
+ if (propTypes.length === 1) {
5698
+ return propTypes[0];
2563
5699
  }
2564
- const variants = [
2565
- ...(Array.isArray(prop?.oneOf) ? prop.oneOf : []),
2566
- ...(Array.isArray(prop?.anyOf) ? prop.anyOf : []),
2567
- ].filter((variant) => variant && typeof variant === 'object');
2568
- const nonNullTypes = Array.from(new Set(variants
2569
- .map((variant) => (typeof variant.type === 'string' ? variant.type.trim() : ''))
2570
- .filter((type) => !!type && type !== 'null')));
5700
+ if (resolvedProp?.type && !Array.isArray(resolvedProp.type)) {
5701
+ return String(resolvedProp.type);
5702
+ }
5703
+ const variants = this.extractUnionVariants(prop, rootSchema);
5704
+ const nonNullTypes = Array.from(new Set(variants.flatMap((variant) => this.extractSchemaNonNullTypes(variant))));
2571
5705
  if (nonNullTypes.length === 1) {
2572
5706
  return nonNullTypes[0];
2573
5707
  }
2574
5708
  // Compatibilidade para schemas de range publicados como oneOf(array|object).
2575
5709
  const controlToken = String(ui?.controlType || '').trim().toLowerCase().replace(/[^a-z0-9]/g, '');
2576
- const isRangeControl = ['daterange', 'datetimerange', 'rangeslider', 'pricerange'].includes(controlToken);
5710
+ const isRangeControl = [
5711
+ 'daterange',
5712
+ 'datetimerange',
5713
+ 'rangeslider',
5714
+ 'pricerange',
5715
+ 'inlinerange',
5716
+ 'inlinecurrencyrange',
5717
+ 'inlinedaterange',
5718
+ 'inlineperiodrange',
5719
+ 'inlineyearrange',
5720
+ 'inlinemonthrange',
5721
+ 'inlinetimerange',
5722
+ 'inlinedistanceradius',
5723
+ 'inlinescorepriority',
5724
+ ].includes(controlToken);
2577
5725
  if (isRangeControl && nonNullTypes.includes('array')) {
2578
5726
  return 'array';
2579
5727
  }
@@ -2589,6 +5737,10 @@ class SchemaNormalizationKernel {
2589
5737
  function normalizeSchemaFields(schema) {
2590
5738
  return new SchemaNormalizationKernel().normalizeSchema(schema);
2591
5739
  }
5740
+ /** Extracts root-level `x-ui` metadata blocks (`formLayout`, `progression`, `timeline`, `schedule`, `hierarchy`, `calculationMemory`). */
5741
+ function extractSchemaRootUiMetadata(schema) {
5742
+ return new SchemaNormalizationKernel().extractRootUiMetadata(schema);
5743
+ }
2592
5744
 
2593
5745
  function isObject(value) {
2594
5746
  return value != null && typeof value === 'object' && !Array.isArray(value);
@@ -2667,8 +5819,18 @@ function clone(v) {
2667
5819
 
2668
5820
  function buildBaseColumnFromDef(def) {
2669
5821
  const type = resolveColumnTypeFromFieldDefinition(def);
2670
- const format = type === 'string' ? resolveTextMaskFormatFromFieldDefinition(def) : undefined;
2671
- const renderer = resolveRendererFromFieldPresentation(def);
5822
+ const format = resolveFormatFromFieldDefinition(def, type);
5823
+ const valueMapping = resolveSchemaValueMappingFromFieldDefinition(def);
5824
+ const renderer = resolveRendererFromFieldDefinition(def);
5825
+ const quickView = resolveQuickViewFromFieldDefinition(def);
5826
+ const isAvatar = renderer?.type === 'avatar';
5827
+ const explicitWidth = firstNonEmptyString(def.width);
5828
+ const resolvedOrder = typeof def.tableOrder === 'number'
5829
+ ? def.tableOrder
5830
+ : typeof def.order === 'number'
5831
+ ? def.order
5832
+ : undefined;
5833
+ const sticky = def.pinned ?? def.sticky;
2672
5834
  return {
2673
5835
  field: def.name,
2674
5836
  header: def.label || def.name,
@@ -2677,9 +5839,14 @@ function buildBaseColumnFromDef(def) {
2677
5839
  sortable: def.sortable !== false,
2678
5840
  filterable: def.filterable === true,
2679
5841
  resizable: true,
2680
- order: typeof def.order === 'number' ? def.order : undefined,
5842
+ ...(sticky !== undefined ? { sticky } : {}),
5843
+ order: resolvedOrder,
5844
+ ...(explicitWidth ? { width: explicitWidth } : isAvatar ? { width: '56px' } : {}),
5845
+ ...(isAvatar ? { align: 'center' } : {}),
2681
5846
  ...(format ? { format } : {}),
5847
+ ...(valueMapping ? { valueMapping } : {}),
2682
5848
  ...(renderer ? { renderer } : {}),
5849
+ ...(quickView ? { quickView } : {}),
2683
5850
  };
2684
5851
  }
2685
5852
  function applyLocalCustomizations(baseCol, localCol) {
@@ -2706,11 +5873,18 @@ function applyLocalCustomizations(baseCol, localCol) {
2706
5873
  result.headerStyle = localCol.headerStyle ?? baseCol.headerStyle;
2707
5874
  result.cssClass = localCol.cssClass ?? baseCol.cssClass;
2708
5875
  result.headerCssClass = localCol.headerCssClass ?? baseCol.headerCssClass;
5876
+ const resolvedQuickView = reconcileFieldQuickViewBinding(baseCol.quickView, localCol.quickView);
5877
+ if (resolvedQuickView) {
5878
+ result.quickView = resolvedQuickView;
5879
+ }
5880
+ else {
5881
+ delete result.quickView;
5882
+ }
2709
5883
  // If server type changed, drop potentially incompatible formatting/renderers.
2710
5884
  if (!typeChanged) {
2711
5885
  result.format = localCol.format ?? baseCol.format;
2712
5886
  result.valueMapping = localCol.valueMapping ?? baseCol.valueMapping;
2713
- result.renderer = localCol.renderer ?? baseCol.renderer;
5887
+ result.renderer = normalizeColumnRendererQuickView(localCol.renderer ?? baseCol.renderer);
2714
5888
  }
2715
5889
  else {
2716
5890
  // Drop local presentation that may be incompatible with the new server type,
@@ -2729,6 +5903,10 @@ function reconcileTableConfig(layout, serverDefs) {
2729
5903
  const localCol = localByField.get(base.field);
2730
5904
  return localCol ? applyLocalCustomizations(base, localCol) : base;
2731
5905
  });
5906
+ if (serverDefs.some((d) => typeof d.tableOrder === 'number')) {
5907
+ mergedColumns.sort((a, b) => (a.order ?? Number.MAX_SAFE_INTEGER) -
5908
+ (b.order ?? Number.MAX_SAFE_INTEGER));
5909
+ }
2732
5910
  const serverFields = new Set(serverDefs.map((d) => d.name));
2733
5911
  const orphans = (local.columns || []).filter((c) => !serverFields.has(c.field));
2734
5912
  const hiddenOrphans = orphans.map((c) => ({ ...c, visible: false }));
@@ -2773,8 +5951,11 @@ function resolveSemanticColumnTypeFromFieldDefinition(def) {
2773
5951
  return 'string';
2774
5952
  if (numericFormat === 'currency' || controlType === 'currency')
2775
5953
  return 'currency';
2776
- if (numericFormat === 'percent' || numericFormat === 'percentage')
5954
+ if (numericFormat === 'percent' ||
5955
+ numericFormat === 'percentage' ||
5956
+ numericFormat === 'fraction') {
2777
5957
  return 'percentage';
5958
+ }
2778
5959
  if (numericFormat === 'date' || numericFormat === 'datetime')
2779
5960
  return 'date';
2780
5961
  if (controlType === 'numerictextbox' || controlType === 'inlinenumber')
@@ -2831,21 +6012,297 @@ function resolveTextMaskFormat(value) {
2831
6012
  const hasInvalidMaskLetters = /[A-WYZa-wyz]/.test(format);
2832
6013
  return hasMaskTokens && !hasInvalidMaskLetters ? format : undefined;
2833
6014
  }
6015
+ function resolveFormatFromFieldDefinition(def, type) {
6016
+ if (type === 'string') {
6017
+ return resolveTextMaskFormatFromFieldDefinition(def);
6018
+ }
6019
+ if (type === 'currency') {
6020
+ return resolveSchemaCurrencyFormatFromFieldDefinition(def);
6021
+ }
6022
+ if (type === 'date') {
6023
+ return (firstNonEmptyString(def.displayFormat) ??
6024
+ firstNonEmptyString(def.extraProperties?.displayFormat));
6025
+ }
6026
+ if (type === 'boolean') {
6027
+ return resolveSchemaBooleanFormatFromFieldDefinition(def);
6028
+ }
6029
+ if (type === 'number') {
6030
+ const schemaDataType = normalizePresentationToken(def.type);
6031
+ const schemaFormat = normalizePresentationToken(def.format);
6032
+ const numericFormat = normalizePresentationToken(def.numericFormat ?? def.extraProperties?.numericFormat);
6033
+ if (schemaDataType === 'integer' ||
6034
+ schemaFormat === 'integer' ||
6035
+ schemaFormat === 'int32' ||
6036
+ schemaFormat === 'int64' ||
6037
+ numericFormat === 'integer' ||
6038
+ numericFormat === 'int32' ||
6039
+ numericFormat === 'int64') {
6040
+ return '1.0-0';
6041
+ }
6042
+ if (numericFormat === 'auto') {
6043
+ return undefined;
6044
+ }
6045
+ const explicitDecimals = firstFiniteNumber(def.decimalPlaces) ??
6046
+ firstFiniteNumber(def.extraProperties?.decimalPlaces);
6047
+ if (explicitDecimals !== undefined && explicitDecimals >= 0) {
6048
+ const decimals = Math.trunc(explicitDecimals);
6049
+ return `1.${decimals}-${decimals}`;
6050
+ }
6051
+ }
6052
+ return undefined;
6053
+ }
6054
+ function resolveSchemaCurrencyFormatFromFieldDefinition(def) {
6055
+ const currency = firstNonEmptyString(def.currency) ??
6056
+ firstNonEmptyString(def.extraProperties?.currency) ??
6057
+ 'BRL';
6058
+ const decimalPlaces = firstFiniteNumber(def.decimalPlaces) ??
6059
+ firstFiniteNumber(def.extraProperties?.decimalPlaces) ??
6060
+ 2;
6061
+ return `${currency}|symbol|${decimalPlaces}`;
6062
+ }
6063
+ function resolveSchemaBooleanFormatFromFieldDefinition(def) {
6064
+ const explicit = firstNonEmptyString(def.booleanFormat) ??
6065
+ firstNonEmptyString(def.extraProperties?.booleanFormat);
6066
+ if (explicit)
6067
+ return explicit;
6068
+ const trueLabel = firstNonEmptyString(def.trueLabel) ??
6069
+ firstNonEmptyString(def.labelTrue) ??
6070
+ firstNonEmptyString(def.presentation?.labelTrue) ??
6071
+ firstNonEmptyString(def.extraProperties?.trueLabel) ??
6072
+ firstNonEmptyString(def.extraProperties?.labelTrue);
6073
+ const falseLabel = firstNonEmptyString(def.falseLabel) ??
6074
+ firstNonEmptyString(def.labelFalse) ??
6075
+ firstNonEmptyString(def.presentation?.labelFalse) ??
6076
+ firstNonEmptyString(def.extraProperties?.falseLabel) ??
6077
+ firstNonEmptyString(def.extraProperties?.labelFalse);
6078
+ if (trueLabel || falseLabel) {
6079
+ const effectiveTrue = trueLabel || 'Sim';
6080
+ const effectiveFalse = falseLabel || 'Não';
6081
+ const tNorm = normalizePresentationToken(effectiveTrue);
6082
+ const fNorm = normalizePresentationToken(effectiveFalse);
6083
+ if (tNorm === 'ativo' && fNorm === 'inativo')
6084
+ return 'active-inactive';
6085
+ if (tNorm === 'sim' && (fNorm === 'nao' || fNorm === 'não'))
6086
+ return 'yes-no';
6087
+ return `custom|${effectiveTrue}|${effectiveFalse}`;
6088
+ }
6089
+ const name = normalizePresentationToken(def.name);
6090
+ if (name === 'ativo' || name === 'active' || name.endsWith('ativo')) {
6091
+ return 'active-inactive';
6092
+ }
6093
+ return undefined;
6094
+ }
6095
+ function resolveSchemaValueMappingFromFieldDefinition(def) {
6096
+ const explicit = def.valueMapping;
6097
+ if (explicit && typeof explicit === 'object' && !Array.isArray(explicit)) {
6098
+ const normalized = Object.entries(explicit).reduce((acc, [key, value]) => {
6099
+ if (key && typeof value === 'string' && value.trim()) {
6100
+ acc[key] = value.trim();
6101
+ }
6102
+ return acc;
6103
+ }, {});
6104
+ if (Object.keys(normalized).length > 0)
6105
+ return normalized;
6106
+ }
6107
+ const options = Array.isArray(def.options) ? def.options : [];
6108
+ if (options.length > 0) {
6109
+ const valueKey = firstNonEmptyString(def.optionValueKey) ?? 'key';
6110
+ const labelKey = firstNonEmptyString(def.optionLabelKey) ?? 'value';
6111
+ const mapping = options.reduce((acc, option) => {
6112
+ if (!option || typeof option !== 'object')
6113
+ return acc;
6114
+ const record = option;
6115
+ const value = record[valueKey] ?? record.key ?? record.id ?? record.value;
6116
+ const label = record[labelKey] ?? record.label ?? record.value ?? record.name;
6117
+ if (value !== undefined && value !== null && label !== undefined && label !== null) {
6118
+ acc[String(value)] = String(label);
6119
+ }
6120
+ return acc;
6121
+ }, {});
6122
+ if (Object.keys(mapping).length > 0)
6123
+ return mapping;
6124
+ }
6125
+ const enumValues = Array.isArray(def.enumValues)
6126
+ ? def.enumValues
6127
+ .map((v) => (v != null ? String(v).trim() : ''))
6128
+ .filter((v) => v.length > 0)
6129
+ : [];
6130
+ if (enumValues.length > 0) {
6131
+ return enumValues.reduce((acc, value) => {
6132
+ acc[value] = humanizeSchemaEnumValue(value);
6133
+ return acc;
6134
+ }, {});
6135
+ }
6136
+ return undefined;
6137
+ }
6138
+ function humanizeSchemaEnumValue(value) {
6139
+ return value
6140
+ .toLowerCase()
6141
+ .split(/[_\-\s]+/)
6142
+ .filter(Boolean)
6143
+ .map((part, index) => (index === 0 ? `${part.charAt(0).toUpperCase()}${part.slice(1)}` : part))
6144
+ .join(' ');
6145
+ }
6146
+ function resolveQuickViewFromFieldDefinition(def) {
6147
+ return (resolveFieldQuickViewBinding(def) ??
6148
+ normalizeResourceQuickViewBinding(def['extraProperties'] && typeof def['extraProperties'] === 'object' ? def['extraProperties']['quickView'] : undefined) ??
6149
+ undefined);
6150
+ }
6151
+ function normalizeColumnRendererQuickView(renderer) {
6152
+ if (!renderer || typeof renderer !== 'object') {
6153
+ return renderer;
6154
+ }
6155
+ const next = { ...renderer };
6156
+ if (next.link && typeof next.link === 'object') {
6157
+ const qv = normalizeResourceQuickViewBinding(next.link.quickView);
6158
+ next.link = { ...next.link };
6159
+ if (qv) {
6160
+ next.link.quickView = qv;
6161
+ }
6162
+ else {
6163
+ delete next.link.quickView;
6164
+ }
6165
+ }
6166
+ if (next.badge && typeof next.badge === 'object') {
6167
+ const qv = normalizeResourceQuickViewBinding(next.badge.quickView);
6168
+ next.badge = { ...next.badge };
6169
+ if (qv) {
6170
+ next.badge.quickView = qv;
6171
+ }
6172
+ else {
6173
+ delete next.badge.quickView;
6174
+ }
6175
+ }
6176
+ if (next.chip && typeof next.chip === 'object') {
6177
+ const qv = normalizeResourceQuickViewBinding(next.chip.quickView);
6178
+ next.chip = { ...next.chip };
6179
+ if (qv) {
6180
+ next.chip.quickView = qv;
6181
+ }
6182
+ else {
6183
+ delete next.chip.quickView;
6184
+ }
6185
+ }
6186
+ if (next.icon && typeof next.icon === 'object') {
6187
+ const qv = normalizeResourceQuickViewBinding(next.icon.quickView);
6188
+ next.icon = { ...next.icon };
6189
+ if (qv) {
6190
+ next.icon.quickView = qv;
6191
+ }
6192
+ else {
6193
+ delete next.icon.quickView;
6194
+ }
6195
+ }
6196
+ if (next.compose && typeof next.compose === 'object' && Array.isArray(next.compose.items)) {
6197
+ next.compose = {
6198
+ ...next.compose,
6199
+ items: next.compose.items.map((item) => {
6200
+ if (!item || typeof item !== 'object')
6201
+ return item;
6202
+ if (item.type === 'value') {
6203
+ const qv = normalizeResourceQuickViewBinding(item.quickView);
6204
+ const cloned = { ...item };
6205
+ if (qv)
6206
+ cloned.quickView = qv;
6207
+ else
6208
+ delete cloned.quickView;
6209
+ return cloned;
6210
+ }
6211
+ if (item.type === 'link' && item.link) {
6212
+ const qv = normalizeResourceQuickViewBinding(item.link.quickView);
6213
+ const link = { ...item.link };
6214
+ if (qv)
6215
+ link.quickView = qv;
6216
+ else
6217
+ delete link.quickView;
6218
+ return { ...item, link };
6219
+ }
6220
+ if (item.type === 'badge' && item.badge) {
6221
+ const qv = normalizeResourceQuickViewBinding(item.badge.quickView);
6222
+ const badge = { ...item.badge };
6223
+ if (qv)
6224
+ badge.quickView = qv;
6225
+ else
6226
+ delete badge.quickView;
6227
+ return { ...item, badge };
6228
+ }
6229
+ if (item.type === 'chip' && item.chip) {
6230
+ const qv = normalizeResourceQuickViewBinding(item.chip.quickView);
6231
+ const chip = { ...item.chip };
6232
+ if (qv)
6233
+ chip.quickView = qv;
6234
+ else
6235
+ delete chip.quickView;
6236
+ return { ...item, chip };
6237
+ }
6238
+ if (item.type === 'icon' && item.icon) {
6239
+ const qv = normalizeResourceQuickViewBinding(item.icon.quickView);
6240
+ const icon = { ...item.icon };
6241
+ if (qv)
6242
+ icon.quickView = qv;
6243
+ else
6244
+ delete icon.quickView;
6245
+ return { ...item, icon };
6246
+ }
6247
+ return item;
6248
+ }),
6249
+ };
6250
+ }
6251
+ return next;
6252
+ }
6253
+ function resolveRendererFromFieldDefinition(def) {
6254
+ const presentationRenderer = resolveRendererFromFieldPresentation(def);
6255
+ if (presentationRenderer)
6256
+ return presentationRenderer;
6257
+ if (isPraxisPresentationVisualizationTableSafe(def.microVisualization)) {
6258
+ return {
6259
+ type: 'microVisualization',
6260
+ microVisualization: {
6261
+ visualization: def.microVisualization,
6262
+ },
6263
+ };
6264
+ }
6265
+ if (normalizePresentationToken(def.controlType) === 'avatar') {
6266
+ const initialsField = firstNonEmptyString(def.initialsField) ??
6267
+ firstNonEmptyString(def.extraProperties?.initialsField) ??
6268
+ 'nomeCompleto';
6269
+ return {
6270
+ type: 'avatar',
6271
+ avatar: {
6272
+ srcField: def.name,
6273
+ initialsField,
6274
+ shape: 'circle',
6275
+ size: 32,
6276
+ },
6277
+ };
6278
+ }
6279
+ return undefined;
6280
+ }
2834
6281
  function resolveRendererFromFieldPresentation(def) {
2835
6282
  const presentation = def.presentation;
2836
6283
  if (!presentation || typeof presentation !== 'object')
2837
6284
  return undefined;
6285
+ if (presentation.presenter === 'microVisualization' &&
6286
+ isPraxisPresentationVisualizationTableSafe(presentation.visualization)) {
6287
+ return {
6288
+ type: 'microVisualization',
6289
+ microVisualization: {
6290
+ visualization: presentation.visualization,
6291
+ },
6292
+ };
6293
+ }
2838
6294
  const presenter = normalizePresentationToken(presentation.presenter ?? presentation.variant);
2839
6295
  const color = resolveSemanticPresentationColor(presentation.tone);
2840
6296
  const variant = resolveSemanticPresentationVariant(presentation.appearance);
2841
6297
  const icon = firstNonEmptyString(presentation.icon);
2842
6298
  const tooltipText = firstNonEmptyString(presentation.tooltip);
2843
6299
  const tooltip = tooltipText ? { text: tooltipText } : undefined;
6300
+ const fixedText = firstNonEmptyString(presentation.label);
2844
6301
  if (presenter === 'chip') {
2845
6302
  return {
2846
6303
  type: 'chip',
2847
6304
  chip: {
2848
- textField: def.name,
6305
+ ...(fixedText ? { text: fixedText } : { textField: def.name }),
2849
6306
  ...(color ? { color } : {}),
2850
6307
  ...(variant ? { variant } : {}),
2851
6308
  ...(icon ? { icon } : {}),
@@ -2857,7 +6314,7 @@ function resolveRendererFromFieldPresentation(def) {
2857
6314
  return {
2858
6315
  type: 'badge',
2859
6316
  badge: {
2860
- textField: def.name,
6317
+ ...(fixedText ? { text: fixedText } : { textField: def.name }),
2861
6318
  ...(color ? { color } : {}),
2862
6319
  ...(variant ? { variant } : {}),
2863
6320
  ...(icon ? { icon } : {}),
@@ -2865,19 +6322,70 @@ function resolveRendererFromFieldPresentation(def) {
2865
6322
  },
2866
6323
  };
2867
6324
  }
2868
- if (presenter === 'iconvalue') {
6325
+ if (presenter === 'progress') {
6326
+ const valueExpr = `= row.${def.name.replace(/\./g, '?.')}`;
6327
+ return {
6328
+ type: 'progress',
6329
+ progress: {
6330
+ valueExpr,
6331
+ showLabel: true,
6332
+ ...(color ? { color } : {}),
6333
+ },
6334
+ };
6335
+ }
6336
+ if (presenter === 'rating') {
6337
+ const valueExpr = `= row.${def.name.replace(/\./g, '?.')}`;
6338
+ return {
6339
+ type: 'rating',
6340
+ rating: {
6341
+ valueExpr,
6342
+ max: 5,
6343
+ ...(color ? { color } : {}),
6344
+ },
6345
+ };
6346
+ }
6347
+ if (presenter === 'iconvalue' || presenter === 'text' || !presenter) {
2869
6348
  const rendererIcon = icon || firstNonEmptyString(def.icon);
2870
6349
  const affixes = resolveSemanticPresentationAffixes(presentation);
2871
6350
  const hasAffixes = !!(affixes.prefix || affixes.suffix);
2872
6351
  if (!rendererIcon && !hasAffixes)
2873
6352
  return undefined;
6353
+ if (affixes.prefix || affixes.suffix || tooltipText) {
6354
+ return {
6355
+ type: 'icon',
6356
+ icon: {
6357
+ ...(!hasAffixes && rendererIcon ? { name: rendererIcon } : {}),
6358
+ textField: def.name,
6359
+ ...(color ? { color } : {}),
6360
+ ...(tooltipText ? { ariaLabel: tooltipText } : {}),
6361
+ ...affixes,
6362
+ },
6363
+ };
6364
+ }
6365
+ if (!rendererIcon)
6366
+ return undefined;
2874
6367
  return {
2875
- type: 'icon',
2876
- icon: {
2877
- ...(rendererIcon && !hasAffixes ? { name: rendererIcon } : {}),
2878
- textField: def.name,
2879
- ...(tooltipText ? { ariaLabel: tooltipText } : {}),
2880
- ...affixes,
6368
+ type: 'compose',
6369
+ compose: {
6370
+ items: [
6371
+ {
6372
+ type: 'icon',
6373
+ icon: {
6374
+ name: rendererIcon,
6375
+ ...(color ? { color } : {}),
6376
+ ...(def.label ? { ariaLabel: def.label } : {}),
6377
+ },
6378
+ },
6379
+ {
6380
+ type: 'value',
6381
+ field: def.name,
6382
+ },
6383
+ ],
6384
+ layout: {
6385
+ direction: 'row',
6386
+ gap: 6,
6387
+ align: 'center',
6388
+ },
2881
6389
  },
2882
6390
  };
2883
6391
  }
@@ -2885,13 +6393,20 @@ function resolveRendererFromFieldPresentation(def) {
2885
6393
  }
2886
6394
  function resolveSemanticPresentationColor(tone) {
2887
6395
  const normalized = normalizePresentationToken(tone);
2888
- if (!normalized || normalized === 'neutral')
6396
+ if (normalized === 'neutral')
6397
+ return 'basic';
6398
+ if (!normalized)
2889
6399
  return undefined;
2890
- return normalized === 'danger' ? 'warn' : normalized;
6400
+ if (normalized === 'danger' || normalized === 'warning')
6401
+ return 'warn';
6402
+ return normalized;
2891
6403
  }
2892
6404
  function resolveSemanticPresentationVariant(appearance) {
2893
6405
  const normalized = normalizePresentationToken(appearance);
2894
- return normalized === 'filled' || normalized === 'outlined' || normalized === 'soft'
6406
+ return normalized === 'filled' ||
6407
+ normalized === 'outlined' ||
6408
+ normalized === 'soft' ||
6409
+ normalized === 'plain'
2895
6410
  ? normalized
2896
6411
  : undefined;
2897
6412
  }
@@ -2909,6 +6424,12 @@ function firstNonEmptyString(value) {
2909
6424
  const trimmed = value.trim();
2910
6425
  return trimmed ? trimmed : undefined;
2911
6426
  }
6427
+ function firstFiniteNumber(value) {
6428
+ if (value === null || value === undefined || value === '')
6429
+ return undefined;
6430
+ const numeric = typeof value === 'number' ? value : Number(value);
6431
+ return Number.isFinite(numeric) ? numeric : undefined;
6432
+ }
2912
6433
  function normalizePresentationToken(value) {
2913
6434
  return String(value ?? '').trim().toLowerCase().replace(/[\s_-]+/g, '');
2914
6435
  }