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

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, #92400e))',
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,10 @@ 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 lastCoord = coords[coords.length - 1];
1358
+ const refLineHtml = renderTrendReferenceLineHtml(points, width, height, padding, visualization, false);
676
1359
  // Highlight extreme/boundary values
677
1360
  let minIdx = 0;
678
1361
  let maxIdx = 0;
@@ -682,9 +1365,10 @@ function renderLineVisualizationHtml(visualization, options) {
682
1365
  if (points[i].value > points[maxIdx].value)
683
1366
  maxIdx = i;
684
1367
  }
1368
+ const lastTone = points[points.length - 1].tone ?? tone;
685
1369
  const markers = [
686
1370
  { 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 }
1371
+ { x: lastCoord.x, y: lastCoord.y, tone: lastTone }
688
1372
  ];
689
1373
  if (minIdx !== 0 && minIdx !== coords.length - 1) {
690
1374
  markers.push({ x: coords[minIdx].x, y: coords[minIdx].y, tone: points[minIdx].tone ?? 'danger' });
@@ -692,18 +1376,21 @@ function renderLineVisualizationHtml(visualization, options) {
692
1376
  if (maxIdx !== 0 && maxIdx !== coords.length - 1) {
693
1377
  markers.push({ x: coords[maxIdx].x, y: coords[maxIdx].y, tone: points[maxIdx].tone ?? 'success' });
694
1378
  }
1379
+ 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
1380
  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('');
1381
+ const scrubLayerHtml = renderTrendScrubLayerHtml(points, coords, width, height, visualization, options);
696
1382
  const isTable = visualization.surface === 'table-cell';
697
1383
  const firstPoint = points[0];
698
1384
  const lastPoint = points[points.length - 1];
1385
+ const suffix = visualization.valueSuffix ?? '';
699
1386
  const leftHtml = isTable ? '' : `
700
1387
  <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>
1388
+ <span class="pfx-micro-trend__value">${escapeHtml(formatVisualizationMetricValue(firstPoint.value, options, visualization.compactValue === true, suffix))}</span>
702
1389
  ${firstPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(firstPoint.label)}</span>` : ''}
703
1390
  </div>`;
704
1391
  const rightHtml = isTable ? '' : `
705
1392
  <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>
1393
+ <span class="pfx-micro-trend__value">${escapeHtml(formatVisualizationMetricValue(lastPoint.value, options, visualization.compactValue === true, suffix))}</span>
707
1394
  ${lastPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(lastPoint.label)}</span>` : ''}
708
1395
  </div>`;
709
1396
  return `
@@ -711,9 +1398,12 @@ function renderLineVisualizationHtml(visualization, options) {
711
1398
  ${leftHtml}
712
1399
  <span class="pfx-micro-viz pfx-micro-viz__line" data-tone="${escapeHtml(tone)}" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">
713
1400
  <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" />
1401
+ ${refLineHtml}
1402
+ <path class="pfx-micro-line__path" d="${pathD}" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" />
1403
+ ${endpointHaloHtml}
715
1404
  ${circlesHtml}
716
1405
  </svg>
1406
+ ${scrubLayerHtml}
717
1407
  </span>
718
1408
  ${rightHtml}
719
1409
  </span>`;
@@ -727,11 +1417,14 @@ function renderAreaVisualizationHtml(visualization, options) {
727
1417
  const width = 100;
728
1418
  const height = 30;
729
1419
  const padding = 4;
730
- const coords = getPointsCoordinates(points, width, height, padding);
1420
+ const coords = getPointsCoordinates(points, width, height, padding, visualization);
731
1421
  const lineD = coords.map((c, i) => `${i === 0 ? 'M' : 'L'} ${c.x.toFixed(1)} ${c.y.toFixed(1)}`).join(' ');
1422
+ const refLineHtml = renderTrendReferenceLineHtml(points, width, height, padding, visualization, false);
732
1423
  const firstX = coords[0].x.toFixed(1);
733
- const lastX = coords[coords.length - 1].x.toFixed(1);
1424
+ const lastCoord = coords[coords.length - 1];
1425
+ const lastX = lastCoord.x.toFixed(1);
734
1426
  const areaD = `${lineD} L ${lastX} ${height} L ${firstX} ${height} Z`;
1427
+ const areaGradId = `pfx-area-grad-${tone}-${computeMicroSvgIdSuffix(visualization, options)}`;
735
1428
  // Highlight extreme/boundary values
736
1429
  let minIdx = 0;
737
1430
  let maxIdx = 0;
@@ -741,9 +1434,10 @@ function renderAreaVisualizationHtml(visualization, options) {
741
1434
  if (points[i].value > points[maxIdx].value)
742
1435
  maxIdx = i;
743
1436
  }
1437
+ const lastTone = points[points.length - 1].tone ?? tone;
744
1438
  const markers = [
745
1439
  { 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 }
1440
+ { x: lastCoord.x, y: lastCoord.y, tone: lastTone }
747
1441
  ];
748
1442
  if (minIdx !== 0 && minIdx !== coords.length - 1) {
749
1443
  markers.push({ x: coords[minIdx].x, y: coords[minIdx].y, tone: points[minIdx].tone ?? 'danger' });
@@ -751,18 +1445,21 @@ function renderAreaVisualizationHtml(visualization, options) {
751
1445
  if (maxIdx !== 0 && maxIdx !== coords.length - 1) {
752
1446
  markers.push({ x: coords[maxIdx].x, y: coords[maxIdx].y, tone: points[maxIdx].tone ?? 'success' });
753
1447
  }
1448
+ 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
1449
  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('');
1450
+ const scrubLayerHtml = renderTrendScrubLayerHtml(points, coords, width, height, visualization, options);
755
1451
  const isTable = visualization.surface === 'table-cell';
756
1452
  const firstPoint = points[0];
757
1453
  const lastPoint = points[points.length - 1];
1454
+ const suffix = visualization.valueSuffix ?? '';
758
1455
  const leftHtml = isTable ? '' : `
759
1456
  <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>
1457
+ <span class="pfx-micro-trend__value">${escapeHtml(formatVisualizationMetricValue(firstPoint.value, options, visualization.compactValue === true, suffix))}</span>
761
1458
  ${firstPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(firstPoint.label)}</span>` : ''}
762
1459
  </div>`;
763
1460
  const rightHtml = isTable ? '' : `
764
1461
  <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>
1462
+ <span class="pfx-micro-trend__value">${escapeHtml(formatVisualizationMetricValue(lastPoint.value, options, visualization.compactValue === true, suffix))}</span>
766
1463
  ${lastPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(lastPoint.label)}</span>` : ''}
767
1464
  </div>`;
768
1465
  return `
@@ -770,10 +1467,19 @@ function renderAreaVisualizationHtml(visualization, options) {
770
1467
  ${leftHtml}
771
1468
  <span class="pfx-micro-viz pfx-micro-viz__area" data-tone="${escapeHtml(tone)}" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">
772
1469
  <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" />
1470
+ <defs>
1471
+ <linearGradient id="${escapeHtml(areaGradId)}" x1="0%" y1="0%" x2="0%" y2="100%">
1472
+ <stop offset="0%" stop-color="currentColor" stop-opacity="0.32" />
1473
+ <stop offset="100%" stop-color="currentColor" stop-opacity="0.02" />
1474
+ </linearGradient>
1475
+ </defs>
1476
+ ${refLineHtml}
1477
+ <path class="pfx-micro-area__fill" d="${areaD}" fill="url(#${escapeHtml(areaGradId)})" />
1478
+ <path class="pfx-micro-area__path" d="${lineD}" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" />
1479
+ ${endpointHaloHtml}
775
1480
  ${circlesHtml}
776
1481
  </svg>
1482
+ ${scrubLayerHtml}
777
1483
  </span>
778
1484
  ${rightHtml}
779
1485
  </span>`;
@@ -787,32 +1493,35 @@ function renderColumnVisualizationHtml(visualization, options) {
787
1493
  const width = 100;
788
1494
  const height = 30;
789
1495
  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;
1496
+ const { minVal, valRange } = resolveTrendBounds(points, visualization, true);
1497
+ const refLineHtml = renderTrendReferenceLineHtml(points, width, height, padding, visualization, true);
794
1498
  const colWidth = Math.max(2, (width - 2 * padding) / points.length - 2);
1499
+ const colCoords = [];
795
1500
  const columnsHtml = points.map((p, i) => {
796
1501
  const x = padding + i * ((width - 2 * padding) / points.length) + 1;
797
1502
  const rectHeight = Math.max(2, ((p.value - minVal) / valRange) * (height - 2 * padding));
798
1503
  const rectY = height - padding - rectHeight;
1504
+ colCoords.push({ x: x + colWidth / 2, y: rectY });
799
1505
  const itemTone = p.tone ??
800
1506
  (visualization.thresholds?.length
801
1507
  ? resolvePraxisMicroVisualizationTone(p.value, visualization.thresholds)?.tone ?? tone
802
1508
  : 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)}" />`;
1509
+ const latestAttr = i === points.length - 1 ? ' data-latest="true"' : '';
1510
+ 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
1511
  }).join('');
1512
+ const scrubLayerHtml = renderTrendScrubLayerHtml(points, colCoords, width, height, visualization, options);
805
1513
  const isTable = visualization.surface === 'table-cell';
806
1514
  const firstPoint = points[0];
807
1515
  const lastPoint = points[points.length - 1];
1516
+ const suffix = visualization.valueSuffix ?? '';
808
1517
  const leftHtml = isTable ? '' : `
809
1518
  <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>
1519
+ <span class="pfx-micro-trend__value">${escapeHtml(formatVisualizationMetricValue(firstPoint.value, options, visualization.compactValue === true, suffix))}</span>
811
1520
  ${firstPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(firstPoint.label)}</span>` : ''}
812
1521
  </div>`;
813
1522
  const rightHtml = isTable ? '' : `
814
1523
  <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>
1524
+ <span class="pfx-micro-trend__value">${escapeHtml(formatVisualizationMetricValue(lastPoint.value, options, visualization.compactValue === true, suffix))}</span>
816
1525
  ${lastPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(lastPoint.label)}</span>` : ''}
817
1526
  </div>`;
818
1527
  return `
@@ -821,7 +1530,9 @@ function renderColumnVisualizationHtml(visualization, options) {
821
1530
  <span class="pfx-micro-viz pfx-micro-viz__column" data-tone="${escapeHtml(tone)}" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">
822
1531
  <svg class="pfx-micro-column__svg" viewBox="0 0 100 30">
823
1532
  ${columnsHtml}
1533
+ ${refLineHtml}
824
1534
  </svg>
1535
+ ${scrubLayerHtml}
825
1536
  </span>
826
1537
  ${rightHtml}
827
1538
  </span>`;
@@ -850,15 +1561,25 @@ function renderProcessFlowVisualizationHtml(visualization, options) {
850
1561
  const itemState = item.state ?? '';
851
1562
  const isLast = index === items.length - 1;
852
1563
  const itemLabel = stepLabels[index];
1564
+ const normalizedIcon = item.icon ? item.icon.replace(/-/g, '_') : undefined;
853
1565
  const label = !isTable && item.label ? `<span class="pfx-micro-step__label"${labelInlineStyle}>${escapeHtml(item.label)}</span>` : '';
1566
+ const isActiveStep = itemState === 'active' ||
1567
+ itemState === 'current' ||
1568
+ itemState === 'in_progress' ||
1569
+ normalizedIcon === 'sync' ||
1570
+ normalizedIcon === 'pending' ||
1571
+ normalizedIcon === 'pending_actions' ||
1572
+ normalizedIcon === 'schedule' ||
1573
+ (!itemState && itemTone === 'warning');
1574
+ const stepReadout = `${index + 1}/${items.length} · ${itemLabel}`;
854
1575
  const connector = !isLast ? `<span class="pfx-micro-step__connector" data-tone="${escapeHtml(itemTone)}"></span>` : '';
855
1576
  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}`}
1577
+ <span class="pfx-micro-step__node" data-tone="${escapeHtml(itemTone)}"${isActiveStep ? ' data-active="true"' : ''} aria-hidden="true">
1578
+ ${normalizedIcon ? `<span class="material-icons pfx-micro-step__icon" aria-hidden="true">${escapeHtml(normalizedIcon)}</span>` : `${index + 1}`}
858
1579
  </span>`;
859
1580
  return `
860
1581
  <div class="pfx-micro-step" data-state="${escapeHtml(itemState)}" data-tone="${escapeHtml(itemTone)}">
861
- <div class="pfx-micro-step__node-wrapper" title="${escapeHtml(itemLabel)}">
1582
+ <div class="pfx-micro-step__node-wrapper" data-micro-readout="${escapeHtml(stepReadout)}" title="${escapeHtml(itemLabel)}">
862
1583
  ${stepCircle}
863
1584
  ${label}
864
1585
  </div>
@@ -870,6 +1591,209 @@ function renderProcessFlowVisualizationHtml(visualization, options) {
870
1591
  ${stepsHtml}
871
1592
  </span>`;
872
1593
  }
1594
+ function formatPraxisWaterfallSignedValue(value, role, options = {}, compactValue = false, suffix = '') {
1595
+ const absFormatted = formatVisualizationMetricValue(Math.abs(Number.isFinite(value) ? value : 0), options, compactValue, suffix);
1596
+ if (role === 'start' || role === 'subtotal' || role === 'total') {
1597
+ const negPrefix = value < 0 ? '-' : '';
1598
+ return `= ${negPrefix}${absFormatted}`;
1599
+ }
1600
+ if (value > 0) {
1601
+ return `+${absFormatted}`;
1602
+ }
1603
+ if (value < 0) {
1604
+ return `-${absFormatted}`;
1605
+ }
1606
+ return absFormatted;
1607
+ }
1608
+ function resolvePraxisMicroWaterfallSteps(visualization, options = {}) {
1609
+ const rawItems = Array.isArray(visualization.items) && visualization.items.length > 0
1610
+ ? visualization.items
1611
+ : Array.isArray(visualization.points)
1612
+ ? visualization.points.map((pt) => typeof pt === 'number'
1613
+ ? { value: pt }
1614
+ : {
1615
+ label: pt.label,
1616
+ value: pt.value,
1617
+ tone: pt.tone,
1618
+ ...(pt.suppressed !== undefined ? { suppressed: pt.suppressed } : {}),
1619
+ ...(pt.privacySuppressed !== undefined ? { privacySuppressed: pt.privacySuppressed } : {}),
1620
+ })
1621
+ : [];
1622
+ if (!rawItems.length) {
1623
+ return [];
1624
+ }
1625
+ const suffix = visualization.valueSuffix ?? '';
1626
+ const compactValue = visualization.compactValue === true;
1627
+ const fallbackAnchorTone = visualization.tone ?? 'info';
1628
+ const steps = [];
1629
+ let running = 0;
1630
+ let hasFiniteNumeric = false;
1631
+ let hadSuppressedItems = resolvePreservedSuppressedCount(visualization.suppressedCount) > 0;
1632
+ let visibleIncrementCount = 0;
1633
+ for (let i = 0; i < rawItems.length; i++) {
1634
+ const raw = rawItems[i];
1635
+ if (!raw || typeof raw !== 'object') {
1636
+ continue;
1637
+ }
1638
+ if (isVisualizationEntrySuppressed(raw)) {
1639
+ hadSuppressedItems = true;
1640
+ continue;
1641
+ }
1642
+ const rawNumeric = toFiniteNumber(raw.value);
1643
+ if (rawNumeric !== undefined) {
1644
+ hasFiniteNumeric = true;
1645
+ }
1646
+ const explicitRole = normalizeEnum$1(raw.role, WATERFALL_ROLES);
1647
+ const role = explicitRole
1648
+ ?? (steps.length === 0 ? 'start' : (rawNumeric ?? 0) < 0 ? 'decrease' : 'increase');
1649
+ if (rawNumeric === undefined && role !== 'subtotal' && role !== 'total') {
1650
+ continue;
1651
+ }
1652
+ if (role !== 'subtotal' && role !== 'total') {
1653
+ visibleIncrementCount += 1;
1654
+ }
1655
+ let start = running;
1656
+ let end = running;
1657
+ let delta = 0;
1658
+ let resolvedValue = rawNumeric ?? running;
1659
+ if (role === 'start') {
1660
+ start = 0;
1661
+ end = rawNumeric ?? 0;
1662
+ delta = end;
1663
+ running = end;
1664
+ resolvedValue = end;
1665
+ }
1666
+ else if (role === 'subtotal' || role === 'total') {
1667
+ const targetEnd = hadSuppressedItems ? running : (rawNumeric ?? running);
1668
+ start = 0;
1669
+ end = targetEnd;
1670
+ delta = targetEnd;
1671
+ running = targetEnd;
1672
+ resolvedValue = targetEnd;
1673
+ }
1674
+ else if (role === 'decrease') {
1675
+ delta = -Math.abs(rawNumeric ?? 0);
1676
+ start = running;
1677
+ end = running + delta;
1678
+ running = end;
1679
+ resolvedValue = delta;
1680
+ }
1681
+ else {
1682
+ delta = Math.abs(rawNumeric ?? 0);
1683
+ start = running;
1684
+ end = running + delta;
1685
+ running = end;
1686
+ resolvedValue = delta;
1687
+ }
1688
+ const defaultTone = role === 'increase'
1689
+ ? 'success'
1690
+ : role === 'decrease'
1691
+ ? 'danger'
1692
+ : role === 'start'
1693
+ ? 'neutral'
1694
+ : fallbackAnchorTone;
1695
+ const tone = normalizeEnum$1(raw.tone, VISUALIZATION_TONES) ?? defaultTone;
1696
+ const label = normalizeText$1(raw.label) ?? normalizeText$1(raw.id) ?? `#${steps.length + 1}`;
1697
+ const signedText = formatPraxisWaterfallSignedValue(role === 'start' || role === 'subtotal' || role === 'total' ? end : delta, role, options, compactValue, suffix);
1698
+ const endText = formatVisualizationMetricValue(Math.abs(end), options, compactValue, suffix);
1699
+ const signedEndText = `${end < 0 ? '-' : ''}${endText}`;
1700
+ const readout = role === 'start' || role === 'subtotal' || role === 'total'
1701
+ ? `${label}: ${signedText}`
1702
+ : `${label}: ${signedText} (=> ${signedEndText})`;
1703
+ steps.push({
1704
+ ...(raw.id ? { id: raw.id } : {}),
1705
+ label,
1706
+ value: resolvedValue,
1707
+ start,
1708
+ end,
1709
+ delta,
1710
+ role,
1711
+ tone,
1712
+ ...(raw.color ? { color: raw.color } : {}),
1713
+ signedText,
1714
+ readout,
1715
+ });
1716
+ }
1717
+ if (!hasFiniteNumeric || (hadSuppressedItems && visibleIncrementCount === 0)) {
1718
+ return [];
1719
+ }
1720
+ return steps;
1721
+ }
1722
+ function renderWaterfallVisualizationHtml(visualization, options) {
1723
+ const steps = resolvePraxisMicroWaterfallSteps(visualization, options);
1724
+ const fallbackTone = visualization.tone ?? 'info';
1725
+ if (steps.length === 0) {
1726
+ return renderFallbackVisualizationHtml(visualization, fallbackTone);
1727
+ }
1728
+ const width = 100;
1729
+ const height = 32;
1730
+ const xPad = 4;
1731
+ const yPad = 4;
1732
+ const plotHeight = height - 2 * yPad;
1733
+ const minVal = Math.min(0, ...steps.flatMap((s) => [s.start, s.end]));
1734
+ const maxVal = Math.max(0, ...steps.flatMap((s) => [s.start, s.end]));
1735
+ const span = Math.max(1e-6, maxVal - minVal);
1736
+ const yFor = (val) => yPad + (1 - (val - minVal) / span) * plotHeight;
1737
+ const slotW = (width - 2 * xPad) / steps.length;
1738
+ const barW = Math.max(3, Math.min(18, slotW * 0.64));
1739
+ const barOffset = (slotW - barW) / 2;
1740
+ const barsHtml = [];
1741
+ const connectorsHtml = [];
1742
+ const scrubSlicesHtml = [];
1743
+ for (let i = 0; i < steps.length; i++) {
1744
+ const step = steps[i];
1745
+ const x = xPad + i * slotW + barOffset;
1746
+ const yStart = yFor(step.start);
1747
+ const yEnd = yFor(step.end);
1748
+ const topY = Math.min(yStart, yEnd);
1749
+ const rectH = Math.max(2, Math.abs(yEnd - yStart));
1750
+ const clampedY = Math.min(height - yPad - 2, topY);
1751
+ const styleAttr = step.color ? ` style="color:${escapeHtml(step.color)}"` : '';
1752
+ 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} />`);
1753
+ if (i < steps.length - 1) {
1754
+ const nextX = xPad + (i + 1) * slotW + barOffset;
1755
+ const connY = step.end > step.start
1756
+ ? clampedY
1757
+ : step.end < step.start
1758
+ ? clampedY + rectH
1759
+ : Math.min(height - yPad, Math.max(clampedY, Math.min(clampedY + rectH, yEnd)));
1760
+ 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)}" />`);
1761
+ }
1762
+ 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>`);
1763
+ }
1764
+ const zeroY = yFor(0);
1765
+ const baselineHtml = `<line class="pfx-micro-waterfall__baseline" x1="2" y1="${zeroY.toFixed(1)}" x2="${(width - 2).toFixed(1)}" y2="${zeroY.toFixed(1)}" />`;
1766
+ const isTable = visualization.surface === 'table-cell';
1767
+ const firstStep = steps[0];
1768
+ const lastStep = steps[steps.length - 1];
1769
+ const aria = visualization.ariaLabel
1770
+ ?? `${visualization.fallbackText}: ${steps.map((s) => s.readout).join('; ')}`;
1771
+ const startSummaryHtml = !isTable && firstStep
1772
+ ? `<div class="pfx-micro-trend__label-col pfx-micro-trend__label-col--start">
1773
+ <span class="pfx-micro-trend__value">${escapeHtml(firstStep.signedText)}</span>
1774
+ <span class="pfx-micro-trend__label">${escapeHtml(firstStep.label)}</span>
1775
+ </div>`
1776
+ : '';
1777
+ const endSummaryHtml = !isTable && lastStep && steps.length > 1
1778
+ ? `<div class="pfx-micro-trend__label-col pfx-micro-trend__label-col--end">
1779
+ <span class="pfx-micro-trend__value">${escapeHtml(lastStep.signedText)}</span>
1780
+ <span class="pfx-micro-trend__label">${escapeHtml(lastStep.label)}</span>
1781
+ </div>`
1782
+ : '';
1783
+ return `
1784
+ <span class="pfx-micro-viz-container">
1785
+ ${startSummaryHtml}
1786
+ <span class="pfx-micro-viz pfx-micro-viz__waterfall" data-tone="${escapeHtml(fallbackTone)}" role="img" aria-label="${escapeHtml(aria)}">
1787
+ <svg class="pfx-micro-waterfall__svg" viewBox="0 0 ${width} ${height}" preserveAspectRatio="none">
1788
+ ${baselineHtml}
1789
+ ${connectorsHtml.join('')}
1790
+ ${barsHtml.join('')}
1791
+ </svg>
1792
+ <span class="pfx-micro-waterfall__scrub-layer">${scrubSlicesHtml.join('')}</span>
1793
+ </span>
1794
+ ${endSummaryHtml}
1795
+ </span>`;
1796
+ }
873
1797
  function renderFallbackVisualizationHtml(visualization, tone) {
874
1798
  return `
875
1799
  <span
@@ -880,75 +1804,545 @@ function renderFallbackVisualizationHtml(visualization, tone) {
880
1804
  >${escapeHtml(visualization.fallbackText)}</span>`;
881
1805
  }
882
1806
 
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',
1807
+ const PRAXIS_QUICK_VIEW_PRESENTER = new InjectionToken('PRAXIS_QUICK_VIEW_PRESENTER');
1808
+ const PRAXIS_QUICK_VIEW_BODY_RENDERER = new InjectionToken('PRAXIS_QUICK_VIEW_BODY_RENDERER');
1809
+ const FORBIDDEN_BINDING_KEYS = new Set([
1810
+ 'element',
1811
+ 'nativeElement',
1812
+ 'anchor',
1813
+ 'hostElement',
1814
+ 'focusOrigin',
1815
+ 'getViewportRect',
1816
+ 'nodes',
1817
+ 'document',
1818
+ 'action',
1819
+ 'actions',
1820
+ 'ctaAction',
1821
+ 'overrideAction',
1822
+ 'route',
1823
+ 'href',
1824
+ 'payload',
1825
+ 'hostCapabilities',
905
1826
  ]);
1827
+ const RESOURCE_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
906
1828
  /**
907
- * Resolves readonly field presentation from a base semantic config plus ordered
908
- * Json Logic rules. Later matching rules override earlier presentation values.
1829
+ * Detecta se um valor candidato à serialização contém referências efêmeras de DOM ou funções.
909
1830
  */
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;
1831
+ function containsEphemeralQuickViewRuntimeValue(value, visited = new Set()) {
1832
+ if (!value || typeof value !== 'object') {
1833
+ return typeof value === 'function';
915
1834
  }
916
- for (const rule of rules) {
917
- if (!rule?.when || !matchesPresentationRule(rule, context, options.jsonLogic)) {
918
- continue;
1835
+ if (visited.has(value)) {
1836
+ return false;
1837
+ }
1838
+ visited.add(value);
1839
+ if (typeof Element !== 'undefined' && value instanceof Element) {
1840
+ return true;
1841
+ }
1842
+ if (typeof value.nodeType === 'number' &&
1843
+ typeof value.nodeName === 'string') {
1844
+ return true;
1845
+ }
1846
+ if (Array.isArray(value)) {
1847
+ return value.some((item) => containsEphemeralQuickViewRuntimeValue(item, visited));
1848
+ }
1849
+ for (const [key, entry] of Object.entries(value)) {
1850
+ if (key === 'element' ||
1851
+ key === 'nativeElement' ||
1852
+ key === 'hostElement' ||
1853
+ key === 'focusOrigin' ||
1854
+ typeof entry === 'function') {
1855
+ return true;
1856
+ }
1857
+ if (containsEphemeralQuickViewRuntimeValue(entry, visited)) {
1858
+ return true;
919
1859
  }
920
- const effect = normalizeFieldPresentation(rule.set ?? rule.effect);
921
- resolved = {
922
- ...resolved,
923
- ...effect,
924
- };
925
- matchedRule = true;
926
1860
  }
927
- return matchedRule ? { ...resolved, matchedRule } : resolved;
1861
+ return false;
928
1862
  }
929
- function normalizeFieldPresentation(value) {
930
- if (!value || typeof value !== 'object') {
931
- return {};
1863
+ function normalizeResourceRecordOpenReference(candidate) {
1864
+ if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {
1865
+ return null;
1866
+ }
1867
+ const record = candidate;
1868
+ const target = record['target'] && typeof record['target'] === 'object' && !Array.isArray(record['target'])
1869
+ ? record['target']
1870
+ : null;
1871
+ const sourceIdentityField = typeof record['sourceIdentityField'] === 'string'
1872
+ ? record['sourceIdentityField'].trim()
1873
+ : '';
1874
+ const resourceKey = typeof target?.['resourceKey'] === 'string'
1875
+ ? target['resourceKey'].trim()
1876
+ : '';
1877
+ const surfaceId = typeof target?.['surfaceId'] === 'string'
1878
+ ? target['surfaceId'].trim()
1879
+ : '';
1880
+ if (!sourceIdentityField ||
1881
+ sourceIdentityField.length > 200 ||
1882
+ !RESOURCE_KEY_PATTERN.test(resourceKey) ||
1883
+ !surfaceId ||
1884
+ surfaceId.length > 200) {
1885
+ return null;
932
1886
  }
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
1887
  return {
950
- ...(presenter ? { presenter } : {}),
951
- ...(tone ? { tone } : {}),
1888
+ sourceIdentityField,
1889
+ target: {
1890
+ resourceKey,
1891
+ surfaceId,
1892
+ },
1893
+ };
1894
+ }
1895
+ /**
1896
+ * Valida e normaliza um `ResourceQuickViewBinding` de forma fail-closed.
1897
+ */
1898
+ function validateResourceQuickViewBinding(value) {
1899
+ const diagnostics = [];
1900
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
1901
+ return {
1902
+ valid: false,
1903
+ binding: null,
1904
+ diagnostics: ['Quick View binding must be a non-null object.'],
1905
+ };
1906
+ }
1907
+ const record = value;
1908
+ for (const forbiddenKey of FORBIDDEN_BINDING_KEYS) {
1909
+ if (forbiddenKey in record && record[forbiddenKey] !== undefined) {
1910
+ diagnostics.push(`Quick View binding cannot contain runtime, inline document or action override property "${forbiddenKey}".`);
1911
+ }
1912
+ }
1913
+ if (containsEphemeralQuickViewRuntimeValue(record)) {
1914
+ diagnostics.push('Quick View binding cannot contain DOM elements or functions.');
1915
+ }
1916
+ const rawRecordOpen = record['recordOpen'];
1917
+ if (!rawRecordOpen || typeof rawRecordOpen !== 'object' || Array.isArray(rawRecordOpen)) {
1918
+ diagnostics.push('Quick View binding requires a valid "recordOpen" object.');
1919
+ }
1920
+ else {
1921
+ const recordOpenObj = rawRecordOpen;
1922
+ for (const forbiddenKey of FORBIDDEN_BINDING_KEYS) {
1923
+ if (forbiddenKey in recordOpenObj && recordOpenObj[forbiddenKey] !== undefined) {
1924
+ diagnostics.push(`Quick View recordOpen cannot contain override property "${forbiddenKey}".`);
1925
+ }
1926
+ }
1927
+ if ('presentation' in recordOpenObj && recordOpenObj['presentation'] === 'popover') {
1928
+ diagnostics.push('Quick View recordOpen cannot declare "popover" presentation.');
1929
+ }
1930
+ }
1931
+ let previewSurfaceId;
1932
+ const rawPreviewSurfaceId = record['previewSurfaceId'];
1933
+ if (rawPreviewSurfaceId !== undefined && rawPreviewSurfaceId !== null) {
1934
+ if (typeof rawPreviewSurfaceId === 'string' &&
1935
+ rawPreviewSurfaceId.trim().length > 0 &&
1936
+ rawPreviewSurfaceId.trim().length <= 200) {
1937
+ previewSurfaceId = rawPreviewSurfaceId.trim();
1938
+ }
1939
+ else {
1940
+ diagnostics.push('Quick View previewSurfaceId must be a non-empty string up to 200 characters.');
1941
+ }
1942
+ }
1943
+ let detailPresentation;
1944
+ const rawDetailPresentation = record['detailPresentation'];
1945
+ if (rawDetailPresentation !== undefined && rawDetailPresentation !== null) {
1946
+ if (rawDetailPresentation === 'drawer' || rawDetailPresentation === 'modal') {
1947
+ detailPresentation = rawDetailPresentation;
1948
+ }
1949
+ else {
1950
+ diagnostics.push(`Quick View detailPresentation must be "drawer" or "modal"; received "${String(rawDetailPresentation)}".`);
1951
+ }
1952
+ }
1953
+ const normalizedRecordOpen = normalizeResourceRecordOpenReference(rawRecordOpen);
1954
+ if (!normalizedRecordOpen) {
1955
+ diagnostics.push('Quick View recordOpen must declare non-empty sourceIdentityField and target.{resourceKey, surfaceId}.');
1956
+ }
1957
+ let normalizedContentRef;
1958
+ const rawContentRef = record['contentRef'];
1959
+ if (rawContentRef !== undefined && rawContentRef !== null) {
1960
+ if (typeof rawContentRef !== 'object' || Array.isArray(rawContentRef)) {
1961
+ diagnostics.push('Quick View contentRef must be an object reference to a rich-block preset.');
1962
+ }
1963
+ else {
1964
+ const refObj = rawContentRef;
1965
+ const kind = typeof refObj['kind'] === 'string' ? refObj['kind'].trim() : '';
1966
+ const namespace = typeof refObj['namespace'] === 'string' ? refObj['namespace'].trim() : '';
1967
+ const presetId = typeof refObj['presetId'] === 'string' ? refObj['presetId'].trim() : '';
1968
+ const version = typeof refObj['version'] === 'string' ? refObj['version'].trim() : '';
1969
+ if (kind !== 'rich-block') {
1970
+ diagnostics.push(`Quick View contentRef.kind must be "rich-block"; received "${kind || 'empty'}".`);
1971
+ }
1972
+ if (!namespace) {
1973
+ diagnostics.push('Quick View contentRef.namespace must be a non-empty string.');
1974
+ }
1975
+ if (!presetId) {
1976
+ diagnostics.push('Quick View contentRef.presetId must be a non-empty string.');
1977
+ }
1978
+ if (!version) {
1979
+ diagnostics.push('Quick View contentRef.version must be explicitly declared.');
1980
+ }
1981
+ if ('nodes' in refObj || 'inputs' in refObj || 'action' in refObj) {
1982
+ diagnostics.push('Quick View contentRef cannot embed inline nodes, inputs or actions.');
1983
+ }
1984
+ if (kind === 'rich-block' &&
1985
+ namespace &&
1986
+ presetId &&
1987
+ version &&
1988
+ !('nodes' in refObj || 'inputs' in refObj || 'action' in refObj)) {
1989
+ normalizedContentRef = {
1990
+ kind: 'rich-block',
1991
+ namespace,
1992
+ presetId,
1993
+ version,
1994
+ };
1995
+ }
1996
+ }
1997
+ }
1998
+ if (diagnostics.length > 0 || !normalizedRecordOpen) {
1999
+ return {
2000
+ valid: false,
2001
+ binding: null,
2002
+ diagnostics,
2003
+ };
2004
+ }
2005
+ return {
2006
+ valid: true,
2007
+ binding: {
2008
+ recordOpen: normalizedRecordOpen,
2009
+ ...(previewSurfaceId ? { previewSurfaceId } : {}),
2010
+ ...(normalizedContentRef ? { contentRef: normalizedContentRef } : {}),
2011
+ ...(detailPresentation ? { detailPresentation } : {}),
2012
+ },
2013
+ diagnostics: [],
2014
+ };
2015
+ }
2016
+ function normalizeResourceQuickViewBinding(value) {
2017
+ return validateResourceQuickViewBinding(value).binding;
2018
+ }
2019
+ /**
2020
+ * Resolve ou sintetiza de forma determinística o `ResourceQuickViewBinding` de um campo
2021
+ * (`FieldDefinition` ou `FieldMetadata`), priorizando:
2022
+ * 1. `field.quickView` explícito;
2023
+ * 2. `field.presentation.interactions.quickView` explícito;
2024
+ * 3. síntese automática a partir de `field.resourceReference` ou `field.optionSource.detail`.
2025
+ *
2026
+ * Protege contra colisão de `valueField`/`optionSource.valuePropertyPath` (`'id'` da opção)
2027
+ * com o identificador da própria entidade pai quando o campo de origem possui outro nome
2028
+ * (ex.: `cargoId`, `fornecedorId`).
2029
+ */
2030
+ function resolveFieldQuickViewBinding(candidate) {
2031
+ if (!candidate || typeof candidate !== 'object') {
2032
+ return null;
2033
+ }
2034
+ const explicitQuickView = normalizeResourceQuickViewBinding(candidate.quickView);
2035
+ if (explicitQuickView) {
2036
+ return explicitQuickView;
2037
+ }
2038
+ const presentationQuickView = normalizeResourceQuickViewBinding(candidate.presentation?.interactions?.quickView);
2039
+ if (presentationQuickView) {
2040
+ return presentationQuickView;
2041
+ }
2042
+ const fieldName = typeof candidate.name === 'string' ? candidate.name.trim() : '';
2043
+ const rawValueField = typeof candidate.valueField === 'string' ? candidate.valueField.trim() : '';
2044
+ const optionValueProperty = typeof candidate.optionSource?.valuePropertyPath === 'string' &&
2045
+ candidate.optionSource.valuePropertyPath.trim().length > 0
2046
+ ? candidate.optionSource.valuePropertyPath.trim()
2047
+ : 'id';
2048
+ // Quando o campo possui optionSource e seu nome não coincide com rawValueField, um valueField
2049
+ // igual a 'id'/'value'/'key' ou a optionValueProperty (ex.: 'numero', 'codigo') refere-se à
2050
+ // chave do OptionDTO e nunca ao campo irmão 'id' do registro pai.
2051
+ const isOptionKeyAlias = rawValueField === 'id' ||
2052
+ rawValueField === 'value' ||
2053
+ rawValueField === 'key' ||
2054
+ rawValueField === optionValueProperty;
2055
+ const effectiveSiblingValueField = rawValueField &&
2056
+ (!candidate.optionSource ||
2057
+ fieldName === rawValueField ||
2058
+ !isOptionKeyAlias)
2059
+ ? rawValueField
2060
+ : '';
2061
+ const refCandidate = candidate.resourceReference?.resourceKey
2062
+ ? {
2063
+ resourceKey: candidate.resourceReference.resourceKey,
2064
+ sourceIdentityField: (typeof candidate.resourceReference.valueField === 'string'
2065
+ ? candidate.resourceReference.valueField.trim()
2066
+ : '') ||
2067
+ effectiveSiblingValueField ||
2068
+ fieldName,
2069
+ surfaceId: candidate.resourceReference.surfaceId || 'detail',
2070
+ previewSurfaceId: candidate.resourceReference.previewSurfaceId,
2071
+ detailPresentation: candidate.resourceReference.detailPresentation === 'drawer' ||
2072
+ candidate.resourceReference.detailPresentation === 'modal'
2073
+ ? candidate.resourceReference.detailPresentation
2074
+ : undefined,
2075
+ }
2076
+ : candidate.optionSource?.detail?.resourceKey
2077
+ ? {
2078
+ resourceKey: candidate.optionSource.detail.resourceKey,
2079
+ sourceIdentityField: effectiveSiblingValueField || fieldName,
2080
+ surfaceId: candidate.optionSource.detail.surfaceId || 'detail',
2081
+ previewSurfaceId: candidate.optionSource.detail.previewSurfaceId,
2082
+ detailPresentation: candidate.optionSource.detail.presentation === 'drawer' ||
2083
+ candidate.optionSource.detail.presentation === 'modal'
2084
+ ? candidate.optionSource.detail.presentation
2085
+ : undefined,
2086
+ }
2087
+ : undefined;
2088
+ if (!refCandidate || !refCandidate.sourceIdentityField) {
2089
+ return null;
2090
+ }
2091
+ return normalizeResourceQuickViewBinding({
2092
+ recordOpen: {
2093
+ sourceIdentityField: refCandidate.sourceIdentityField,
2094
+ target: {
2095
+ resourceKey: refCandidate.resourceKey,
2096
+ surfaceId: refCandidate.surfaceId || 'detail',
2097
+ },
2098
+ },
2099
+ ...(refCandidate.previewSurfaceId
2100
+ ? { previewSurfaceId: refCandidate.previewSurfaceId }
2101
+ : {}),
2102
+ ...(refCandidate.detailPresentation
2103
+ ? { detailPresentation: refCandidate.detailPresentation }
2104
+ : {}),
2105
+ });
2106
+ }
2107
+ /**
2108
+ * Reconcilia o `ResourceQuickViewBinding` entre a definição base do servidor e uma
2109
+ * customização local persistida:
2110
+ * - Um `local` indefinido, nulo ou inválido nunca apaga o binding canônico do servidor (`base`).
2111
+ * - Quando o campo possui binding canônico do servidor (`base`), `base.recordOpen`
2112
+ * (recurso de destino, `surfaceId` e `sourceIdentityField`) permanece autoritativo
2113
+ * do servidor, permitindo que o `local` customize apenas preferências visuais de UX
2114
+ * (`trigger`, `previewSurfaceId`, `detailPresentation`).
2115
+ */
2116
+ function reconcileFieldQuickViewBinding(base, local) {
2117
+ const normalizedBase = normalizeResourceQuickViewBinding(base);
2118
+ const normalizedLocal = normalizeResourceQuickViewBinding(local);
2119
+ if (normalizedBase && normalizedLocal) {
2120
+ return {
2121
+ ...normalizedBase,
2122
+ ...normalizedLocal,
2123
+ recordOpen: normalizedBase.recordOpen,
2124
+ };
2125
+ }
2126
+ return normalizedLocal ?? normalizedBase ?? undefined;
2127
+ }
2128
+ function readQuickViewFieldOrPath(target, path) {
2129
+ if (Object.prototype.hasOwnProperty.call(target, path)) {
2130
+ return target[path];
2131
+ }
2132
+ if (!path.includes('.')) {
2133
+ return undefined;
2134
+ }
2135
+ return path.split('.').reduce((acc, segment) => {
2136
+ if (!acc || typeof acc !== 'object' || Array.isArray(acc)) {
2137
+ return undefined;
2138
+ }
2139
+ return Object.prototype.hasOwnProperty.call(acc, segment)
2140
+ ? acc[segment]
2141
+ : undefined;
2142
+ }, target);
2143
+ }
2144
+ /**
2145
+ * Resolve de forma determinística o alvo (`resourceKey`, `surfaceId`, `previewSurfaceId`, `identity`)
2146
+ * a partir de um `ResourceQuickViewBinding` e de um registro candidato (`sourceRecord`).
2147
+ */
2148
+ function resolveResourceQuickViewTarget(binding, sourceRecord) {
2149
+ const normalized = normalizeResourceQuickViewBinding(binding);
2150
+ if (!normalized ||
2151
+ !sourceRecord ||
2152
+ typeof sourceRecord !== 'object' ||
2153
+ Array.isArray(sourceRecord)) {
2154
+ return null;
2155
+ }
2156
+ const record = sourceRecord;
2157
+ const sourceField = normalized.recordOpen.sourceIdentityField;
2158
+ let candidate = readQuickViewFieldOrPath(record, sourceField);
2159
+ if (candidate === undefined) {
2160
+ for (const envelopeKey of ['row', 'item', 'values']) {
2161
+ const nested = record[envelopeKey];
2162
+ if (nested && typeof nested === 'object' && !Array.isArray(nested)) {
2163
+ candidate = readQuickViewFieldOrPath(nested, sourceField);
2164
+ if (candidate !== undefined) {
2165
+ break;
2166
+ }
2167
+ }
2168
+ }
2169
+ }
2170
+ if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
2171
+ const candidateObj = candidate;
2172
+ candidate =
2173
+ candidateObj['id'] ?? candidateObj['value'] ?? candidateObj['key'];
2174
+ }
2175
+ if (typeof candidate === 'number' && Number.isFinite(candidate)) {
2176
+ return {
2177
+ resourceKey: normalized.recordOpen.target.resourceKey,
2178
+ surfaceId: normalized.recordOpen.target.surfaceId,
2179
+ previewSurfaceId: normalized.previewSurfaceId || normalized.recordOpen.target.surfaceId,
2180
+ identity: candidate,
2181
+ };
2182
+ }
2183
+ if (typeof candidate === 'string' && candidate.trim().length > 0) {
2184
+ return {
2185
+ resourceKey: normalized.recordOpen.target.resourceKey,
2186
+ surfaceId: normalized.recordOpen.target.surfaceId,
2187
+ previewSurfaceId: normalized.previewSurfaceId || normalized.recordOpen.target.surfaceId,
2188
+ identity: candidate.trim(),
2189
+ };
2190
+ }
2191
+ return null;
2192
+ }
2193
+ /**
2194
+ * Verifica se a âncora efêmera de runtime permanece conectada e visível na viewport.
2195
+ */
2196
+ function isResourceQuickViewAnchorValid(anchor, trigger) {
2197
+ if (!anchor || typeof anchor !== 'object') {
2198
+ return false;
2199
+ }
2200
+ if (typeof anchor.isValid === 'function' && !anchor.isValid()) {
2201
+ return false;
2202
+ }
2203
+ const viewportWidth = typeof window !== 'undefined' && Number.isFinite(window.innerWidth) && window.innerWidth > 0
2204
+ ? window.innerWidth
2205
+ : 1920;
2206
+ const viewportHeight = typeof window !== 'undefined' && Number.isFinite(window.innerHeight) && window.innerHeight > 0
2207
+ ? window.innerHeight
2208
+ : 1080;
2209
+ if (anchor.kind === 'element') {
2210
+ const el = anchor.element;
2211
+ if (!el || typeof el.getBoundingClientRect !== 'function' || el.isConnected === false) {
2212
+ return false;
2213
+ }
2214
+ const rect = el.getBoundingClientRect();
2215
+ if (!Number.isFinite(rect.left) || !Number.isFinite(rect.top)) {
2216
+ return false;
2217
+ }
2218
+ if (rect.width === 0 && rect.height === 0) {
2219
+ return false;
2220
+ }
2221
+ const edgeTolerance = trigger === 'focus-shortcut' || trigger === 'explicit-button' ? 96 : 0;
2222
+ return (rect.bottom >= -edgeTolerance &&
2223
+ rect.right >= -edgeTolerance &&
2224
+ rect.top <= viewportHeight + edgeTolerance &&
2225
+ rect.left <= viewportWidth + edgeTolerance);
2226
+ }
2227
+ if (anchor.kind === 'virtual-rect') {
2228
+ if (!anchor.anchorKey || !anchor.anchorKey.trim()) {
2229
+ return false;
2230
+ }
2231
+ if (anchor.hostElement && anchor.hostElement.isConnected === false) {
2232
+ return false;
2233
+ }
2234
+ if (typeof anchor.getViewportRect !== 'function') {
2235
+ return false;
2236
+ }
2237
+ const rect = anchor.getViewportRect();
2238
+ if (!rect ||
2239
+ !Number.isFinite(rect.x) ||
2240
+ !Number.isFinite(rect.y) ||
2241
+ !Number.isFinite(rect.width) ||
2242
+ !Number.isFinite(rect.height) ||
2243
+ rect.width < 0 ||
2244
+ rect.height < 0) {
2245
+ return false;
2246
+ }
2247
+ const right = rect.right ?? rect.x + rect.width;
2248
+ const bottom = rect.bottom ?? rect.y + rect.height;
2249
+ const left = rect.left ?? rect.x;
2250
+ const top = rect.top ?? rect.y;
2251
+ return (bottom >= 0 &&
2252
+ right >= 0 &&
2253
+ top <= viewportHeight &&
2254
+ left <= viewportWidth);
2255
+ }
2256
+ return false;
2257
+ }
2258
+ function resolveQuickViewAnchorKey(anchor) {
2259
+ if (anchor.kind === 'virtual-rect') {
2260
+ return anchor.anchorKey.trim();
2261
+ }
2262
+ const explicit = anchor.anchorKey?.trim();
2263
+ if (explicit) {
2264
+ return explicit;
2265
+ }
2266
+ const focusKey = anchor.element?.getAttribute?.('data-praxis-focus-key')?.trim();
2267
+ if (focusKey) {
2268
+ return focusKey;
2269
+ }
2270
+ const id = anchor.element?.id?.trim();
2271
+ if (id) {
2272
+ return `element:${id}`;
2273
+ }
2274
+ return 'element:anonymous';
2275
+ }
2276
+
2277
+ const TONES = new Set([
2278
+ 'neutral',
2279
+ 'info',
2280
+ 'success',
2281
+ 'warning',
2282
+ 'danger',
2283
+ ]);
2284
+ const APPEARANCES = new Set([
2285
+ 'plain',
2286
+ 'soft',
2287
+ 'outlined',
2288
+ 'filled',
2289
+ ]);
2290
+ const PRESENTERS = new Set([
2291
+ 'text',
2292
+ 'badge',
2293
+ 'chip',
2294
+ 'status',
2295
+ 'iconValue',
2296
+ 'progress',
2297
+ 'rating',
2298
+ 'microVisualization',
2299
+ ]);
2300
+ /**
2301
+ * Resolves readonly field presentation from a base semantic config plus ordered
2302
+ * Json Logic rules. Later matching rules override earlier presentation values.
2303
+ */
2304
+ function resolveFieldPresentation(base, rules, context = {}, options = {}) {
2305
+ let resolved = normalizeFieldPresentation(base);
2306
+ let matchedRule = false;
2307
+ if (!Array.isArray(rules) || !options.jsonLogic) {
2308
+ return resolved;
2309
+ }
2310
+ for (const rule of rules) {
2311
+ if (!rule?.when || !matchesPresentationRule(rule, context, options.jsonLogic)) {
2312
+ continue;
2313
+ }
2314
+ const effect = normalizeFieldPresentation(rule.set ?? rule.effect);
2315
+ resolved = {
2316
+ ...resolved,
2317
+ ...effect,
2318
+ };
2319
+ matchedRule = true;
2320
+ }
2321
+ return matchedRule ? { ...resolved, matchedRule } : resolved;
2322
+ }
2323
+ function normalizeFieldPresentation(value) {
2324
+ if (!value || typeof value !== 'object') {
2325
+ return {};
2326
+ }
2327
+ const presenter = normalizePresenter(value.presenter ?? value.variant);
2328
+ const tone = normalizeTone(value.tone);
2329
+ const appearance = normalizeAppearance(value.appearance);
2330
+ const icon = normalizeText(value.icon);
2331
+ const label = normalizeText(value.label);
2332
+ const badge = normalizeText(value.badge);
2333
+ const tooltip = normalizeText(value.tooltip);
2334
+ const prefix = normalizeText(value.prefix);
2335
+ const suffix = normalizeText(value.suffix);
2336
+ const iconTrue = normalizeText(value.iconTrue);
2337
+ const iconFalse = normalizeText(value.iconFalse);
2338
+ const toneTrue = normalizeTone(value.toneTrue);
2339
+ const toneFalse = normalizeTone(value.toneFalse);
2340
+ const labelTrue = normalizeText(value.labelTrue);
2341
+ const labelFalse = normalizeText(value.labelFalse);
2342
+ const visualization = normalizePraxisPresentationVisualization(value.visualization);
2343
+ return {
2344
+ ...(presenter ? { presenter } : {}),
2345
+ ...(tone ? { tone } : {}),
952
2346
  ...(appearance ? { appearance } : {}),
953
2347
  ...(icon ? { icon } : {}),
954
2348
  ...(label ? { label } : {}),
@@ -1006,14 +2400,475 @@ function normalizeText(value) {
1006
2400
  return trimmed.length ? trimmed : undefined;
1007
2401
  }
1008
2402
  function normalizeInteractions(value) {
2403
+ const quickView = normalizeResourceQuickViewBinding(value.quickView);
1009
2404
  return {
1010
2405
  ...(value.copy === true ? { copy: true } : {}),
1011
2406
  ...(value.details === true ? { details: true } : {}),
1012
2407
  ...(value.expand === true ? { expand: true } : {}),
1013
2408
  ...(value.link === true ? { link: true } : {}),
2409
+ ...(quickView ? { quickView } : {}),
1014
2410
  };
1015
2411
  }
1016
2412
 
2413
+ /** Converts UI tokens only under declared scalar items; invalid input is never dropped or partially converted. */
2414
+ function normalizeScalarArrayValue(value, items) {
2415
+ if (items.enum !== undefined && !isScalarEnum(items.enum))
2416
+ return { valid: false, invalidIndices: [-1] };
2417
+ if (value == null)
2418
+ return { valid: true, value };
2419
+ if (!Array.isArray(value))
2420
+ return { valid: false, invalidIndices: [-1] };
2421
+ const converted = [];
2422
+ const invalidIndices = [];
2423
+ for (let index = 0; index < value.length; index += 1) {
2424
+ const item = normalizeItem(value[index], items);
2425
+ if (item === undefined || items.enum && !items.enum.some(candidate => candidate === item))
2426
+ invalidIndices.push(index);
2427
+ else
2428
+ converted.push(item);
2429
+ }
2430
+ return invalidIndices.length ? { valid: false, invalidIndices } : { valid: true, value: converted };
2431
+ }
2432
+ function normalizeItem(value, items) {
2433
+ if (value == null)
2434
+ return undefined;
2435
+ if (items.type === 'boolean') {
2436
+ if (typeof value === 'boolean')
2437
+ return value;
2438
+ return value === 'true' ? true : value === 'false' ? false : undefined;
2439
+ }
2440
+ if (items.type === 'integer' || items.type === 'number') {
2441
+ const number = typeof value === 'number' ? value : typeof value === 'string' &&
2442
+ /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(value) ? Number(value) : NaN;
2443
+ if (!Number.isFinite(number) || items.type === 'integer' && !Number.isSafeInteger(number))
2444
+ return undefined;
2445
+ return number;
2446
+ }
2447
+ if (items.type !== 'string')
2448
+ return undefined;
2449
+ if (items.format === 'date') {
2450
+ if (value instanceof Date) {
2451
+ if (Number.isNaN(value.getTime()))
2452
+ return undefined;
2453
+ const date = `${String(value.getFullYear()).padStart(4, '0')}-${String(value.getMonth() + 1).padStart(2, '0')}-${String(value.getDate()).padStart(2, '0')}`;
2454
+ return isIsoDate(date) ? date : undefined;
2455
+ }
2456
+ return typeof value === 'string' && isIsoDate(value) ? value : undefined;
2457
+ }
2458
+ if (items.format === 'date-time') {
2459
+ if (value instanceof Date)
2460
+ return Number.isNaN(value.getTime()) ? undefined : value.toISOString();
2461
+ return typeof value === 'string' && isIsoDateTime(value) ? value : undefined;
2462
+ }
2463
+ return typeof value === 'string' ? value : undefined;
2464
+ }
2465
+ function isIsoDate(value) {
2466
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
2467
+ if (!match)
2468
+ return false;
2469
+ const year = Number(match[1]), month = Number(match[2]), day = Number(match[3]);
2470
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
2471
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
2472
+ return month >= 1 && month <= 12 && day >= 1 && day <= days[month - 1];
2473
+ }
2474
+ function isIsoDateTime(value) {
2475
+ 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);
2476
+ if (!match || !isIsoDate(match[1]))
2477
+ return false;
2478
+ if (Number(match[2]) > 23 || Number(match[3]) > 59 || Number(match[4] ?? 0) > 59)
2479
+ return false;
2480
+ const offsetHours = Number(match[7] ?? 0), offsetMinutes = Number(match[8] ?? 0);
2481
+ return offsetHours <= 18 && offsetMinutes <= 59 && (offsetHours !== 18 || offsetMinutes === 0);
2482
+ }
2483
+ /** Internal admission of the scalar subset already published in JSON Schema items. */
2484
+ function normalizeScalarItemsSchema(value) {
2485
+ if (!value || typeof value !== 'object' || Array.isArray(value))
2486
+ return undefined;
2487
+ const record = value;
2488
+ if (typeof record['type'] !== 'string' || !['string', 'integer', 'number', 'boolean'].includes(record['type']))
2489
+ return undefined;
2490
+ const result = { type: record['type'] };
2491
+ if (typeof record['format'] === 'string')
2492
+ result.format = record['format'];
2493
+ if (record['enum'] !== undefined) {
2494
+ if (!isScalarEnum(record['enum']))
2495
+ throw new TypeError('Scalar items enum must contain JSON scalar values.');
2496
+ result.enum = [...record['enum']];
2497
+ }
2498
+ return result;
2499
+ }
2500
+ function isScalarEnum(value) {
2501
+ return Array.isArray(value) && value.length > 0 && value.every(item => item === null || typeof item === 'string' || typeof item === 'boolean' || typeof item === 'number' && Number.isFinite(item));
2502
+ }
2503
+
2504
+ /**
2505
+ * Enum que define os tipos de controle (`CONTROL_TYPE`) disponíveis para a apresentação dos campos de formulário.
2506
+ *
2507
+ * O `CONTROL_TYPE` especifica o tipo de elemento de UI (User Interface) que será usado para capturar ou exibir dados do campo.
2508
+ * Essa configuração permite que a camada de apresentação saiba como renderizar o campo e oferecer a interação adequada ao usuário.
2509
+ * Em casos onde o `CONTROL_TYPE` não é especificado, a camada de apresentação pode usar o valor de `TYPE` (definido em `FieldDataType`)
2510
+ * para decidir o controle mais adequado de forma automática.
2511
+ */
2512
+ const FieldControlType = {
2513
+ AI_PROMPT: 'aiPrompt',
2514
+ APP_BAR: 'appBar',
2515
+ ARC_GAUGE: 'arcGauge',
2516
+ ARRAY_INPUT: 'array',
2517
+ ASYNC_SELECT: 'async-select',
2518
+ AUTO_COMPLETE: 'autoComplete',
2519
+ AVATAR: 'avatar',
2520
+ BARCODE_GENERATOR: 'barcodeGenerator',
2521
+ BOTTOM_NAVIGATION: 'bottomNavigation',
2522
+ BREADCRUMB: 'breadcrumb',
2523
+ BUTTON: 'button',
2524
+ BUTTON_TOGGLE: 'buttonToggle',
2525
+ CALENDAR: 'calendar',
2526
+ CARD: 'card',
2527
+ CHECKBOX: 'checkbox',
2528
+ CHIP_INPUT: 'chipInput',
2529
+ CHIP_LIST: 'chipList',
2530
+ CIRCULAR_GAUGE: 'circularGauge',
2531
+ COLOR_GRADIENT: 'colorGradient',
2532
+ CPF_CNPJ_INPUT: 'cpfCnpjInput',
2533
+ COLOR_PALETTE: 'colorPalette',
2534
+ COLOR_PICKER: 'colorPicker',
2535
+ COLOR_INPUT: 'color',
2536
+ CRON_BUILDER: 'cronBuilder',
2537
+ CONTEXT_MENU: 'contextMenu',
2538
+ CONVERSATIONAL_UI: 'conversationalUI',
2539
+ CURRENCY_INPUT: 'currency',
2540
+ DATE_INPUT: 'dateInput',
2541
+ DATE_PICKER: 'date',
2542
+ DATE_RANGE: 'dateRange',
2543
+ DATE_TIME_PICKER: 'dateTime',
2544
+ DATE_TIME_RANGE: 'dateTimeRange',
2545
+ DATETIME_LOCAL_INPUT: 'dateTimeLocal',
2546
+ DIALOG: 'dialog',
2547
+ DRAWER: 'drawer',
2548
+ DROP_DOWN_TREE: 'dropDownTree',
2549
+ EMAIL_INPUT: 'email',
2550
+ ENTITY_LOOKUP: 'entityLookup',
2551
+ EXPANSION_PANEL: 'expansionPanel',
2552
+ FILE_SAVER: 'fileSaver',
2553
+ FILE_SELECT: 'fileSelect',
2554
+ FILE_UPLOAD: 'upload',
2555
+ FILTER: 'filter',
2556
+ FLOATING_LABEL: 'floatingLabel',
2557
+ FLOATING_ACTION_BUTTON: 'floatingActionButton',
2558
+ GRID: 'grid',
2559
+ GRID_LAYOUT: 'gridLayout',
2560
+ INPUT: 'input',
2561
+ INLINE_SELECT: 'inlineSelect',
2562
+ INLINE_SEARCHABLE_SELECT: 'inlineSearchableSelect',
2563
+ INLINE_ASYNC_SELECT: 'inlineAsyncSelect',
2564
+ INLINE_ENTITY_LOOKUP: 'inlineEntityLookup',
2565
+ INLINE_AUTOCOMPLETE: 'inlineAutocomplete',
2566
+ INLINE_INPUT: 'inlineInput',
2567
+ INLINE_PHONE: 'inlinePhone',
2568
+ INLINE_NUMBER: 'inlineNumber',
2569
+ INLINE_CURRENCY: 'inlineCurrency',
2570
+ INLINE_CURRENCY_RANGE: 'inlineCurrencyRange',
2571
+ INLINE_MULTISELECT: 'inlineMultiSelect',
2572
+ INLINE_TOGGLE: 'inlineToggle',
2573
+ INLINE_RANGE: 'inlineRange',
2574
+ INLINE_PERIOD_RANGE: 'inlinePeriodRange',
2575
+ INLINE_YEAR_RANGE: 'inlineYearRange',
2576
+ INLINE_MONTH_RANGE: 'inlineMonthRange',
2577
+ INLINE_DATE: 'inlineDate',
2578
+ INLINE_DATE_RANGE: 'inlineDateRange',
2579
+ INLINE_TIME: 'inlineTime',
2580
+ INLINE_TIME_RANGE: 'inlineTimeRange',
2581
+ INLINE_TREE_SELECT: 'inlineTreeSelect',
2582
+ INLINE_RATING: 'inlineRating',
2583
+ INLINE_DISTANCE_RADIUS: 'inlineDistanceRadius',
2584
+ INLINE_PIPELINE_STATUS: 'inlinePipelineStatus',
2585
+ INLINE_SCORE_PRIORITY: 'inlineScorePriority',
2586
+ INLINE_RELATIVE_PERIOD: 'inlineRelativePeriod',
2587
+ INLINE_SENTIMENT: 'inlineSentiment',
2588
+ INLINE_COLOR_LABEL: 'inlineColorLabel',
2589
+ LINEAR_GAUGE: 'linearGauge',
2590
+ LIST_VIEW: 'listView',
2591
+ MAP: 'map',
2592
+ MASKED_TEXT_BOX: 'maskedTextBox',
2593
+ MONTH_INPUT: 'month',
2594
+ MULTI_COLUMN_COMBO_BOX: 'multiColumnComboBox',
2595
+ MULTI_SELECT: 'multiSelect',
2596
+ MULTI_SELECT_TREE: 'multiSelectTree',
2597
+ TRANSFER_LIST: 'transferList',
2598
+ NOTIFICATION: 'notification',
2599
+ NUMERIC_TEXT_BOX: 'numericTextBox',
2600
+ PAGER: 'pager',
2601
+ PAGINATOR: 'paginator',
2602
+ PASSWORD: 'password',
2603
+ PDF_VIEWER: 'pdfViewer',
2604
+ PHONE: 'phone',
2605
+ PIVOT_GRID: 'pivotGrid',
2606
+ POPUP: 'popup',
2607
+ PROGRESS_BAR: 'progressBar',
2608
+ PROGRESS_SPINNER: 'progressSpinner',
2609
+ QR_CODE: 'qrCode',
2610
+ RADIO: 'radio',
2611
+ RADIAL_GAUGE: 'radialGauge',
2612
+ RANGE_SLIDER: 'rangeSlider',
2613
+ PRICE_RANGE: 'priceRange',
2614
+ RATING: 'rating',
2615
+ RICH_TEXT_EDITOR: 'richTextEditor',
2616
+ RIPPLE: 'ripple',
2617
+ SCROLL_VIEW: 'scrollView',
2618
+ SEARCH_INPUT: 'search',
2619
+ SEARCHABLE_SELECT: 'searchable-select',
2620
+ SELECTION_LIST: 'selectionList',
2621
+ SELECT: 'select',
2622
+ SIGNATURE: 'signature',
2623
+ SLIDER: 'slider',
2624
+ SORTABLE: 'sortable',
2625
+ SORTABLE_TABLE: 'sortableTable',
2626
+ SPLITTER: 'splitter',
2627
+ SPREADSHEET: 'spreadsheet',
2628
+ STACK_LAYOUT: 'stackLayout',
2629
+ STEP_BAR: 'stepBar',
2630
+ STEPPER: 'stepper',
2631
+ SVG_ICON: 'svgIcon',
2632
+ TABS: 'tabs',
2633
+ TEXTAREA: 'textarea',
2634
+ TIME_INPUT: 'time',
2635
+ TIME_PICKER: 'timePicker',
2636
+ TIME_RANGE: 'timeRange',
2637
+ TIMELINE: 'timeline',
2638
+ TOGGLE: 'toggle',
2639
+ TOOLBAR: 'toolbar',
2640
+ TOOLTIP: 'tooltip',
2641
+ TREE_VIEW: 'treeView',
2642
+ TREE_SELECT: 'treeSelect',
2643
+ TYPOGRAPHY: 'typography',
2644
+ URL_INPUT: 'url',
2645
+ WEEK_INPUT: 'week',
2646
+ WINDOW: 'window',
2647
+ YEAR_INPUT: 'year',
2648
+ };
2649
+
2650
+ const INLINE_FILTER_CONTROL_TYPES = Object.freeze({
2651
+ SELECT: FieldControlType.INLINE_SELECT,
2652
+ SEARCHABLE_SELECT: FieldControlType.INLINE_SEARCHABLE_SELECT,
2653
+ ASYNC_SELECT: FieldControlType.INLINE_ASYNC_SELECT,
2654
+ ENTITY_LOOKUP: FieldControlType.INLINE_ENTITY_LOOKUP,
2655
+ AUTOCOMPLETE: FieldControlType.INLINE_AUTOCOMPLETE,
2656
+ NUMBER: FieldControlType.INLINE_NUMBER,
2657
+ CURRENCY: FieldControlType.INLINE_CURRENCY,
2658
+ CURRENCY_RANGE: FieldControlType.INLINE_CURRENCY_RANGE,
2659
+ MULTI_SELECT: FieldControlType.INLINE_MULTISELECT,
2660
+ INPUT: FieldControlType.INLINE_INPUT,
2661
+ PHONE: FieldControlType.INLINE_PHONE,
2662
+ TOGGLE: FieldControlType.INLINE_TOGGLE,
2663
+ RANGE: FieldControlType.INLINE_RANGE,
2664
+ PERIOD_RANGE: FieldControlType.INLINE_PERIOD_RANGE,
2665
+ YEAR_RANGE: FieldControlType.INLINE_YEAR_RANGE,
2666
+ MONTH_RANGE: FieldControlType.INLINE_MONTH_RANGE,
2667
+ DATE: FieldControlType.INLINE_DATE,
2668
+ DATE_RANGE: FieldControlType.INLINE_DATE_RANGE,
2669
+ TIME: FieldControlType.INLINE_TIME,
2670
+ TIME_RANGE: FieldControlType.INLINE_TIME_RANGE,
2671
+ TREE_SELECT: FieldControlType.INLINE_TREE_SELECT,
2672
+ RATING: FieldControlType.INLINE_RATING,
2673
+ DISTANCE_RADIUS: FieldControlType.INLINE_DISTANCE_RADIUS,
2674
+ PIPELINE_STATUS: FieldControlType.INLINE_PIPELINE_STATUS,
2675
+ SCORE_PRIORITY: FieldControlType.INLINE_SCORE_PRIORITY,
2676
+ RELATIVE_PERIOD: FieldControlType.INLINE_RELATIVE_PERIOD,
2677
+ SENTIMENT: FieldControlType.INLINE_SENTIMENT,
2678
+ COLOR_LABEL: FieldControlType.INLINE_COLOR_LABEL,
2679
+ });
2680
+ const INLINE_FILTER_CONTROL_TYPE_VALUES = Object.freeze(Object.values(INLINE_FILTER_CONTROL_TYPES));
2681
+ const INLINE_FILTER_CONTROL_TYPE_SET = new Set(INLINE_FILTER_CONTROL_TYPE_VALUES);
2682
+ function normalizeInlineControlTypeToken(value) {
2683
+ return String(value || '')
2684
+ .trim()
2685
+ .toLowerCase()
2686
+ .replace(/[-_\s]/g, '');
2687
+ }
2688
+ const INLINE_FILTER_CANONICAL_TOKEN_TO_CONTROL_TYPE_MAP = {
2689
+ inlineselect: INLINE_FILTER_CONTROL_TYPES.SELECT,
2690
+ inlinesearchableselect: INLINE_FILTER_CONTROL_TYPES.SEARCHABLE_SELECT,
2691
+ inlineasyncselect: INLINE_FILTER_CONTROL_TYPES.ASYNC_SELECT,
2692
+ inlineentitylookup: INLINE_FILTER_CONTROL_TYPES.ENTITY_LOOKUP,
2693
+ inlineautocomplete: INLINE_FILTER_CONTROL_TYPES.AUTOCOMPLETE,
2694
+ inlinenumber: INLINE_FILTER_CONTROL_TYPES.NUMBER,
2695
+ inlinecurrency: INLINE_FILTER_CONTROL_TYPES.CURRENCY,
2696
+ inlinecurrencyrange: INLINE_FILTER_CONTROL_TYPES.CURRENCY_RANGE,
2697
+ inlinemultiselect: INLINE_FILTER_CONTROL_TYPES.MULTI_SELECT,
2698
+ inlineinput: INLINE_FILTER_CONTROL_TYPES.INPUT,
2699
+ inlinephone: INLINE_FILTER_CONTROL_TYPES.PHONE,
2700
+ inlinetoggle: INLINE_FILTER_CONTROL_TYPES.TOGGLE,
2701
+ inlinerange: INLINE_FILTER_CONTROL_TYPES.RANGE,
2702
+ inlineperiodrange: INLINE_FILTER_CONTROL_TYPES.PERIOD_RANGE,
2703
+ inlineyearrange: INLINE_FILTER_CONTROL_TYPES.YEAR_RANGE,
2704
+ inlinemonthrange: INLINE_FILTER_CONTROL_TYPES.MONTH_RANGE,
2705
+ inlinedate: INLINE_FILTER_CONTROL_TYPES.DATE,
2706
+ inlinedaterange: INLINE_FILTER_CONTROL_TYPES.DATE_RANGE,
2707
+ inlinetime: INLINE_FILTER_CONTROL_TYPES.TIME,
2708
+ inlinetimerange: INLINE_FILTER_CONTROL_TYPES.TIME_RANGE,
2709
+ inlinetreeselect: INLINE_FILTER_CONTROL_TYPES.TREE_SELECT,
2710
+ inlinerating: INLINE_FILTER_CONTROL_TYPES.RATING,
2711
+ inlinedistanceradius: INLINE_FILTER_CONTROL_TYPES.DISTANCE_RADIUS,
2712
+ inlinepipelinestatus: INLINE_FILTER_CONTROL_TYPES.PIPELINE_STATUS,
2713
+ inlinescorepriority: INLINE_FILTER_CONTROL_TYPES.SCORE_PRIORITY,
2714
+ inlinerelativeperiod: INLINE_FILTER_CONTROL_TYPES.RELATIVE_PERIOD,
2715
+ inlinesentiment: INLINE_FILTER_CONTROL_TYPES.SENTIMENT,
2716
+ inlinecolorlabel: INLINE_FILTER_CONTROL_TYPES.COLOR_LABEL,
2717
+ };
2718
+ const INLINE_FILTER_ALIAS_TOKEN_MAP = {};
2719
+ for (const [token, controlType] of Object.entries(INLINE_FILTER_CANONICAL_TOKEN_TO_CONTROL_TYPE_MAP)) {
2720
+ INLINE_FILTER_ALIAS_TOKEN_MAP[`filter${token}`] = controlType;
2721
+ INLINE_FILTER_ALIAS_TOKEN_MAP[`pdxfilter${token}`] = controlType;
2722
+ }
2723
+ const INLINE_FILTER_TOKEN_TO_CONTROL_TYPE = Object.freeze({
2724
+ ...INLINE_FILTER_CANONICAL_TOKEN_TO_CONTROL_TYPE_MAP,
2725
+ ...INLINE_FILTER_ALIAS_TOKEN_MAP,
2726
+ });
2727
+ const INLINE_FILTER_ALIAS_TOKENS = Object.freeze(Object.keys(INLINE_FILTER_ALIAS_TOKEN_MAP));
2728
+ const INLINE_FILTER_CANONICAL_TOKEN_TO_BASE_CONTROL_TYPE_MAP = {
2729
+ inlineselect: FieldControlType.SELECT,
2730
+ inlinesearchableselect: FieldControlType.SEARCHABLE_SELECT,
2731
+ inlineasyncselect: FieldControlType.ASYNC_SELECT,
2732
+ inlineentitylookup: FieldControlType.ENTITY_LOOKUP,
2733
+ inlineautocomplete: FieldControlType.AUTO_COMPLETE,
2734
+ inlinenumber: FieldControlType.NUMERIC_TEXT_BOX,
2735
+ inlinecurrency: FieldControlType.CURRENCY_INPUT,
2736
+ inlinecurrencyrange: FieldControlType.PRICE_RANGE,
2737
+ inlinemultiselect: FieldControlType.MULTI_SELECT,
2738
+ inlineinput: FieldControlType.INPUT,
2739
+ inlinephone: FieldControlType.PHONE,
2740
+ inlinetoggle: FieldControlType.TOGGLE,
2741
+ inlinerange: FieldControlType.RANGE_SLIDER,
2742
+ inlineperiodrange: FieldControlType.RANGE_SLIDER,
2743
+ inlineyearrange: FieldControlType.YEAR_INPUT,
2744
+ inlinemonthrange: FieldControlType.MONTH_INPUT,
2745
+ inlinedate: FieldControlType.DATE_PICKER,
2746
+ inlinedaterange: FieldControlType.DATE_RANGE,
2747
+ inlinetime: FieldControlType.TIME_PICKER,
2748
+ inlinetimerange: FieldControlType.TIME_RANGE,
2749
+ inlinetreeselect: FieldControlType.TREE_SELECT,
2750
+ inlinerating: FieldControlType.RATING,
2751
+ inlinedistanceradius: FieldControlType.INLINE_DISTANCE_RADIUS,
2752
+ inlinepipelinestatus: FieldControlType.INLINE_PIPELINE_STATUS,
2753
+ inlinescorepriority: FieldControlType.INLINE_SCORE_PRIORITY,
2754
+ inlinerelativeperiod: FieldControlType.INLINE_RELATIVE_PERIOD,
2755
+ inlinesentiment: FieldControlType.INLINE_SENTIMENT,
2756
+ inlinecolorlabel: FieldControlType.INLINE_COLOR_LABEL,
2757
+ };
2758
+ const INLINE_FILTER_ALIAS_TOKEN_TO_BASE_CONTROL_TYPE_MAP = {};
2759
+ for (const [aliasToken, controlType] of Object.entries(INLINE_FILTER_ALIAS_TOKEN_MAP)) {
2760
+ const canonicalToken = aliasToken.startsWith('pdxfilter')
2761
+ ? aliasToken.replace(/^pdxfilter/, '')
2762
+ : aliasToken.replace(/^filter/, '');
2763
+ const baseControlType = INLINE_FILTER_CANONICAL_TOKEN_TO_BASE_CONTROL_TYPE_MAP[canonicalToken];
2764
+ if (baseControlType) {
2765
+ INLINE_FILTER_ALIAS_TOKEN_TO_BASE_CONTROL_TYPE_MAP[aliasToken] = baseControlType;
2766
+ }
2767
+ }
2768
+ const INLINE_FILTER_TOKEN_TO_BASE_CONTROL_TYPE = Object.freeze({
2769
+ ...INLINE_FILTER_CANONICAL_TOKEN_TO_BASE_CONTROL_TYPE_MAP,
2770
+ ...INLINE_FILTER_ALIAS_TOKEN_TO_BASE_CONTROL_TYPE_MAP,
2771
+ });
2772
+ function resolveInlineFilterControlType(value) {
2773
+ const token = normalizeInlineControlTypeToken(value);
2774
+ if (!token)
2775
+ return undefined;
2776
+ return INLINE_FILTER_TOKEN_TO_CONTROL_TYPE[token];
2777
+ }
2778
+ function resolveInlineFilterControlTypeToBaseControlType(value) {
2779
+ const token = normalizeInlineControlTypeToken(value);
2780
+ if (!token)
2781
+ return undefined;
2782
+ return INLINE_FILTER_TOKEN_TO_BASE_CONTROL_TYPE[token];
2783
+ }
2784
+ function isInlineFilterControlType(value) {
2785
+ return INLINE_FILTER_CONTROL_TYPE_SET.has(String(value || '').trim());
2786
+ }
2787
+
2788
+ function toUpperSnakeCase(raw) {
2789
+ return raw
2790
+ .trim()
2791
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
2792
+ .replace(/[-\s]+/g, '_')
2793
+ .replace(/__+/g, '_')
2794
+ .toUpperCase();
2795
+ }
2796
+ function normalizeControlTypeToken(value) {
2797
+ return String(value || '')
2798
+ .trim()
2799
+ .toLowerCase()
2800
+ .replace(/[-_\s]/g, '');
2801
+ }
2802
+ const CONTROL_TYPE_TOKEN_TO_KEY = Object.entries(FieldControlType).reduce((acc, [key, controlTypeValue]) => {
2803
+ acc[normalizeControlTypeToken(key)] = key;
2804
+ acc[normalizeControlTypeToken(controlTypeValue)] = key;
2805
+ return acc;
2806
+ }, {});
2807
+ const ALIAS_TOKEN_TO_CONTROL_TYPE = {
2808
+ // Legacy/common synonyms
2809
+ searchable: FieldControlType.SEARCHABLE_SELECT,
2810
+ searchableinput: FieldControlType.SEARCHABLE_SELECT,
2811
+ searchableselect: FieldControlType.SEARCHABLE_SELECT,
2812
+ materialsearchableselect: FieldControlType.SEARCHABLE_SELECT,
2813
+ asyncselect: FieldControlType.ASYNC_SELECT,
2814
+ materialasyncselect: FieldControlType.ASYNC_SELECT,
2815
+ entitylookup: FieldControlType.ENTITY_LOOKUP,
2816
+ materialentitylookup: FieldControlType.ENTITY_LOOKUP,
2817
+ autocomplete: FieldControlType.AUTO_COMPLETE,
2818
+ multiselect: FieldControlType.MULTI_SELECT,
2819
+ multiselecttree: FieldControlType.MULTI_SELECT_TREE,
2820
+ treeselect: FieldControlType.TREE_SELECT,
2821
+ datepicker: FieldControlType.DATE_PICKER,
2822
+ daterange: FieldControlType.DATE_RANGE,
2823
+ datetime: FieldControlType.DATETIME_LOCAL_INPUT,
2824
+ timepicker: FieldControlType.TIME_PICKER,
2825
+ timerange: FieldControlType.TIME_RANGE,
2826
+ pricerange: FieldControlType.PRICE_RANGE,
2827
+ rangeslider: FieldControlType.RANGE_SLIDER,
2828
+ number: FieldControlType.NUMERIC_TEXT_BOX,
2829
+ numeric: FieldControlType.NUMERIC_TEXT_BOX,
2830
+ currencyinput: FieldControlType.CURRENCY_INPUT,
2831
+ switch: FieldControlType.TOGGLE,
2832
+ radiogroup: FieldControlType.RADIO,
2833
+ checkboxgroup: FieldControlType.CHECKBOX,
2834
+ chiplist: FieldControlType.CHIP_LIST,
2835
+ chipinput: FieldControlType.CHIP_INPUT,
2836
+ searchinput: FieldControlType.SEARCH_INPUT,
2837
+ };
2838
+ function normalizeControlTypeKey(value) {
2839
+ const token = normalizeControlTypeToken(value);
2840
+ if (!token)
2841
+ return '';
2842
+ const resolvedKey = CONTROL_TYPE_TOKEN_TO_KEY[token];
2843
+ if (resolvedKey)
2844
+ return resolvedKey;
2845
+ return toUpperSnakeCase(String(value || ''));
2846
+ }
2847
+ function resolveControlTypeAlias(value, fallback = FieldControlType.INPUT) {
2848
+ const raw = String(value || '').trim();
2849
+ if (!raw)
2850
+ return fallback;
2851
+ const token = normalizeControlTypeToken(raw);
2852
+ const inlineAliased = INLINE_FILTER_TOKEN_TO_BASE_CONTROL_TYPE[token];
2853
+ if (inlineAliased)
2854
+ return inlineAliased;
2855
+ const aliased = ALIAS_TOKEN_TO_CONTROL_TYPE[token];
2856
+ if (aliased)
2857
+ return aliased;
2858
+ const resolvedKey = CONTROL_TYPE_TOKEN_TO_KEY[token];
2859
+ if (resolvedKey) {
2860
+ return FieldControlType[resolvedKey];
2861
+ }
2862
+ return raw;
2863
+ }
2864
+
2865
+ const MAX_OPTION_SOURCE_DEPTH = 3;
2866
+ // Mirrors the backend custom-field key policy. Ordinary static field names are
2867
+ // outside this boundary; custom keys must be safe across all runtime consumers.
2868
+ const RESERVED_CUSTOM_FIELD_KEYS = new Set([
2869
+ 'constructor', 'prototype', 'hasOwnProperty', 'isPrototypeOf',
2870
+ 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf',
2871
+ ]);
1017
2872
  const VALUE_PRESENTATION_TYPES = new Set([
1018
2873
  'string',
1019
2874
  'number',
@@ -1262,6 +3117,33 @@ class SchemaNormalizationKernel {
1262
3117
  }
1263
3118
  return false;
1264
3119
  }
3120
+ parseOptionalBoolean(value) {
3121
+ if (typeof value === 'boolean') {
3122
+ return value;
3123
+ }
3124
+ if (typeof value === 'string') {
3125
+ const normalized = value.trim().toLowerCase();
3126
+ if (normalized === 'true') {
3127
+ return true;
3128
+ }
3129
+ if (normalized === 'false') {
3130
+ return false;
3131
+ }
3132
+ }
3133
+ return undefined;
3134
+ }
3135
+ parseOptionalFiniteNumber(value) {
3136
+ if (typeof value === 'number' && Number.isFinite(value)) {
3137
+ return value;
3138
+ }
3139
+ if (typeof value === 'string' && value.trim().length > 0) {
3140
+ const parsed = Number(value);
3141
+ if (Number.isFinite(parsed)) {
3142
+ return parsed;
3143
+ }
3144
+ }
3145
+ return undefined;
3146
+ }
1265
3147
  /** Ensure an array of strings from various inputs. */
1266
3148
  parseStringArray(value) {
1267
3149
  if (Array.isArray(value)) {
@@ -1278,6 +3160,41 @@ class SchemaNormalizationKernel {
1278
3160
  .filter((v) => v.length > 0);
1279
3161
  return normalized.filter((v, index) => normalized.indexOf(v) === index);
1280
3162
  }
3163
+ parseDependsOn(value) {
3164
+ const rawItems = Array.isArray(value)
3165
+ ? value
3166
+ : typeof value === 'string'
3167
+ ? value.split(',')
3168
+ : [];
3169
+ const normalized = rawItems
3170
+ .map((item) => (typeof item === 'string' ? item.trim() : ''))
3171
+ .filter((item) => item.length > 0);
3172
+ return normalized.filter((item, index) => normalized.indexOf(item) === index);
3173
+ }
3174
+ parseStrictStringRecord(value) {
3175
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
3176
+ return undefined;
3177
+ }
3178
+ const normalized = Object.entries(value)
3179
+ .reduce((acc, [key, mapValue]) => {
3180
+ if (typeof mapValue !== 'string') {
3181
+ return acc;
3182
+ }
3183
+ const normalizedKey = String(key).trim();
3184
+ if (!normalizedKey ||
3185
+ normalizedKey === '__proto__' ||
3186
+ normalizedKey === 'constructor' ||
3187
+ normalizedKey === 'prototype') {
3188
+ return acc;
3189
+ }
3190
+ const normalizedValue = mapValue.trim();
3191
+ if (normalizedValue) {
3192
+ acc[normalizedKey] = normalizedValue;
3193
+ }
3194
+ return acc;
3195
+ }, {});
3196
+ return Object.keys(normalized).length ? normalized : undefined;
3197
+ }
1281
3198
  parseStringRecord(value) {
1282
3199
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
1283
3200
  return undefined;
@@ -1365,9 +3282,15 @@ class SchemaNormalizationKernel {
1365
3282
  if (value.kind !== undefined) {
1366
3283
  detail.kind = String(value.kind);
1367
3284
  }
3285
+ if (value.resourceKey !== undefined && String(value.resourceKey).trim().length > 0) {
3286
+ detail.resourceKey = String(value.resourceKey).trim();
3287
+ }
1368
3288
  if (value.surfaceId !== undefined) {
1369
3289
  detail.surfaceId = String(value.surfaceId);
1370
3290
  }
3291
+ if (value.previewSurfaceId !== undefined && String(value.previewSurfaceId).trim().length > 0) {
3292
+ detail.previewSurfaceId = String(value.previewSurfaceId).trim();
3293
+ }
1371
3294
  if (value.presentation !== undefined) {
1372
3295
  detail.presentation = String(value.presentation);
1373
3296
  }
@@ -1392,6 +3315,11 @@ class SchemaNormalizationKernel {
1392
3315
  'resultLayout',
1393
3316
  'primaryPropertyPath',
1394
3317
  'avatarPropertyPath',
3318
+ 'detailActionLabel',
3319
+ 'quickViewActionLabel',
3320
+ 'copyCodeActionLabel',
3321
+ 'copyIdActionLabel',
3322
+ 'createActionLabel',
1395
3323
  ];
1396
3324
  stringKeys.forEach((key) => {
1397
3325
  if (value[key] !== undefined) {
@@ -1429,6 +3357,10 @@ class SchemaNormalizationKernel {
1429
3357
  if (value.maxVisibleBadges !== undefined && !Number.isNaN(Number(value.maxVisibleBadges))) {
1430
3358
  display.maxVisibleBadges = Number(value.maxVisibleBadges);
1431
3359
  }
3360
+ const actions = this.parseLookupActions(value.actions);
3361
+ if (actions) {
3362
+ display.actions = actions;
3363
+ }
1432
3364
  return Object.keys(display).length ? display : undefined;
1433
3365
  }
1434
3366
  parseLookupDisplayField(value) {
@@ -1443,6 +3375,28 @@ class SchemaNormalizationKernel {
1443
3375
  });
1444
3376
  return Object.keys(field).length ? field : undefined;
1445
3377
  }
3378
+ parseLookupActions(value) {
3379
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
3380
+ return undefined;
3381
+ }
3382
+ const actions = {};
3383
+ if (value.showDetail !== undefined) {
3384
+ actions.showDetail = this.parseBoolean(value.showDetail);
3385
+ }
3386
+ if (value.showQuickView !== undefined) {
3387
+ actions.showQuickView = this.parseBoolean(value.showQuickView);
3388
+ }
3389
+ if (value.showCopyCode !== undefined) {
3390
+ actions.showCopyCode = this.parseBoolean(value.showCopyCode);
3391
+ }
3392
+ if (value.showCopyId !== undefined) {
3393
+ actions.showCopyId = this.parseBoolean(value.showCopyId);
3394
+ }
3395
+ if (value.showCreate !== undefined) {
3396
+ actions.showCreate = this.parseBoolean(value.showCreate);
3397
+ }
3398
+ return Object.keys(actions).length ? actions : undefined;
3399
+ }
1446
3400
  parseLookupCreate(value) {
1447
3401
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
1448
3402
  return undefined;
@@ -1498,10 +3452,13 @@ class SchemaNormalizationKernel {
1498
3452
  }
1499
3453
  const dialog = {};
1500
3454
  if (value.enabled !== undefined) {
1501
- dialog.enabled = this.parseBoolean(value.enabled);
3455
+ const enabled = this.parseOptionalBoolean(value.enabled);
3456
+ if (enabled !== undefined) {
3457
+ dialog.enabled = enabled;
3458
+ }
1502
3459
  }
1503
- if (value.title !== undefined) {
1504
- const title = String(value.title).trim();
3460
+ if (typeof value.title === 'string') {
3461
+ const title = value.title.trim();
1505
3462
  if (title) {
1506
3463
  dialog.title = title;
1507
3464
  }
@@ -1513,13 +3470,22 @@ class SchemaNormalizationKernel {
1513
3470
  }
1514
3471
  }
1515
3472
  if (value.previewPanel !== undefined) {
1516
- dialog.previewPanel = this.parseBoolean(value.previewPanel);
3473
+ const previewPanel = this.parseOptionalBoolean(value.previewPanel);
3474
+ if (previewPanel !== undefined) {
3475
+ dialog.previewPanel = previewPanel;
3476
+ }
1517
3477
  }
1518
3478
  if (value.allowColumnChooser !== undefined) {
1519
- dialog.allowColumnChooser = this.parseBoolean(value.allowColumnChooser);
3479
+ const allowColumnChooser = this.parseOptionalBoolean(value.allowColumnChooser);
3480
+ if (allowColumnChooser !== undefined) {
3481
+ dialog.allowColumnChooser = allowColumnChooser;
3482
+ }
1520
3483
  }
1521
3484
  if (value.allowSavedViews !== undefined) {
1522
- dialog.allowSavedViews = this.parseBoolean(value.allowSavedViews);
3485
+ const allowSavedViews = this.parseOptionalBoolean(value.allowSavedViews);
3486
+ if (allowSavedViews !== undefined) {
3487
+ dialog.allowSavedViews = allowSavedViews;
3488
+ }
1523
3489
  }
1524
3490
  if (Array.isArray(value.resultColumns)) {
1525
3491
  const resultColumns = value.resultColumns
@@ -1529,20 +3495,20 @@ class SchemaNormalizationKernel {
1529
3495
  dialog.resultColumns = resultColumns;
1530
3496
  }
1531
3497
  }
1532
- if (value.openActionLabel !== undefined) {
1533
- const openActionLabel = String(value.openActionLabel).trim();
3498
+ if (typeof value.openActionLabel === 'string') {
3499
+ const openActionLabel = value.openActionLabel.trim();
1534
3500
  if (openActionLabel) {
1535
3501
  dialog.openActionLabel = openActionLabel;
1536
3502
  }
1537
3503
  }
1538
- if (value.applyActionLabel !== undefined) {
1539
- const applyActionLabel = String(value.applyActionLabel).trim();
3504
+ if (typeof value.applyActionLabel === 'string') {
3505
+ const applyActionLabel = value.applyActionLabel.trim();
1540
3506
  if (applyActionLabel) {
1541
3507
  dialog.applyActionLabel = applyActionLabel;
1542
3508
  }
1543
3509
  }
1544
- if (value.cancelActionLabel !== undefined) {
1545
- const cancelActionLabel = String(value.cancelActionLabel).trim();
3510
+ if (typeof value.cancelActionLabel === 'string') {
3511
+ const cancelActionLabel = value.cancelActionLabel.trim();
1546
3512
  if (cancelActionLabel) {
1547
3513
  dialog.cancelActionLabel = cancelActionLabel;
1548
3514
  }
@@ -1553,19 +3519,19 @@ class SchemaNormalizationKernel {
1553
3519
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
1554
3520
  return undefined;
1555
3521
  }
1556
- const field = String(value.field ?? '').trim();
3522
+ const field = typeof value.field === 'string' ? value.field.trim() : '';
1557
3523
  if (!field) {
1558
3524
  return undefined;
1559
3525
  }
1560
3526
  const column = { field };
1561
- if (value.label !== undefined) {
1562
- const label = String(value.label).trim();
3527
+ if (typeof value.label === 'string') {
3528
+ const label = value.label.trim();
1563
3529
  if (label) {
1564
3530
  column.label = label;
1565
3531
  }
1566
3532
  }
1567
- if (value.kind !== undefined) {
1568
- const kind = String(value.kind).trim();
3533
+ if (typeof value.kind === 'string') {
3534
+ const kind = value.kind.trim();
1569
3535
  if (kind === 'code' ||
1570
3536
  kind === 'label' ||
1571
3537
  kind === 'description' ||
@@ -1575,15 +3541,137 @@ class SchemaNormalizationKernel {
1575
3541
  column.kind = kind;
1576
3542
  }
1577
3543
  }
1578
- if (value.width !== undefined) {
1579
- const width = String(value.width).trim();
3544
+ if (typeof value.width === 'string') {
3545
+ const width = value.width.trim();
1580
3546
  if (width) {
1581
3547
  column.width = width;
1582
3548
  }
1583
3549
  }
1584
3550
  return column;
1585
3551
  }
1586
- parseLookupFilterDefinition(value) {
3552
+ mergeLookupDialog(base, override) {
3553
+ const merged = {
3554
+ ...(this.parseLookupDialog(base) ?? {}),
3555
+ ...(this.parseLookupDialog(override) ?? {}),
3556
+ };
3557
+ return Object.keys(merged).length ? merged : undefined;
3558
+ }
3559
+ parseLookupFilterOptions(value) {
3560
+ if (!Array.isArray(value)) {
3561
+ return undefined;
3562
+ }
3563
+ const options = [];
3564
+ const seen = new Set();
3565
+ for (const item of value) {
3566
+ if (typeof item === 'string' ||
3567
+ typeof item === 'number' ||
3568
+ typeof item === 'boolean') {
3569
+ let parsedValue;
3570
+ if (typeof item === 'string') {
3571
+ const trimmed = item.trim();
3572
+ if (!trimmed) {
3573
+ continue;
3574
+ }
3575
+ parsedValue = trimmed;
3576
+ }
3577
+ else if (typeof item === 'number') {
3578
+ if (!Number.isFinite(item)) {
3579
+ continue;
3580
+ }
3581
+ parsedValue = item;
3582
+ }
3583
+ else {
3584
+ parsedValue = item;
3585
+ }
3586
+ const dedupeKey = `${typeof parsedValue}:${String(parsedValue)}`;
3587
+ if (seen.has(dedupeKey)) {
3588
+ continue;
3589
+ }
3590
+ seen.add(dedupeKey);
3591
+ options.push({
3592
+ value: parsedValue,
3593
+ label: String(parsedValue),
3594
+ });
3595
+ continue;
3596
+ }
3597
+ if (!item || typeof item !== 'object' || Array.isArray(item)) {
3598
+ continue;
3599
+ }
3600
+ const raw = item;
3601
+ const isLegacyKeyValue = raw['key'] !== undefined &&
3602
+ raw['key'] !== null &&
3603
+ raw['label'] === undefined &&
3604
+ raw['text'] === undefined &&
3605
+ typeof raw['value'] === 'string' &&
3606
+ raw['key'] !== raw['value'];
3607
+ const rawValue = isLegacyKeyValue
3608
+ ? raw['key']
3609
+ : raw['value'] !== undefined && raw['value'] !== null
3610
+ ? raw['value']
3611
+ : raw['key'];
3612
+ const rawLabel = isLegacyKeyValue
3613
+ ? raw['value']
3614
+ : raw['label'] ?? raw['text'];
3615
+ let parsedValue;
3616
+ if (typeof rawValue === 'string') {
3617
+ const trimmed = rawValue.trim();
3618
+ if (!trimmed) {
3619
+ continue;
3620
+ }
3621
+ parsedValue = trimmed;
3622
+ }
3623
+ else if (typeof rawValue === 'number') {
3624
+ if (!Number.isFinite(rawValue)) {
3625
+ continue;
3626
+ }
3627
+ parsedValue = rawValue;
3628
+ }
3629
+ else if (typeof rawValue === 'boolean') {
3630
+ parsedValue = rawValue;
3631
+ }
3632
+ else {
3633
+ continue;
3634
+ }
3635
+ const dedupeKey = `${typeof parsedValue}:${String(parsedValue)}`;
3636
+ if (seen.has(dedupeKey)) {
3637
+ continue;
3638
+ }
3639
+ seen.add(dedupeKey);
3640
+ let label;
3641
+ if (typeof rawLabel === 'string' && rawLabel.trim().length > 0) {
3642
+ label = rawLabel.trim();
3643
+ }
3644
+ else if ((typeof rawLabel === 'number' && Number.isFinite(rawLabel)) ||
3645
+ typeof rawLabel === 'boolean') {
3646
+ label = String(rawLabel);
3647
+ }
3648
+ else {
3649
+ label = String(parsedValue);
3650
+ }
3651
+ const option = {
3652
+ value: parsedValue,
3653
+ label,
3654
+ };
3655
+ if (typeof raw['icon'] === 'string' && raw['icon'].trim()) {
3656
+ option.icon = raw['icon'].trim();
3657
+ }
3658
+ if (typeof raw['tone'] === 'string' && raw['tone'].trim()) {
3659
+ option.tone = raw['tone'].trim();
3660
+ }
3661
+ if (typeof raw['description'] === 'string' && raw['description'].trim()) {
3662
+ option.description = raw['description'].trim();
3663
+ }
3664
+ if (raw['disabled'] !== undefined) {
3665
+ const disabled = this.parseOptionalBoolean(raw['disabled']);
3666
+ if (disabled !== undefined) {
3667
+ option.disabled = disabled;
3668
+ }
3669
+ }
3670
+ options.push(option);
3671
+ }
3672
+ return options.length ? options : undefined;
3673
+ }
3674
+ parseLookupFilterDefinition(value, optionSourceDepth = 0, visitedOptionSources = new Set()) {
1587
3675
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
1588
3676
  return undefined;
1589
3677
  }
@@ -1608,8 +3696,38 @@ class SchemaNormalizationKernel {
1608
3696
  if (defaultOperator && operators.includes(defaultOperator)) {
1609
3697
  definition.defaultOperator = defaultOperator;
1610
3698
  }
1611
- if (value.optionsSource !== undefined) {
1612
- const optionsSource = String(value.optionsSource).trim();
3699
+ if (value.options !== undefined) {
3700
+ const options = this.parseLookupFilterOptions(value.options);
3701
+ if (options) {
3702
+ definition.options = options;
3703
+ }
3704
+ }
3705
+ if (typeof value.optionSource === 'string') {
3706
+ const optionSource = value.optionSource.trim();
3707
+ if (optionSource) {
3708
+ definition.optionSource = optionSource;
3709
+ }
3710
+ }
3711
+ else if (value.optionSource &&
3712
+ typeof value.optionSource === 'object' &&
3713
+ !Array.isArray(value.optionSource)) {
3714
+ const optionSource = this.parseOptionSource(value.optionSource, optionSourceDepth + 1, visitedOptionSources);
3715
+ if (optionSource) {
3716
+ definition.optionSource = optionSource;
3717
+ }
3718
+ }
3719
+ if (value.dependsOn !== undefined) {
3720
+ const dependsOn = this.parseDependsOn(value.dependsOn);
3721
+ if (dependsOn.length) {
3722
+ definition.dependsOn = dependsOn;
3723
+ }
3724
+ }
3725
+ const dependencyFilterMap = this.parseStrictStringRecord(value.dependencyFilterMap);
3726
+ if (dependencyFilterMap) {
3727
+ definition.dependencyFilterMap = dependencyFilterMap;
3728
+ }
3729
+ if (typeof value.optionsSource === 'string') {
3730
+ const optionsSource = value.optionsSource.trim();
1613
3731
  if (optionsSource) {
1614
3732
  definition.optionsSource = optionsSource;
1615
3733
  }
@@ -1643,7 +3761,7 @@ class SchemaNormalizationKernel {
1643
3761
  }, {});
1644
3762
  return Object.keys(normalized).length ? normalized : undefined;
1645
3763
  }
1646
- parseLookupFiltering(value) {
3764
+ parseLookupFiltering(value, optionSourceDepth = 0, visitedOptionSources = new Set()) {
1647
3765
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
1648
3766
  return undefined;
1649
3767
  }
@@ -1651,7 +3769,7 @@ class SchemaNormalizationKernel {
1651
3769
  if (value.availableFilters !== undefined) {
1652
3770
  const availableFilters = Array.isArray(value.availableFilters)
1653
3771
  ? value.availableFilters
1654
- .map((item) => this.parseLookupFilterDefinition(item))
3772
+ .map((item) => this.parseLookupFilterDefinition(item, optionSourceDepth, visitedOptionSources))
1655
3773
  .filter((item) => !!item)
1656
3774
  : [];
1657
3775
  if (availableFilters.length) {
@@ -1737,6 +3855,12 @@ class SchemaNormalizationKernel {
1737
3855
  filtering.searchStrategies = searchStrategies;
1738
3856
  }
1739
3857
  }
3858
+ if (typeof value.defaultSearchStrategy === 'string') {
3859
+ const defaultSearchStrategy = value.defaultSearchStrategy.trim();
3860
+ if (defaultSearchStrategy) {
3861
+ filtering.defaultSearchStrategy = defaultSearchStrategy;
3862
+ }
3863
+ }
1740
3864
  return Object.keys(filtering).length ? filtering : undefined;
1741
3865
  }
1742
3866
  /** Parse option arrays into `{ key, value }` objects with label preservation. */
@@ -1767,16 +3891,23 @@ class SchemaNormalizationKernel {
1767
3891
  return { key: String(opt), value: String(opt) };
1768
3892
  });
1769
3893
  }
1770
- parseOptionSource(value) {
1771
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
3894
+ parseOptionSource(value, depth = 0, visited = new Set()) {
3895
+ if (!value ||
3896
+ typeof value !== 'object' ||
3897
+ Array.isArray(value) ||
3898
+ depth > MAX_OPTION_SOURCE_DEPTH ||
3899
+ visited.has(value)) {
1772
3900
  return undefined;
1773
3901
  }
1774
- const optionSource = {
1775
- key: String(value.key ?? '').trim(),
1776
- };
1777
- if (!optionSource.key) {
3902
+ const key = String(value.key ?? '').trim();
3903
+ if (!key) {
1778
3904
  return undefined;
1779
3905
  }
3906
+ const nextVisited = new Set(visited);
3907
+ nextVisited.add(value);
3908
+ const optionSource = {
3909
+ key,
3910
+ };
1780
3911
  if (value.type !== undefined) {
1781
3912
  const optionSourceType = this.parseOptionSourceType(value.type);
1782
3913
  if (optionSourceType) {
@@ -1820,12 +3951,12 @@ class SchemaNormalizationKernel {
1820
3951
  optionSource.searchPropertyPaths = this.parseStringArray(value.searchPropertyPaths);
1821
3952
  }
1822
3953
  if (value.dependsOn !== undefined) {
1823
- const dependsOn = this.parseNonBlankStringArray(value.dependsOn);
3954
+ const dependsOn = this.parseDependsOn(value.dependsOn);
1824
3955
  if (dependsOn.length) {
1825
3956
  optionSource.dependsOn = dependsOn;
1826
3957
  }
1827
3958
  }
1828
- const dependencyFilterMap = this.parseStringRecord(value.dependencyFilterMap);
3959
+ const dependencyFilterMap = this.parseStrictStringRecord(value.dependencyFilterMap);
1829
3960
  if (dependencyFilterMap) {
1830
3961
  optionSource.dependencyFilterMap = dependencyFilterMap;
1831
3962
  }
@@ -1849,10 +3980,14 @@ class SchemaNormalizationKernel {
1849
3980
  if (create) {
1850
3981
  optionSource.create = create;
1851
3982
  }
1852
- const filtering = this.parseLookupFiltering(value.filtering);
3983
+ const filtering = this.parseLookupFiltering(value.filtering, depth, nextVisited);
1853
3984
  if (filtering) {
1854
3985
  optionSource.filtering = filtering;
1855
3986
  }
3987
+ const dialog = this.parseLookupDialog(value.dialog);
3988
+ if (dialog) {
3989
+ optionSource.dialog = dialog;
3990
+ }
1856
3991
  if (value.excludeSelfField !== undefined) {
1857
3992
  optionSource.excludeSelfField = this.parseBoolean(value.excludeSelfField);
1858
3993
  }
@@ -1898,6 +4033,34 @@ class SchemaNormalizationKernel {
1898
4033
  const normalized = String(value ?? '').trim();
1899
4034
  return OPTION_SOURCE_INVALID_SORT_POLICIES.has(normalized) ? normalized : undefined;
1900
4035
  }
4036
+ parseResourceReference(value) {
4037
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
4038
+ return undefined;
4039
+ }
4040
+ const raw = value;
4041
+ const resourceKey = String(raw['resourceKey'] ?? '').trim();
4042
+ if (!resourceKey) {
4043
+ return undefined;
4044
+ }
4045
+ const ref = { resourceKey };
4046
+ const valueField = String(raw['valueField'] ?? '').trim();
4047
+ if (valueField) {
4048
+ ref.valueField = valueField;
4049
+ }
4050
+ const surfaceId = String(raw['surfaceId'] ?? '').trim();
4051
+ if (surfaceId) {
4052
+ ref.surfaceId = surfaceId;
4053
+ }
4054
+ const previewSurfaceId = String(raw['previewSurfaceId'] ?? '').trim();
4055
+ if (previewSurfaceId) {
4056
+ ref.previewSurfaceId = previewSurfaceId;
4057
+ }
4058
+ const detailPresentation = String(raw['detailPresentation'] ?? '').trim();
4059
+ if (detailPresentation === 'drawer' || detailPresentation === 'modal') {
4060
+ ref.detailPresentation = detailPresentation;
4061
+ }
4062
+ return ref;
4063
+ }
1901
4064
  parseLookupOpenDetailMode(value) {
1902
4065
  const normalized = String(value ?? '').trim();
1903
4066
  return LOOKUP_OPEN_DETAIL_MODES.has(normalized) ? normalized : undefined;
@@ -2015,10 +4178,14 @@ class SchemaNormalizationKernel {
2015
4178
  out.maxLength = Number(ui.maxLength);
2016
4179
  if (ui.maxLengthMessage !== undefined)
2017
4180
  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);
4181
+ if (ui.min !== undefined) {
4182
+ const parsedMin = Number(ui.min);
4183
+ out.min = Number.isFinite(parsedMin) ? parsedMin : String(ui.min).trim();
4184
+ }
4185
+ if (ui.max !== undefined) {
4186
+ const parsedMax = Number(ui.max);
4187
+ out.max = Number.isFinite(parsedMax) ? parsedMax : String(ui.max).trim();
4188
+ }
2022
4189
  if (ui.minMessage !== undefined)
2023
4190
  out.minMessage = ui.minMessage;
2024
4191
  if (ui.maxMessage !== undefined)
@@ -2155,14 +4322,25 @@ class SchemaNormalizationKernel {
2155
4322
  return ['number', 'integer', 'int', 'float', 'double', 'decimal'].includes(token);
2156
4323
  }
2157
4324
  resolveNumericFormatToken(prop, ui, resolvedType) {
4325
+ if (ui?.numberFormat?.percentage === true || ui?.['numberFormat.percentage'] === true) {
4326
+ return 'percent';
4327
+ }
4328
+ const explicitUiFormat = this.resolveNonEmptyStringToken(ui?.numericFormat, ui?.numberFormat?.style, ui?.['numberFormat.style']);
4329
+ if (explicitUiFormat) {
4330
+ return explicitUiFormat;
4331
+ }
2158
4332
  const typeToken = resolvedType ?? prop?.type;
2159
4333
  if (!this.isNumericSchemaType(typeToken)) {
2160
4334
  return undefined;
2161
4335
  }
2162
- if (ui?.numberFormat?.percentage === true || ui?.['numberFormat.percentage'] === true) {
2163
- return 'percent';
4336
+ const explicitFormat = this.resolveNonEmptyStringToken(ui?.format, prop?.format);
4337
+ if (explicitFormat) {
4338
+ return explicitFormat;
2164
4339
  }
2165
- return this.resolveNonEmptyStringToken(ui?.numericFormat, ui?.format, ui?.numberFormat?.style, ui?.['numberFormat.style'], prop?.format);
4340
+ if (String(prop?.type ?? '').trim().toLowerCase() === 'integer') {
4341
+ return 'integer';
4342
+ }
4343
+ return undefined;
2166
4344
  }
2167
4345
  /**
2168
4346
  * Converte o schema bruto do backend (OpenAPI + x-ui) em FieldDefinition[] tipado.
@@ -2177,6 +4355,232 @@ class SchemaNormalizationKernel {
2177
4355
  normalizeSchema(schema) {
2178
4356
  return this.normalizeSchemaWithRoot(schema, schema);
2179
4357
  }
4358
+ /**
4359
+ * Extrai metadados estruturais de nível raiz (`x-ui` no objeto schema),
4360
+ * cobrindo `formLayout`, `progression`, `timeline`, `schedule`, `hierarchy`,
4361
+ * `calculationMemory`, `contextBinding` e `resourceState`.
4362
+ */
4363
+ extractRootUiMetadata(schema) {
4364
+ const ui = schema &&
4365
+ typeof schema === 'object' &&
4366
+ !Array.isArray(schema) &&
4367
+ schema['x-ui'] &&
4368
+ typeof schema['x-ui'] === 'object' &&
4369
+ !Array.isArray(schema['x-ui'])
4370
+ ? schema['x-ui']
4371
+ : undefined;
4372
+ if (!ui) {
4373
+ return null;
4374
+ }
4375
+ const out = {};
4376
+ const formLayout = this.parseSchemaFormLayout(ui['formLayout']);
4377
+ if (formLayout)
4378
+ out.formLayout = formLayout;
4379
+ if (ui['progression'] && typeof ui['progression'] === 'object' && !Array.isArray(ui['progression'])) {
4380
+ out.progression = this.clonePlain(ui['progression']);
4381
+ }
4382
+ if (ui['timeline'] && typeof ui['timeline'] === 'object' && !Array.isArray(ui['timeline'])) {
4383
+ out.timeline = this.clonePlain(ui['timeline']);
4384
+ }
4385
+ if (ui['timelineLanes'] && typeof ui['timelineLanes'] === 'object' && !Array.isArray(ui['timelineLanes'])) {
4386
+ out.timelineLanes = this.clonePlain(ui['timelineLanes']);
4387
+ }
4388
+ if (ui['schedule'] && typeof ui['schedule'] === 'object' && !Array.isArray(ui['schedule'])) {
4389
+ out.schedule = this.clonePlain(ui['schedule']);
4390
+ }
4391
+ if (ui['hierarchy'] && typeof ui['hierarchy'] === 'object' && !Array.isArray(ui['hierarchy'])) {
4392
+ out.hierarchy = this.clonePlain(ui['hierarchy']);
4393
+ }
4394
+ if (ui['relationshipGraph'] && typeof ui['relationshipGraph'] === 'object' && !Array.isArray(ui['relationshipGraph'])) {
4395
+ out.relationshipGraph = this.clonePlain(ui['relationshipGraph']);
4396
+ }
4397
+ if (ui['calculationMemory'] && typeof ui['calculationMemory'] === 'object' && !Array.isArray(ui['calculationMemory'])) {
4398
+ out.calculationMemory = this.clonePlain(ui['calculationMemory']);
4399
+ }
4400
+ const contextBinding = this.parseContextBinding(ui['contextBinding']);
4401
+ if (contextBinding)
4402
+ out.contextBinding = contextBinding;
4403
+ const resourceState = this.parseResourceState(ui['resourceState']);
4404
+ if (resourceState)
4405
+ out.resourceState = resourceState;
4406
+ return Object.keys(out).length > 0 ? out : null;
4407
+ }
4408
+ parseSchemaFormLayout(raw) {
4409
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
4410
+ return undefined;
4411
+ }
4412
+ const record = raw;
4413
+ const rawMode = String(record['mode'] ?? 'flat').trim().toLowerCase();
4414
+ const mode = rawMode === 'tabs' || rawMode === 'accordion' || rawMode === 'stepper' || rawMode === 'flat'
4415
+ ? rawMode
4416
+ : rawMode === 'vertical'
4417
+ ? 'flat'
4418
+ : 'flat';
4419
+ const defaultTabId = typeof record['defaultTabId'] === 'string' && record['defaultTabId'].trim()
4420
+ ? record['defaultTabId'].trim()
4421
+ : undefined;
4422
+ const rawTabsAppearance = typeof record['tabsAppearance'] === 'string'
4423
+ ? record['tabsAppearance'].trim().toLowerCase()
4424
+ : '';
4425
+ const tabsAppearance = rawTabsAppearance === 'pills' ||
4426
+ rawTabsAppearance === 'underline' ||
4427
+ rawTabsAppearance === 'buttons'
4428
+ ? rawTabsAppearance
4429
+ : undefined;
4430
+ const accordionMulti = this.parseOptionalBoolean(record['accordionMulti']);
4431
+ const hideSectionHeaderInTabs = this.parseOptionalBoolean(record['hideSectionHeaderInTabs']);
4432
+ const hideSectionHeaderInStepper = this.parseOptionalBoolean(record['hideSectionHeaderInStepper']);
4433
+ const rawStepperInReadMode = typeof record['stepperInReadMode'] === 'string'
4434
+ ? record['stepperInReadMode'].trim().toLowerCase()
4435
+ : '';
4436
+ const stepperInReadMode = rawStepperInReadMode === 'presentation' ||
4437
+ rawStepperInReadMode === 'all' ||
4438
+ rawStepperInReadMode === 'none'
4439
+ ? rawStepperInReadMode
4440
+ : undefined;
4441
+ const stepperReviewStep = this.parseOptionalBoolean(record['stepperReviewStep']);
4442
+ const rawSections = Array.isArray(record['sections']) ? record['sections'] : [];
4443
+ const sections = [];
4444
+ for (let idx = 0; idx < rawSections.length; idx++) {
4445
+ const entry = rawSections[idx];
4446
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
4447
+ continue;
4448
+ const item = entry;
4449
+ const id = String(item['id'] ?? '').trim();
4450
+ const title = String(item['title'] ?? '').trim();
4451
+ if (!id || !title)
4452
+ continue;
4453
+ const orderNum = Number(item['order']);
4454
+ const subtitle = typeof item['subtitle'] === 'string' && item['subtitle'].trim() ? item['subtitle'].trim() : undefined;
4455
+ const icon = typeof item['icon'] === 'string' && item['icon'].trim() ? item['icon'].trim() : undefined;
4456
+ const groups = this.parseNonBlankStringArray(item['groups']);
4457
+ const optional = this.parseOptionalBoolean(item['optional']);
4458
+ sections.push({
4459
+ id,
4460
+ title,
4461
+ ...(subtitle ? { subtitle } : {}),
4462
+ ...(icon ? { icon } : {}),
4463
+ order: Number.isFinite(orderNum) ? orderNum : idx,
4464
+ ...(groups.length ? { groups } : {}),
4465
+ ...(optional !== undefined ? { optional } : {}),
4466
+ });
4467
+ }
4468
+ sections.sort((a, b) => a.order - b.order);
4469
+ const rawSteps = Array.isArray(record['steps']) ? record['steps'] : [];
4470
+ const steps = [];
4471
+ for (const entry of rawSteps) {
4472
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
4473
+ continue;
4474
+ const item = entry;
4475
+ const id = String(item['id'] ?? '').trim();
4476
+ const label = String(item['label'] ?? '').trim() || id;
4477
+ const sectionIds = this.parseNonBlankStringArray(item['sectionIds']);
4478
+ if (!id || !sectionIds.length)
4479
+ continue;
4480
+ const description = typeof item['description'] === 'string' && item['description'].trim()
4481
+ ? item['description'].trim()
4482
+ : undefined;
4483
+ const icon = typeof item['icon'] === 'string' && item['icon'].trim()
4484
+ ? item['icon'].trim()
4485
+ : undefined;
4486
+ const optional = this.parseOptionalBoolean(item['optional']);
4487
+ const disabled = this.parseOptionalBoolean(item['disabled']);
4488
+ const tooltip = typeof item['tooltip'] === 'string' && item['tooltip'].trim()
4489
+ ? item['tooltip'].trim()
4490
+ : undefined;
4491
+ const rawBadge = item['badge'];
4492
+ const badge = typeof rawBadge === 'string'
4493
+ ? (rawBadge.trim() ? rawBadge.trim() : undefined)
4494
+ : typeof rawBadge === 'number' && Number.isFinite(rawBadge)
4495
+ ? rawBadge
4496
+ : undefined;
4497
+ steps.push({
4498
+ id,
4499
+ label,
4500
+ ...(description ? { description } : {}),
4501
+ ...(icon ? { icon } : {}),
4502
+ sectionIds,
4503
+ ...(optional !== undefined ? { optional } : {}),
4504
+ ...(badge !== undefined ? { badge } : {}),
4505
+ ...(disabled !== undefined ? { disabled } : {}),
4506
+ ...(tooltip ? { tooltip } : {}),
4507
+ });
4508
+ }
4509
+ return {
4510
+ mode,
4511
+ ...(defaultTabId ? { defaultTabId } : {}),
4512
+ ...(tabsAppearance ? { tabsAppearance } : {}),
4513
+ ...(accordionMulti !== undefined ? { accordionMulti } : {}),
4514
+ ...(hideSectionHeaderInTabs !== undefined ? { hideSectionHeaderInTabs } : {}),
4515
+ ...(hideSectionHeaderInStepper !== undefined ? { hideSectionHeaderInStepper } : {}),
4516
+ ...(stepperInReadMode ? { stepperInReadMode } : {}),
4517
+ ...(stepperReviewStep !== undefined ? { stepperReviewStep } : {}),
4518
+ ...(sections.length ? { sections } : {}),
4519
+ ...(steps.length ? { steps } : {}),
4520
+ };
4521
+ }
4522
+ parseContextBinding(raw) {
4523
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
4524
+ return undefined;
4525
+ }
4526
+ const record = raw;
4527
+ const dim = String(record['dimension'] ?? '').trim().toLowerCase();
4528
+ if (dim !== 'organization' &&
4529
+ dim !== 'company_group' &&
4530
+ dim !== 'unit' &&
4531
+ dim !== 'person' &&
4532
+ dim !== 'bond' &&
4533
+ dim !== 'contract') {
4534
+ return undefined;
4535
+ }
4536
+ const targetField = typeof record['targetField'] === 'string' && record['targetField'].trim()
4537
+ ? record['targetField'].trim()
4538
+ : undefined;
4539
+ return {
4540
+ dimension: dim,
4541
+ lockWhenActive: this.parseBoolean(record['lockWhenActive']),
4542
+ ...(targetField ? { targetField } : {}),
4543
+ };
4544
+ }
4545
+ parseResourceState(raw) {
4546
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
4547
+ return undefined;
4548
+ }
4549
+ const record = raw;
4550
+ const initialStates = this.parseNonBlankStringArray(record['initialStates']);
4551
+ const putMutableStates = this.parseNonBlankStringArray(record['putMutableStates']);
4552
+ if (!initialStates.length && !putMutableStates.length) {
4553
+ return undefined;
4554
+ }
4555
+ return {
4556
+ ...(initialStates.length ? { initialStates } : {}),
4557
+ ...(putMutableStates.length ? { putMutableStates } : {}),
4558
+ };
4559
+ }
4560
+ parseMicroVisualization(raw) {
4561
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
4562
+ return undefined;
4563
+ }
4564
+ const normalized = normalizePraxisPresentationVisualization(raw);
4565
+ if (normalized) {
4566
+ return normalized;
4567
+ }
4568
+ const clone = this.clonePlain(raw);
4569
+ if (typeof clone['kind'] === 'string' && clone['kind'].trim()) {
4570
+ const rawKind = clone['kind'].trim();
4571
+ const upper = rawKind.toUpperCase();
4572
+ if (upper === 'HARVEY_BALL')
4573
+ clone['kind'] = 'harveyBall';
4574
+ else if (upper === 'STACKED_BAR')
4575
+ clone['kind'] = 'stackedBar';
4576
+ else if (upper === 'PROCESS_FLOW')
4577
+ clone['kind'] = 'processFlow';
4578
+ else if (upper === upper && /^[A-Z_]+$/.test(rawKind))
4579
+ clone['kind'] = rawKind.toLowerCase();
4580
+ return clone;
4581
+ }
4582
+ return undefined;
4583
+ }
2180
4584
  normalizeSchemaWithRoot(schema, rootSchema) {
2181
4585
  if (!schema || typeof schema !== 'object') {
2182
4586
  return [];
@@ -2195,16 +4599,62 @@ class SchemaNormalizationKernel {
2195
4599
  !Array.isArray(prop['x-ui'])
2196
4600
  ? prop['x-ui']
2197
4601
  : undefined;
4602
+ const hasChildProperties = prop?.properties &&
4603
+ typeof prop.properties === 'object' &&
4604
+ !Array.isArray(prop.properties);
4605
+ const isCustomFieldsContainer = ui?.customFieldsContainer === true ||
4606
+ (name === 'customFields' && prop?.type === 'object' && hasChildProperties);
4607
+ if (isCustomFieldsContainer) {
4608
+ if (hasChildProperties) {
4609
+ for (const key of Object.keys(prop.properties)) {
4610
+ if (RESERVED_CUSTOM_FIELD_KEYS.has(key)) {
4611
+ throw new Error(`Unsupported custom field key "${name}.${key}". Publish a key admitted by the canonical backend custom-field policy.`);
4612
+ }
4613
+ }
4614
+ const parentAccess = normalizeFieldAccessMetadata(ui?.fieldAccess);
4615
+ for (const childField of this.normalizeSchemaWithRoot(prop, rootSchema)) {
4616
+ const originalKey = childField.name;
4617
+ if (parentAccess && childField.fieldAccess &&
4618
+ !this.haveEquivalentFieldAccess(parentAccess, childField.fieldAccess)) {
4619
+ throw new Error(`Conflicting fieldAccess on custom-field container "${name}" and child "${originalKey}". Publish the effective access policy on each leaf field.`);
4620
+ }
4621
+ fields.push({
4622
+ ...childField,
4623
+ name: `${name}.${originalKey}`,
4624
+ customField: true,
4625
+ customFieldKey: childField.customFieldKey ?? originalKey,
4626
+ customFieldScope: childField.customFieldScope ?? 'tenant',
4627
+ ...(ui?.disabled !== undefined && this.parseBoolean(ui.disabled) ? { disabled: true } : {}),
4628
+ ...(ui?.readOnly !== undefined && this.parseBoolean(ui.readOnly) ? { readOnly: true } : {}),
4629
+ ...(ui?.formHidden !== undefined && this.parseBoolean(ui.formHidden) ? { formHidden: true } : {}),
4630
+ ...(parentAccess && !childField.fieldAccess ? { fieldAccess: normalizeFieldAccessMetadata(parentAccess) } : {}),
4631
+ });
4632
+ }
4633
+ }
4634
+ // The container is wire structure, never an independent field control.
4635
+ continue;
4636
+ }
2198
4637
  // Skip properties without x-ui metadata
2199
4638
  if (!ui || Object.keys(ui).length === 0) {
2200
4639
  continue;
2201
4640
  }
2202
4641
  const field = { name };
4642
+ if (ui.customField !== undefined) {
4643
+ field.customField = this.parseBoolean(ui.customField);
4644
+ }
4645
+ if (ui.customFieldKey != null) {
4646
+ field.customFieldKey = String(ui.customFieldKey);
4647
+ }
4648
+ if (ui.customFieldScope != null) {
4649
+ field.customFieldScope = String(ui.customFieldScope);
4650
+ }
2203
4651
  // -------------------------------------------------------------------
2204
4652
  // Basic information
2205
4653
  // -------------------------------------------------------------------
2206
4654
  field.label = ui.label ?? prop.title ?? name;
2207
- field.type = this.resolveFieldType(prop, ui);
4655
+ field.type = this.resolveFieldType(prop, ui, rootSchema);
4656
+ if (field.type === 'array')
4657
+ field.items = normalizeScalarItemsSchema(prop?.items);
2208
4658
  const numericFormat = this.resolveNumericFormatToken(prop, ui, field.type);
2209
4659
  if (numericFormat) {
2210
4660
  field.numericFormat = numericFormat;
@@ -2221,6 +4671,18 @@ class SchemaNormalizationKernel {
2221
4671
  if (ui.controlType) {
2222
4672
  field.controlType = ui.controlType;
2223
4673
  }
4674
+ if (this.isCanonicalMonetaryRangeUnion(prop, rootSchema)) {
4675
+ field.type = 'array';
4676
+ const controlToken = normalizeControlTypeToken(field.controlType);
4677
+ const isInlineCurrencyRange = controlToken === 'inlinecurrencyrange' ||
4678
+ resolveInlineFilterControlType(field.controlType) === 'inlineCurrencyRange';
4679
+ if (!isInlineCurrencyRange) {
4680
+ field.controlType = 'priceRange';
4681
+ }
4682
+ }
4683
+ if (this.inferRequireTwoBoundsFromUnion(prop, rootSchema)) {
4684
+ field.requireTwoBounds = true;
4685
+ }
2224
4686
  if (field.controlType === 'array' || ui.array !== undefined) {
2225
4687
  const arrayConfig = this.normalizeArrayConfig(ui, prop, rootSchema);
2226
4688
  if (arrayConfig) {
@@ -2314,6 +4776,40 @@ class SchemaNormalizationKernel {
2314
4776
  if (condRequired !== undefined) {
2315
4777
  field.conditionalRequired = condRequired;
2316
4778
  }
4779
+ if (ui.conditionalReadOnly !== undefined && ui.conditionalReadOnly !== null) {
4780
+ if (typeof ui.conditionalReadOnly === 'string') {
4781
+ const trimmed = ui.conditionalReadOnly.trim();
4782
+ if (trimmed) {
4783
+ field.conditionalReadOnly = trimmed;
4784
+ }
4785
+ }
4786
+ else {
4787
+ const condReadOnly = this.parseJsonLogicExpression(ui.conditionalReadOnly, name, 'x-ui.conditionalReadOnly');
4788
+ if (condReadOnly !== undefined) {
4789
+ field.conditionalReadOnly = condReadOnly;
4790
+ }
4791
+ }
4792
+ }
4793
+ if (ui.colSpan !== undefined) {
4794
+ const parsedSpan = this.parseOptionalFiniteNumber(ui.colSpan);
4795
+ if (parsedSpan !== undefined) {
4796
+ field.colSpan = Math.min(12, Math.max(1, Math.trunc(parsedSpan)));
4797
+ }
4798
+ }
4799
+ const contextBinding = this.parseContextBinding(ui.contextBinding);
4800
+ if (contextBinding) {
4801
+ field.contextBinding = contextBinding;
4802
+ }
4803
+ if (ui.draftCleared !== undefined) {
4804
+ const parsedDraftCleared = this.parseOptionalBoolean(ui.draftCleared);
4805
+ if (parsedDraftCleared !== undefined) {
4806
+ field.draftCleared = parsedDraftCleared;
4807
+ }
4808
+ }
4809
+ const resourceState = this.parseResourceState(ui.resourceState);
4810
+ if (resourceState) {
4811
+ field.resourceState = resourceState;
4812
+ }
2317
4813
  const transformFn = this.parseTransformFunction(ui.transformValueFunction);
2318
4814
  if (transformFn) {
2319
4815
  field.transformValueFunction = transformFn;
@@ -2328,9 +4824,57 @@ class SchemaNormalizationKernel {
2328
4824
  if (ui.tableHidden !== undefined) {
2329
4825
  field.tableHidden = this.parseBoolean(ui.tableHidden);
2330
4826
  }
4827
+ if (ui.tableOrder !== undefined) {
4828
+ const parsedTableOrder = this.parseOptionalFiniteNumber(ui.tableOrder);
4829
+ if (parsedTableOrder !== undefined) {
4830
+ field.tableOrder = parsedTableOrder;
4831
+ }
4832
+ }
4833
+ if (ui.pinned !== undefined && typeof ui.pinned === 'string') {
4834
+ const pinned = ui.pinned.trim().toLowerCase();
4835
+ if (pinned === 'start' || pinned === 'end') {
4836
+ field.pinned = pinned;
4837
+ }
4838
+ }
4839
+ if (ui.primarySearch !== undefined) {
4840
+ const primarySearch = this.parseOptionalBoolean(ui.primarySearch);
4841
+ if (primarySearch !== undefined) {
4842
+ field.primarySearch = primarySearch;
4843
+ }
4844
+ }
4845
+ if (ui.inlineFilter !== undefined) {
4846
+ const inlineFilter = this.parseOptionalBoolean(ui.inlineFilter);
4847
+ if (inlineFilter !== undefined) {
4848
+ field.inlineFilter = inlineFilter;
4849
+ }
4850
+ }
4851
+ if (ui.inline !== undefined) {
4852
+ const inline = this.parseOptionalBoolean(ui.inline);
4853
+ if (inline !== undefined) {
4854
+ field.inline = inline;
4855
+ }
4856
+ }
4857
+ if (ui.microVisualization !== undefined) {
4858
+ const microVisualization = this.parseMicroVisualization(ui.microVisualization);
4859
+ if (microVisualization) {
4860
+ field.microVisualization = microVisualization;
4861
+ }
4862
+ }
2331
4863
  if (ui.formHidden !== undefined) {
2332
4864
  field.formHidden = this.parseBoolean(ui.formHidden);
2333
4865
  }
4866
+ if (ui.quickViewVisible !== undefined) {
4867
+ const quickViewVisible = this.parseOptionalBoolean(ui.quickViewVisible);
4868
+ if (quickViewVisible !== undefined) {
4869
+ field.quickViewVisible = quickViewVisible;
4870
+ }
4871
+ }
4872
+ if (ui.quickViewOrder !== undefined) {
4873
+ const quickViewOrder = this.parseOptionalFiniteNumber(ui.quickViewOrder);
4874
+ if (quickViewOrder !== undefined) {
4875
+ field.quickViewOrder = quickViewOrder;
4876
+ }
4877
+ }
2334
4878
  if (ui.width !== undefined) {
2335
4879
  field.width = ui.width;
2336
4880
  }
@@ -2414,6 +4958,9 @@ class SchemaNormalizationKernel {
2414
4958
  if (ui.options !== undefined) {
2415
4959
  field.options = this.parseOptions(ui.options);
2416
4960
  }
4961
+ if (Array.isArray(prop?.enum) && prop.enum.length > 0 && field.enumValues === undefined) {
4962
+ field.enumValues = [...prop.enum];
4963
+ }
2417
4964
  if (ui.optionGroups !== undefined) {
2418
4965
  field.optionGroups = this.parseOptions(ui.optionGroups);
2419
4966
  }
@@ -2431,11 +4978,11 @@ class SchemaNormalizationKernel {
2431
4978
  if (optionSource) {
2432
4979
  // Java metadata publishes cascade context beside optionSource. Keep the
2433
4980
  // runtime contract canonical by materializing it inside optionSource.
2434
- const dependsOn = this.parseNonBlankStringArray(ui.dependsOn);
4981
+ const dependsOn = this.parseDependsOn(ui.dependsOn);
2435
4982
  if (!optionSource.dependsOn?.length && dependsOn.length) {
2436
4983
  optionSource.dependsOn = dependsOn;
2437
4984
  }
2438
- const dependencyFilterMap = this.parseStringRecord(ui.dependencyFilterMap);
4985
+ const dependencyFilterMap = this.parseStrictStringRecord(ui.dependencyFilterMap);
2439
4986
  if (!optionSource.dependencyFilterMap &&
2440
4987
  dependencyFilterMap) {
2441
4988
  optionSource.dependencyFilterMap = dependencyFilterMap;
@@ -2452,6 +4999,24 @@ class SchemaNormalizationKernel {
2452
4999
  if (ui.filterField !== undefined) {
2453
5000
  field.filterField = ui.filterField;
2454
5001
  }
5002
+ if (ui.resourceReference !== undefined) {
5003
+ const resourceReference = this.parseResourceReference(ui.resourceReference);
5004
+ if (resourceReference) {
5005
+ field.resourceReference = resourceReference;
5006
+ }
5007
+ }
5008
+ if (ui.quickView !== undefined) {
5009
+ const explicitQuickView = normalizeResourceQuickViewBinding(ui.quickView);
5010
+ if (explicitQuickView) {
5011
+ field.quickView = explicitQuickView;
5012
+ }
5013
+ }
5014
+ if (!field.quickView) {
5015
+ const synthesized = resolveFieldQuickViewBinding(field);
5016
+ if (synthesized) {
5017
+ field.quickView = synthesized;
5018
+ }
5019
+ }
2455
5020
  if (ui.multiple !== undefined) {
2456
5021
  field.multiple = this.parseBoolean(ui.multiple);
2457
5022
  }
@@ -2464,11 +5029,10 @@ class SchemaNormalizationKernel {
2464
5029
  if (ui.filter !== undefined) {
2465
5030
  field.filter = ui.filter;
2466
5031
  }
2467
- if (ui.dialog !== undefined) {
2468
- const dialog = this.parseLookupDialog(ui.dialog);
2469
- if (dialog) {
2470
- field.dialog = dialog;
2471
- }
5032
+ const explicitDialog = ui.dialog !== undefined ? this.parseLookupDialog(ui.dialog) : undefined;
5033
+ const resolvedDialog = this.mergeLookupDialog(field.optionSource?.dialog, explicitDialog);
5034
+ if (resolvedDialog) {
5035
+ field.dialog = resolvedDialog;
2472
5036
  }
2473
5037
  if (ui.detailActionLabel !== undefined) {
2474
5038
  const detailActionLabel = String(ui.detailActionLabel).trim();
@@ -2476,6 +5040,12 @@ class SchemaNormalizationKernel {
2476
5040
  field.detailActionLabel = detailActionLabel;
2477
5041
  }
2478
5042
  }
5043
+ if (ui.quickViewActionLabel !== undefined) {
5044
+ const quickViewActionLabel = String(ui.quickViewActionLabel).trim();
5045
+ if (quickViewActionLabel) {
5046
+ field.quickViewActionLabel = quickViewActionLabel;
5047
+ }
5048
+ }
2479
5049
  if (ui.copyCodeActionLabel !== undefined) {
2480
5050
  const copyCodeActionLabel = String(ui.copyCodeActionLabel).trim();
2481
5051
  if (copyCodeActionLabel) {
@@ -2499,6 +5069,9 @@ class SchemaNormalizationKernel {
2499
5069
  if (ui.actions.showDetail !== undefined) {
2500
5070
  actions.showDetail = this.parseBoolean(ui.actions.showDetail);
2501
5071
  }
5072
+ if (ui.actions.showQuickView !== undefined) {
5073
+ actions.showQuickView = this.parseBoolean(ui.actions.showQuickView);
5074
+ }
2502
5075
  if (ui.actions.showCopyCode !== undefined) {
2503
5076
  actions.showCopyCode = this.parseBoolean(ui.actions.showCopyCode);
2504
5077
  }
@@ -2530,10 +5103,22 @@ class SchemaNormalizationKernel {
2530
5103
  field.numericStep = Number(ui.numericStep);
2531
5104
  }
2532
5105
  if (ui.numericMin !== undefined) {
2533
- field.numericMin = Number(ui.numericMin);
5106
+ const parsedMin = Number(ui.numericMin);
5107
+ if (Number.isFinite(parsedMin)) {
5108
+ field.numericMin = parsedMin;
5109
+ }
5110
+ else if (field.min === undefined && String(ui.numericMin).trim().length > 0) {
5111
+ field.min = String(ui.numericMin).trim();
5112
+ }
2534
5113
  }
2535
5114
  if (ui.numericMax !== undefined) {
2536
- field.numericMax = Number(ui.numericMax);
5115
+ const parsedMax = Number(ui.numericMax);
5116
+ if (Number.isFinite(parsedMax)) {
5117
+ field.numericMax = parsedMax;
5118
+ }
5119
+ else if (field.max === undefined && String(ui.numericMax).trim().length > 0) {
5120
+ field.max = String(ui.numericMax).trim();
5121
+ }
2537
5122
  }
2538
5123
  if (ui.numericMaxLength !== undefined) {
2539
5124
  field.numericMaxLength = Number(ui.numericMaxLength);
@@ -2541,8 +5126,419 @@ class SchemaNormalizationKernel {
2541
5126
  if (ui.buttons !== undefined) {
2542
5127
  field.buttons = this.parseButtons(ui.buttons);
2543
5128
  }
5129
+ if (ui.valueLabelDisplay !== undefined) {
5130
+ const normalizedValueLabelDisplay = typeof ui.valueLabelDisplay === 'string'
5131
+ ? ui.valueLabelDisplay.trim().toLowerCase()
5132
+ : '';
5133
+ if (normalizedValueLabelDisplay === 'off' ||
5134
+ normalizedValueLabelDisplay === 'auto' ||
5135
+ normalizedValueLabelDisplay === 'on') {
5136
+ field.valueLabelDisplay = normalizedValueLabelDisplay;
5137
+ }
5138
+ }
5139
+ const sliderBooleanKeys = [
5140
+ 'thumbLabel',
5141
+ 'discrete',
5142
+ 'showInputs',
5143
+ 'showInlineInputs',
5144
+ 'showCurrencySymbol',
5145
+ 'disableThumbSwap',
5146
+ 'vertical',
5147
+ 'invert',
5148
+ ];
5149
+ for (const key of sliderBooleanKeys) {
5150
+ if (ui[key] !== undefined) {
5151
+ const parsed = this.parseOptionalBoolean(ui[key]);
5152
+ if (parsed !== undefined) {
5153
+ field[key] = parsed;
5154
+ }
5155
+ }
5156
+ }
5157
+ for (const guideKey of ['showTicks', 'showAnchors']) {
5158
+ const rawGuide = ui[guideKey];
5159
+ if (rawGuide !== undefined) {
5160
+ const parsedGuide = this.parseOptionalBoolean(rawGuide);
5161
+ if (parsedGuide !== undefined) {
5162
+ field[guideKey] = parsedGuide;
5163
+ }
5164
+ else if (typeof rawGuide === 'string' &&
5165
+ rawGuide.trim().toLowerCase() === 'auto') {
5166
+ field[guideKey] = 'auto';
5167
+ }
5168
+ }
5169
+ }
5170
+ const sliderNumberKeys = [
5171
+ 'sliderStep',
5172
+ 'shiftStep',
5173
+ 'minDistance',
5174
+ 'maxDistance',
5175
+ 'decimalPlaces',
5176
+ ];
5177
+ for (const key of sliderNumberKeys) {
5178
+ if (ui[key] !== undefined) {
5179
+ const parsed = this.parseOptionalFiniteNumber(ui[key]);
5180
+ if (parsed !== undefined) {
5181
+ field[key] = parsed;
5182
+ }
5183
+ }
5184
+ }
5185
+ // -------------------------------------------------------------------
5186
+ // Inline filter and specialized control metadata (x-ui)
5187
+ // -------------------------------------------------------------------
5188
+ const inlinePassThroughKeys = [
5189
+ 'prefixIcon',
5190
+ 'suffixIcon',
5191
+ 'prefixIconColor',
5192
+ 'suffixIconColor',
5193
+ 'chipLeadingIcon',
5194
+ 'chipTrailingIcon',
5195
+ 'chipLeadingIconColor',
5196
+ 'chipTrailingIconColor',
5197
+ 'clearIcon',
5198
+ 'clearIconColor',
5199
+ 'showQuickClear',
5200
+ 'clearable',
5201
+ 'inlineAutoSize',
5202
+ 'inlineAutoSizeMaxPx',
5203
+ 'inlineAutoSizeMaxVw',
5204
+ 'inlineOverlay',
5205
+ 'inlineChipDisplay',
5206
+ 'inlineChipSummaryTemplate',
5207
+ 'inlineChipUnitLabel',
5208
+ 'inlinePanelTitle',
5209
+ 'inlinePanelSubtitle',
5210
+ 'inlinePanelIcon',
5211
+ 'inlinePanelIconColor',
5212
+ 'inlineQuickPresets',
5213
+ 'inlineQuickPresetsApplyMode',
5214
+ 'inlineTexts',
5215
+ 'shortcuts',
5216
+ 'showShortcuts',
5217
+ 'quickPresets',
5218
+ 'quickPresetsAuto',
5219
+ 'quickPresetsLabels',
5220
+ 'granularity',
5221
+ 'defaultGranularity',
5222
+ 'selectionGrid',
5223
+ 'showSlider',
5224
+ 'minPeriod',
5225
+ 'maxPeriod',
5226
+ 'minYear',
5227
+ 'maxYear',
5228
+ 'minTime',
5229
+ 'maxTime',
5230
+ 'stepMinute',
5231
+ 'stepMinutes',
5232
+ 'interval',
5233
+ 'inlineTimeTrackShifts',
5234
+ 'inlineTrackShifts',
5235
+ 'trackShifts',
5236
+ 'minDistanceMinutes',
5237
+ 'maxDistanceMinutes',
5238
+ 'startField',
5239
+ 'endField',
5240
+ 'startLabel',
5241
+ 'endLabel',
5242
+ 'startPlaceholder',
5243
+ 'endPlaceholder',
5244
+ 'inputMinLabel',
5245
+ 'inputMaxLabel',
5246
+ 'inputExactLabel',
5247
+ 'startMin',
5248
+ 'startMax',
5249
+ 'endMin',
5250
+ 'endMax',
5251
+ 'startMinMessage',
5252
+ 'startMaxMessage',
5253
+ 'endMinMessage',
5254
+ 'endMaxMessage',
5255
+ 'endMinOffset',
5256
+ 'endMinOffsetMessage',
5257
+ 'startMaxOffset',
5258
+ 'startMaxOffsetMessage',
5259
+ 'maxVisibleChips',
5260
+ 'maxVisibleBadges',
5261
+ 'showSelectAll',
5262
+ 'selectAllLabel',
5263
+ 'clearSelectionLabel',
5264
+ 'searchPlaceholder',
5265
+ 'noResultsText',
5266
+ 'allowSelectAll',
5267
+ 'governedPaletteRef',
5268
+ 'palette',
5269
+ 'paletteColors',
5270
+ 'paletteSettings',
5271
+ 'documentType',
5272
+ 'version',
5273
+ 'nodes',
5274
+ 'nodeIdField',
5275
+ 'parentIdField',
5276
+ 'childrenField',
5277
+ 'lazyLoad',
5278
+ 'marks',
5279
+ 'semanticBands',
5280
+ 'distribution',
5281
+ 'inlineDistribution',
5282
+ 'track',
5283
+ 'trueLabel',
5284
+ 'falseLabel',
5285
+ 'labelTrue',
5286
+ 'labelFalse',
5287
+ 'iconTrue',
5288
+ 'iconFalse',
5289
+ 'tone',
5290
+ 'toneTrue',
5291
+ 'toneFalse',
5292
+ 'booleanFormat',
5293
+ 'displayFormat',
5294
+ 'currency',
5295
+ 'currencyCode',
5296
+ 'currencyPosition',
5297
+ 'thousandSeparator',
5298
+ 'thousandsSeparator',
5299
+ 'decimalSeparator',
5300
+ 'allowNegative',
5301
+ 'operatorModes',
5302
+ 'defaultOperatorMode',
5303
+ 'requireTwoBounds',
5304
+ 'locale',
5305
+ 'precision',
5306
+ 'initialsField',
5307
+ 'optionLabelKey',
5308
+ 'optionValueKey',
5309
+ 'extraProperties',
5310
+ 'rangeMode',
5311
+ 'maxRating',
5312
+ 'ratingMin',
5313
+ 'ratingMax',
5314
+ 'itemsCount',
5315
+ 'ratingStep',
5316
+ 'allowHalf',
5317
+ 'ratingAllowHalf',
5318
+ 'ratingPrecision',
5319
+ 'ratingIcon',
5320
+ 'ratingEmptyIcon',
5321
+ 'ratingHalfIcon',
5322
+ 'ratingActiveIcon',
5323
+ 'ratingInactiveIcon',
5324
+ 'ratingTone',
5325
+ 'ratingToneColors',
5326
+ 'ratingColors',
5327
+ 'starColors',
5328
+ 'ratingLowColor',
5329
+ 'ratingMidColor',
5330
+ 'ratingHighColor',
5331
+ 'ratingGradientLowColor',
5332
+ 'ratingGradientMidColor',
5333
+ 'ratingGradientHighColor',
5334
+ 'ratingToneLowColor',
5335
+ 'ratingToneMidColor',
5336
+ 'ratingToneHighColor',
5337
+ 'ratingBadgeColor',
5338
+ 'ratingBadgeIcon',
5339
+ 'ratingBadgeIconColor',
5340
+ 'ratingIndicatorColor',
5341
+ 'ratingLabels',
5342
+ 'distanceUnit',
5343
+ 'distanceBaseUnit',
5344
+ 'distanceUnits',
5345
+ 'distanceAllowUnitToggle',
5346
+ 'distanceUnitLabels',
5347
+ 'distanceDisplayDecimals',
5348
+ 'distanceDecimalsKm',
5349
+ 'distanceDecimalsMi',
5350
+ 'distancePresets',
5351
+ 'distanceSubtitle',
5352
+ 'distanceIcon',
5353
+ 'distanceStart',
5354
+ 'distanceEnd',
5355
+ 'radiusMin',
5356
+ 'radiusMax',
5357
+ 'radiusStep',
5358
+ 'radiusMode',
5359
+ 'distanceSliderStep',
5360
+ 'distanceRadialRings',
5361
+ 'distanceAccentColor',
5362
+ 'distanceRingColor',
5363
+ 'distanceTrackColor',
5364
+ 'distanceGlowColor',
5365
+ 'distanceGradientLowColor',
5366
+ 'distanceGradientMidColor',
5367
+ 'distanceGradientHighColor',
5368
+ 'distanceRangeBandOpacity',
5369
+ 'pipelineOptions',
5370
+ 'pipelineColors',
5371
+ 'pipelineTexts',
5372
+ 'scoreBands',
5373
+ 'priorityBands',
5374
+ 'severityBands',
5375
+ 'scorePalette',
5376
+ 'scoreTexts',
5377
+ 'scoreSubtitle',
5378
+ 'scoreUnit',
5379
+ 'scoreDisplayDecimals',
5380
+ 'scoreShowScaleLabels',
5381
+ 'scoreShowBandChips',
5382
+ 'scoreRangeSeparator',
5383
+ 'scoreGradientLowColor',
5384
+ 'scoreGradientMidColor',
5385
+ 'scoreGradientHighColor',
5386
+ 'scoreValueFallbackColor',
5387
+ 'scoreEmptyGradient',
5388
+ 'scoreIcon',
5389
+ 'scoreBandsAriaLabel',
5390
+ 'scoreBandAriaLabelTemplate',
5391
+ 'scoreMin',
5392
+ 'scoreMax',
5393
+ 'scoreStep',
5394
+ 'scoreMode',
5395
+ 'scoreSliderStep',
5396
+ 'relativePeriodOptions',
5397
+ 'relativePeriodPresets',
5398
+ 'relativePeriodTexts',
5399
+ 'sentimentOptions',
5400
+ 'sentimentPalette',
5401
+ 'sentimentTexts',
5402
+ 'colorLabelOptions',
5403
+ 'colorLabelPalette',
5404
+ 'colorLabelTexts',
5405
+ 'timeOptions',
5406
+ 'inlineTimeQuickPresets',
5407
+ 'inlineVisualStyle',
5408
+ 'percentPresets',
5409
+ 'numberFormat',
5410
+ 'valueLabelFormat',
5411
+ 'scale',
5412
+ 'optionSubtitleKey',
5413
+ 'optionWeightKey',
5414
+ 'optionColorKey',
5415
+ 'optionIconKey',
5416
+ 'optionEmojiKey',
5417
+ 'panelSearchIcon',
5418
+ 'panelSearchIconColor',
5419
+ 'panelResetIcon',
5420
+ 'panelResetIconColor',
5421
+ 'optionSelectedIcon',
5422
+ 'optionSelectedIconColor',
5423
+ 'columns',
5424
+ 'pipelineTitle',
5425
+ 'pipelineSubtitle',
5426
+ 'pipelineMode',
5427
+ 'pipelineMultiple',
5428
+ 'pipelineSearchable',
5429
+ 'pipelineSearchPlaceholder',
5430
+ 'pipelineOptionSubtitleKey',
5431
+ 'pipelineOptionWeightKey',
5432
+ 'pipelineOptionColorKey',
5433
+ 'pipelineShowBar',
5434
+ 'pipelineShowSelectionPills',
5435
+ 'pipelineShowSelectAll',
5436
+ 'pipelineSelectAllText',
5437
+ 'pipelineShowClearAction',
5438
+ 'pipelineClearActionText',
5439
+ 'pipelineChipMaxVisible',
5440
+ 'statusColors',
5441
+ 'pipelineGradientLowColor',
5442
+ 'pipelineGradientMidColor',
5443
+ 'pipelineGradientHighColor',
5444
+ 'pipelineEmptyStateText',
5445
+ 'pipelineSelectionActionsAriaLabel',
5446
+ 'pipelineOptionsGroupAriaLabelMultiple',
5447
+ 'pipelineOptionsGroupAriaLabelSingle',
5448
+ 'pipelineSelectionPillsAriaLabel',
5449
+ 'pipelineBarAriaLabelEmpty',
5450
+ 'pipelineBarAriaLabelSelected',
5451
+ 'pipelineIcon',
5452
+ 'pipelineSearchIcon',
5453
+ 'pipelineSearchIconColor',
5454
+ 'relativePeriodTitle',
5455
+ 'relativePeriodSubtitle',
5456
+ 'relativePeriodShowProgress',
5457
+ 'relativePeriodProgressGradientLowColor',
5458
+ 'relativePeriodProgressGradientMidColor',
5459
+ 'relativePeriodProgressGradientHighColor',
5460
+ 'relativePeriodColumns',
5461
+ 'relativePeriodCloseOnSelect',
5462
+ 'relativePeriodMultiple',
5463
+ 'relativePeriodSearchable',
5464
+ 'relativePeriodIcon',
5465
+ 'relativePeriodIconKey',
5466
+ 'relativePeriodSubtitleKey',
5467
+ 'relativePeriodSelectedIcon',
5468
+ 'relativePeriodSelectedIconColor',
5469
+ 'relativePeriodOptionsAriaLabel',
5470
+ 'relativePeriodProgressEmptyLabel',
5471
+ 'relativePeriodEmptyStateText',
5472
+ 'sentimentTitle',
5473
+ 'sentimentSubtitle',
5474
+ 'sentimentGradientLowColor',
5475
+ 'sentimentGradientMidColor',
5476
+ 'sentimentGradientHighColor',
5477
+ 'sentimentShowBar',
5478
+ 'sentimentAnimatedEmoji',
5479
+ 'sentimentCloseOnSelect',
5480
+ 'sentimentMultiple',
5481
+ 'sentimentShowSelectionPills',
5482
+ 'sentimentIcon',
5483
+ 'sentimentColorKey',
5484
+ 'sentimentEmojiKey',
5485
+ 'sentimentOptionsAriaLabel',
5486
+ 'sentimentSelectionPillsAriaLabel',
5487
+ 'sentimentEmptyStateText',
5488
+ 'colorLabelTitle',
5489
+ 'colorLabelSubtitle',
5490
+ 'colorLabelMultiple',
5491
+ 'colorLabelColumns',
5492
+ 'colorLabelShowSelectedBadges',
5493
+ 'colorLabelCloseOnSelect',
5494
+ 'colorLabelSelectionTitle',
5495
+ 'colorLabelIcon',
5496
+ 'colorLabelSelectedIcon',
5497
+ 'colorLabelSelectedIconColor',
5498
+ 'colorLabelBadgeRemoveIcon',
5499
+ 'colorLabelBadgeRemoveIconColor',
5500
+ 'colorLabelColorKey',
5501
+ 'colorLabelOptionsAriaLabel',
5502
+ 'colorLabelSelectionBadgesAriaLabel',
5503
+ 'colorLabelRemoveSelectionAriaLabel',
5504
+ 'colorLabelEmptyStateText',
5505
+ 'startAriaLabel',
5506
+ 'endAriaLabel',
5507
+ 'inlineQuickPresetsAriaLabel',
5508
+ 'inlineQuickPresetsCancelLabel',
5509
+ 'inlineQuickPresetsCancelAriaLabel',
5510
+ 'inlineQuickPresetsApplyLabel',
5511
+ 'inlineQuickPresetsApplyAriaLabel',
5512
+ 'shortcutsPosition',
5513
+ 'applyOnShortcutClick',
5514
+ 'i18nShortcuts',
5515
+ 'startView',
5516
+ 'startAt',
5517
+ 'touchUi',
5518
+ 'minDate',
5519
+ 'maxDate',
5520
+ ];
5521
+ for (const key of inlinePassThroughKeys) {
5522
+ if (ui[key] !== undefined && field[key] === undefined) {
5523
+ field[key] = ui[key];
5524
+ }
5525
+ }
2544
5526
  fields.push(field);
2545
5527
  }
5528
+ if (fields.length === 0 &&
5529
+ properties['parameters'] &&
5530
+ typeof properties['parameters'] === 'object' &&
5531
+ !Array.isArray(properties['parameters'])) {
5532
+ const parametersProp = properties['parameters'];
5533
+ const resolvedParametersSchema = this.resolveSchemaRef(parametersProp.$ref, rootSchema) ?? parametersProp;
5534
+ if (resolvedParametersSchema &&
5535
+ typeof resolvedParametersSchema === 'object' &&
5536
+ resolvedParametersSchema !== schema &&
5537
+ resolvedParametersSchema.properties &&
5538
+ typeof resolvedParametersSchema.properties === 'object') {
5539
+ return this.normalizeObjectSchema(resolvedParametersSchema, rootSchema);
5540
+ }
5541
+ }
2546
5542
  // Order by the optional 'order' property when present
2547
5543
  fields.sort((a, b) => {
2548
5544
  const orderA = a.order ?? Number.MAX_SAFE_INTEGER;
@@ -2551,29 +5547,177 @@ class SchemaNormalizationKernel {
2551
5547
  });
2552
5548
  return fields;
2553
5549
  }
2554
- resolveFieldType(prop, ui) {
5550
+ haveEquivalentFieldAccess(left, right) {
5551
+ const identity = (access) => JSON.stringify([
5552
+ [...(access.visibleForAuthorities ?? [])].sort(),
5553
+ [...(access.editableForAuthorities ?? [])].sort(),
5554
+ ]);
5555
+ return identity(left) === identity(right);
5556
+ }
5557
+ resolveSchemaNode(node, rootSchema, visited = new Set()) {
5558
+ if (!node || typeof node !== 'object' || Array.isArray(node)) {
5559
+ return node;
5560
+ }
5561
+ const ref = typeof node.$ref === 'string' ? node.$ref.trim() : '';
5562
+ if (!ref || visited.has(ref)) {
5563
+ return node;
5564
+ }
5565
+ const resolved = this.resolveSchemaRef(ref, rootSchema);
5566
+ if (!resolved || typeof resolved !== 'object' || Array.isArray(resolved)) {
5567
+ return node;
5568
+ }
5569
+ const nextVisited = new Set(visited);
5570
+ nextVisited.add(ref);
5571
+ const resolvedDeep = this.resolveSchemaNode(resolved, rootSchema, nextVisited);
5572
+ const { $ref: _ignoredRef, ...rest } = node;
5573
+ return {
5574
+ ...(resolvedDeep && typeof resolvedDeep === 'object' ? resolvedDeep : {}),
5575
+ ...rest,
5576
+ };
5577
+ }
5578
+ extractSchemaNonNullTypes(node) {
5579
+ if (!node || typeof node !== 'object') {
5580
+ return [];
5581
+ }
5582
+ const collected = [];
5583
+ const pushType = (raw) => {
5584
+ if (typeof raw !== 'string') {
5585
+ return;
5586
+ }
5587
+ const normalized = raw.trim().toLowerCase();
5588
+ if (normalized && normalized !== 'null' && !collected.includes(normalized)) {
5589
+ collected.push(normalized);
5590
+ }
5591
+ };
5592
+ const pushFrom = (raw) => {
5593
+ if (typeof raw === 'string') {
5594
+ pushType(raw);
5595
+ }
5596
+ else if (Array.isArray(raw)) {
5597
+ for (const item of raw) {
5598
+ pushType(item);
5599
+ }
5600
+ }
5601
+ else if (raw instanceof Set) {
5602
+ for (const item of raw) {
5603
+ pushType(item);
5604
+ }
5605
+ }
5606
+ };
5607
+ pushFrom(node.type);
5608
+ pushFrom(node.types);
5609
+ return collected;
5610
+ }
5611
+ extractUnionVariants(prop, rootSchema) {
5612
+ const resolvedProp = this.resolveSchemaNode(prop, rootSchema);
5613
+ if (!resolvedProp || typeof resolvedProp !== 'object' || Array.isArray(resolvedProp)) {
5614
+ return [];
5615
+ }
5616
+ const rawVariants = [
5617
+ ...(Array.isArray(resolvedProp.oneOf) ? resolvedProp.oneOf : []),
5618
+ ...(Array.isArray(resolvedProp.anyOf) ? resolvedProp.anyOf : []),
5619
+ ];
5620
+ return rawVariants
5621
+ .filter((variant) => variant && typeof variant === 'object' && !Array.isArray(variant))
5622
+ .map((variant) => this.resolveSchemaNode(variant, rootSchema));
5623
+ }
5624
+ isArrayVariant(variant) {
5625
+ return this.extractSchemaNonNullTypes(variant).includes('array');
5626
+ }
5627
+ isObjectVariant(variant) {
5628
+ const types = this.extractSchemaNonNullTypes(variant);
5629
+ return (types.includes('object') ||
5630
+ (types.length === 0 &&
5631
+ !!variant?.properties &&
5632
+ typeof variant.properties === 'object' &&
5633
+ !Array.isArray(variant.properties)));
5634
+ }
5635
+ isCanonicalMonetaryRangeUnion(prop, rootSchema) {
5636
+ const variants = this.extractUnionVariants(prop, rootSchema);
5637
+ if (variants.length === 0) {
5638
+ return false;
5639
+ }
5640
+ const hasArrayBranch = variants.some((variant) => this.isArrayVariant(variant));
5641
+ if (!hasArrayBranch) {
5642
+ return false;
5643
+ }
5644
+ return variants.some((variant) => {
5645
+ if (!this.isObjectVariant(variant)) {
5646
+ return false;
5647
+ }
5648
+ const props = variant?.properties;
5649
+ if (!props || typeof props !== 'object' || Array.isArray(props)) {
5650
+ return false;
5651
+ }
5652
+ return (Object.prototype.hasOwnProperty.call(props, 'minPrice') &&
5653
+ props.minPrice != null &&
5654
+ Object.prototype.hasOwnProperty.call(props, 'maxPrice') &&
5655
+ props.maxPrice != null);
5656
+ });
5657
+ }
5658
+ inferRequireTwoBoundsFromUnion(prop, rootSchema) {
5659
+ const variants = this.extractUnionVariants(prop, rootSchema);
5660
+ if (variants.length === 0) {
5661
+ return false;
5662
+ }
5663
+ const requiredPairs = [
5664
+ ['minPrice', 'maxPrice'],
5665
+ ['min', 'max'],
5666
+ ['startDate', 'endDate'],
5667
+ ];
5668
+ for (const variant of variants) {
5669
+ if (this.isArrayVariant(variant) && Number(variant?.minItems) === 2) {
5670
+ return true;
5671
+ }
5672
+ if (this.isObjectVariant(variant) && Array.isArray(variant?.required)) {
5673
+ const requiredSet = new Set(variant.required.filter((entry) => typeof entry === 'string'));
5674
+ if (requiredPairs.some(([lower, upper]) => requiredSet.has(lower) && requiredSet.has(upper))) {
5675
+ return true;
5676
+ }
5677
+ }
5678
+ }
5679
+ return false;
5680
+ }
5681
+ resolveFieldType(prop, ui, rootSchema) {
5682
+ if (this.isCanonicalMonetaryRangeUnion(prop, rootSchema)) {
5683
+ return 'array';
5684
+ }
2555
5685
  if (ui?.type !== undefined && ui?.type !== null && String(ui.type).trim() !== '') {
2556
5686
  return String(ui.type);
2557
5687
  }
2558
5688
  if (String(ui?.controlType ?? '').trim() === 'array') {
2559
5689
  return 'array';
2560
5690
  }
2561
- if (prop?.type) {
2562
- return String(prop.type);
5691
+ const resolvedProp = this.resolveSchemaNode(prop, rootSchema);
5692
+ const propTypes = this.extractSchemaNonNullTypes(resolvedProp);
5693
+ if (propTypes.length === 1) {
5694
+ return propTypes[0];
2563
5695
  }
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')));
5696
+ if (resolvedProp?.type && !Array.isArray(resolvedProp.type)) {
5697
+ return String(resolvedProp.type);
5698
+ }
5699
+ const variants = this.extractUnionVariants(prop, rootSchema);
5700
+ const nonNullTypes = Array.from(new Set(variants.flatMap((variant) => this.extractSchemaNonNullTypes(variant))));
2571
5701
  if (nonNullTypes.length === 1) {
2572
5702
  return nonNullTypes[0];
2573
5703
  }
2574
5704
  // Compatibilidade para schemas de range publicados como oneOf(array|object).
2575
5705
  const controlToken = String(ui?.controlType || '').trim().toLowerCase().replace(/[^a-z0-9]/g, '');
2576
- const isRangeControl = ['daterange', 'datetimerange', 'rangeslider', 'pricerange'].includes(controlToken);
5706
+ const isRangeControl = [
5707
+ 'daterange',
5708
+ 'datetimerange',
5709
+ 'rangeslider',
5710
+ 'pricerange',
5711
+ 'inlinerange',
5712
+ 'inlinecurrencyrange',
5713
+ 'inlinedaterange',
5714
+ 'inlineperiodrange',
5715
+ 'inlineyearrange',
5716
+ 'inlinemonthrange',
5717
+ 'inlinetimerange',
5718
+ 'inlinedistanceradius',
5719
+ 'inlinescorepriority',
5720
+ ].includes(controlToken);
2577
5721
  if (isRangeControl && nonNullTypes.includes('array')) {
2578
5722
  return 'array';
2579
5723
  }
@@ -2589,6 +5733,10 @@ class SchemaNormalizationKernel {
2589
5733
  function normalizeSchemaFields(schema) {
2590
5734
  return new SchemaNormalizationKernel().normalizeSchema(schema);
2591
5735
  }
5736
+ /** Extracts root-level `x-ui` metadata blocks (`formLayout`, `progression`, `timeline`, `schedule`, `hierarchy`, `calculationMemory`). */
5737
+ function extractSchemaRootUiMetadata(schema) {
5738
+ return new SchemaNormalizationKernel().extractRootUiMetadata(schema);
5739
+ }
2592
5740
 
2593
5741
  function isObject(value) {
2594
5742
  return value != null && typeof value === 'object' && !Array.isArray(value);
@@ -2667,8 +5815,18 @@ function clone(v) {
2667
5815
 
2668
5816
  function buildBaseColumnFromDef(def) {
2669
5817
  const type = resolveColumnTypeFromFieldDefinition(def);
2670
- const format = type === 'string' ? resolveTextMaskFormatFromFieldDefinition(def) : undefined;
2671
- const renderer = resolveRendererFromFieldPresentation(def);
5818
+ const format = resolveFormatFromFieldDefinition(def, type);
5819
+ const valueMapping = resolveSchemaValueMappingFromFieldDefinition(def);
5820
+ const renderer = resolveRendererFromFieldDefinition(def);
5821
+ const quickView = resolveQuickViewFromFieldDefinition(def);
5822
+ const isAvatar = renderer?.type === 'avatar';
5823
+ const explicitWidth = firstNonEmptyString(def.width);
5824
+ const resolvedOrder = typeof def.tableOrder === 'number'
5825
+ ? def.tableOrder
5826
+ : typeof def.order === 'number'
5827
+ ? def.order
5828
+ : undefined;
5829
+ const sticky = def.pinned ?? def.sticky;
2672
5830
  return {
2673
5831
  field: def.name,
2674
5832
  header: def.label || def.name,
@@ -2677,9 +5835,14 @@ function buildBaseColumnFromDef(def) {
2677
5835
  sortable: def.sortable !== false,
2678
5836
  filterable: def.filterable === true,
2679
5837
  resizable: true,
2680
- order: typeof def.order === 'number' ? def.order : undefined,
5838
+ ...(sticky !== undefined ? { sticky } : {}),
5839
+ order: resolvedOrder,
5840
+ ...(explicitWidth ? { width: explicitWidth } : isAvatar ? { width: '56px' } : {}),
5841
+ ...(isAvatar ? { align: 'center' } : {}),
2681
5842
  ...(format ? { format } : {}),
5843
+ ...(valueMapping ? { valueMapping } : {}),
2682
5844
  ...(renderer ? { renderer } : {}),
5845
+ ...(quickView ? { quickView } : {}),
2683
5846
  };
2684
5847
  }
2685
5848
  function applyLocalCustomizations(baseCol, localCol) {
@@ -2706,11 +5869,18 @@ function applyLocalCustomizations(baseCol, localCol) {
2706
5869
  result.headerStyle = localCol.headerStyle ?? baseCol.headerStyle;
2707
5870
  result.cssClass = localCol.cssClass ?? baseCol.cssClass;
2708
5871
  result.headerCssClass = localCol.headerCssClass ?? baseCol.headerCssClass;
5872
+ const resolvedQuickView = reconcileFieldQuickViewBinding(baseCol.quickView, localCol.quickView);
5873
+ if (resolvedQuickView) {
5874
+ result.quickView = resolvedQuickView;
5875
+ }
5876
+ else {
5877
+ delete result.quickView;
5878
+ }
2709
5879
  // If server type changed, drop potentially incompatible formatting/renderers.
2710
5880
  if (!typeChanged) {
2711
5881
  result.format = localCol.format ?? baseCol.format;
2712
5882
  result.valueMapping = localCol.valueMapping ?? baseCol.valueMapping;
2713
- result.renderer = localCol.renderer ?? baseCol.renderer;
5883
+ result.renderer = normalizeColumnRendererQuickView(localCol.renderer ?? baseCol.renderer);
2714
5884
  }
2715
5885
  else {
2716
5886
  // Drop local presentation that may be incompatible with the new server type,
@@ -2729,6 +5899,10 @@ function reconcileTableConfig(layout, serverDefs) {
2729
5899
  const localCol = localByField.get(base.field);
2730
5900
  return localCol ? applyLocalCustomizations(base, localCol) : base;
2731
5901
  });
5902
+ if (serverDefs.some((d) => typeof d.tableOrder === 'number')) {
5903
+ mergedColumns.sort((a, b) => (a.order ?? Number.MAX_SAFE_INTEGER) -
5904
+ (b.order ?? Number.MAX_SAFE_INTEGER));
5905
+ }
2732
5906
  const serverFields = new Set(serverDefs.map((d) => d.name));
2733
5907
  const orphans = (local.columns || []).filter((c) => !serverFields.has(c.field));
2734
5908
  const hiddenOrphans = orphans.map((c) => ({ ...c, visible: false }));
@@ -2773,8 +5947,11 @@ function resolveSemanticColumnTypeFromFieldDefinition(def) {
2773
5947
  return 'string';
2774
5948
  if (numericFormat === 'currency' || controlType === 'currency')
2775
5949
  return 'currency';
2776
- if (numericFormat === 'percent' || numericFormat === 'percentage')
5950
+ if (numericFormat === 'percent' ||
5951
+ numericFormat === 'percentage' ||
5952
+ numericFormat === 'fraction') {
2777
5953
  return 'percentage';
5954
+ }
2778
5955
  if (numericFormat === 'date' || numericFormat === 'datetime')
2779
5956
  return 'date';
2780
5957
  if (controlType === 'numerictextbox' || controlType === 'inlinenumber')
@@ -2831,21 +6008,297 @@ function resolveTextMaskFormat(value) {
2831
6008
  const hasInvalidMaskLetters = /[A-WYZa-wyz]/.test(format);
2832
6009
  return hasMaskTokens && !hasInvalidMaskLetters ? format : undefined;
2833
6010
  }
6011
+ function resolveFormatFromFieldDefinition(def, type) {
6012
+ if (type === 'string') {
6013
+ return resolveTextMaskFormatFromFieldDefinition(def);
6014
+ }
6015
+ if (type === 'currency') {
6016
+ return resolveSchemaCurrencyFormatFromFieldDefinition(def);
6017
+ }
6018
+ if (type === 'date') {
6019
+ return (firstNonEmptyString(def.displayFormat) ??
6020
+ firstNonEmptyString(def.extraProperties?.displayFormat));
6021
+ }
6022
+ if (type === 'boolean') {
6023
+ return resolveSchemaBooleanFormatFromFieldDefinition(def);
6024
+ }
6025
+ if (type === 'number') {
6026
+ const schemaDataType = normalizePresentationToken(def.type);
6027
+ const schemaFormat = normalizePresentationToken(def.format);
6028
+ const numericFormat = normalizePresentationToken(def.numericFormat ?? def.extraProperties?.numericFormat);
6029
+ if (schemaDataType === 'integer' ||
6030
+ schemaFormat === 'integer' ||
6031
+ schemaFormat === 'int32' ||
6032
+ schemaFormat === 'int64' ||
6033
+ numericFormat === 'integer' ||
6034
+ numericFormat === 'int32' ||
6035
+ numericFormat === 'int64') {
6036
+ return '1.0-0';
6037
+ }
6038
+ if (numericFormat === 'auto') {
6039
+ return undefined;
6040
+ }
6041
+ const explicitDecimals = firstFiniteNumber(def.decimalPlaces) ??
6042
+ firstFiniteNumber(def.extraProperties?.decimalPlaces);
6043
+ if (explicitDecimals !== undefined && explicitDecimals >= 0) {
6044
+ const decimals = Math.trunc(explicitDecimals);
6045
+ return `1.${decimals}-${decimals}`;
6046
+ }
6047
+ }
6048
+ return undefined;
6049
+ }
6050
+ function resolveSchemaCurrencyFormatFromFieldDefinition(def) {
6051
+ const currency = firstNonEmptyString(def.currency) ??
6052
+ firstNonEmptyString(def.extraProperties?.currency) ??
6053
+ 'BRL';
6054
+ const decimalPlaces = firstFiniteNumber(def.decimalPlaces) ??
6055
+ firstFiniteNumber(def.extraProperties?.decimalPlaces) ??
6056
+ 2;
6057
+ return `${currency}|symbol|${decimalPlaces}`;
6058
+ }
6059
+ function resolveSchemaBooleanFormatFromFieldDefinition(def) {
6060
+ const explicit = firstNonEmptyString(def.booleanFormat) ??
6061
+ firstNonEmptyString(def.extraProperties?.booleanFormat);
6062
+ if (explicit)
6063
+ return explicit;
6064
+ const trueLabel = firstNonEmptyString(def.trueLabel) ??
6065
+ firstNonEmptyString(def.labelTrue) ??
6066
+ firstNonEmptyString(def.presentation?.labelTrue) ??
6067
+ firstNonEmptyString(def.extraProperties?.trueLabel) ??
6068
+ firstNonEmptyString(def.extraProperties?.labelTrue);
6069
+ const falseLabel = firstNonEmptyString(def.falseLabel) ??
6070
+ firstNonEmptyString(def.labelFalse) ??
6071
+ firstNonEmptyString(def.presentation?.labelFalse) ??
6072
+ firstNonEmptyString(def.extraProperties?.falseLabel) ??
6073
+ firstNonEmptyString(def.extraProperties?.labelFalse);
6074
+ if (trueLabel || falseLabel) {
6075
+ const effectiveTrue = trueLabel || 'Sim';
6076
+ const effectiveFalse = falseLabel || 'Não';
6077
+ const tNorm = normalizePresentationToken(effectiveTrue);
6078
+ const fNorm = normalizePresentationToken(effectiveFalse);
6079
+ if (tNorm === 'ativo' && fNorm === 'inativo')
6080
+ return 'active-inactive';
6081
+ if (tNorm === 'sim' && (fNorm === 'nao' || fNorm === 'não'))
6082
+ return 'yes-no';
6083
+ return `custom|${effectiveTrue}|${effectiveFalse}`;
6084
+ }
6085
+ const name = normalizePresentationToken(def.name);
6086
+ if (name === 'ativo' || name === 'active' || name.endsWith('ativo')) {
6087
+ return 'active-inactive';
6088
+ }
6089
+ return undefined;
6090
+ }
6091
+ function resolveSchemaValueMappingFromFieldDefinition(def) {
6092
+ const explicit = def.valueMapping;
6093
+ if (explicit && typeof explicit === 'object' && !Array.isArray(explicit)) {
6094
+ const normalized = Object.entries(explicit).reduce((acc, [key, value]) => {
6095
+ if (key && typeof value === 'string' && value.trim()) {
6096
+ acc[key] = value.trim();
6097
+ }
6098
+ return acc;
6099
+ }, {});
6100
+ if (Object.keys(normalized).length > 0)
6101
+ return normalized;
6102
+ }
6103
+ const options = Array.isArray(def.options) ? def.options : [];
6104
+ if (options.length > 0) {
6105
+ const valueKey = firstNonEmptyString(def.optionValueKey) ?? 'key';
6106
+ const labelKey = firstNonEmptyString(def.optionLabelKey) ?? 'value';
6107
+ const mapping = options.reduce((acc, option) => {
6108
+ if (!option || typeof option !== 'object')
6109
+ return acc;
6110
+ const record = option;
6111
+ const value = record[valueKey] ?? record.key ?? record.id ?? record.value;
6112
+ const label = record[labelKey] ?? record.label ?? record.value ?? record.name;
6113
+ if (value !== undefined && value !== null && label !== undefined && label !== null) {
6114
+ acc[String(value)] = String(label);
6115
+ }
6116
+ return acc;
6117
+ }, {});
6118
+ if (Object.keys(mapping).length > 0)
6119
+ return mapping;
6120
+ }
6121
+ const enumValues = Array.isArray(def.enumValues)
6122
+ ? def.enumValues
6123
+ .map((v) => (v != null ? String(v).trim() : ''))
6124
+ .filter((v) => v.length > 0)
6125
+ : [];
6126
+ if (enumValues.length > 0) {
6127
+ return enumValues.reduce((acc, value) => {
6128
+ acc[value] = humanizeSchemaEnumValue(value);
6129
+ return acc;
6130
+ }, {});
6131
+ }
6132
+ return undefined;
6133
+ }
6134
+ function humanizeSchemaEnumValue(value) {
6135
+ return value
6136
+ .toLowerCase()
6137
+ .split(/[_\-\s]+/)
6138
+ .filter(Boolean)
6139
+ .map((part, index) => (index === 0 ? `${part.charAt(0).toUpperCase()}${part.slice(1)}` : part))
6140
+ .join(' ');
6141
+ }
6142
+ function resolveQuickViewFromFieldDefinition(def) {
6143
+ return (resolveFieldQuickViewBinding(def) ??
6144
+ normalizeResourceQuickViewBinding(def['extraProperties'] && typeof def['extraProperties'] === 'object' ? def['extraProperties']['quickView'] : undefined) ??
6145
+ undefined);
6146
+ }
6147
+ function normalizeColumnRendererQuickView(renderer) {
6148
+ if (!renderer || typeof renderer !== 'object') {
6149
+ return renderer;
6150
+ }
6151
+ const next = { ...renderer };
6152
+ if (next.link && typeof next.link === 'object') {
6153
+ const qv = normalizeResourceQuickViewBinding(next.link.quickView);
6154
+ next.link = { ...next.link };
6155
+ if (qv) {
6156
+ next.link.quickView = qv;
6157
+ }
6158
+ else {
6159
+ delete next.link.quickView;
6160
+ }
6161
+ }
6162
+ if (next.badge && typeof next.badge === 'object') {
6163
+ const qv = normalizeResourceQuickViewBinding(next.badge.quickView);
6164
+ next.badge = { ...next.badge };
6165
+ if (qv) {
6166
+ next.badge.quickView = qv;
6167
+ }
6168
+ else {
6169
+ delete next.badge.quickView;
6170
+ }
6171
+ }
6172
+ if (next.chip && typeof next.chip === 'object') {
6173
+ const qv = normalizeResourceQuickViewBinding(next.chip.quickView);
6174
+ next.chip = { ...next.chip };
6175
+ if (qv) {
6176
+ next.chip.quickView = qv;
6177
+ }
6178
+ else {
6179
+ delete next.chip.quickView;
6180
+ }
6181
+ }
6182
+ if (next.icon && typeof next.icon === 'object') {
6183
+ const qv = normalizeResourceQuickViewBinding(next.icon.quickView);
6184
+ next.icon = { ...next.icon };
6185
+ if (qv) {
6186
+ next.icon.quickView = qv;
6187
+ }
6188
+ else {
6189
+ delete next.icon.quickView;
6190
+ }
6191
+ }
6192
+ if (next.compose && typeof next.compose === 'object' && Array.isArray(next.compose.items)) {
6193
+ next.compose = {
6194
+ ...next.compose,
6195
+ items: next.compose.items.map((item) => {
6196
+ if (!item || typeof item !== 'object')
6197
+ return item;
6198
+ if (item.type === 'value') {
6199
+ const qv = normalizeResourceQuickViewBinding(item.quickView);
6200
+ const cloned = { ...item };
6201
+ if (qv)
6202
+ cloned.quickView = qv;
6203
+ else
6204
+ delete cloned.quickView;
6205
+ return cloned;
6206
+ }
6207
+ if (item.type === 'link' && item.link) {
6208
+ const qv = normalizeResourceQuickViewBinding(item.link.quickView);
6209
+ const link = { ...item.link };
6210
+ if (qv)
6211
+ link.quickView = qv;
6212
+ else
6213
+ delete link.quickView;
6214
+ return { ...item, link };
6215
+ }
6216
+ if (item.type === 'badge' && item.badge) {
6217
+ const qv = normalizeResourceQuickViewBinding(item.badge.quickView);
6218
+ const badge = { ...item.badge };
6219
+ if (qv)
6220
+ badge.quickView = qv;
6221
+ else
6222
+ delete badge.quickView;
6223
+ return { ...item, badge };
6224
+ }
6225
+ if (item.type === 'chip' && item.chip) {
6226
+ const qv = normalizeResourceQuickViewBinding(item.chip.quickView);
6227
+ const chip = { ...item.chip };
6228
+ if (qv)
6229
+ chip.quickView = qv;
6230
+ else
6231
+ delete chip.quickView;
6232
+ return { ...item, chip };
6233
+ }
6234
+ if (item.type === 'icon' && item.icon) {
6235
+ const qv = normalizeResourceQuickViewBinding(item.icon.quickView);
6236
+ const icon = { ...item.icon };
6237
+ if (qv)
6238
+ icon.quickView = qv;
6239
+ else
6240
+ delete icon.quickView;
6241
+ return { ...item, icon };
6242
+ }
6243
+ return item;
6244
+ }),
6245
+ };
6246
+ }
6247
+ return next;
6248
+ }
6249
+ function resolveRendererFromFieldDefinition(def) {
6250
+ const presentationRenderer = resolveRendererFromFieldPresentation(def);
6251
+ if (presentationRenderer)
6252
+ return presentationRenderer;
6253
+ if (isPraxisPresentationVisualizationTableSafe(def.microVisualization)) {
6254
+ return {
6255
+ type: 'microVisualization',
6256
+ microVisualization: {
6257
+ visualization: def.microVisualization,
6258
+ },
6259
+ };
6260
+ }
6261
+ if (normalizePresentationToken(def.controlType) === 'avatar') {
6262
+ const initialsField = firstNonEmptyString(def.initialsField) ??
6263
+ firstNonEmptyString(def.extraProperties?.initialsField) ??
6264
+ 'nomeCompleto';
6265
+ return {
6266
+ type: 'avatar',
6267
+ avatar: {
6268
+ srcField: def.name,
6269
+ initialsField,
6270
+ shape: 'circle',
6271
+ size: 32,
6272
+ },
6273
+ };
6274
+ }
6275
+ return undefined;
6276
+ }
2834
6277
  function resolveRendererFromFieldPresentation(def) {
2835
6278
  const presentation = def.presentation;
2836
6279
  if (!presentation || typeof presentation !== 'object')
2837
6280
  return undefined;
6281
+ if (presentation.presenter === 'microVisualization' &&
6282
+ isPraxisPresentationVisualizationTableSafe(presentation.visualization)) {
6283
+ return {
6284
+ type: 'microVisualization',
6285
+ microVisualization: {
6286
+ visualization: presentation.visualization,
6287
+ },
6288
+ };
6289
+ }
2838
6290
  const presenter = normalizePresentationToken(presentation.presenter ?? presentation.variant);
2839
6291
  const color = resolveSemanticPresentationColor(presentation.tone);
2840
6292
  const variant = resolveSemanticPresentationVariant(presentation.appearance);
2841
6293
  const icon = firstNonEmptyString(presentation.icon);
2842
6294
  const tooltipText = firstNonEmptyString(presentation.tooltip);
2843
6295
  const tooltip = tooltipText ? { text: tooltipText } : undefined;
6296
+ const fixedText = firstNonEmptyString(presentation.label);
2844
6297
  if (presenter === 'chip') {
2845
6298
  return {
2846
6299
  type: 'chip',
2847
6300
  chip: {
2848
- textField: def.name,
6301
+ ...(fixedText ? { text: fixedText } : { textField: def.name }),
2849
6302
  ...(color ? { color } : {}),
2850
6303
  ...(variant ? { variant } : {}),
2851
6304
  ...(icon ? { icon } : {}),
@@ -2857,7 +6310,7 @@ function resolveRendererFromFieldPresentation(def) {
2857
6310
  return {
2858
6311
  type: 'badge',
2859
6312
  badge: {
2860
- textField: def.name,
6313
+ ...(fixedText ? { text: fixedText } : { textField: def.name }),
2861
6314
  ...(color ? { color } : {}),
2862
6315
  ...(variant ? { variant } : {}),
2863
6316
  ...(icon ? { icon } : {}),
@@ -2865,19 +6318,70 @@ function resolveRendererFromFieldPresentation(def) {
2865
6318
  },
2866
6319
  };
2867
6320
  }
2868
- if (presenter === 'iconvalue') {
6321
+ if (presenter === 'progress') {
6322
+ const valueExpr = `= row.${def.name.replace(/\./g, '?.')}`;
6323
+ return {
6324
+ type: 'progress',
6325
+ progress: {
6326
+ valueExpr,
6327
+ showLabel: true,
6328
+ ...(color ? { color } : {}),
6329
+ },
6330
+ };
6331
+ }
6332
+ if (presenter === 'rating') {
6333
+ const valueExpr = `= row.${def.name.replace(/\./g, '?.')}`;
6334
+ return {
6335
+ type: 'rating',
6336
+ rating: {
6337
+ valueExpr,
6338
+ max: 5,
6339
+ ...(color ? { color } : {}),
6340
+ },
6341
+ };
6342
+ }
6343
+ if (presenter === 'iconvalue' || presenter === 'text' || !presenter) {
2869
6344
  const rendererIcon = icon || firstNonEmptyString(def.icon);
2870
6345
  const affixes = resolveSemanticPresentationAffixes(presentation);
2871
6346
  const hasAffixes = !!(affixes.prefix || affixes.suffix);
2872
6347
  if (!rendererIcon && !hasAffixes)
2873
6348
  return undefined;
6349
+ if (affixes.prefix || affixes.suffix || tooltipText) {
6350
+ return {
6351
+ type: 'icon',
6352
+ icon: {
6353
+ ...(!hasAffixes && rendererIcon ? { name: rendererIcon } : {}),
6354
+ textField: def.name,
6355
+ ...(color ? { color } : {}),
6356
+ ...(tooltipText ? { ariaLabel: tooltipText } : {}),
6357
+ ...affixes,
6358
+ },
6359
+ };
6360
+ }
6361
+ if (!rendererIcon)
6362
+ return undefined;
2874
6363
  return {
2875
- type: 'icon',
2876
- icon: {
2877
- ...(rendererIcon && !hasAffixes ? { name: rendererIcon } : {}),
2878
- textField: def.name,
2879
- ...(tooltipText ? { ariaLabel: tooltipText } : {}),
2880
- ...affixes,
6364
+ type: 'compose',
6365
+ compose: {
6366
+ items: [
6367
+ {
6368
+ type: 'icon',
6369
+ icon: {
6370
+ name: rendererIcon,
6371
+ ...(color ? { color } : {}),
6372
+ ...(def.label ? { ariaLabel: def.label } : {}),
6373
+ },
6374
+ },
6375
+ {
6376
+ type: 'value',
6377
+ field: def.name,
6378
+ },
6379
+ ],
6380
+ layout: {
6381
+ direction: 'row',
6382
+ gap: 6,
6383
+ align: 'center',
6384
+ },
2881
6385
  },
2882
6386
  };
2883
6387
  }
@@ -2885,13 +6389,20 @@ function resolveRendererFromFieldPresentation(def) {
2885
6389
  }
2886
6390
  function resolveSemanticPresentationColor(tone) {
2887
6391
  const normalized = normalizePresentationToken(tone);
2888
- if (!normalized || normalized === 'neutral')
6392
+ if (normalized === 'neutral')
6393
+ return 'basic';
6394
+ if (!normalized)
2889
6395
  return undefined;
2890
- return normalized === 'danger' ? 'warn' : normalized;
6396
+ if (normalized === 'danger' || normalized === 'warning')
6397
+ return 'warn';
6398
+ return normalized;
2891
6399
  }
2892
6400
  function resolveSemanticPresentationVariant(appearance) {
2893
6401
  const normalized = normalizePresentationToken(appearance);
2894
- return normalized === 'filled' || normalized === 'outlined' || normalized === 'soft'
6402
+ return normalized === 'filled' ||
6403
+ normalized === 'outlined' ||
6404
+ normalized === 'soft' ||
6405
+ normalized === 'plain'
2895
6406
  ? normalized
2896
6407
  : undefined;
2897
6408
  }
@@ -2909,6 +6420,12 @@ function firstNonEmptyString(value) {
2909
6420
  const trimmed = value.trim();
2910
6421
  return trimmed ? trimmed : undefined;
2911
6422
  }
6423
+ function firstFiniteNumber(value) {
6424
+ if (value === null || value === undefined || value === '')
6425
+ return undefined;
6426
+ const numeric = typeof value === 'number' ? value : Number(value);
6427
+ return Number.isFinite(numeric) ? numeric : undefined;
6428
+ }
2912
6429
  function normalizePresentationToken(value) {
2913
6430
  return String(value ?? '').trim().toLowerCase().replace(/[\s_-]+/g, '');
2914
6431
  }