@asteby/metacore-runtime-react 53.28.0 → 53.29.1
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.
- package/CHANGELOG.md +24 -0
- package/dist/business/customer-picker.d.ts.map +1 -1
- package/dist/business/customer-picker.js +4 -0
- package/dist/dialogs/create-record-dialog.d.ts +1 -1
- package/dist/dialogs/create-record-dialog.d.ts.map +1 -1
- package/dist/dialogs/create-record-dialog.js +2 -2
- package/dist/dialogs/dynamic-record.d.ts +16 -1
- package/dist/dialogs/dynamic-record.d.ts.map +1 -1
- package/dist/dialogs/dynamic-record.js +49 -3
- package/dist/dialogs/types.d.ts +4 -0
- package/dist/dialogs/types.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/loom/index.d.ts +9 -0
- package/dist/loom/index.d.ts.map +1 -0
- package/dist/loom/index.js +9 -0
- package/dist/loom/overlay.d.ts +74 -0
- package/dist/loom/overlay.d.ts.map +1 -0
- package/dist/loom/overlay.js +142 -0
- package/dist/loom/proposals.d.ts +26 -0
- package/dist/loom/proposals.d.ts.map +1 -0
- package/dist/loom/proposals.js +74 -0
- package/dist/loom/provider.d.ts +28 -0
- package/dist/loom/provider.d.ts.map +1 -0
- package/dist/loom/provider.js +31 -0
- package/dist/loom/resolve.d.ts +23 -0
- package/dist/loom/resolve.d.ts.map +1 -0
- package/dist/loom/resolve.js +138 -0
- package/dist/loom/seam.d.ts +28 -0
- package/dist/loom/seam.d.ts.map +1 -0
- package/dist/loom/seam.js +127 -0
- package/dist/loom/seams.d.ts +31 -0
- package/dist/loom/seams.d.ts.map +1 -0
- package/dist/loom/seams.js +21 -0
- package/dist/loom/store.d.ts +16 -0
- package/dist/loom/store.d.ts.map +1 -0
- package/dist/loom/store.js +72 -0
- package/dist/loom/types.d.ts +153 -0
- package/dist/loom/types.d.ts.map +1 -0
- package/dist/loom/types.js +1 -0
- package/dist/record-picker-dialog.d.ts +7 -1
- package/dist/record-picker-dialog.d.ts.map +1 -1
- package/dist/record-picker-dialog.js +18 -3
- package/package.json +6 -6
- package/src/__tests__/dynamic-record-seam.test.tsx +194 -0
- package/src/__tests__/loom-overlay.test.ts +94 -0
- package/src/__tests__/loom-page-graph.test.ts +75 -0
- package/src/__tests__/loom-resolve.test.ts +108 -0
- package/src/business/customer-picker.tsx +4 -0
- package/src/dialogs/create-record-dialog.tsx +4 -0
- package/src/dialogs/dynamic-record.tsx +83 -0
- package/src/dialogs/types.ts +4 -0
- package/src/index.ts +1 -0
- package/src/loom/index.ts +36 -0
- package/src/loom/overlay.ts +196 -0
- package/src/loom/proposals.tsx +156 -0
- package/src/loom/provider.tsx +69 -0
- package/src/loom/resolve.ts +136 -0
- package/src/loom/seam.tsx +235 -0
- package/src/loom/seams.ts +42 -0
- package/src/loom/store.ts +81 -0
- package/src/loom/types.ts +167 -0
- package/src/record-picker-dialog.tsx +37 -1
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it } from 'vitest'
|
|
2
|
+
import {
|
|
3
|
+
attenuatePatch,
|
|
4
|
+
clearLoom,
|
|
5
|
+
projectLenses,
|
|
6
|
+
redactMessage,
|
|
7
|
+
registerPart,
|
|
8
|
+
resolveSeam,
|
|
9
|
+
sensitiveClasses,
|
|
10
|
+
type GraftDef,
|
|
11
|
+
type LoomEnv,
|
|
12
|
+
type SeamContract,
|
|
13
|
+
} from '../loom'
|
|
14
|
+
|
|
15
|
+
const C = () => null
|
|
16
|
+
const contract: SeamContract = {
|
|
17
|
+
id: 'record.dialog.header',
|
|
18
|
+
version: '1.2.0',
|
|
19
|
+
lenses: { values: 'pii', model: 'public', fiscal: 'pii.fiscal' },
|
|
20
|
+
writable: new Set(['tax_id', 'postal_code', 'fiscal_data.regime']),
|
|
21
|
+
}
|
|
22
|
+
const env = (over: Partial<LoomEnv> = {}): LoomEnv => ({ can: () => true, model: 'customers.Customer', mode: 'create', ...over })
|
|
23
|
+
const g = (over: Partial<GraftDef>): GraftDef => ({ id: 'a.x', seam: 'record.dialog.header', component: C, ...over })
|
|
24
|
+
|
|
25
|
+
afterEach(clearLoom)
|
|
26
|
+
|
|
27
|
+
describe('resolveSeam', () => {
|
|
28
|
+
it('ordena por order y conserva el orden de entrada en empates', () => {
|
|
29
|
+
const r = resolveSeam(contract, [g({ id: 'a.b', order: 5 }), g({ id: 'a.c' }), g({ id: 'a.d' })], env())
|
|
30
|
+
expect(r.mounted.map((x) => x.id)).toEqual(['a.c', 'a.d', 'a.b'])
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('explica cada descarte', () => {
|
|
34
|
+
const r = resolveSeam(
|
|
35
|
+
contract,
|
|
36
|
+
[
|
|
37
|
+
g({ id: 'a.perm', when: { permission: 'customers.csf' } }),
|
|
38
|
+
g({ id: 'a.flag', when: { flag: 'csf' } }),
|
|
39
|
+
g({ id: 'a.set', when: { setting: { key: 'csf.enabled' } } }),
|
|
40
|
+
g({ id: 'a.model', when: { model: ['Supplier'] } }),
|
|
41
|
+
g({ id: 'a.mode', when: { mode: ['edit'] } }),
|
|
42
|
+
g({ id: 'a.ver', requires: '^2' }),
|
|
43
|
+
g({ id: 'a.part', component: undefined, part: 'a.missing' }),
|
|
44
|
+
g({ id: 'a.ok', when: { model: ['Customer'], mode: ['create'] }, requires: '^1.1' }),
|
|
45
|
+
],
|
|
46
|
+
env({ can: (p) => p !== 'customers.csf' }),
|
|
47
|
+
)
|
|
48
|
+
expect(r.mounted.map((x) => x.id)).toEqual(['a.ok'])
|
|
49
|
+
expect(Object.fromEntries(r.skipped.map((s) => [s.graft.id, s.reason]))).toEqual({
|
|
50
|
+
'a.perm': 'permission',
|
|
51
|
+
'a.flag': 'flag',
|
|
52
|
+
'a.set': 'setting',
|
|
53
|
+
'a.model': 'model',
|
|
54
|
+
'a.mode': 'mode',
|
|
55
|
+
'a.ver': 'version',
|
|
56
|
+
'a.part': 'no_component',
|
|
57
|
+
})
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
it('con lista del servidor, lo no autorizado no se monta', () => {
|
|
61
|
+
const r = resolveSeam(contract, [g({ id: 'a.x' }), g({ id: 'a.y' })], env({ granted: new Set(['a.y']) }))
|
|
62
|
+
expect(r.mounted.map((x) => x.id)).toEqual(['a.y'])
|
|
63
|
+
expect(r.skipped[0]).toMatchObject({ reason: 'not_granted' })
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
it('resuelve el componente por Part registrado', () => {
|
|
67
|
+
registerPart({ id: 'fiscal.csf', component: C })
|
|
68
|
+
const r = resolveSeam(contract, [g({ id: 'a.p', component: undefined, part: 'fiscal.csf' })], env())
|
|
69
|
+
expect(r.mounted).toHaveLength(1)
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
it('ignora injertos de otros seams', () => {
|
|
73
|
+
expect(resolveSeam(contract, [g({ seam: 'otro' })], env()).mounted).toEqual([])
|
|
74
|
+
})
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
describe('capacidades', () => {
|
|
78
|
+
it('writes ∩ writable: lo demás se descarta', () => {
|
|
79
|
+
const r = attenuatePatch(
|
|
80
|
+
{ tax_id: 'X', organization_id: 'hack', postal_code: '1', 'fiscal_data.regime': '601' },
|
|
81
|
+
['tax_id', 'fiscal_data.*', 'organization_id'],
|
|
82
|
+
contract.writable,
|
|
83
|
+
)
|
|
84
|
+
expect(r.allowed).toEqual({ tax_id: 'X', 'fiscal_data.regime': '601' })
|
|
85
|
+
expect(r.dropped.sort()).toEqual(['organization_id', 'postal_code'])
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
it('sin writes no escribe nada', () => {
|
|
89
|
+
expect(attenuatePatch({ tax_id: 'X' }, undefined, contract.writable).allowed).toEqual({})
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
it('lentes: sólo las declaradas, congeladas y sin tocar el original', () => {
|
|
93
|
+
const values = { name: 'A', nested: { x: 1 } }
|
|
94
|
+
const view = projectLenses({ values, model: 'Customer', fiscal: {} }, ['values'])
|
|
95
|
+
expect(Object.keys(view)).toEqual(['values'])
|
|
96
|
+
expect(Object.isFrozen((view.values as typeof values).nested)).toBe(true)
|
|
97
|
+
expect(Object.isFrozen(values)).toBe(false)
|
|
98
|
+
expect(Object.isFrozen(values.nested)).toBe(false)
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
it('redacta errores de injertos que leen datos sensibles', () => {
|
|
102
|
+
expect(sensitiveClasses(contract, ['model'])).toEqual([])
|
|
103
|
+
const cls = sensitiveClasses(contract, ['values', 'fiscal'])
|
|
104
|
+
expect(cls).toEqual(['pii', 'pii.fiscal'])
|
|
105
|
+
expect(redactMessage('RFC XAXX010101000 inválido', cls)).not.toContain('XAXX')
|
|
106
|
+
expect(redactMessage('boom', [])).toBe('boom')
|
|
107
|
+
})
|
|
108
|
+
})
|
|
@@ -115,6 +115,10 @@ export function CustomerPicker({
|
|
|
115
115
|
prefillField: 'name',
|
|
116
116
|
createDefaults,
|
|
117
117
|
ensureFields,
|
|
118
|
+
onSelectExisting: (rec) => {
|
|
119
|
+
onChange(toResult(rec))
|
|
120
|
+
setText('')
|
|
121
|
+
},
|
|
118
122
|
onSaved: (rec, kind) => {
|
|
119
123
|
const next = toResult(rec)
|
|
120
124
|
// Al editar se conservan saldo/crédito/alertas que el registro no trae.
|
|
@@ -28,6 +28,8 @@ export function CreateRecordDialog({
|
|
|
28
28
|
onCreate,
|
|
29
29
|
onUpdate,
|
|
30
30
|
onSaved,
|
|
31
|
+
onIntent,
|
|
32
|
+
initialProposal,
|
|
31
33
|
}: CreateRecordDialogProps) {
|
|
32
34
|
const mode = recordId ? 'edit' : 'create'
|
|
33
35
|
return (
|
|
@@ -45,6 +47,8 @@ export function CreateRecordDialog({
|
|
|
45
47
|
onCreate={onCreate}
|
|
46
48
|
onUpdate={onUpdate}
|
|
47
49
|
onSaved={onSaved}
|
|
50
|
+
onIntent={onIntent}
|
|
51
|
+
initialProposal={initialProposal}
|
|
48
52
|
/>
|
|
49
53
|
)
|
|
50
54
|
}
|
|
@@ -101,6 +101,9 @@ import { CollectionCell, type ItemField } from '../collection-cell'
|
|
|
101
101
|
import type { ActionFieldDef, RelationMeta } from '../types'
|
|
102
102
|
import { ImageUrlContext, identityImageUrl, type GetImageUrl } from '../image-url-context'
|
|
103
103
|
import { getFieldWidget, useFieldWidgetRegistryVersion } from '../field-widget-registry'
|
|
104
|
+
import { Seam } from '../loom/seam'
|
|
105
|
+
import { ProposalReview, useProposalQueue } from '../loom/proposals'
|
|
106
|
+
import { RECORD_FORM_SECTION, recordDialogHeaderContract } from '../loom/seams'
|
|
104
107
|
import { TimeZoneContext, CurrencyContext, useNumberLocale, useSystemActor } from '../org-runtime-context'
|
|
105
108
|
import { AuthorshipCell, hasSpecialAuthorship, readProvenance } from '../provenance'
|
|
106
109
|
|
|
@@ -452,6 +455,16 @@ export interface DynamicRecordDialogProps {
|
|
|
452
455
|
* own list/detail query so the parent row's totals refresh underneath.
|
|
453
456
|
*/
|
|
454
457
|
onChange?: () => void
|
|
458
|
+
/**
|
|
459
|
+
* Intenciones que piden los injertos del seam `record.dialog.header` (Loom, RFC 0005):
|
|
460
|
+
* `record.select` `{ record }` y `record.edit` `{ id, patch }`. Devuelve true si la atendió.
|
|
461
|
+
*/
|
|
462
|
+
onIntent?: (intent: string, payload: unknown) => boolean
|
|
463
|
+
/**
|
|
464
|
+
* Propuesta inicial (p. ej. la que trae una intención `record.edit`): se muestra como diff
|
|
465
|
+
* revisable sobre el registro cargado. Sólo pasan campos editables del formulario.
|
|
466
|
+
*/
|
|
467
|
+
initialProposal?: { patch: Record<string, unknown>; reason?: string; labels?: Record<string, string>; apply?: 'review' | 'auto' }
|
|
455
468
|
}
|
|
456
469
|
|
|
457
470
|
function resolvePath(obj: any, path: string): any {
|
|
@@ -826,6 +839,8 @@ export function DynamicRecordDialog({
|
|
|
826
839
|
timeZone,
|
|
827
840
|
currency,
|
|
828
841
|
onChange,
|
|
842
|
+
onIntent,
|
|
843
|
+
initialProposal,
|
|
829
844
|
}: DynamicRecordDialogProps) {
|
|
830
845
|
const api = useApi()
|
|
831
846
|
const branchGate = useBranchCreateGate()
|
|
@@ -907,6 +922,54 @@ export function DynamicRecordDialog({
|
|
|
907
922
|
(patch: Record<string, any>) => setFormValues(prev => ({ ...prev, ...patch })),
|
|
908
923
|
[],
|
|
909
924
|
)
|
|
925
|
+
// Loom: seam `record.dialog.header`. Los injertos proponen; el diálogo muestra el diff y aplica.
|
|
926
|
+
const proposals = useProposalQueue(formValues, applyPrefill)
|
|
927
|
+
const headerContract = useMemo(() => recordDialogHeaderContract(prefillAllowedKeys), [prefillAllowedKeys])
|
|
928
|
+
const sectionContract = useMemo(
|
|
929
|
+
() => recordDialogHeaderContract(prefillAllowedKeys, RECORD_FORM_SECTION),
|
|
930
|
+
[prefillAllowedKeys],
|
|
931
|
+
)
|
|
932
|
+
const headerLenses = useMemo(
|
|
933
|
+
() => ({
|
|
934
|
+
model,
|
|
935
|
+
mode: isCreate ? 'create' : 'edit',
|
|
936
|
+
recordId: recordId ?? undefined,
|
|
937
|
+
values: formValues,
|
|
938
|
+
fields: (modalMeta?.fields ?? []).map((f: any) => ({
|
|
939
|
+
key: String(f.key),
|
|
940
|
+
label: f.label ? localizeFieldLabel(f.label, t) : String(f.key),
|
|
941
|
+
type: f.type,
|
|
942
|
+
})),
|
|
943
|
+
}),
|
|
944
|
+
[model, isCreate, recordId, formValues, modalMeta, t],
|
|
945
|
+
)
|
|
946
|
+
const fieldLabelOf = useCallback(
|
|
947
|
+
(key: string) => headerLenses.fields.find(f => f.key === key)?.label ?? key,
|
|
948
|
+
[headerLenses],
|
|
949
|
+
)
|
|
950
|
+
// La propuesta inicial entra una vez, cuando el formulario ya tiene sus campos.
|
|
951
|
+
const seededProposal = useRef(false)
|
|
952
|
+
useEffect(() => {
|
|
953
|
+
if (!open) {
|
|
954
|
+
seededProposal.current = false
|
|
955
|
+
return
|
|
956
|
+
}
|
|
957
|
+
if (seededProposal.current || !initialProposal || loading || !modalMeta) return
|
|
958
|
+
seededProposal.current = true
|
|
959
|
+
const patch: Record<string, unknown> = {}
|
|
960
|
+
for (const [k, v] of Object.entries(initialProposal.patch)) if (prefillAllowedKeys.has(k)) patch[k] = v
|
|
961
|
+
if (!Object.keys(patch).length) return
|
|
962
|
+
proposals.push({
|
|
963
|
+
...initialProposal,
|
|
964
|
+
patch,
|
|
965
|
+
id: 'host#initial',
|
|
966
|
+
graft: 'host.initial',
|
|
967
|
+
addon: 'host',
|
|
968
|
+
previous: {},
|
|
969
|
+
dropped: [],
|
|
970
|
+
})
|
|
971
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
972
|
+
}, [open, initialProposal, loading, modalMeta, prefillAllowedKeys])
|
|
910
973
|
const config = MODE_CONFIG[mode]
|
|
911
974
|
|
|
912
975
|
// ── Fetch metadata + record when dialog opens ──────────────────────────
|
|
@@ -1449,6 +1512,16 @@ export function DynamicRecordDialog({
|
|
|
1449
1512
|
onApply={applyPrefill}
|
|
1450
1513
|
/>
|
|
1451
1514
|
)}
|
|
1515
|
+
{isEditable && (
|
|
1516
|
+
<Seam
|
|
1517
|
+
contract={headerContract}
|
|
1518
|
+
lenses={headerLenses}
|
|
1519
|
+
host={{ model, mode: isCreate ? 'create' : 'edit' }}
|
|
1520
|
+
onProposal={proposals.push}
|
|
1521
|
+
onIntent={onIntent ? (intent, payload) => onIntent(intent, payload) : undefined}
|
|
1522
|
+
/>
|
|
1523
|
+
)}
|
|
1524
|
+
{isEditable && <ProposalReview queue={proposals} values={formValues} labelOf={fieldLabelOf} />}
|
|
1452
1525
|
<form
|
|
1453
1526
|
id={formId}
|
|
1454
1527
|
// Stable Aby / guidance contract: unique id={formId}
|
|
@@ -1510,6 +1583,16 @@ export function DynamicRecordDialog({
|
|
|
1510
1583
|
</div>
|
|
1511
1584
|
)}
|
|
1512
1585
|
</form>
|
|
1586
|
+
{isEditable && (
|
|
1587
|
+
<Seam
|
|
1588
|
+
contract={sectionContract}
|
|
1589
|
+
lenses={headerLenses}
|
|
1590
|
+
host={{ model, mode: isCreate ? 'create' : 'edit' }}
|
|
1591
|
+
onProposal={proposals.push}
|
|
1592
|
+
onIntent={onIntent ? (intent, payload) => onIntent(intent, payload) : undefined}
|
|
1593
|
+
className="mt-4 grid gap-3"
|
|
1594
|
+
/>
|
|
1595
|
+
)}
|
|
1513
1596
|
|
|
1514
1597
|
|
|
1515
1598
|
{/* Líneas del documento: SOLO las relaciones de
|
package/src/dialogs/types.ts
CHANGED
|
@@ -115,6 +115,10 @@ export interface CreateRecordDialogProps extends RecordDialogProps {
|
|
|
115
115
|
lockedFields?: string[]
|
|
116
116
|
/** Fields merged into the modal schema after load (see DynamicRecordDialog.ensureFields). */
|
|
117
117
|
ensureFields?: import('./dynamic-record').FieldDef[]
|
|
118
|
+
/** Intenciones del seam `record.dialog.header` (see DynamicRecordDialog.onIntent). */
|
|
119
|
+
onIntent?: (intent: string, payload: unknown) => boolean
|
|
120
|
+
/** Propuesta inicial mostrada como diff (see DynamicRecordDialog.initialProposal). */
|
|
121
|
+
initialProposal?: import('./dynamic-record').DynamicRecordDialogProps['initialProposal']
|
|
118
122
|
/** Notification when a create or update succeeds. */
|
|
119
123
|
onSaved?: () => void
|
|
120
124
|
}
|
package/src/index.ts
CHANGED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Loom — sistema de contribuciones de UI (RFC 0005 del kernel).
|
|
2
|
+
export * from './types'
|
|
3
|
+
export {
|
|
4
|
+
registerGraft,
|
|
5
|
+
registerPart,
|
|
6
|
+
getPart,
|
|
7
|
+
listGrafts,
|
|
8
|
+
unregisterLoomByAddon,
|
|
9
|
+
clearLoom,
|
|
10
|
+
subscribeLoom,
|
|
11
|
+
loomVersion,
|
|
12
|
+
} from './store'
|
|
13
|
+
export { resolveSeam, attenuatePatch, matchesWrite, projectLenses, sensitiveClasses, redactMessage } from './resolve'
|
|
14
|
+
export { LoomProvider, useLoomConfig, type LoomProviderProps, type LoomConfig } from './provider'
|
|
15
|
+
export { Seam, SeamInspector, useSeam, type SeamProps, type SeamHostContext } from './seam'
|
|
16
|
+
export { useProposalQueue, ProposalReview, type ProposalQueue, type ProposalReviewProps } from './proposals'
|
|
17
|
+
export {
|
|
18
|
+
applyOverlays,
|
|
19
|
+
mergeConfig,
|
|
20
|
+
type PageBlock,
|
|
21
|
+
type BlockGraph,
|
|
22
|
+
type OverlayOp,
|
|
23
|
+
type OverlayScope,
|
|
24
|
+
type OverlayLayer,
|
|
25
|
+
type OverlayConflict,
|
|
26
|
+
type OverlayConflictReason,
|
|
27
|
+
type OverlayResult,
|
|
28
|
+
type BlockProvenance,
|
|
29
|
+
} from './overlay'
|
|
30
|
+
export {
|
|
31
|
+
RECORD_DIALOG_HEADER,
|
|
32
|
+
RECORD_FORM_SECTION,
|
|
33
|
+
recordDialogHeaderContract,
|
|
34
|
+
type RecordDialogHeaderLenses,
|
|
35
|
+
type RecordFormSeam,
|
|
36
|
+
} from './seams'
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
// Overlays — parches declarativos sobre el grafo de bloques de una página
|
|
2
|
+
// («kustomize para UI»). Base de OPS + capas de preset, organización, sucursal,
|
|
3
|
+
// rol y usuario, fusionadas en orden fijo y de forma determinista.
|
|
4
|
+
//
|
|
5
|
+
// Reglas (RFC 0005 §7):
|
|
6
|
+
// - Orden de capas por alcance: preset < org < branch < role < user; empate = orden de entrada.
|
|
7
|
+
// - Cada capa es ATÓMICA: si una operación no aplica limpio, la capa entera se descarta y se
|
|
8
|
+
// reporta el conflicto; la página queda como estaba antes de esa capa (nunca a medias).
|
|
9
|
+
// - Una capa con `targets` (rango semver de la base) que no cumple la versión de la base no se
|
|
10
|
+
// aplica: si la base cambió y rompe el overlay, se cae al comportamiento base y se avisa.
|
|
11
|
+
// - `replace` guarda el bloque original como `fallback`: el render lo usa si el reemplazo falla.
|
|
12
|
+
// - Procedencia: cada bloque sabe de qué capa viene y qué capas lo tocaron (Explain).
|
|
13
|
+
// Función pura, sin React.
|
|
14
|
+
import { satisfiesSdkRange } from '../slots/sdk-range'
|
|
15
|
+
|
|
16
|
+
export interface PageBlock {
|
|
17
|
+
id: string
|
|
18
|
+
type: string
|
|
19
|
+
region?: string
|
|
20
|
+
config?: Record<string, unknown>
|
|
21
|
+
/** Lo rellena `replace`: el bloque al que sustituyó. */
|
|
22
|
+
fallback?: PageBlock
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface BlockGraph {
|
|
26
|
+
id: string
|
|
27
|
+
/** Semver de la base (`1.4.0`). */
|
|
28
|
+
version: string
|
|
29
|
+
blocks: PageBlock[]
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
type Anchor = { before?: string; after?: string }
|
|
33
|
+
|
|
34
|
+
export type OverlayOp =
|
|
35
|
+
| ({ op: 'add'; block: PageBlock } & Anchor)
|
|
36
|
+
| { op: 'remove'; id: string }
|
|
37
|
+
| ({ op: 'move'; id: string; region?: string } & Anchor)
|
|
38
|
+
/** Fusión profunda de `config`; un valor `null` borra la clave. */
|
|
39
|
+
| { op: 'configure'; id: string; set: Record<string, unknown> }
|
|
40
|
+
| { op: 'replace'; id: string; with: PageBlock }
|
|
41
|
+
|
|
42
|
+
export type OverlayScope = 'preset' | 'org' | 'branch' | 'role' | 'user'
|
|
43
|
+
|
|
44
|
+
export interface OverlayLayer {
|
|
45
|
+
id: string
|
|
46
|
+
scope: OverlayScope
|
|
47
|
+
/** Rango semver de la base contra la que se escribió (`^1.2`). */
|
|
48
|
+
targets?: string
|
|
49
|
+
ops: OverlayOp[]
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export type OverlayConflictReason = 'base_incompatible' | 'missing_target' | 'missing_anchor' | 'duplicate_id'
|
|
53
|
+
|
|
54
|
+
export interface OverlayConflict {
|
|
55
|
+
layer: string
|
|
56
|
+
/** Índice de la operación (-1 = la capa entera). */
|
|
57
|
+
index: number
|
|
58
|
+
reason: OverlayConflictReason
|
|
59
|
+
detail: string
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface BlockProvenance {
|
|
63
|
+
/** `base` o id de la capa que lo añadió. */
|
|
64
|
+
origin: string
|
|
65
|
+
/** Capas que lo modificaron, en orden. */
|
|
66
|
+
touchedBy: string[]
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface OverlayResult {
|
|
70
|
+
graph: BlockGraph
|
|
71
|
+
applied: string[]
|
|
72
|
+
conflicts: OverlayConflict[]
|
|
73
|
+
provenance: Record<string, BlockProvenance>
|
|
74
|
+
/** Bloques quitados y por qué capa (Explain: «¿por qué NO veo esto?»). */
|
|
75
|
+
removed: Record<string, string>
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const RANK: Record<OverlayScope, number> = { preset: 0, org: 1, branch: 2, role: 3, user: 4 }
|
|
79
|
+
|
|
80
|
+
function isPlain(v: unknown): v is Record<string, unknown> {
|
|
81
|
+
return !!v && typeof v === 'object' && !Array.isArray(v)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Fusión profunda; arrays se sustituyen enteros; `null` borra. */
|
|
85
|
+
export function mergeConfig(base: Record<string, unknown> | undefined, set: Record<string, unknown>): Record<string, unknown> {
|
|
86
|
+
const out: Record<string, unknown> = { ...(base ?? {}) }
|
|
87
|
+
for (const [k, v] of Object.entries(set)) {
|
|
88
|
+
if (v === null) delete out[k]
|
|
89
|
+
else if (isPlain(v) && isPlain(out[k])) out[k] = mergeConfig(out[k] as Record<string, unknown>, v)
|
|
90
|
+
else out[k] = v
|
|
91
|
+
}
|
|
92
|
+
return out
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function insertAt(list: PageBlock[], block: PageBlock, a: Anchor): string | null {
|
|
96
|
+
const ref = a.before ?? a.after
|
|
97
|
+
if (!ref) {
|
|
98
|
+
list.push(block)
|
|
99
|
+
return null
|
|
100
|
+
}
|
|
101
|
+
const i = list.findIndex((b) => b.id === ref)
|
|
102
|
+
if (i < 0) return ref
|
|
103
|
+
list.splice(a.before ? i : i + 1, 0, block)
|
|
104
|
+
return null
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function applyOverlays(base: BlockGraph, layers: readonly OverlayLayer[]): OverlayResult {
|
|
108
|
+
let blocks = base.blocks.map((b) => ({ ...b }))
|
|
109
|
+
let provenance: Record<string, BlockProvenance> = {}
|
|
110
|
+
for (const b of blocks) provenance[b.id] = { origin: 'base', touchedBy: [] }
|
|
111
|
+
let removed: Record<string, string> = {}
|
|
112
|
+
const applied: string[] = []
|
|
113
|
+
const conflicts: OverlayConflict[] = []
|
|
114
|
+
|
|
115
|
+
const ordered = layers.map((l, i) => ({ l, i })).sort((a, b) => RANK[a.l.scope] - RANK[b.l.scope] || a.i - b.i)
|
|
116
|
+
|
|
117
|
+
for (const { l: layer } of ordered) {
|
|
118
|
+
if (layer.targets && satisfiesSdkRange(base.version, layer.targets) === false) {
|
|
119
|
+
conflicts.push({
|
|
120
|
+
layer: layer.id,
|
|
121
|
+
index: -1,
|
|
122
|
+
reason: 'base_incompatible',
|
|
123
|
+
detail: `escrita para ${base.id}@${layer.targets}, la base es ${base.version}`,
|
|
124
|
+
})
|
|
125
|
+
continue
|
|
126
|
+
}
|
|
127
|
+
const next = blocks.map((b) => ({ ...b }))
|
|
128
|
+
const prov: Record<string, BlockProvenance> = {}
|
|
129
|
+
for (const [k, v] of Object.entries(provenance)) prov[k] = { origin: v.origin, touchedBy: [...v.touchedBy] }
|
|
130
|
+
const rem = { ...removed }
|
|
131
|
+
let failed: OverlayConflict | null = null
|
|
132
|
+
const fail = (index: number, reason: OverlayConflictReason, detail: string) => {
|
|
133
|
+
failed = { layer: layer.id, index, reason, detail }
|
|
134
|
+
}
|
|
135
|
+
const find = (id: string) => next.findIndex((b) => b.id === id)
|
|
136
|
+
const touch = (id: string) => prov[id]?.touchedBy.push(layer.id)
|
|
137
|
+
|
|
138
|
+
layer.ops.forEach((op, index) => {
|
|
139
|
+
if (failed) return
|
|
140
|
+
switch (op.op) {
|
|
141
|
+
case 'add': {
|
|
142
|
+
if (find(op.block.id) >= 0) return fail(index, 'duplicate_id', op.block.id)
|
|
143
|
+
const miss = insertAt(next, { ...op.block }, op)
|
|
144
|
+
if (miss) return fail(index, 'missing_anchor', miss)
|
|
145
|
+
prov[op.block.id] = { origin: layer.id, touchedBy: [] }
|
|
146
|
+
delete rem[op.block.id]
|
|
147
|
+
return
|
|
148
|
+
}
|
|
149
|
+
case 'remove': {
|
|
150
|
+
const i = find(op.id)
|
|
151
|
+
if (i < 0) return fail(index, 'missing_target', op.id)
|
|
152
|
+
next.splice(i, 1)
|
|
153
|
+
rem[op.id] = layer.id
|
|
154
|
+
delete prov[op.id]
|
|
155
|
+
return
|
|
156
|
+
}
|
|
157
|
+
case 'move': {
|
|
158
|
+
const i = find(op.id)
|
|
159
|
+
if (i < 0) return fail(index, 'missing_target', op.id)
|
|
160
|
+
const [b] = next.splice(i, 1)
|
|
161
|
+
const moved = op.region ? { ...b, region: op.region } : b
|
|
162
|
+
if (op.before ?? op.after) {
|
|
163
|
+
const miss = insertAt(next, moved, op)
|
|
164
|
+
if (miss) return fail(index, 'missing_anchor', miss)
|
|
165
|
+
} else next.splice(i, 0, moved)
|
|
166
|
+
touch(op.id)
|
|
167
|
+
return
|
|
168
|
+
}
|
|
169
|
+
case 'configure': {
|
|
170
|
+
const i = find(op.id)
|
|
171
|
+
if (i < 0) return fail(index, 'missing_target', op.id)
|
|
172
|
+
next[i] = { ...next[i], config: mergeConfig(next[i].config, op.set) }
|
|
173
|
+
touch(op.id)
|
|
174
|
+
return
|
|
175
|
+
}
|
|
176
|
+
case 'replace': {
|
|
177
|
+
const i = find(op.id)
|
|
178
|
+
if (i < 0) return fail(index, 'missing_target', op.id)
|
|
179
|
+
const original = next[i]
|
|
180
|
+
next[i] = { ...op.with, id: original.id, fallback: original.fallback ?? original }
|
|
181
|
+
touch(op.id)
|
|
182
|
+
return
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
})
|
|
186
|
+
if (failed) {
|
|
187
|
+
conflicts.push(failed)
|
|
188
|
+
continue
|
|
189
|
+
}
|
|
190
|
+
blocks = next
|
|
191
|
+
provenance = prov
|
|
192
|
+
removed = rem
|
|
193
|
+
applied.push(layer.id)
|
|
194
|
+
}
|
|
195
|
+
return { graph: { ...base, blocks }, applied, conflicts, provenance, removed }
|
|
196
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// Proposals: un injerto no muta el formulario; propone un parche. El anfitrión
|
|
2
|
+
// lo muestra como diff («antes → después»), lo aplica o lo descarta, y lo
|
|
3
|
+
// aplicado siempre se puede deshacer. Mismo flujo para la constancia fiscal,
|
|
4
|
+
// una sugerencia de precio o una sugerencia de Aby.
|
|
5
|
+
import { useCallback, useRef, useState } from 'react'
|
|
6
|
+
import { useTranslation } from 'react-i18next'
|
|
7
|
+
import { Button } from '@asteby/metacore-ui/primitives'
|
|
8
|
+
import type { Proposal } from './types'
|
|
9
|
+
|
|
10
|
+
export interface ProposalQueue {
|
|
11
|
+
pending: Proposal[]
|
|
12
|
+
/** Último parche aplicado, mientras se pueda deshacer. */
|
|
13
|
+
applied: Proposal | null
|
|
14
|
+
/** Entra a la cola (o se aplica directo si `apply: 'auto'`). */
|
|
15
|
+
push: (p: Proposal) => void
|
|
16
|
+
accept: (id: string) => void
|
|
17
|
+
discard: (id: string) => void
|
|
18
|
+
undo: () => void
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Cola de propuestas sobre unos valores. `apply` recibe el parche a fusionar; para el
|
|
23
|
+
* deshacer se fusionan los valores previos de las claves tocadas.
|
|
24
|
+
*/
|
|
25
|
+
export function useProposalQueue(
|
|
26
|
+
values: Record<string, unknown>,
|
|
27
|
+
apply: (patch: Record<string, unknown>) => void,
|
|
28
|
+
): ProposalQueue {
|
|
29
|
+
const [pending, setPending] = useState<Proposal[]>([])
|
|
30
|
+
const [applied, setApplied] = useState<Proposal | null>(null)
|
|
31
|
+
const valuesRef = useRef(values)
|
|
32
|
+
valuesRef.current = values
|
|
33
|
+
|
|
34
|
+
const commit = useCallback(
|
|
35
|
+
(p: Proposal) => {
|
|
36
|
+
// El "antes" se toma al aplicar (el usuario pudo teclear desde que llegó la propuesta).
|
|
37
|
+
const previous: Record<string, unknown> = {}
|
|
38
|
+
for (const k of Object.keys(p.patch)) previous[k] = valuesRef.current[k]
|
|
39
|
+
apply(p.patch)
|
|
40
|
+
setApplied({ ...p, previous })
|
|
41
|
+
},
|
|
42
|
+
[apply],
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
const push = useCallback(
|
|
46
|
+
(p: Proposal) => {
|
|
47
|
+
if (p.apply === 'auto') commit(p)
|
|
48
|
+
else setPending((list) => [...list.filter((x) => x.graft !== p.graft), p])
|
|
49
|
+
},
|
|
50
|
+
[commit],
|
|
51
|
+
)
|
|
52
|
+
const pendingRef = useRef(pending)
|
|
53
|
+
pendingRef.current = pending
|
|
54
|
+
const appliedRef = useRef(applied)
|
|
55
|
+
appliedRef.current = applied
|
|
56
|
+
const accept = useCallback(
|
|
57
|
+
(id: string) => {
|
|
58
|
+
const p = pendingRef.current.find((x) => x.id === id)
|
|
59
|
+
if (p) commit(p)
|
|
60
|
+
setPending((list) => list.filter((x) => x.id !== id))
|
|
61
|
+
},
|
|
62
|
+
[commit],
|
|
63
|
+
)
|
|
64
|
+
const discard = useCallback((id: string) => setPending((list) => list.filter((x) => x.id !== id)), [])
|
|
65
|
+
const undo = useCallback(() => {
|
|
66
|
+
const a = appliedRef.current
|
|
67
|
+
if (a) apply(a.previous)
|
|
68
|
+
setApplied(null)
|
|
69
|
+
}, [apply])
|
|
70
|
+
|
|
71
|
+
return { pending, applied, push, accept, discard, undo }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const show = (v: unknown): string => {
|
|
75
|
+
if (v == null || v === '') return '—'
|
|
76
|
+
if (typeof v === 'object') return (v as { label?: string }).label ?? JSON.stringify(v)
|
|
77
|
+
return String(v)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface ProposalReviewProps {
|
|
81
|
+
queue: ProposalQueue
|
|
82
|
+
/** Etiqueta del campo (la del formulario del anfitrión). */
|
|
83
|
+
labelOf?: (key: string) => string
|
|
84
|
+
/** Valores actuales, para el «antes». */
|
|
85
|
+
values: Record<string, unknown>
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Diff revisable de las propuestas pendientes + barra de deshacer de la última aplicada. */
|
|
89
|
+
export function ProposalReview({ queue, labelOf, values }: ProposalReviewProps) {
|
|
90
|
+
const { t } = useTranslation()
|
|
91
|
+
const label = (p: Proposal, k: string) => p.labels?.[k] ?? labelOf?.(k) ?? k
|
|
92
|
+
if (!queue.pending.length && !queue.applied) return null
|
|
93
|
+
return (
|
|
94
|
+
<div className="mb-4 grid gap-2" data-loom-proposals="">
|
|
95
|
+
{queue.pending.map((p) => {
|
|
96
|
+
const keys = Object.keys(p.patch)
|
|
97
|
+
return (
|
|
98
|
+
<section
|
|
99
|
+
key={p.id}
|
|
100
|
+
aria-label={p.reason ?? t('loom.proposal.title', { defaultValue: 'Cambios propuestos' })}
|
|
101
|
+
data-loom-proposal={p.graft}
|
|
102
|
+
className="rounded-lg border bg-muted/40 p-3 text-sm"
|
|
103
|
+
>
|
|
104
|
+
<p className="font-medium">
|
|
105
|
+
{p.reason ?? t('loom.proposal.title', { defaultValue: 'Cambios propuestos' })}
|
|
106
|
+
</p>
|
|
107
|
+
<table className="mt-2 w-full text-xs">
|
|
108
|
+
<thead className="sr-only">
|
|
109
|
+
<tr>
|
|
110
|
+
<th>{t('loom.proposal.field', { defaultValue: 'Campo' })}</th>
|
|
111
|
+
<th>{t('loom.proposal.before', { defaultValue: 'Antes' })}</th>
|
|
112
|
+
<th>{t('loom.proposal.after', { defaultValue: 'Después' })}</th>
|
|
113
|
+
</tr>
|
|
114
|
+
</thead>
|
|
115
|
+
<tbody>
|
|
116
|
+
{keys.map((k) => {
|
|
117
|
+
const same = show(values[k]) === show(p.patch[k])
|
|
118
|
+
return (
|
|
119
|
+
<tr key={k} data-field={k} className={same ? 'text-muted-foreground' : undefined}>
|
|
120
|
+
<td className="py-0.5 pr-2 font-medium">{label(p, k)}</td>
|
|
121
|
+
<td className="py-0.5 pr-2 text-muted-foreground line-through decoration-muted-foreground/50">
|
|
122
|
+
{same ? '' : show(values[k])}
|
|
123
|
+
</td>
|
|
124
|
+
<td className="py-0.5">{show(p.patch[k])}</td>
|
|
125
|
+
</tr>
|
|
126
|
+
)
|
|
127
|
+
})}
|
|
128
|
+
</tbody>
|
|
129
|
+
</table>
|
|
130
|
+
<div className="mt-2 flex gap-2">
|
|
131
|
+
<Button type="button" size="sm" onClick={() => queue.accept(p.id)}>
|
|
132
|
+
{t('loom.proposal.apply', { defaultValue: 'Aplicar' })}
|
|
133
|
+
</Button>
|
|
134
|
+
<Button type="button" size="sm" variant="ghost" onClick={() => queue.discard(p.id)}>
|
|
135
|
+
{t('loom.proposal.discard', { defaultValue: 'Descartar' })}
|
|
136
|
+
</Button>
|
|
137
|
+
</div>
|
|
138
|
+
</section>
|
|
139
|
+
)
|
|
140
|
+
})}
|
|
141
|
+
{queue.applied ? (
|
|
142
|
+
<div role="status" className="flex items-center justify-between gap-2 rounded-lg border px-3 py-2 text-xs" data-loom-applied="">
|
|
143
|
+
<span>
|
|
144
|
+
{t('loom.proposal.applied', {
|
|
145
|
+
defaultValue: 'Se aplicaron {{count}} campos',
|
|
146
|
+
count: Object.keys(queue.applied.patch).length,
|
|
147
|
+
})}
|
|
148
|
+
</span>
|
|
149
|
+
<Button type="button" size="sm" variant="ghost" onClick={queue.undo}>
|
|
150
|
+
{t('loom.proposal.undo', { defaultValue: 'Deshacer' })}
|
|
151
|
+
</Button>
|
|
152
|
+
</div>
|
|
153
|
+
) : null}
|
|
154
|
+
</div>
|
|
155
|
+
)
|
|
156
|
+
}
|