@asteby/metacore-runtime-react 53.27.0 → 53.29.0

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.
Files changed (88) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/business/customer-picker.d.ts +10 -1
  3. package/dist/business/customer-picker.d.ts.map +1 -1
  4. package/dist/business/customer-picker.js +7 -2
  5. package/dist/dialogs/create-record-dialog.d.ts +1 -1
  6. package/dist/dialogs/create-record-dialog.d.ts.map +1 -1
  7. package/dist/dialogs/create-record-dialog.js +2 -2
  8. package/dist/dialogs/dynamic-record.d.ts +19 -2
  9. package/dist/dialogs/dynamic-record.d.ts.map +1 -1
  10. package/dist/dialogs/dynamic-record.js +83 -25
  11. package/dist/dialogs/types.d.ts +6 -0
  12. package/dist/dialogs/types.d.ts.map +1 -1
  13. package/dist/dynamic-crud-page.d.ts.map +1 -1
  14. package/dist/dynamic-crud-page.js +3 -0
  15. package/dist/dynamic-form.d.ts.map +1 -1
  16. package/dist/dynamic-form.js +6 -5
  17. package/dist/field-widget-registry.d.ts +6 -0
  18. package/dist/field-widget-registry.d.ts.map +1 -1
  19. package/dist/index.d.ts +4 -1
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +3 -1
  22. package/dist/loom/index.d.ts +9 -0
  23. package/dist/loom/index.d.ts.map +1 -0
  24. package/dist/loom/index.js +9 -0
  25. package/dist/loom/overlay.d.ts +74 -0
  26. package/dist/loom/overlay.d.ts.map +1 -0
  27. package/dist/loom/overlay.js +142 -0
  28. package/dist/loom/proposals.d.ts +26 -0
  29. package/dist/loom/proposals.d.ts.map +1 -0
  30. package/dist/loom/proposals.js +74 -0
  31. package/dist/loom/provider.d.ts +28 -0
  32. package/dist/loom/provider.d.ts.map +1 -0
  33. package/dist/loom/provider.js +31 -0
  34. package/dist/loom/resolve.d.ts +23 -0
  35. package/dist/loom/resolve.d.ts.map +1 -0
  36. package/dist/loom/resolve.js +138 -0
  37. package/dist/loom/seam.d.ts +28 -0
  38. package/dist/loom/seam.d.ts.map +1 -0
  39. package/dist/loom/seam.js +127 -0
  40. package/dist/loom/seams.d.ts +31 -0
  41. package/dist/loom/seams.d.ts.map +1 -0
  42. package/dist/loom/seams.js +21 -0
  43. package/dist/loom/store.d.ts +16 -0
  44. package/dist/loom/store.d.ts.map +1 -0
  45. package/dist/loom/store.js +72 -0
  46. package/dist/loom/types.d.ts +153 -0
  47. package/dist/loom/types.d.ts.map +1 -0
  48. package/dist/loom/types.js +1 -0
  49. package/dist/model-labels.d.ts +26 -0
  50. package/dist/model-labels.d.ts.map +1 -1
  51. package/dist/model-labels.js +22 -5
  52. package/dist/record-picker-dialog.d.ts +10 -1
  53. package/dist/record-picker-dialog.d.ts.map +1 -1
  54. package/dist/record-picker-dialog.js +18 -3
  55. package/dist/record-picker.d.ts +6 -0
  56. package/dist/record-picker.d.ts.map +1 -1
  57. package/dist/record-picker.js +4 -1
  58. package/dist/types.d.ts +10 -0
  59. package/dist/types.d.ts.map +1 -1
  60. package/package.json +6 -6
  61. package/src/__tests__/dynamic-record-seam.test.tsx +194 -0
  62. package/src/__tests__/dynamic-record-texts.test.tsx +22 -0
  63. package/src/__tests__/field-widget-set-values.test.tsx +65 -0
  64. package/src/__tests__/loom-overlay.test.ts +94 -0
  65. package/src/__tests__/loom-resolve.test.ts +108 -0
  66. package/src/__tests__/model-labels.test.tsx +41 -1
  67. package/src/__tests__/record-picker-open-on-focus.test.tsx +49 -0
  68. package/src/business/customer-picker.tsx +17 -0
  69. package/src/dialogs/create-record-dialog.tsx +6 -0
  70. package/src/dialogs/dynamic-record.tsx +131 -26
  71. package/src/dialogs/types.ts +6 -0
  72. package/src/dynamic-crud-page.tsx +3 -0
  73. package/src/dynamic-form.tsx +9 -2
  74. package/src/field-widget-registry.tsx +6 -0
  75. package/src/index.ts +4 -1
  76. package/src/loom/index.ts +36 -0
  77. package/src/loom/overlay.ts +196 -0
  78. package/src/loom/proposals.tsx +156 -0
  79. package/src/loom/provider.tsx +69 -0
  80. package/src/loom/resolve.ts +136 -0
  81. package/src/loom/seam.tsx +235 -0
  82. package/src/loom/seams.ts +42 -0
  83. package/src/loom/store.ts +81 -0
  84. package/src/loom/types.ts +167 -0
  85. package/src/model-labels.ts +45 -5
  86. package/src/record-picker-dialog.tsx +42 -1
  87. package/src/record-picker.tsx +10 -0
  88. package/src/types.ts +10 -0
@@ -0,0 +1,235 @@
1
+ // <Seam> — punto de extensión tipado. El anfitrión publica el contrato (lentes con
2
+ // clase de datos, campos escribibles, intenciones) y Seam monta los injertos que
3
+ // lo cumplen: cada uno aislado (error boundary + Suspense + carga perezosa), con
4
+ // sólo las lentes que declaró y un `propose` atenuado a sus `writes`.
5
+ import {
6
+ lazy,
7
+ Suspense,
8
+ useCallback,
9
+ useMemo,
10
+ useRef,
11
+ useSyncExternalStore,
12
+ type ComponentType,
13
+ type LazyExoticComponent,
14
+ type ReactNode,
15
+ } from 'react'
16
+ import { FederatedErrorBoundary } from '../federated-error-boundary'
17
+ import { useCan } from '../permissions-context'
18
+ import { useLoomConfig } from './provider'
19
+ import { attenuatePatch, projectLenses, redactMessage, resolveSeam, sensitiveClasses } from './resolve'
20
+ import { getPart, listGrafts, loomVersion, subscribeLoom } from './store'
21
+ import type {
22
+ GraftCapabilities,
23
+ GraftComponent,
24
+ GraftDef,
25
+ GraftModule,
26
+ LoomEvent,
27
+ ProposalInput,
28
+ Proposal,
29
+ ResolvedSeam,
30
+ SeamContract,
31
+ } from './types'
32
+
33
+ export interface SeamHostContext {
34
+ model?: string
35
+ mode?: string
36
+ }
37
+
38
+ /** Injertos de un seam ya resueltos (montados + descartados con motivo). */
39
+ export function useSeam(contract: SeamContract, host: SeamHostContext = {}): ResolvedSeam {
40
+ const cfg = useLoomConfig()
41
+ const can = useCan()
42
+ const v = useSyncExternalStore(subscribeLoom, loomVersion, loomVersion)
43
+ return useMemo(() => {
44
+ const local = listGrafts(contract.id)
45
+ const byId = new Map<string, GraftDef>()
46
+ for (const g of local) byId.set(g.id, g)
47
+ // Lo servido manda en metadatos (orden, props); el código local aporta el componente.
48
+ for (const s of cfg?.grafts ?? []) {
49
+ if (s.seam !== contract.id) continue
50
+ const l = byId.get(s.id)
51
+ byId.set(s.id, l ? { ...l, ...s, component: l.component, load: s.load ?? l.load, part: s.part ?? l.part } : s)
52
+ }
53
+ const granted = cfg?.serverAuthoritative ? new Set((cfg.grafts ?? []).map((g) => g.id)) : undefined
54
+ return resolveSeam(contract, [...byId.values()], {
55
+ can,
56
+ flags: cfg?.flags,
57
+ settings: cfg?.settings,
58
+ model: host.model,
59
+ mode: host.mode,
60
+ granted,
61
+ })
62
+ // eslint-disable-next-line react-hooks/exhaustive-deps
63
+ }, [contract, cfg, can, host.model, host.mode, v])
64
+ }
65
+
66
+ const lazyCache = new WeakMap<() => Promise<GraftModule>, LazyExoticComponent<ComponentType<any>>>()
67
+
68
+ function toLazy(load: () => Promise<GraftModule>): LazyExoticComponent<ComponentType<any>> {
69
+ let c = lazyCache.get(load)
70
+ if (!c) {
71
+ c = lazy(async () => {
72
+ const mod = await load()
73
+ const C = (mod as { default?: GraftComponent }).default ?? mod
74
+ if (typeof C !== 'function' && !(C && typeof C === 'object' && '$$typeof' in C)) {
75
+ throw new Error('el módulo del injerto no exporta un componente')
76
+ }
77
+ return { default: C as ComponentType<any> }
78
+ })
79
+ lazyCache.set(load, c)
80
+ }
81
+ return c
82
+ }
83
+
84
+ function componentOf(g: GraftDef): ComponentType<any> | null {
85
+ if (g.component) return g.component
86
+ if (g.load) return toLazy(g.load)
87
+ const p = g.part ? getPart(g.part) : undefined
88
+ if (p?.component) return p.component
89
+ if (p?.load) return toLazy(p.load)
90
+ return null
91
+ }
92
+
93
+ export interface SeamProps {
94
+ contract: SeamContract
95
+ /** Valores de las lentes del contrato. */
96
+ lenses: Readonly<Record<string, unknown>>
97
+ host?: SeamHostContext
98
+ /** Recibe las propuestas ya atenuadas. Sin él, el seam no acepta propuestas. */
99
+ onProposal?: (p: Proposal) => void
100
+ /** Atiende una intención; devuelve true si la manejó. */
101
+ onIntent?: (intent: string, payload: unknown, graft: GraftDef) => boolean
102
+ /** Mientras un injerto perezoso baja. */
103
+ loading?: ReactNode
104
+ className?: string
105
+ }
106
+
107
+ let proposalSeq = 0
108
+
109
+ function GraftMount({
110
+ graft,
111
+ contract,
112
+ lenses,
113
+ onProposal,
114
+ onIntent,
115
+ loading,
116
+ report,
117
+ }: {
118
+ graft: GraftDef
119
+ contract: SeamContract
120
+ lenses: Readonly<Record<string, unknown>>
121
+ onProposal?: (p: Proposal) => void
122
+ onIntent?: SeamProps['onIntent']
123
+ loading: ReactNode
124
+ report: (e: LoomEvent) => void
125
+ }) {
126
+ const can = useCan()
127
+ const addon = graft.addon ?? graft.id.split('.')[0] ?? 'host'
128
+ const C = useMemo(() => componentOf(graft), [graft])
129
+ const view = useMemo(() => projectLenses(lenses, graft.reads), [lenses, graft.reads])
130
+ const classes = useMemo(() => sensitiveClasses(contract, graft.reads), [contract, graft.reads])
131
+ const live = useRef({ onProposal, onIntent, report })
132
+ live.current = { onProposal, onIntent, report }
133
+
134
+ const propose = useCallback(
135
+ (input: ProposalInput) => {
136
+ const { allowed, dropped } = attenuatePatch(input.patch, graft.writes, contract.writable)
137
+ if (dropped.length) {
138
+ live.current.report({ type: 'proposal_dropped_keys', seam: contract.id, graft: graft.id, addon, keys: dropped })
139
+ }
140
+ if (!Object.keys(allowed).length || !live.current.onProposal) return
141
+ live.current.onProposal({
142
+ ...input,
143
+ patch: allowed,
144
+ id: `${graft.id}#${++proposalSeq}`,
145
+ graft: graft.id,
146
+ addon,
147
+ previous: {},
148
+ dropped,
149
+ })
150
+ },
151
+ [graft.id, graft.writes, contract.id, contract.writable, addon],
152
+ )
153
+ const emit = useCallback(
154
+ (intent: string, payload?: unknown) => {
155
+ if (!contract.intents?.includes(intent)) return false
156
+ return live.current.onIntent?.(intent, payload, graft) ?? false
157
+ },
158
+ [contract.intents, graft],
159
+ )
160
+ const caps = useMemo<GraftCapabilities>(() => ({ propose, emit, can }), [propose, emit, can])
161
+ const meta = useMemo(() => ({ id: graft.id, addon, seam: contract.id }), [graft.id, addon, contract.id])
162
+
163
+ if (!C) return null
164
+ return (
165
+ <div data-loom-graft={graft.id} data-loom-addon={addon} style={{ display: 'contents' }}>
166
+ <FederatedErrorBoundary
167
+ addonKey={addon}
168
+ onError={(err) =>
169
+ report({
170
+ type: 'graft_failed',
171
+ seam: contract.id,
172
+ graft: graft.id,
173
+ addon,
174
+ reason: 'render',
175
+ message: redactMessage(err.message, classes),
176
+ })
177
+ }
178
+ // Falla en silencio: el anfitrión sigue igual que sin el injerto.
179
+ fallback={() => null}
180
+ >
181
+ <Suspense fallback={loading}>
182
+ <C lenses={view} props={graft.props ?? EMPTY} caps={caps} graft={meta} />
183
+ </Suspense>
184
+ </FederatedErrorBoundary>
185
+ </div>
186
+ )
187
+ }
188
+
189
+ const EMPTY: Record<string, unknown> = Object.freeze({}) as Record<string, unknown>
190
+
191
+ export function Seam({ contract, lenses, host, onProposal, onIntent, loading = null, className }: SeamProps) {
192
+ const cfg = useLoomConfig()
193
+ const resolved = useSeam(contract, host)
194
+ const report = useCallback((e: LoomEvent) => cfg?.onEvent?.(e), [cfg])
195
+ if (!resolved.mounted.length && !cfg?.inspect) return null
196
+ return (
197
+ <div data-loom-seam={contract.id} data-loom-seam-version={contract.version} className={className} style={className ? undefined : { display: 'contents' }}>
198
+ {resolved.mounted.map((g) => (
199
+ <GraftMount
200
+ key={g.id}
201
+ graft={g}
202
+ contract={contract}
203
+ lenses={lenses}
204
+ onProposal={onProposal}
205
+ onIntent={onIntent}
206
+ loading={loading}
207
+ report={report}
208
+ />
209
+ ))}
210
+ {cfg?.inspect ? <SeamInspector contract={contract} resolved={resolved} /> : null}
211
+ </div>
212
+ )
213
+ }
214
+
215
+ /** Inspector de desarrollo: qué llena el seam y por qué lo demás no se montó. */
216
+ export function SeamInspector({ contract, resolved }: { contract: SeamContract; resolved: ResolvedSeam }) {
217
+ return (
218
+ <details data-loom-inspector={contract.id} className="rounded border border-dashed border-primary/50 px-2 py-1 text-[11px] text-muted-foreground">
219
+ <summary>
220
+ {contract.id}@{contract.version} · {resolved.mounted.length} montados · {resolved.skipped.length} no
221
+ </summary>
222
+ <ul>
223
+ {resolved.mounted.map((g) => (
224
+ <li key={g.id}>montado: {g.id}</li>
225
+ ))}
226
+ {resolved.skipped.map((s) => (
227
+ <li key={s.graft.id}>
228
+ no montado: {s.graft.id}: {s.reason}
229
+ {s.detail ? ` (${s.detail})` : ''}
230
+ </li>
231
+ ))}
232
+ </ul>
233
+ </details>
234
+ )
235
+ }
@@ -0,0 +1,42 @@
1
+ // Catálogo de seams del SDK (contratos versionados). Cada seam documenta sus
2
+ // lentes (con clase de datos), lo que acepta como propuesta y sus intenciones.
3
+ import type { SeamContract } from './types'
4
+
5
+ /** Arriba del formulario de DynamicRecordDialog (alta/edición). */
6
+ export const RECORD_DIALOG_HEADER = 'record.dialog.header'
7
+ /** Debajo de los campos del formulario, antes del pie: contenido (no sólo botones) dentro del modal. */
8
+ export const RECORD_FORM_SECTION = 'record.form.section'
9
+ export type RecordFormSeam = typeof RECORD_DIALOG_HEADER | typeof RECORD_FORM_SECTION
10
+
11
+ export interface RecordDialogHeaderLenses {
12
+ /** Modelo del formulario (`Customer`). */
13
+ model: string
14
+ mode: 'create' | 'edit'
15
+ /** Id del registro en edición. */
16
+ recordId?: string
17
+ /** Valores vivos del formulario. Clase `pii`: pueden traer datos personales. */
18
+ values: Record<string, unknown>
19
+ /** Campos del formulario: `{ key, label, type }`. */
20
+ fields: Array<{ key: string; label: string; type?: string }>
21
+ }
22
+
23
+ /**
24
+ * Contrato v1 de `record.dialog.header` y `record.form.section` (mismas lentes y propuestas).
25
+ * `writable` = campos editables que el formulario
26
+ * declara (lo calcula el diálogo). Intenciones:
27
+ * - `record.select` `{ record }`: usar un registro existente en lugar de crear (p. ej. el
28
+ * RFC ya existe). Lo atiende quien abrió el diálogo (CustomerPicker la convierte en selección).
29
+ * - `record.edit` `{ id, patch }`: abrir la edición de otro registro con `patch` como propuesta.
30
+ */
31
+ export function recordDialogHeaderContract(
32
+ writable: ReadonlySet<string>,
33
+ id: RecordFormSeam = RECORD_DIALOG_HEADER,
34
+ ): SeamContract {
35
+ return {
36
+ id,
37
+ version: '1.0.0',
38
+ lenses: { model: 'public', mode: 'public', recordId: 'internal', values: 'pii', fields: 'public' },
39
+ writable,
40
+ intents: ['record.select', 'record.edit'],
41
+ }
42
+ }
@@ -0,0 +1,81 @@
1
+ // Registro en proceso de Parts e injertos. Mismo patrón observable que
2
+ // field-widget-registry / slotStore: Map de módulo + versión para useSyncExternalStore.
3
+ // Cada entrada lleva su addon dueño para soltarla en bloque (unbind del fiber).
4
+ import type { GraftDef, PartDef } from './types'
5
+
6
+ type Listener = () => void
7
+
8
+ const grafts = new Map<string, { def: GraftDef; seq: number }>()
9
+ const parts = new Map<string, PartDef>()
10
+ const listeners = new Set<Listener>()
11
+ let version = 0
12
+ let seq = 0
13
+
14
+ function emit(): void {
15
+ version++
16
+ for (const l of [...listeners]) l()
17
+ }
18
+
19
+ /** Registra (o reemplaza, mismo id) un injerto. Devuelve el disposer. */
20
+ export function registerGraft(def: GraftDef): () => void {
21
+ const entry = { def, seq: ++seq }
22
+ grafts.set(def.id, entry)
23
+ emit()
24
+ return () => {
25
+ if (grafts.get(def.id) === entry) {
26
+ grafts.delete(def.id)
27
+ emit()
28
+ }
29
+ }
30
+ }
31
+
32
+ /** Registra (o reemplaza) un componente expuesto. */
33
+ export function registerPart(def: PartDef): () => void {
34
+ parts.set(def.id, def)
35
+ emit()
36
+ return () => {
37
+ if (parts.get(def.id) === def) {
38
+ parts.delete(def.id)
39
+ emit()
40
+ }
41
+ }
42
+ }
43
+
44
+ export function getPart(id: string): PartDef | undefined {
45
+ return parts.get(id)
46
+ }
47
+
48
+ /** Injertos registrados para un seam, en orden de registro. */
49
+ export function listGrafts(seam?: string): GraftDef[] {
50
+ return [...grafts.values()]
51
+ .filter((e) => !seam || e.def.seam === seam)
52
+ .sort((a, b) => a.seq - b.seq)
53
+ .map((e) => e.def)
54
+ }
55
+
56
+ /** Quita todo lo de un addon (unbind). Devuelve cuántas entradas. */
57
+ export function unregisterLoomByAddon(addon: string): number {
58
+ let n = 0
59
+ for (const [id, e] of [...grafts]) if (e.def.addon === addon) (grafts.delete(id), n++)
60
+ for (const [id, p] of [...parts]) if (p.addon === addon) (parts.delete(id), n++)
61
+ if (n) emit()
62
+ return n
63
+ }
64
+
65
+ export function clearLoom(): void {
66
+ if (!grafts.size && !parts.size) return
67
+ grafts.clear()
68
+ parts.clear()
69
+ emit()
70
+ }
71
+
72
+ export function subscribeLoom(l: Listener): () => void {
73
+ listeners.add(l)
74
+ return () => {
75
+ listeners.delete(l)
76
+ }
77
+ }
78
+
79
+ export function loomVersion(): number {
80
+ return version
81
+ }
@@ -0,0 +1,167 @@
1
+ // Loom — contratos del sistema de contribuciones de UI (RFC 0005 del kernel).
2
+ //
3
+ // Seam punto de extensión tipado de un componente anfitrión (`record.dialog.header`).
4
+ // Part componente expuesto por un addon con contrato (`fiscal_mexico.csf-import`).
5
+ // Graft injerto: Part → Seam con orden, condiciones, lentes leídas y campos escritos.
6
+ // Lens proyección de solo lectura del contexto del seam, con clase de datos.
7
+ // Proposal lo que un injerto quiere cambiar: el anfitrión lo aplica, lo muestra como diff o lo descarta.
8
+ //
9
+ // El servidor es la fuente de verdad de QUÉ injertos ve el usuario (RBAC, ajustes, preset);
10
+ // el cliente vuelve a filtrar sólo para UX y explica por qué algo no se montó.
11
+ import type { ComponentType } from 'react'
12
+
13
+ /** Clase de datos de una lente. Decide la redacción en errores/telemetría. */
14
+ export type DataClass = 'public' | 'internal' | 'money' | 'pii' | 'pii.fiscal' | 'secret'
15
+
16
+ /** Contrato que el anfitrión publica para un seam. */
17
+ export interface SeamContract {
18
+ id: string
19
+ /** Semver del contrato (`1.0.0`). Un injerto declara `requires: '^1'`. */
20
+ version: string
21
+ /** Lentes que el seam ofrece y su clase de datos. */
22
+ lenses: Readonly<Record<string, DataClass>>
23
+ /**
24
+ * Campos que un injerto puede proponer cambiar en este seam. `undefined` = el seam no
25
+ * acepta propuestas. El anfitrión lo calcula (p. ej. los campos editables del formulario).
26
+ */
27
+ writable?: ReadonlySet<string>
28
+ /** Intenciones que el anfitrión atiende (`record.select`, `record.edit`). */
29
+ intents?: readonly string[]
30
+ }
31
+
32
+ export type GraftKind = 'view' | 'action' | 'transform' | 'source'
33
+
34
+ /** Condiciones de montaje. Todas las presentes deben cumplirse. */
35
+ export interface GraftWhen {
36
+ /** Todos estos permisos RBAC. */
37
+ permission?: string | string[]
38
+ /** Al menos uno de estos permisos. */
39
+ anyPermission?: string[]
40
+ /** Feature flag activo. */
41
+ flag?: string
42
+ /** Ajuste de la organización/addon: presente y verdadero, o igual a `equals`. */
43
+ setting?: { key: string; equals?: unknown }
44
+ /** Modelos del anfitrión (acepta `Customer` o `customers.Customer`). */
45
+ model?: string[]
46
+ /** Modos del anfitrión (`create`, `edit`, `view`). */
47
+ mode?: string[]
48
+ }
49
+
50
+ export interface GraftCapabilities {
51
+ /** Proponer un parche. Sólo pasan los campos de `writes` ∩ `contract.writable`. */
52
+ propose: (p: ProposalInput) => void
53
+ /** Pedir al anfitrión una intención declarada en el contrato. false = nadie la atendió. */
54
+ emit: (intent: string, payload?: unknown) => boolean
55
+ /** RBAC del usuario actual (mismo `useCan` del host). */
56
+ can: (permission: string) => boolean
57
+ }
58
+
59
+ export interface GraftProps<P = Record<string, unknown>> {
60
+ /** Sólo las lentes declaradas en `reads`, congeladas. */
61
+ lenses: Readonly<Record<string, unknown>>
62
+ /** Props estáticas del manifiesto/registro. */
63
+ props: P
64
+ caps: GraftCapabilities
65
+ graft: { id: string; addon: string; seam: string }
66
+ }
67
+
68
+ export type GraftComponent<P = Record<string, unknown>> = ComponentType<GraftProps<P>>
69
+
70
+ export type GraftModule = GraftComponent<any> | { default: GraftComponent<any> }
71
+
72
+ /** Componente expuesto por un addon (lo que el manifiesto llama `extension_points.parts[]`). */
73
+ export interface PartDef {
74
+ /** `<addon>.<nombre>`. */
75
+ id: string
76
+ addon?: string
77
+ version?: string
78
+ component?: GraftComponent<any>
79
+ /** Carga perezosa (chunk local o remoto federado). */
80
+ load?: () => Promise<GraftModule>
81
+ }
82
+
83
+ export interface GraftDef {
84
+ /** Id estable `<addon>.<nombre>`; registrar el mismo id reemplaza. */
85
+ id: string
86
+ addon?: string
87
+ seam: string
88
+ /** Rango semver del contrato del seam (`^1`). Sin él, cualquiera. */
89
+ requires?: string
90
+ kind?: GraftKind
91
+ /** Ascendente; empates por orden de registro. */
92
+ order?: number
93
+ when?: GraftWhen
94
+ /** Lentes que lee. Una lente no declarada no llega. */
95
+ reads?: string[]
96
+ /** Campos que puede proponer cambiar. Admite `prefijo.*`. */
97
+ writes?: string[]
98
+ /** Red que necesita (declarativo; lo hace cumplir el sandbox/CSP, ver RFC §Seguridad). */
99
+ network?: 'none' | 'org' | string[]
100
+ offline?: boolean
101
+ props?: Record<string, unknown>
102
+ /** Part que monta (registrado con `registerPart`) o el componente en línea. */
103
+ part?: string
104
+ component?: GraftComponent<any>
105
+ load?: () => Promise<GraftModule>
106
+ }
107
+
108
+ export interface ProposalInput {
109
+ patch: Record<string, unknown>
110
+ /** Por qué (se muestra al usuario): «Datos de la constancia fiscal». */
111
+ reason?: string
112
+ /** 0..1. */
113
+ confidence?: number
114
+ /** Etiquetas legibles por campo, si el injerto las conoce. */
115
+ labels?: Record<string, string>
116
+ /** `review` (por omisión) o `auto` si el preset lo permite. */
117
+ apply?: 'review' | 'auto'
118
+ }
119
+
120
+ export interface Proposal extends ProposalInput {
121
+ id: string
122
+ graft: string
123
+ addon: string
124
+ /** Valores antes del parche (para el diff y el deshacer). */
125
+ previous: Record<string, unknown>
126
+ /** Claves descartadas por no estar en `writes`/`writable`. */
127
+ dropped: string[]
128
+ }
129
+
130
+ export type SkipReason =
131
+ | 'not_granted'
132
+ | 'permission'
133
+ | 'flag'
134
+ | 'setting'
135
+ | 'model'
136
+ | 'mode'
137
+ | 'version'
138
+ | 'no_component'
139
+
140
+ export interface SkippedGraft {
141
+ graft: GraftDef
142
+ reason: SkipReason
143
+ detail?: string
144
+ }
145
+
146
+ export interface ResolvedSeam {
147
+ mounted: GraftDef[]
148
+ skipped: SkippedGraft[]
149
+ }
150
+
151
+ /** Lo que el anfitrión sabe del usuario/organización para evaluar `when`. */
152
+ export interface LoomEnv {
153
+ can: (permission: string) => boolean
154
+ flags?: ReadonlySet<string>
155
+ settings?: Readonly<Record<string, unknown>>
156
+ model?: string
157
+ mode?: string
158
+ /**
159
+ * Ids de injertos que el servidor autorizó para este usuario. Presente = el cliente no monta
160
+ * nada fuera de la lista (el servidor manda). Ausente = sólo código local de confianza.
161
+ */
162
+ granted?: ReadonlySet<string>
163
+ }
164
+
165
+ export type LoomEvent =
166
+ | { type: 'graft_failed'; seam: string; graft: string; addon: string; reason: 'load' | 'render'; message: string }
167
+ | { type: 'proposal_dropped_keys'; seam: string; graft: string; addon: string; keys: string[] }
@@ -16,6 +16,12 @@ import { useTranslation } from 'react-i18next'
16
16
  * `models.<model>.new` exists the label is `common.new_model` interpolated
17
17
  * with the singular name (`{{prefix}} {{name}}`), prefix overridable via
18
18
  * `common.new`.
19
+ *
20
+ * Backend-declared names (already localized by the kernel/bridge) slot in below
21
+ * the host i18n keys: `singular_label` feeds the singular and `new_label` the
22
+ * create label, so a backend that ships "cliente"/"Nuevo cliente" never needs a
23
+ * per-model i18n entry. The create prefix honours grammatical gender
24
+ * (`common.new_f` = "Nueva", `common.new_m` = "Nuevo") before the neutral `common.new`.
19
25
  */
20
26
  export type ModelLabelT = (key: string, opts?: Record<string, unknown>) => string
21
27
 
@@ -29,6 +35,12 @@ export interface ModelLabelInput {
29
35
  newPrefix?: string
30
36
  titleOverride?: string
31
37
  newLabelOverride?: string
38
+ /** Backend singular noun (`singular_label`), e.g. "cliente". */
39
+ singularLabel?: string
40
+ /** Backend create label (`new_label`), e.g. "Nuevo cliente". */
41
+ newLabelMeta?: string
42
+ /** Grammatical gender of the singular ("m" | "f" | "n"); picks `common.new_<gender>`. */
43
+ gender?: string
32
44
  }
33
45
 
34
46
  export interface ModelLabels {
@@ -60,21 +72,49 @@ export function resolveModelLabels(t: ModelLabelT, input: ModelLabelInput): Mode
60
72
  input.title ??
61
73
  model
62
74
  const singular =
63
- tryKey(t, `models.${model}.singular`) ?? defaultSingular(title)
75
+ tryKey(t, `models.${model}.singular`) ?? input.singularLabel ?? defaultSingular(title)
64
76
  const newLabel =
65
77
  input.newLabelOverride ??
66
78
  tryKey(t, `models.${model}.new`) ??
67
- `${tryKey(t, 'common.new') ?? input.newPrefix ?? 'New'} ${singular}`
79
+ input.newLabelMeta ??
80
+ `${tryKey(t, input.gender ? `common.new_${input.gender}` : undefined) ?? tryKey(t, 'common.new') ?? input.newPrefix ?? 'New'} ${singular}`
68
81
  return { title, singular, newLabel }
69
82
  }
70
83
 
84
+ export interface ModelNounInput {
85
+ model: string
86
+ singularLabel?: string
87
+ titleKey?: string
88
+ title?: string
89
+ }
90
+
91
+ /**
92
+ * Noun used inside dialog verbs ("Editar {noun}"). Order: host i18n
93
+ * `models.<model>.singular` > backend `singular_label` > translated `titleKey`
94
+ * > backend `title`. Empty string when nothing is known (caller falls back).
95
+ */
96
+ export function resolveModelNoun(t: ModelLabelT, input: ModelNounInput): string {
97
+ return (
98
+ tryKey(t, input.model ? `models.${input.model}.singular` : undefined) ??
99
+ (input.singularLabel?.trim() || undefined) ??
100
+ tryKey(t, input.titleKey) ??
101
+ input.title ??
102
+ ''
103
+ )
104
+ }
105
+
106
+ /** Dialog verb ("Crear {{name}}", "Editar {{name}}", "Eliminar {{name}}") through i18n `dynamic.<verb>_title`. */
107
+ export function modelVerbTitle(t: ModelLabelT, verb: 'create' | 'edit' | 'delete', name: string, fallback: string): string {
108
+ return t(`dynamic.${verb}_title`, { name, defaultValue: fallback })
109
+ }
110
+
71
111
  /** Hook form of {@link resolveModelLabels}, bound to the active i18n instance. */
72
112
  export function useModelLabels(input: ModelLabelInput): ModelLabels {
73
113
  const { t, i18n } = useTranslation()
74
- const { model, title, titleKey, newPrefix, titleOverride, newLabelOverride } = input
114
+ const { model, title, titleKey, newPrefix, titleOverride, newLabelOverride, singularLabel, newLabelMeta, gender } = input
75
115
  return useMemo(
76
- () => resolveModelLabels(t as unknown as ModelLabelT, { model, title, titleKey, newPrefix, titleOverride, newLabelOverride }),
116
+ () => resolveModelLabels(t as unknown as ModelLabelT, { model, title, titleKey, newPrefix, titleOverride, newLabelOverride, singularLabel, newLabelMeta, gender }),
77
117
  // eslint-disable-next-line react-hooks/exhaustive-deps
78
- [t, i18n?.language, model, title, titleKey, newPrefix, titleOverride, newLabelOverride],
118
+ [t, i18n?.language, model, title, titleKey, newPrefix, titleOverride, newLabelOverride, singularLabel, newLabelMeta, gender],
79
119
  )
80
120
  }
@@ -10,6 +10,7 @@
10
10
  import { unwrapResponse } from '@asteby/metacore-lib/envelope'
11
11
  import { useState, type ReactNode } from 'react'
12
12
  import { CreateRecordDialog } from './dialogs/create-record-dialog'
13
+ import type { FieldDef } from './dialogs/dynamic-record'
13
14
  import { useApi } from './api-context'
14
15
  import { withSearchPrefill } from './record-picker-actions'
15
16
 
@@ -24,6 +25,14 @@ export interface UseRecordPickerDialogOptions {
24
25
  createDefaults?: Record<string, unknown>
25
26
  /** Fields of `createDefaults` rendered locked on create. */
26
27
  lockedCreateFields?: string[]
28
+ /** Fields merged into the modal schema (e.g. a `widget` field that fills siblings via `setValues`). */
29
+ ensureFields?: FieldDef[]
30
+ /**
31
+ * Un injerto del modal (Loom `record.dialog.header`) detectó que el registro ya existe y pide
32
+ * usarlo (`record.select`): se cierra el modal y se entrega el registro. Sin él, la intención
33
+ * no se atiende y el injerto sigue su camino (p. ej. rellena el formulario).
34
+ */
35
+ onSelectExisting?: (record: Record<string, unknown>) => void
27
36
  /** The saved record (`{ id, ...fields }`). */
28
37
  onSaved: (record: Record<string, unknown>, kind: 'create' | 'edit') => void
29
38
  }
@@ -43,14 +52,43 @@ export function useRecordPickerDialog({
43
52
  prefillField = 'name',
44
53
  createDefaults,
45
54
  lockedCreateFields,
55
+ ensureFields,
56
+ onSelectExisting,
46
57
  onSaved,
47
58
  }: UseRecordPickerDialogOptions): UseRecordPickerDialogResult {
48
59
  const api = useApi()
49
60
  const base = endpoint ?? `/data/${model}/me`
50
- const [state, setState] = useState<{ recordId?: string; defaults?: Record<string, unknown> } | null>(null)
61
+ const [state, setState] = useState<{
62
+ recordId?: string
63
+ defaults?: Record<string, unknown>
64
+ proposal?: { patch: Record<string, unknown>; reason?: string; apply?: 'review' | 'auto' }
65
+ } | null>(null)
66
+
67
+ // Intenciones Loom: `record.select` entrega el existente; `record.edit` reabre en edición con
68
+ // el parche como propuesta revisable (nada se guarda sin confirmar).
69
+ const onIntent = (intent: string, payload: unknown): boolean => {
70
+ const p = (payload ?? {}) as {
71
+ record?: Record<string, unknown>
72
+ id?: unknown
73
+ patch?: Record<string, unknown>
74
+ reason?: string
75
+ apply?: 'review' | 'auto'
76
+ }
77
+ if (intent === 'record.select' && onSelectExisting && p.record) {
78
+ setState(null)
79
+ onSelectExisting(p.record)
80
+ return true
81
+ }
82
+ if (intent === 'record.edit' && p.id != null) {
83
+ setState({ recordId: String(p.id), proposal: p.patch ? { patch: p.patch, reason: p.reason, apply: p.apply } : undefined })
84
+ return true
85
+ }
86
+ return false
87
+ }
51
88
 
52
89
  const dialog = state ? (
53
90
  <CreateRecordDialog
91
+ key={state.recordId ?? 'new'}
54
92
  modelKey={model}
55
93
  open
56
94
  onOpenChange={(o) => {
@@ -60,6 +98,9 @@ export function useRecordPickerDialog({
60
98
  endpoint={base}
61
99
  defaults={state.recordId ? undefined : state.defaults}
62
100
  lockedFields={state.recordId ? undefined : lockedCreateFields}
101
+ ensureFields={ensureFields}
102
+ onIntent={onIntent}
103
+ initialProposal={state.proposal}
63
104
  onCreate={async (data) => {
64
105
  const rec = unwrapRecord(await api.post(base, data))
65
106
  onSaved(rec, 'create')