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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,12 @@
1
1
  import { validateRichContentDocument, isSafeRichContentClassName } from '@praxisui/rich-content';
2
2
  import { resolveColumnTypeFromFieldDefinition, deepMerge, isPraxisPresentationVisualizationTableSafe, resolveTextMaskFormatFromFieldDefinition } from '@praxisui/core/schema';
3
+ import { uiLayoutJsonIdentity, cloneBoundedUiLayoutJsonDocument, derivePageChildRuntimeId } from '@praxisui/core';
3
4
 
4
5
  const ORIGIN = '__praxisAuthoredDisabled';
5
- const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
6
+ const hasOwn$1 = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
6
7
  const isAction = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
7
8
  const hasRuntimeState = (action) => Object.keys(action).some(key => key.startsWith('__praxis'));
9
+ const isRuntimeDiscoveredOnly = (action) => Boolean(action['__praxisDiscoveredAction']) || Boolean(action['__praxisBulkSyncAction']);
8
10
  function authoredDisabled(action) {
9
11
  const origin = action[ORIGIN];
10
12
  if (isAction(origin) && typeof origin['present'] === 'boolean'
@@ -32,18 +34,30 @@ function identity(action) {
32
34
  }
33
35
  /** Projects only canonical action slots, never arbitrary business payloads or callback values. */
34
36
  function projectTableActionAuthoring(config, authored, report) {
37
+ const hasAuthoredBaseline = authored !== undefined && authored !== null;
35
38
  function actions(value, original, path) {
36
39
  if (!Array.isArray(value))
37
40
  return value;
38
- const originals = Array.isArray(original) ? original.filter(isAction) : [];
39
- return value.map((item, index) => {
40
- if (!isAction(item))
41
- return item;
41
+ const originals = Array.isArray(original)
42
+ ? original.filter((candidate) => isAction(candidate) && !isRuntimeDiscoveredOnly(candidate))
43
+ : [];
44
+ const projected = [];
45
+ value.forEach((item, index) => {
46
+ if (!isAction(item)) {
47
+ projected.push(item);
48
+ return;
49
+ }
42
50
  const key = identity(item);
43
51
  const matches = key ? originals.filter(candidate => identity(candidate) === key) : [];
44
52
  // No label matching, positional matching or guessing across duplicate identities.
45
53
  const source = matches.length === 1 && value.filter(candidate => isAction(candidate) && identity(candidate) === key).length === 1
46
54
  ? matches[0] : undefined;
55
+ const isRuntimeSynthesizedOnly = Boolean(item['__praxisDiscoveredAction']) ||
56
+ Boolean(item['__praxisBulkSyncAction']) ||
57
+ (hasAuthoredBaseline && Boolean(item['__praxisCollectionCreateAction']));
58
+ if (isRuntimeSynthesizedOnly && !source) {
59
+ return;
60
+ }
47
61
  const result = { ...item };
48
62
  if (hasRuntimeState(item)) {
49
63
  const origin = source && !hasRuntimeState(source) ? authoredDisabled(source) : authoredDisabled(item);
@@ -61,16 +75,17 @@ function projectTableActionAuthoring(config, authored, report) {
61
75
  if (name.startsWith('__praxis'))
62
76
  delete result[name];
63
77
  }
64
- if (hasOwn(item, 'children'))
78
+ if (hasOwn$1(item, 'children'))
65
79
  result['children'] = actions(item['children'], source?.['children'], `${path}[${index}].children`);
66
- return result;
80
+ projected.push(result);
67
81
  });
82
+ return projected;
68
83
  }
69
84
  const result = { ...config };
70
85
  if (config?.toolbar)
71
86
  result.toolbar = {
72
87
  ...config.toolbar,
73
- ...(hasOwn(config.toolbar, 'actions') ? { actions: actions(config.toolbar.actions, authored?.toolbar?.actions, 'config.toolbar.actions') } : {}),
88
+ ...(hasOwn$1(config.toolbar, 'actions') ? { actions: actions(config.toolbar.actions, authored?.toolbar?.actions, 'config.toolbar.actions') } : {}),
74
89
  };
75
90
  if (config?.actions) {
76
91
  result.actions = { ...config.actions };
@@ -79,7 +94,7 @@ function projectTableActionAuthoring(config, authored, report) {
79
94
  if (group)
80
95
  result.actions[slot] = {
81
96
  ...group,
82
- ...(hasOwn(group, 'actions') ? { actions: actions(group.actions, authored?.actions?.[slot]?.actions, `config.actions.${slot}.actions`) } : {}),
97
+ ...(hasOwn$1(group, 'actions') ? { actions: actions(group.actions, authored?.actions?.[slot]?.actions, `config.actions.${slot}.actions`) } : {}),
83
98
  };
84
99
  }
85
100
  }
@@ -295,7 +310,7 @@ function tableDetailAuthoringIssues(config) {
295
310
  || (detail.presentation?.initiallyCollapsed !== undefined && typeof detail.presentation.initiallyCollapsed !== 'boolean')
296
311
  || (detail.presentation?.bottomStackPosition !== undefined && !['beforeControls', 'afterControls'].includes(detail.presentation.bottomStackPosition))
297
312
  || (detail.presentation?.emptyBehavior !== undefined && !['message', 'hide'].includes(detail.presentation.emptyBehavior))
298
- || (detail.source?.mode !== undefined && !['inline', 'resource', 'resourcePath', 'hypermedia'].includes(detail.source.mode))
313
+ || (detail.source?.mode !== undefined && !['inline', 'resource', 'resourcePath', 'hypermedia', 'schema'].includes(detail.source.mode))
299
314
  || (detail.source?.inlineSchema !== undefined && !isObject(detail.source.inlineSchema))
300
315
  || (detail.source?.inlineSchema?.items !== undefined && !Array.isArray(detail.source.inlineSchema.items))
301
316
  || (resource !== undefined && !isObject(resource))
@@ -389,8 +404,197 @@ function inspectInlineDetailSchema(schema, config) {
389
404
  Object.values(node).forEach(visit);
390
405
  };
391
406
  visit(schema);
407
+ const offContract = hasOffContractRichChildren([schema]);
408
+ if (offContract.cardGrid)
409
+ issues.push('cardGridContent');
410
+ if (offContract.compose)
411
+ issues.push('composeContent');
392
412
  return issues;
393
413
  }
414
+ /** Rich node types accepted as `cardGrid` card content by the canonical `TableDetailCardGridCardNode` contract. */
415
+ const TABLE_DETAIL_CARD_GRID_PRESENTER_TYPES = new Set([
416
+ 'text', 'icon', 'image', 'badge', 'avatar', 'metric', 'progress', 'progressBar',
417
+ 'microVisualization', 'link', 'chip', 'button', 'rating',
418
+ ]);
419
+ /** `RichComposeNode.items` accepts presenters only (no nested compose). */
420
+ function isTableDetailComposeItemNode(node) {
421
+ if (!node || typeof node !== 'object' || Array.isArray(node))
422
+ return false;
423
+ return TABLE_DETAIL_CARD_GRID_PRESENTER_TYPES.has(String(node['type'] || '').trim());
424
+ }
425
+ function isTableDetailCardGridContentNode(node) {
426
+ if (!node || typeof node !== 'object' || Array.isArray(node))
427
+ return false;
428
+ const type = String(node['type'] || '').trim();
429
+ return type === 'compose' || TABLE_DETAIL_CARD_GRID_PRESENTER_TYPES.has(type);
430
+ }
431
+ /**
432
+ * Projects an authored node into canonical `cardGrid` card content (`RichPresenterNode | RichComposeNode`).
433
+ * Table-detail `value` fields become `metric` (labelled) or `text` presenters; structural blocks that
434
+ * cannot live inside a rich card (stack, tabs, card, timeline, chartRef, richContent) return `null`.
435
+ */
436
+ function toTableDetailCardGridContentNode(node) {
437
+ if (isTableDetailCardGridContentNode(node))
438
+ return node;
439
+ const type = String(node?.['type'] || '').trim();
440
+ if (type === 'cardGrid') {
441
+ const firstCard = Array.isArray(node['cards']) ? node['cards'][0] : undefined;
442
+ const firstList = Array.isArray(firstCard?.content)
443
+ ? firstCard.content
444
+ : Array.isArray(firstCard?.items)
445
+ ? firstCard.items
446
+ : undefined;
447
+ const first = firstList?.[0];
448
+ return first ? toTableDetailCardGridContentNode(structuredClone(first)) : null;
449
+ }
450
+ if (type !== 'value')
451
+ return null;
452
+ const field = String(node['field'] || node['valueField'] || '').trim();
453
+ const authoredExpr = typeof node['valueExpr'] === 'string' ? node['valueExpr'].trim().replace(/^=\s*/, '') : '';
454
+ const valueExpr = authoredExpr || (field ? `row.${field}` : '');
455
+ const label = typeof node['label'] === 'string' && node['label'].trim()
456
+ ? node['label'].trim()
457
+ : typeof node['title'] === 'string' && node['title'].trim()
458
+ ? node['title'].trim()
459
+ : '';
460
+ if (valueExpr) {
461
+ return {
462
+ ...(node['id'] ? { id: node['id'] } : {}),
463
+ ...(label ? { type: 'metric', label, valueExpr } : { type: 'text', textExpr: valueExpr }),
464
+ ...(node['visibleWhen'] !== undefined && node['visibleWhen'] !== null ? { visibleWhen: node['visibleWhen'] } : {}),
465
+ };
466
+ }
467
+ if (Object.prototype.hasOwnProperty.call(node, 'value') && node['value'] !== undefined && node['value'] !== null) {
468
+ const literalText = String(node['value']);
469
+ if (label) {
470
+ return {
471
+ type: 'compose',
472
+ ...(node['id'] ? { id: node['id'] } : {}),
473
+ className: 'pfx-expansion-node pfx-expansion-node-value',
474
+ direction: 'column',
475
+ gap: 'xs',
476
+ items: [
477
+ { type: 'text', className: 'pfx-expansion-node-value__label', text: label },
478
+ { type: 'text', className: 'pfx-expansion-node-value__content', text: literalText },
479
+ ],
480
+ ...(node['visibleWhen'] !== undefined && node['visibleWhen'] !== null ? { visibleWhen: node['visibleWhen'] } : {}),
481
+ };
482
+ }
483
+ return {
484
+ type: 'text',
485
+ ...(node['id'] ? { id: node['id'] } : {}),
486
+ text: literalText,
487
+ ...(node['visibleWhen'] !== undefined && node['visibleWhen'] !== null ? { visibleWhen: node['visibleWhen'] } : {}),
488
+ };
489
+ }
490
+ return null;
491
+ }
492
+ /** Projects an authored node into a canonical compose item (presenter); a compose result yields its first presenter. */
493
+ function toTableDetailComposeItemNode(node) {
494
+ if (node &&
495
+ typeof node === 'object' &&
496
+ node['type'] === 'value' &&
497
+ !node['field'] &&
498
+ !node['valueField'] &&
499
+ !node['valueExpr'] &&
500
+ Object.prototype.hasOwnProperty.call(node, 'value') &&
501
+ node['value'] !== undefined &&
502
+ node['value'] !== null) {
503
+ const label = typeof node['label'] === 'string' && node['label'].trim()
504
+ ? node['label'].trim()
505
+ : typeof node['title'] === 'string' && node['title'].trim()
506
+ ? node['title'].trim()
507
+ : '';
508
+ return {
509
+ type: 'text',
510
+ ...(node['id'] ? { id: node['id'] } : {}),
511
+ text: label ? `${label}: ${String(node['value'])}` : String(node['value']),
512
+ ...(node['visibleWhen'] !== undefined && node['visibleWhen'] !== null ? { visibleWhen: node['visibleWhen'] } : {}),
513
+ };
514
+ }
515
+ const projected = toTableDetailCardGridContentNode(node);
516
+ if (!projected)
517
+ return null;
518
+ if (projected['type'] !== 'compose')
519
+ return projected;
520
+ const first = Array.isArray(projected['items'])
521
+ ? projected['items'].find((item) => isTableDetailComposeItemNode(item))
522
+ : undefined;
523
+ return first ? structuredClone(first) : null;
524
+ }
525
+ /** True when a cardGrid card or a compose (outside richContent documents) holds off-contract children. */
526
+ function hasOffContractRichChildren(nodes) {
527
+ const result = { cardGrid: false, compose: false };
528
+ const visit = (value) => {
529
+ if (!Array.isArray(value))
530
+ return;
531
+ for (const node of value) {
532
+ if (!node || typeof node !== 'object' || Array.isArray(node))
533
+ continue;
534
+ const record = node;
535
+ if (record['type'] === 'richContent')
536
+ continue;
537
+ if (record['type'] === 'cardGrid' && Array.isArray(record['cards'])) {
538
+ for (const card of record['cards']) {
539
+ const content = Array.isArray(card?.['content']) ? card?.['content'] : card?.['items'];
540
+ if (Array.isArray(content) && content.some((item) => !isTableDetailCardGridContentNode(item))) {
541
+ result.cardGrid = true;
542
+ }
543
+ }
544
+ }
545
+ if (record['type'] === 'compose' && Array.isArray(record['items'])
546
+ && record['items'].some((item) => !isTableDetailComposeItemNode(item))) {
547
+ result.compose = true;
548
+ }
549
+ visit(record['items']);
550
+ visit(record['content']);
551
+ visit(record['cards']);
552
+ }
553
+ };
554
+ visit(nodes);
555
+ return result;
556
+ }
557
+ /**
558
+ * Losslessly rewrites legacy table-detail `value` fields that sit inside cardGrid cards or compose items
559
+ * into canonical presenters. Structural blocks are left untouched (still reported) to avoid data loss.
560
+ * Returns the number of rewritten nodes.
561
+ */
562
+ function normalizeTableDetailRichChildren(schema) {
563
+ let rewritten = 0;
564
+ const rewrite = (list, project, accepts) => {
565
+ if (!Array.isArray(list))
566
+ return;
567
+ list.forEach((item, index) => {
568
+ if (accepts(item) || item?.['type'] !== 'value')
569
+ return;
570
+ const projected = project(item);
571
+ if (projected) {
572
+ list[index] = projected;
573
+ rewritten += 1;
574
+ }
575
+ });
576
+ };
577
+ const visit = (value) => {
578
+ if (!Array.isArray(value))
579
+ return;
580
+ for (const node of value) {
581
+ if (!node || typeof node !== 'object' || Array.isArray(node) || node['type'] === 'richContent')
582
+ continue;
583
+ if (node['type'] === 'cardGrid' && Array.isArray(node['cards'])) {
584
+ for (const card of node['cards']) {
585
+ rewrite(Array.isArray(card?.['content']) ? card?.['content'] : card?.['items'], toTableDetailCardGridContentNode, isTableDetailCardGridContentNode);
586
+ }
587
+ }
588
+ if (node['type'] === 'compose')
589
+ rewrite(node['items'], toTableDetailComposeItemNode, isTableDetailComposeItemNode);
590
+ visit(node['items']);
591
+ visit(node['content']);
592
+ visit(node['cards']);
593
+ }
594
+ };
595
+ visit([schema]);
596
+ return rewritten;
597
+ }
394
598
  /** Edits the original authoring tree; keys exist only in the editor's WeakMap. */
395
599
  class TableDetailTreeDraft {
396
600
  keys = new WeakMap();
@@ -449,17 +653,71 @@ class TableDetailTreeDraft {
449
653
  entry.siblings.splice(next, 0, entry.node);
450
654
  }
451
655
  add(node, nested = false) {
452
- const selected = this.selected()?.node;
453
- const childKey = selected?.type === 'card' || selected?.type === 'tab' ? 'content' : 'items';
656
+ const selectedEntry = this.selected();
657
+ const selected = selectedEntry?.node;
658
+ const isCardLike = selected?.type === 'card' || (!selected?.type && (Array.isArray(selected?.content) || Array.isArray(selected?.items)));
659
+ // Cards stored in `cardGrid.cards` follow TableDetailCardGridCardNode: rich presenters/compose only.
660
+ const isCardGridCard = !!selectedEntry && isCardLike && this.entries().some((entry) => entry.node['type'] === 'cardGrid' && entry.node['cards'] === selectedEntry.siblings);
661
+ const childKey = selected?.type === 'cardGrid'
662
+ ? 'cards'
663
+ : (isCardLike || selected?.type === 'tab')
664
+ ? (!Array.isArray(selected?.content) && Array.isArray(selected?.items) ? 'items' : 'content')
665
+ : 'items';
454
666
  const parent = nested && selected ? selected : this.schema;
455
667
  const key = nested && selected ? childKey : 'items';
456
668
  if (!nested && this.schema.layout === 'tabs' && node.type !== 'tab') {
457
669
  node = { type: 'tab', title: node.title || node.label || node.type, content: [node] };
458
670
  }
671
+ else if (nested && selected?.type === 'cardGrid') {
672
+ if (node.type === 'cardGrid' && Array.isArray(node.cards) && node.cards.length > 0) {
673
+ node = structuredClone(node.cards[0]);
674
+ }
675
+ else if (node.type === 'card') {
676
+ const rawCardChildren = Array.isArray(node.content) ? node.content : Array.isArray(node.items) ? node.items : [];
677
+ const content = rawCardChildren
678
+ .map((child) => toTableDetailCardGridContentNode(child))
679
+ .filter((child) => !!child);
680
+ node = {
681
+ ...(node.id ? { id: node.id } : {}),
682
+ title: node.title ?? '',
683
+ ...(node.subtitle !== undefined ? { subtitle: node.subtitle } : {}),
684
+ content: content.length ? content : [{ type: 'text', text: node.title || 'Detalhe' }],
685
+ };
686
+ }
687
+ else if (!Array.isArray(node.content) && !Array.isArray(node.items)) {
688
+ const content = toTableDetailCardGridContentNode(node);
689
+ if (!content)
690
+ return null;
691
+ node = {
692
+ title: node.title || node.label || '',
693
+ content: [content],
694
+ };
695
+ }
696
+ }
697
+ else if (nested && isCardGridCard) {
698
+ const content = toTableDetailCardGridContentNode(node);
699
+ if (!content)
700
+ return null;
701
+ node = content;
702
+ }
703
+ else if (nested && selected?.type === 'compose') {
704
+ // RichComposeNode.items accepts presenters only; the runtime drops anything else silently.
705
+ const item = toTableDetailComposeItemNode(node);
706
+ if (!item)
707
+ return null;
708
+ node = item;
709
+ }
710
+ else if (nested && isCardLike && node.type === 'cardGrid' && Array.isArray(node.cards)) {
711
+ const firstCardContent = node.cards[0]?.content ?? node.cards[0]?.items;
712
+ if (Array.isArray(firstCardContent) && firstCardContent.length > 0) {
713
+ node = structuredClone(firstCardContent[0]);
714
+ }
715
+ }
459
716
  if (!Array.isArray(parent[key]))
460
717
  parent[key] = [];
461
718
  parent[key].push(node);
462
719
  this.selectedKey = this.entries().find(entry => entry.node === node)?.key ?? null;
720
+ return node;
463
721
  }
464
722
  }
465
723
 
@@ -546,7 +804,7 @@ function validateTableAuthoringDocument(doc, context) {
546
804
  }
547
805
  const rawColumns = Array.isArray(rawConfig.columns)
548
806
  ? rawConfig.columns
549
- : normalized.config.columns;
807
+ : (normalized.config.columns || []);
550
808
  const columnFields = new Set();
551
809
  rawColumns.forEach((column, index) => {
552
810
  const field = trimString(column?.field);
@@ -916,13 +1174,15 @@ function infoDiagnostic(code, message, path) {
916
1174
  class TableSchemaColumnProjector {
917
1175
  convertFieldToColumn(field) {
918
1176
  const apiType = resolveColumnTypeFromFieldDefinition(field, this.inferFieldTypeFromFieldName(field.name));
1177
+ const sticky = field.pinned ?? field.sticky;
919
1178
  const col = {
920
1179
  field: field.name,
921
1180
  header: field.label ?? field.name,
922
- order: field.order,
1181
+ order: field.tableOrder ?? field.order,
923
1182
  width: field.width ?? undefined,
924
1183
  sortable: field.sortable,
925
1184
  visible: field.tableHidden || field.hidden ? false : true,
1185
+ ...(sticky === 'start' || sticky === 'end' || sticky === true ? { sticky } : {}),
926
1186
  type: apiType,
927
1187
  _originalApiType: apiType,
928
1188
  _isApiField: true,
@@ -946,26 +1206,40 @@ class TableSchemaColumnProjector {
946
1206
  const includeOrder = new Map(include.map((field, index) => [field, index]));
947
1207
  const order = Array.isArray(projection?.order) ? projection.order : include;
948
1208
  const presentationOrder = new Map(order.map((field, index) => [field, index]));
1209
+ const fieldsByName = new Map();
1210
+ for (const field of Array.isArray(fields) ? fields : []) {
1211
+ const name = typeof field?.name === 'string' ? field.name.trim() : '';
1212
+ if (name)
1213
+ fieldsByName.set(name, field);
1214
+ }
949
1215
  const schemaColumns = (Array.isArray(fields) ? fields : [])
950
1216
  .filter((field) => !field.tableHidden && !field.hidden)
951
1217
  .filter((field) => include.length === 0 || includeOrder.has(field.name))
952
1218
  .sort((left, right) => {
953
- return (presentationOrder.get(left.name) ?? Number.MAX_SAFE_INTEGER)
1219
+ const orderDiff = (presentationOrder.get(left.name) ?? Number.MAX_SAFE_INTEGER)
954
1220
  - (presentationOrder.get(right.name) ?? Number.MAX_SAFE_INTEGER);
1221
+ if (orderDiff !== 0) {
1222
+ return orderDiff;
1223
+ }
1224
+ return (left.tableOrder ?? left.order ?? Number.MAX_SAFE_INTEGER)
1225
+ - (right.tableOrder ?? right.order ?? Number.MAX_SAFE_INTEGER);
955
1226
  })
956
1227
  .map((field) => {
957
1228
  const base = this.convertFieldToColumn(field);
958
1229
  const override = overrides[field.name];
959
1230
  if (!override || typeof override !== 'object' || Array.isArray(override)) {
1231
+ this.applySchemaComposeItemsQuickView(base, fieldsByName);
960
1232
  return base;
961
1233
  }
962
1234
  const merged = deepMerge(base, override);
963
- return {
1235
+ const projected = {
964
1236
  ...merged,
965
1237
  field: base.field,
966
1238
  _isApiField: base._isApiField,
967
1239
  _originalApiType: base._originalApiType,
968
1240
  };
1241
+ this.applySchemaComposeItemsQuickView(projected, fieldsByName);
1242
+ return projected;
969
1243
  });
970
1244
  const canonicalFields = new Set((Array.isArray(fields) ? fields : [])
971
1245
  .map((field) => String(field?.name || '').trim())
@@ -982,82 +1256,129 @@ class TableSchemaColumnProjector {
982
1256
  // It never admits hidden fields, overrides field identity, or selects membership.
983
1257
  const combined = [...schemaColumns, ...additions];
984
1258
  if (Array.isArray(projection?.order) && projection.order.length > 0) {
1259
+ const additionFields = new Set(additions.map((col) => col.field));
985
1260
  combined.sort((left, right) => {
986
1261
  return (presentationOrder.get(left.field) ?? Number.MAX_SAFE_INTEGER)
987
1262
  - (presentationOrder.get(right.field) ?? Number.MAX_SAFE_INTEGER);
988
1263
  });
989
- return combined.map((column) => {
990
- const explicitOrder = presentationOrder.get(column.field);
991
- return explicitOrder !== undefined ? { ...column, order: explicitOrder } : column;
1264
+ return combined.map((column, index) => {
1265
+ if (!additionFields.has(column.field) || presentationOrder.has(column.field)) {
1266
+ return { ...column, order: index };
1267
+ }
1268
+ return column;
992
1269
  });
993
1270
  }
994
1271
  return combined;
995
1272
  }
996
1273
  inferFieldTypeFromFieldName(fieldName) {
997
1274
  const lowercaseName = fieldName.toLowerCase();
998
- // Date/time patterns - more specific patterns first
1275
+ // Date/time patterns - more specific patterns first (EN + PT-BR)
999
1276
  if (lowercaseName.endsWith('date') ||
1000
1277
  lowercaseName.endsWith('time') ||
1001
1278
  lowercaseName.endsWith('at') ||
1002
1279
  lowercaseName.startsWith('date') ||
1280
+ lowercaseName.startsWith('data') ||
1281
+ lowercaseName.startsWith('dt_') ||
1282
+ lowercaseName.startsWith('dt') ||
1283
+ lowercaseName.endsWith('_em') ||
1003
1284
  lowercaseName === 'created' ||
1004
1285
  lowercaseName === 'updated' ||
1005
1286
  lowercaseName === 'modified' ||
1287
+ lowercaseName === 'nascimento' ||
1288
+ lowercaseName === 'admissao' ||
1289
+ lowercaseName === 'demissao' ||
1290
+ lowercaseName === 'vencimento' ||
1006
1291
  lowercaseName.includes('timestamp')) {
1007
1292
  return 'date';
1008
1293
  }
1009
- // Boolean patterns - most specific first to avoid conflicts
1294
+ // Boolean patterns - most specific first to avoid conflicts (EN + PT-BR)
1010
1295
  if (lowercaseName.startsWith('is_') ||
1011
1296
  lowercaseName.startsWith('has_') ||
1012
1297
  lowercaseName.startsWith('can_') ||
1013
1298
  lowercaseName.startsWith('should_') ||
1299
+ lowercaseName.startsWith('fl_') ||
1300
+ lowercaseName.startsWith('ind_') ||
1014
1301
  lowercaseName === 'active' ||
1302
+ lowercaseName === 'ativo' ||
1303
+ lowercaseName === 'inativo' ||
1015
1304
  lowercaseName === 'enabled' ||
1305
+ lowercaseName === 'habilitado' ||
1016
1306
  lowercaseName === 'visible' ||
1307
+ lowercaseName === 'visivel' ||
1017
1308
  lowercaseName === 'deleted' ||
1309
+ lowercaseName === 'excluido' ||
1018
1310
  lowercaseName === 'archived' ||
1311
+ lowercaseName === 'arquivado' ||
1019
1312
  lowercaseName.endsWith('_flag') ||
1020
1313
  lowercaseName.endsWith('_enabled') ||
1021
- lowercaseName.endsWith('_active')) {
1314
+ lowercaseName.endsWith('_active') ||
1315
+ lowercaseName.endsWith('_ativo')) {
1022
1316
  return 'boolean';
1023
1317
  }
1024
- // Currency/money patterns - exclude common false positives
1318
+ // Currency/money patterns - exclude common false positives (EN + PT-BR)
1025
1319
  if ((lowercaseName.includes('price') ||
1320
+ lowercaseName.includes('preco') ||
1026
1321
  lowercaseName.includes('amount') ||
1027
1322
  lowercaseName.includes('cost') ||
1323
+ lowercaseName.includes('custo') ||
1028
1324
  lowercaseName.includes('salary') ||
1325
+ lowercaseName.includes('salario') ||
1326
+ lowercaseName.includes('remuneracao') ||
1327
+ lowercaseName.includes('orcamento') ||
1328
+ lowercaseName.includes('indenizacao') ||
1329
+ lowercaseName.includes('multa') ||
1330
+ lowercaseName.includes('desconto') ||
1331
+ lowercaseName.includes('liquido') ||
1332
+ lowercaseName.includes('bruto') ||
1029
1333
  lowercaseName.includes('wage') ||
1030
1334
  lowercaseName.includes('fee') ||
1031
- (lowercaseName.includes('value') &&
1335
+ ((lowercaseName.includes('value') || lowercaseName.includes('valor') || lowercaseName.startsWith('vl_')) &&
1032
1336
  !lowercaseName.includes('id') &&
1033
1337
  !lowercaseName.includes('key'))) &&
1034
1338
  !lowercaseName.includes('count') &&
1035
- !lowercaseName.includes('type')) {
1339
+ !lowercaseName.includes('type') &&
1340
+ !lowercaseName.includes('tipo')) {
1036
1341
  return 'currency';
1037
1342
  }
1038
- // Percentage patterns - be more specific
1343
+ // Percentage patterns - be more specific (EN + PT-BR)
1039
1344
  if (lowercaseName.includes('percent') ||
1345
+ lowercaseName.includes('percentual') ||
1346
+ lowercaseName.includes('aliquota') ||
1347
+ lowercaseName.includes('margem') ||
1348
+ lowercaseName.startsWith('pct_') ||
1040
1349
  lowercaseName.endsWith('_rate') ||
1041
1350
  lowercaseName.endsWith('_ratio') ||
1042
1351
  lowercaseName.endsWith('_pct') ||
1043
- (lowercaseName.includes('rate') &&
1352
+ lowercaseName.endsWith('_taxa') ||
1353
+ ((lowercaseName.includes('rate') || lowercaseName.includes('taxa')) &&
1044
1354
  !lowercaseName.includes('created') &&
1045
1355
  !lowercaseName.includes('updated')) ||
1046
1356
  lowercaseName.endsWith('_score')) {
1047
1357
  return 'percentage';
1048
1358
  }
1049
- // Number patterns - exclude common false positives like string IDs
1359
+ // Number patterns - exclude common false positives like string IDs (EN + PT-BR)
1050
1360
  if ((lowercaseName.endsWith('_id') && lowercaseName !== 'id') || // composite IDs might be strings
1051
1361
  lowercaseName === 'id' ||
1052
1362
  lowercaseName.includes('count') ||
1053
1363
  lowercaseName.includes('quantity') ||
1364
+ lowercaseName.includes('quantidade') ||
1365
+ lowercaseName.includes('qtd') ||
1054
1366
  lowercaseName.includes('number') ||
1367
+ lowercaseName.includes('numero') ||
1055
1368
  lowercaseName.includes('total') ||
1056
1369
  lowercaseName.includes('sum') ||
1370
+ lowercaseName.includes('soma') ||
1057
1371
  lowercaseName.includes('age') ||
1372
+ lowercaseName.includes('idade') ||
1058
1373
  lowercaseName.includes('weight') ||
1374
+ lowercaseName.includes('peso') ||
1059
1375
  lowercaseName.includes('height') ||
1376
+ lowercaseName.includes('altura') ||
1060
1377
  lowercaseName.includes('size') ||
1378
+ lowercaseName.includes('tamanho') ||
1379
+ lowercaseName.includes('pontuacao') ||
1380
+ lowercaseName.includes('score') ||
1381
+ lowercaseName.includes('nota') ||
1061
1382
  lowercaseName.endsWith('_num') ||
1062
1383
  lowercaseName.endsWith('_number')) {
1063
1384
  return 'number';
@@ -1065,32 +1386,66 @@ class TableSchemaColumnProjector {
1065
1386
  // Default to string for ambiguous cases
1066
1387
  return 'string';
1067
1388
  }
1389
+ applySchemaComposeItemsQuickView(col, fieldsByName) {
1390
+ const renderer = col?.renderer;
1391
+ if (renderer?.type !== 'compose' || !Array.isArray(renderer?.compose?.items)) {
1392
+ return;
1393
+ }
1394
+ for (const item of renderer.compose.items) {
1395
+ if (!item || typeof item !== 'object')
1396
+ continue;
1397
+ const itemType = typeof item.type === 'string' ? item.type.trim() : 'value';
1398
+ if (itemType !== 'value' || item.quickView !== undefined)
1399
+ continue;
1400
+ const itemFieldName = typeof item.field === 'string' ? item.field.trim() : '';
1401
+ if (!itemFieldName)
1402
+ continue;
1403
+ const itemField = fieldsByName.get(itemFieldName);
1404
+ if (itemField?.quickView) {
1405
+ item.quickView = this.clonePlainObject(itemField.quickView);
1406
+ }
1407
+ }
1408
+ }
1068
1409
  applySchemaFieldPresentation(field, col) {
1069
1410
  if (!field || !col)
1070
1411
  return;
1412
+ if (field.quickView && !col.quickView) {
1413
+ col.quickView = this.clonePlainObject(field.quickView);
1414
+ }
1071
1415
  const controlType = this.normalizePresentationToken(field.controlType);
1072
1416
  const numericFormat = this.normalizePresentationToken(field.numericFormat ?? field.format);
1073
1417
  const valuePresentationType = this.normalizePresentationToken(field.valuePresentation?.type);
1074
1418
  const displayFormat = this.firstNonEmptyString(field.displayFormat, field.extraProperties?.displayFormat);
1075
1419
  const valueMapping = this.resolveSchemaValueMapping(field);
1076
- if (valueMapping) {
1420
+ if (valueMapping && (!col.valueMapping || Object.keys(col.valueMapping).length === 0)) {
1077
1421
  col.valueMapping = valueMapping;
1078
1422
  }
1079
1423
  const presentation = field.presentation;
1080
- if (presentation?.presenter === 'microVisualization' &&
1081
- isPraxisPresentationVisualizationTableSafe(presentation?.visualization)) {
1424
+ const resolvedMicroViz = presentation?.presenter === 'microVisualization' &&
1425
+ isPraxisPresentationVisualizationTableSafe(presentation?.visualization)
1426
+ ? presentation.visualization
1427
+ : isPraxisPresentationVisualizationTableSafe(field.microVisualization)
1428
+ ? field.microVisualization
1429
+ : null;
1430
+ if (resolvedMicroViz && !col.renderer?.type) {
1082
1431
  col.renderer = {
1083
1432
  ...(col.renderer || {}),
1084
1433
  type: 'microVisualization',
1085
1434
  microVisualization: {
1086
- visualization: presentation.visualization,
1435
+ visualization: resolvedMicroViz,
1087
1436
  },
1088
1437
  };
1089
1438
  }
1439
+ if (col.sticky === undefined && (field.pinned === 'start' || field.pinned === 'end')) {
1440
+ col.sticky = field.pinned;
1441
+ }
1090
1442
  this.applySchemaSemanticCellPresentation(field, col, presentation);
1091
1443
  if (numericFormat === 'currency' || controlType === 'currency' || col.type === 'currency') {
1444
+ const wasCurrency = col.type === 'currency';
1092
1445
  col.type = 'currency';
1093
- col.format = this.resolveSchemaCurrencyFormat(field);
1446
+ if (!col.format || (!wasCurrency && !String(col.format).includes('|'))) {
1447
+ col.format = this.resolveSchemaCurrencyFormat(field);
1448
+ }
1094
1449
  return;
1095
1450
  }
1096
1451
  if (numericFormat === 'date' ||
@@ -1103,13 +1458,29 @@ class TableSchemaColumnProjector {
1103
1458
  controlType === 'date' ||
1104
1459
  controlType === 'datetime') {
1105
1460
  col.type = 'date';
1106
- col.format = displayFormat || (numericFormat === 'datetime' ||
1107
- valuePresentationType === 'datetime' ||
1108
- controlType === 'datetimepicker' ||
1109
- controlType === 'datetimelocal' ||
1110
- controlType === 'datetime'
1111
- ? 'dd/MM/yyyy HH:mm'
1112
- : 'dd/MM/yyyy');
1461
+ if (!col.format) {
1462
+ col.format = displayFormat || (numericFormat === 'datetime' ||
1463
+ valuePresentationType === 'datetime' ||
1464
+ controlType === 'datetimepicker' ||
1465
+ controlType === 'datetimelocal' ||
1466
+ controlType === 'datetime'
1467
+ ? 'dd/MM/yyyy HH:mm'
1468
+ : 'dd/MM/yyyy');
1469
+ }
1470
+ return;
1471
+ }
1472
+ if (numericFormat === 'percent' ||
1473
+ numericFormat === 'percentage' ||
1474
+ numericFormat === 'fraction' ||
1475
+ valuePresentationType === 'percent' ||
1476
+ valuePresentationType === 'percentage' ||
1477
+ col.type === 'percentage') {
1478
+ col.type = 'percentage';
1479
+ if (!col.format) {
1480
+ col.format =
1481
+ displayFormat ||
1482
+ (numericFormat === 'fraction' ? '1.0-2|x100' : '1.0-2|raw');
1483
+ }
1113
1484
  return;
1114
1485
  }
1115
1486
  if (col.type === 'boolean' && !col.format) {
@@ -1117,10 +1488,26 @@ class TableSchemaColumnProjector {
1117
1488
  }
1118
1489
  const schemaDataType = this.normalizePresentationToken(field.type);
1119
1490
  const schemaFormat = this.normalizePresentationToken(field.format);
1120
- if (col.type === 'number' &&
1121
- !col.format &&
1122
- (schemaDataType === 'integer' || schemaFormat === 'int32' || schemaFormat === 'int64')) {
1123
- col.format = '1.0-0';
1491
+ if (col.type === 'number' && !col.format) {
1492
+ if (displayFormat) {
1493
+ col.format = displayFormat;
1494
+ }
1495
+ else if (schemaDataType === 'integer' ||
1496
+ schemaFormat === 'integer' ||
1497
+ schemaFormat === 'int32' ||
1498
+ schemaFormat === 'int64' ||
1499
+ numericFormat === 'integer' ||
1500
+ numericFormat === 'int32' ||
1501
+ numericFormat === 'int64') {
1502
+ col.format = '1.0-0';
1503
+ }
1504
+ else {
1505
+ const explicitDecimals = this.firstFiniteNumber(field.decimalPlaces, field.extraProperties?.decimalPlaces);
1506
+ if (explicitDecimals !== undefined && explicitDecimals >= 0) {
1507
+ const decimals = Math.trunc(explicitDecimals);
1508
+ col.format = `1.${decimals}-${decimals}`;
1509
+ }
1510
+ }
1124
1511
  }
1125
1512
  const textMaskFormat = resolveTextMaskFormatFromFieldDefinition(field);
1126
1513
  const maskResolvedType = resolveColumnTypeFromFieldDefinition(field, col.type);
@@ -1137,22 +1524,24 @@ class TableSchemaColumnProjector {
1137
1524
  return;
1138
1525
  const ctl = (field.controlType || '').toString().trim().toLowerCase();
1139
1526
  const fname = (field.name || '').toString();
1140
- const lname = fname.toLowerCase();
1141
1527
  const isAvatarByControl = ctl === 'avatar';
1142
1528
  if (isAvatarByControl) {
1529
+ const initialsField = this.firstNonEmptyString(field.initialsField, field.extraProperties?.initialsField) || 'nomeCompleto';
1143
1530
  col.renderer = {
1144
1531
  type: 'avatar',
1145
1532
  avatar: {
1146
1533
  srcField: fname,
1147
- initialsField: 'nomeCompleto',
1534
+ initialsField,
1148
1535
  shape: 'circle',
1149
1536
  size: 32,
1150
1537
  },
1151
1538
  };
1152
- // Sensible defaults for avatar column
1539
+ // Sensible defaults for avatar column (84px prevents header truncation when centered with sort/resize gutters; not sortable by default)
1153
1540
  col.align = col.align || 'center';
1541
+ if (col.sortable === undefined)
1542
+ col.sortable = false;
1154
1543
  if (!col.width)
1155
- col.width = '56px';
1544
+ col.width = '84px';
1156
1545
  return;
1157
1546
  }
1158
1547
  }
@@ -1243,7 +1632,31 @@ class TableSchemaColumnProjector {
1243
1632
  };
1244
1633
  return;
1245
1634
  }
1246
- if (presenter === 'iconvalue') {
1635
+ if (presenter === 'progress') {
1636
+ const valueExpr = `= row.${textField.replace(/\./g, '?.')}`;
1637
+ col.renderer = {
1638
+ type: 'progress',
1639
+ progress: {
1640
+ valueExpr,
1641
+ showLabel: true,
1642
+ ...(color ? { color } : {}),
1643
+ },
1644
+ };
1645
+ return;
1646
+ }
1647
+ if (presenter === 'rating') {
1648
+ const valueExpr = `= row.${textField.replace(/\./g, '?.')}`;
1649
+ col.renderer = {
1650
+ type: 'rating',
1651
+ rating: {
1652
+ valueExpr,
1653
+ max: 5,
1654
+ ...(color ? { color } : {}),
1655
+ },
1656
+ };
1657
+ return;
1658
+ }
1659
+ if (presenter === 'iconvalue' || presenter === 'text' || !presenter) {
1247
1660
  const rendererIcon = icon || this.firstNonEmptyString(field.icon);
1248
1661
  const affixes = this.resolveSemanticPresentationAffixes(presentation);
1249
1662
  const hasAffixes = !!(affixes.prefix || affixes.suffix);
@@ -1255,6 +1668,7 @@ class TableSchemaColumnProjector {
1255
1668
  icon: {
1256
1669
  ...(!hasAffixes && rendererIcon ? { name: rendererIcon } : {}),
1257
1670
  textField,
1671
+ ...(color ? { color } : {}),
1258
1672
  ...(tooltipText ? { ariaLabel: tooltipText } : {}),
1259
1673
  ...affixes,
1260
1674
  },
@@ -1298,6 +1712,19 @@ class TableSchemaColumnProjector {
1298
1712
  const explicit = this.firstNonEmptyString(field.booleanFormat, field.extraProperties?.booleanFormat);
1299
1713
  if (explicit)
1300
1714
  return explicit;
1715
+ const trueLabel = this.firstNonEmptyString(field.trueLabel, field.labelTrue, field.presentation?.labelTrue, field.extraProperties?.trueLabel, field.extraProperties?.labelTrue);
1716
+ const falseLabel = this.firstNonEmptyString(field.falseLabel, field.labelFalse, field.presentation?.labelFalse, field.extraProperties?.falseLabel, field.extraProperties?.labelFalse);
1717
+ if (trueLabel || falseLabel) {
1718
+ const effectiveTrue = trueLabel || 'Sim';
1719
+ const effectiveFalse = falseLabel || 'Não';
1720
+ const tNorm = this.normalizePresentationToken(effectiveTrue);
1721
+ const fNorm = this.normalizePresentationToken(effectiveFalse);
1722
+ if (tNorm === 'ativo' && fNorm === 'inativo')
1723
+ return 'active-inactive';
1724
+ if (tNorm === 'sim' && (fNorm === 'nao' || fNorm === 'não'))
1725
+ return 'yes-no';
1726
+ return `custom|${effectiveTrue}|${effectiveFalse}`;
1727
+ }
1301
1728
  const name = this.normalizePresentationToken(field.name);
1302
1729
  if (name === 'ativo' || name === 'active' || name.endsWith('ativo')) {
1303
1730
  return 'active-inactive';
@@ -1456,8 +1883,382 @@ function deriveTableEditorDocument(input) {
1456
1883
  });
1457
1884
  }
1458
1885
 
1886
+ /** Shared presentation ordering; hidden columns must not shift visible fallback positions. */
1887
+ function orderTableColumns(columns) {
1888
+ if (!columns.some(column => Number.isFinite(column.order)))
1889
+ return [...columns];
1890
+ let visibleIndex = 0;
1891
+ return columns.map((column, originalIndex) => {
1892
+ const fallback = column.visible === false ? originalIndex : visibleIndex++;
1893
+ return { column, originalIndex, explicit: Number.isFinite(column.order), order: Number.isFinite(column.order) ? Number(column.order) : fallback };
1894
+ }).sort((left, right) => left.order - right.order
1895
+ || Number(right.explicit) - Number(left.explicit)
1896
+ || left.originalIndex - right.originalIndex).map(entry => entry.column);
1897
+ }
1898
+
1899
+ const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
1900
+ /** Preserve authored values; runtime/schema defaults remain transient unless explicitly edited. */
1901
+ function applyTableAuthoringChanges(authored, baseline, edited) {
1902
+ return projectChanges(authored, baseline, edited, true);
1903
+ }
1904
+ function projectChanges(authored, baseline, edited, tableConfigRoot) {
1905
+ if (sameAuthoringValue(baseline, edited))
1906
+ return authored;
1907
+ if (!edited || typeof edited !== 'object' || Array.isArray(edited))
1908
+ return edited;
1909
+ const original = authored && typeof authored === 'object' ? authored : {};
1910
+ const before = baseline && typeof baseline === 'object' ? baseline : {};
1911
+ const after = edited;
1912
+ const result = { ...original };
1913
+ for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {
1914
+ if (sameAuthoringValue(before[key], after[key]))
1915
+ continue;
1916
+ if (!hasOwn(after, key))
1917
+ delete result[key];
1918
+ else
1919
+ Object.defineProperty(result, key, {
1920
+ value: projectChanges(hasOwn(original, key) ? original[key] : undefined, hasOwn(before, key) ? before[key] : undefined, after[key], false),
1921
+ enumerable: true, configurable: true, writable: true,
1922
+ });
1923
+ }
1924
+ if (tableConfigRoot && isRecord(original['columnProjection']) && original['columnProjection']['source'] === 'schema'
1925
+ && isRecord(result['columnProjection']) && result['columnProjection']['source'] === 'schema'
1926
+ && Array.isArray(after['columns']) && JSON.stringify(before['columns']) !== JSON.stringify(after['columns'])) {
1927
+ result['columns'] = [];
1928
+ result['columnProjection'] = projectSchemaColumnChanges(result['columnProjection'], before['columns'], after['columns'], isRecord(before['columnProjection']) ? before['columnProjection'] : original['columnProjection'], after['columnProjection']);
1929
+ }
1930
+ return result;
1931
+ }
1932
+ /** Write the existing compact schema projection, never a partial columns snapshot. */
1933
+ function projectSchemaColumnChanges(authored, baseline, edited, baselineProjection, editedProjection) {
1934
+ if (!isRecord(authored) || authored['source'] !== 'schema') {
1935
+ throw new Error('Table schema authorship requires its canonical columnProjection.');
1936
+ }
1937
+ const projection = structuredClone(authored);
1938
+ const overrides = Object.assign(Object.create(null), isRecord(projection['overrides']) ? projection['overrides'] : {});
1939
+ const additions = columnsByField(Array.isArray(projection['additions']) ? projection['additions'] : []);
1940
+ const before = columnsByField(Array.isArray(baseline) ? baseline : []);
1941
+ const after = columnsByField(edited);
1942
+ const nextAdditions = [...additions].filter(([field]) => !before.has(field) && !after.has(field))
1943
+ .map(([, column]) => structuredClone(column));
1944
+ for (const [field, column] of after) {
1945
+ if (additions.has(field) || !before.has(field)) {
1946
+ nextAdditions.push(structuredClone(column));
1947
+ continue;
1948
+ }
1949
+ const previousOverride = isRecord(overrides[field]) ? overrides[field] : {};
1950
+ if (hasOwn(previousOverride, 'field')) {
1951
+ throw new Error('Table schema overrides cannot replace canonical field identity.');
1952
+ }
1953
+ const projected = projectChanges({ field, ...previousOverride }, before.get(field), column, false);
1954
+ const override = isRecord(projected) ? { ...projected } : {};
1955
+ // A direct edit of native intent is stronger evidence than a rematerialized snapshot.
1956
+ const baselineOverrides = isRecord(baselineProjection) && isRecord(baselineProjection['overrides'])
1957
+ ? baselineProjection['overrides'] : {};
1958
+ const editedOverrides = isRecord(editedProjection) && isRecord(editedProjection['overrides'])
1959
+ ? editedProjection['overrides'] : {};
1960
+ const oldIntent = isRecord(baselineOverrides[field]) ? baselineOverrides[field] : {};
1961
+ const newIntent = isRecord(editedOverrides[field]) ? editedOverrides[field] : {};
1962
+ if (isRecord(editedProjection)) {
1963
+ for (const key of new Set([...Object.keys(oldIntent), ...Object.keys(newIntent)])) {
1964
+ if (!changedNativeValue(oldIntent, newIntent, key))
1965
+ continue;
1966
+ if (hasOwn(previousOverride, key))
1967
+ override[key] = structuredClone(previousOverride[key]);
1968
+ else
1969
+ delete override[key];
1970
+ }
1971
+ }
1972
+ delete override['field'];
1973
+ delete override['order']; // Ordering has a dedicated projection field.
1974
+ if (Object.keys(override).length)
1975
+ overrides[field] = override;
1976
+ else
1977
+ delete overrides[field];
1978
+ }
1979
+ // Missing fields do not erase their overrides; membership and intent are separate.
1980
+ const previousOrder = orderedFields(before, additions);
1981
+ const nextOrder = orderedFields(after, additions).filter(field => before.has(field));
1982
+ if (!changedNativeValue(baselineProjection, editedProjection, 'include')
1983
+ && previousOrder.some(field => !nextOrder.includes(field))) {
1984
+ const include = Array.isArray(projection['include']) ? projection['include'] : [];
1985
+ projection['include'] = [...nextOrder, ...include.filter(field => !before.has(field))];
1986
+ }
1987
+ if (!changedNativeValue(baselineProjection, editedProjection, 'order')
1988
+ && JSON.stringify(previousOrder) !== JSON.stringify(nextOrder)) {
1989
+ const order = Array.isArray(projection['order']) ? projection['order'] : [];
1990
+ projection['order'] = [...nextOrder, ...order.filter(field => !before.has(field) && !nextOrder.includes(field))];
1991
+ }
1992
+ if (Object.keys(overrides).length)
1993
+ projection['overrides'] = overrides;
1994
+ else
1995
+ delete projection['overrides'];
1996
+ if (nextAdditions.length)
1997
+ projection['additions'] = nextAdditions;
1998
+ else
1999
+ delete projection['additions'];
2000
+ return projection;
2001
+ }
2002
+ function changedNativeValue(before, after, key) {
2003
+ if (!isRecord(after))
2004
+ return false;
2005
+ const previous = isRecord(before) ? before : {};
2006
+ return hasOwn(previous, key) !== hasOwn(after, key)
2007
+ || !sameAuthoringValue(previous[key], after[key]);
2008
+ }
2009
+ function orderedFields(columns, additions) {
2010
+ return orderTableColumns([...columns].map(([field, column]) => ({
2011
+ field, order: typeof column['order'] === 'number' ? column['order'] : undefined,
2012
+ visible: typeof column['visible'] === 'boolean' ? column['visible'] : undefined,
2013
+ }))).map(column => column.field).filter(field => !additions.has(field));
2014
+ }
2015
+ function columnsByField(columns) {
2016
+ const result = new Map();
2017
+ for (const column of columns) {
2018
+ if (!isRecord(column) || typeof column['field'] !== 'string' || !column['field'].trim()) {
2019
+ throw new Error('Table authoring requires a non-empty column field identity.');
2020
+ }
2021
+ const identity = column['field'].trim();
2022
+ if (result.has(identity))
2023
+ throw new Error('Table authoring requires unique column field identities.');
2024
+ result.set(identity, column);
2025
+ }
2026
+ return result;
2027
+ }
2028
+ function isRecord(value) {
2029
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
2030
+ }
2031
+ /** Object insertion order is not authored intent; undefined is an internal absence sentinel. */
2032
+ function sameAuthoringValue(left, right) {
2033
+ if (left === undefined || right === undefined)
2034
+ return left === right;
2035
+ try {
2036
+ return uiLayoutJsonIdentity(left) === uiLayoutJsonIdentity(right);
2037
+ }
2038
+ catch {
2039
+ if (Array.isArray(left) || Array.isArray(right))
2040
+ return Array.isArray(left) && Array.isArray(right)
2041
+ && left.length === right.length && left.every((value, index) => sameAuthoringValue(value, right[index]));
2042
+ if (!isRecord(left) || !isRecord(right))
2043
+ return left === right;
2044
+ const keys = Object.keys(left).filter(key => left[key] !== undefined);
2045
+ const otherKeys = Object.keys(right).filter(key => right[key] !== undefined);
2046
+ return keys.length === otherKeys.length && keys.every(key => Object.prototype.hasOwnProperty.call(right, key)
2047
+ && sameAuthoringValue(left[key], right[key]));
2048
+ }
2049
+ }
2050
+
2051
+ const BINDINGS = ['resourcePath', 'horizontalScroll'];
2052
+ const INPUTS = ['config', ...BINDINGS];
2053
+ /** Raw compact schema authorship only; native normalization remains an editor/runtime projection. */
2054
+ function decodeTablePageInputs(value) {
2055
+ let inputs;
2056
+ try {
2057
+ inputs = cloneBoundedUiLayoutJsonDocument(value);
2058
+ }
2059
+ catch {
2060
+ return { document: null, diagnostics: [problem('table.page.json.invalid', '/definition/inputs')] };
2061
+ }
2062
+ const diagnostics = [];
2063
+ extras(inputs, INPUTS, '/definition/inputs', diagnostics);
2064
+ const config = inputs['config'];
2065
+ if (!record(config) || !Array.isArray(config['columns']) || config['columns'].length !== 0
2066
+ || !record(config['columnProjection']) || config['columnProjection']['source'] !== 'schema')
2067
+ diagnostics.push(problem('table.page.config.schema-required', '/definition/inputs/config'));
2068
+ if (record(config))
2069
+ nulls(config, '/definition/inputs/config', diagnostics);
2070
+ if (Object.prototype.hasOwnProperty.call(inputs, 'resourcePath') && inputs['resourcePath'] !== null && (typeof inputs['resourcePath'] !== 'string' || [...inputs['resourcePath']].length > 1024))
2071
+ diagnostics.push(problem('table.page.resourcePath.invalid', '/definition/inputs/resourcePath'));
2072
+ if (Object.prototype.hasOwnProperty.call(inputs, 'horizontalScroll') && !['auto', 'wrap', 'none'].includes(inputs['horizontalScroll']))
2073
+ diagnostics.push(problem('table.page.horizontalScroll.invalid', '/definition/inputs/horizontalScroll'));
2074
+ const bindings = Object.fromEntries(BINDINGS.filter(key => Object.prototype.hasOwnProperty.call(inputs, key)).map(key => [key, inputs[key]]));
2075
+ const document = { kind: 'praxis.table.editor', version: 1, config, ...(Object.keys(bindings).length ? { bindings } : {}) };
2076
+ if (!diagnostics.length) {
2077
+ try {
2078
+ diagnostics.push(...validateTableAuthoringDocument(document).filter(d => d.level === 'error').map(d => ({ ...d, path: nativePath(d.path) })));
2079
+ }
2080
+ catch {
2081
+ diagnostics.push(problem('table.page.native.invalid', '/definition/inputs/config'));
2082
+ }
2083
+ }
2084
+ if (!diagnostics.length) {
2085
+ try {
2086
+ cloneBoundedUiLayoutJsonDocument(document);
2087
+ }
2088
+ catch {
2089
+ diagnostics.push(problem('table.page.json.invalid', '/definition/inputs'));
2090
+ }
2091
+ }
2092
+ return { document: diagnostics.length ? null : document, diagnostics };
2093
+ }
2094
+ /** Core prefixes these widget-relative JSON Pointers; this callback never resolves a source/latest. */
2095
+ function validateTablePageWidget(widget) {
2096
+ if (widget.definition.id !== 'praxis-table')
2097
+ return [{ code: 'table.page.component.invalid', path: '/definition/id' }];
2098
+ return decodeTablePageInputs(widget.definition.inputs).diagnostics.map(d => ({ code: d.code, path: d.path ?? '/definition/inputs' }));
2099
+ }
2100
+ function encodeTablePageInputs(value) {
2101
+ let document;
2102
+ try {
2103
+ document = cloneBoundedUiLayoutJsonDocument(value);
2104
+ }
2105
+ catch {
2106
+ return { inputs: null, diagnostics: [problem('table.page.json.invalid', '/')] };
2107
+ }
2108
+ const diagnostics = [];
2109
+ extras(document, ['kind', 'version', 'config', 'bindings'], '', diagnostics);
2110
+ if (document['kind'] !== 'praxis.table.editor' || document['version'] !== 1)
2111
+ diagnostics.push(problem('table.page.native.invalid', '/'));
2112
+ const inputs = { config: document['config'] };
2113
+ if (Object.prototype.hasOwnProperty.call(document, 'bindings')) {
2114
+ const bindings = document['bindings'];
2115
+ if (!record(bindings) || !Object.keys(bindings).length)
2116
+ diagnostics.push(problem('table.page.envelope.unrepresentable', '/bindings'));
2117
+ else {
2118
+ extras(bindings, BINDINGS, '/bindings', diagnostics);
2119
+ Object.assign(inputs, bindings);
2120
+ }
2121
+ }
2122
+ const decoded = diagnostics.length ? null : decodeTablePageInputs(inputs);
2123
+ return { inputs: diagnostics.length || decoded?.diagnostics.length ? null : inputs, diagnostics: [...diagnostics, ...(decoded?.diagnostics ?? [])] };
2124
+ }
2125
+ /** No-change values in a materialized native editor cannot author defaults or erase absent keys. */
2126
+ function projectTablePageEditorChanges(authoredInputs, editorBaseline, editorValue) {
2127
+ const original = decodeTablePageInputs(authoredInputs);
2128
+ if (!original.document)
2129
+ return { inputs: null, diagnostics: original.diagnostics };
2130
+ let baseline;
2131
+ let edited;
2132
+ try {
2133
+ baseline = cloneBoundedUiLayoutJsonDocument(editorBaseline);
2134
+ edited = cloneBoundedUiLayoutJsonDocument(editorValue);
2135
+ }
2136
+ catch {
2137
+ return { inputs: null, diagnostics: [problem('table.page.json.invalid', '/')] };
2138
+ }
2139
+ const authored = original.document;
2140
+ // Native config delta has schema-column projection semantics; envelope delta is plain JSON.
2141
+ let candidate;
2142
+ try {
2143
+ candidate = applyTableAuthoringChanges(authored, baseline, edited);
2144
+ candidate['config'] = applyTableAuthoringChanges(authored['config'], baseline['config'], edited['config']);
2145
+ }
2146
+ catch {
2147
+ return { inputs: null, diagnostics: [problem('table.page.editor.invalid', '/definition/inputs/config')] };
2148
+ }
2149
+ const before = { ...authored };
2150
+ const after = { ...candidate };
2151
+ delete before['config'];
2152
+ delete after['config'];
2153
+ if (uiLayoutJsonIdentity(before) !== uiLayoutJsonIdentity(after))
2154
+ return { inputs: null, diagnostics: [problem('table.page.seed.replacement-required', '/definition/inputs')] };
2155
+ return encodeTablePageInputs(candidate);
2156
+ }
2157
+ function extras(source, allowed, path, diagnostics) {
2158
+ for (const key of Object.keys(source))
2159
+ if (!allowed.includes(key))
2160
+ diagnostics.push(problem('table.page.profile.unsupported', path + '/' + pointer(key)));
2161
+ }
2162
+ function nulls(value, path, diagnostics) {
2163
+ if (value === null)
2164
+ diagnostics.push(problem('table.page.config.null', path));
2165
+ else if (Array.isArray(value))
2166
+ value.forEach((item, index) => nulls(item, path + '/' + index, diagnostics));
2167
+ else if (record(value))
2168
+ Object.entries(value).forEach(([key, item]) => nulls(item, path + '/' + pointer(key), diagnostics));
2169
+ }
2170
+ function pointer(key) { return key.replace(/~/g, '~0').replace(/\//g, '~1'); }
2171
+ function record(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); }
2172
+ function problem(code, path) { return { level: 'error', code, path, message: code }; }
2173
+ /** Derive execution-only identity and disable independent preferences. Never persist this projection. */
2174
+ function materializeTablePageRuntimeInputs(value, pageId, widgetKey, options) {
2175
+ const decoded = decodeTablePageInputs(value);
2176
+ if (!decoded.document)
2177
+ return { inputs: null, diagnostics: decoded.diagnostics };
2178
+ let id;
2179
+ try {
2180
+ id = derivePageChildRuntimeId(pageId, widgetKey);
2181
+ }
2182
+ catch {
2183
+ return { inputs: null, diagnostics: [problem('table.page.identity.invalid', '/key')] };
2184
+ }
2185
+ const cloned = cloneBoundedUiLayoutJsonDocument(value);
2186
+ if (options?.preview && record(cloned['config'])) {
2187
+ const previewConfig = { ...cloned['config'] };
2188
+ if (record(previewConfig['actions'])) {
2189
+ const actions = { ...previewConfig['actions'] };
2190
+ if (record(actions['row'])) {
2191
+ actions['row'] = {
2192
+ ...actions['row'],
2193
+ edit: false,
2194
+ delete: false,
2195
+ duplicate: false,
2196
+ custom: [],
2197
+ };
2198
+ }
2199
+ if (record(actions['toolbar'])) {
2200
+ actions['toolbar'] = {
2201
+ ...actions['toolbar'],
2202
+ add: false,
2203
+ create: false,
2204
+ delete: false,
2205
+ import: false,
2206
+ custom: [],
2207
+ };
2208
+ }
2209
+ if (record(actions['bulk'])) {
2210
+ actions['bulk'] = {
2211
+ ...actions['bulk'],
2212
+ enabled: false,
2213
+ actions: [],
2214
+ };
2215
+ }
2216
+ previewConfig['actions'] = actions;
2217
+ }
2218
+ if (record(previewConfig['editing'])) {
2219
+ previewConfig['editing'] = {
2220
+ ...previewConfig['editing'],
2221
+ enabled: false,
2222
+ };
2223
+ }
2224
+ cloned['config'] = previewConfig;
2225
+ }
2226
+ return {
2227
+ inputs: {
2228
+ ...cloned,
2229
+ tableId: id,
2230
+ componentInstanceId: id,
2231
+ configPersistenceStrategy: 'volatile',
2232
+ enableCustomization: false,
2233
+ },
2234
+ diagnostics: [],
2235
+ };
2236
+ }
2237
+ const TABLE_GOVERNED_PAGE_PREVIEW_ADAPTER = {
2238
+ widgetDefinitionId: 'praxis-table',
2239
+ certifiedForInteractivePreview: true,
2240
+ validate: validateTablePageWidget,
2241
+ materializePreviewInputs: (widget, pageId) => {
2242
+ const materialized = materializeTablePageRuntimeInputs(widget.definition.inputs, pageId, widget.key, { preview: true });
2243
+ if (!materialized.inputs) {
2244
+ throw new Error(materialized.diagnostics[0]?.code ?? 'table.page.preview.invalid');
2245
+ }
2246
+ return materialized.inputs;
2247
+ },
2248
+ };
2249
+ function nativePath(value) {
2250
+ // The native dot-path protocol does not escape dynamic field identities. Its
2251
+ // overrides ancestor is precise; splitting that field would invent a pointer.
2252
+ if (value?.startsWith('config.columnProjection.overrides.'))
2253
+ return '/definition/inputs/config/columnProjection/overrides';
2254
+ const parts = (value ?? 'config').replace(/\[(\d+)\]/g, '.$1').split('.');
2255
+ if (parts[0] === 'bindings')
2256
+ parts.shift();
2257
+ return '/definition/inputs/' + parts.map(pointer).join('/');
2258
+ }
2259
+
1459
2260
  /**
1460
2261
  * Generated bundle index. Do not edit.
1461
2262
  */
1462
2263
 
1463
- export { buildTableApplyPlan, createTableAuthoringDocument, deriveTableEditorDocument, normalizeTableAuthoringDocument, parseLegacyOrTableDocument, serializeTableAuthoringDocument, toCanonicalTableConfig, validateTableAuthoringDocument };
2264
+ export { TABLE_GOVERNED_PAGE_PREVIEW_ADAPTER, buildTableApplyPlan, createTableAuthoringDocument, decodeTablePageInputs, deriveTableEditorDocument, encodeTablePageInputs, materializeTablePageRuntimeInputs, normalizeTableAuthoringDocument, parseLegacyOrTableDocument, projectTablePageEditorChanges, serializeTableAuthoringDocument, toCanonicalTableConfig, validateTableAuthoringDocument, validateTablePageWidget };