@entifix/next-shell 0.23.1 → 0.23.3

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.
@@ -27,6 +27,12 @@ export interface EntityCrudFormProps<TEntity extends Entity> {
27
27
  * record": the host drops the draft and the failure and loads it again.
28
28
  */
29
29
  readonly onLoadCurrent?: () => void;
30
+ /**
31
+ * Told whenever the draft starts or stops differing from the record it was
32
+ * seeded from. The host uses it to hold a refetched record back while there
33
+ * is unsaved input (ADR 0032 §8): a newer record must not reseed over it.
34
+ */
35
+ readonly onDirtyChange?: (dirty: boolean) => void;
30
36
  readonly onSave: (entity: TEntity) => void;
31
37
  /** Omitted for a create — there is nothing to delete yet. */
32
38
  readonly onDelete?: () => void;
@@ -64,5 +70,5 @@ export interface EntityCrudFormProps<TEntity extends Entity> {
64
70
  * `useEntityForm` owns the draft and seeds it once, so the page keys this
65
71
  * component by the record id to reseed when the record arrives.
66
72
  */
67
- export declare function EntityCrudForm<TEntity extends Entity>({ entityConstructor, catalogKey, hiddenFields, links, entity, isLoading, isSaving, isPending, isDeleting, error, onRetry, onConflictResolved, onLoadCurrent, onSave, onDelete, deletePolicy, backHref, renderLink, draft, metadataSource, onUseCase, }: EntityCrudFormProps<TEntity>): import("react").JSX.Element;
73
+ export declare function EntityCrudForm<TEntity extends Entity>({ entityConstructor, catalogKey, hiddenFields, links, entity, isLoading, isSaving, isPending, isDeleting, error, onRetry, onConflictResolved, onLoadCurrent, onDirtyChange, onSave, onDelete, deletePolicy, backHref, renderLink, draft, metadataSource, onUseCase, }: EntityCrudFormProps<TEntity>): import("react").JSX.Element;
68
74
  //# sourceMappingURL=entity-crud-form.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"entity-crud-form.d.ts","sourceRoot":"","sources":["../../../src/lib/crud/entity-crud-form.tsx"],"names":[],"mappings":"AAEA,OAAO,EACL,KAAK,cAAc,EACnB,KAAK,MAAM,EACX,KAAK,iBAAiB,EACtB,KAAK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AE,gBAAgB,CAAC;IAClC;;;;OAIG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,oBAAoB,CAAC;IAC/C,sEAAsE;IACtE,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;CAC5C;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,cAAc,CAAC,OAAO,SAAS,MAAM,EAAE,EACrD,iBAAiB,EACjB,UAAU,EACV,YAAY,EACZ,KAAK,EACL,MAAM,EACN,SAAiB,EACjB,QAAgB,EAChB,SAAiB,EACjB,UAAkB,EAClB,KAAK,EACL,OAAO,EACP,kBAAkB,EAClB,aAAa,EACb,aAAa,EACb,MAAM,EACN,QAAQ,EACR,YAAY,EACZ,QAAQ,EACR,UAAU,EACV,KAAK,EACL,cAAc,EACd,SAAS,GACV,EAAE,mBAAmB,CAAC,OAAO,CAAC,+BAqI9B"}
@@ -21,7 +21,7 @@ import { useEntityLinkSources } from './use-entity-link-sources.js';
21
21
  *
22
22
  * `useEntityForm` owns the draft and seeds it once, so the page keys this
23
23
  * component by the record id to reseed when the record arrives.
24
- */ export function EntityCrudForm({ entityConstructor, catalogKey, hiddenFields, links, entity, isLoading = false, isSaving = false, isPending = false, isDeleting = false, error, onRetry, onConflictResolved, onLoadCurrent, onSave, onDelete, deletePolicy, backHref, renderLink, draft, metadataSource, onUseCase }) {
24
+ */ export function EntityCrudForm({ entityConstructor, catalogKey, hiddenFields, links, entity, isLoading = false, isSaving = false, isPending = false, isDeleting = false, error, onRetry, onConflictResolved, onLoadCurrent, onDirtyChange, onSave, onDelete, deletePolicy, backHref, renderLink, draft, metadataSource, onUseCase }) {
25
25
  const et = useT('entity');
26
26
  // A runtime-key translator, so a message names the field by its catalog word
27
27
  // (`labelKey`) and a schema's keyed message resolves at all. Without it both
@@ -36,6 +36,13 @@ import { useEntityLinkSources } from './use-entity-link-sources.js';
36
36
  existing: entity
37
37
  }))
38
38
  });
39
+ const { isDirty } = form;
40
+ useEffect(()=>{
41
+ onDirtyChange == null ? void 0 : onDirtyChange(isDirty);
42
+ }, [
43
+ isDirty,
44
+ onDirtyChange
45
+ ]);
39
46
  const linkSources = useEntityLinkSources(links, {
40
47
  values: form.values,
41
48
  selection: form.links
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/crud/entity-crud-form.tsx"],"sourcesContent":["'use client';\n\nimport {\n type EntifixFailure,\n type Entity,\n type EntityConstructor,\n type EntityMetadataSource,\n reconstructEntity,\n REVISION_KEY,\n} from '@entifix/core';\nimport {\n EntityField,\n EntityForm,\n type RenderLink,\n useT,\n useTranslateKey,\n} from '@entifix/react-controls';\nimport {\n type EntityDraftStore,\n useEntityForm,\n} from '@entifix/react-integration';\nimport { useEffect } from 'react';\n\nimport type {\n EntityCatalogKey,\n EntityCrudLinkSource,\n} from './make-entity-crud.types.js';\nimport { useEntityAffordances } from './use-entity-affordances.js';\nimport { useEntityLinkSources } from './use-entity-link-sources.js';\n\nexport interface EntityCrudFormProps<TEntity extends Entity> {\n readonly entityConstructor: EntityConstructor<TEntity>;\n readonly catalogKey: EntityCatalogKey;\n readonly hiddenFields: readonly string[];\n readonly links: readonly EntityCrudLinkSource[];\n /** The record being edited; `undefined` means this is a create. */\n readonly entity?: TEntity;\n readonly isLoading?: boolean;\n readonly isSaving?: boolean;\n /** A write handed to a flow that has not settled: the form waits, keeping its input. */\n readonly isPending?: boolean;\n readonly isDeleting?: boolean;\n readonly error?: EntifixFailure;\n /** Loads the record again — offered as Retry on a failed load. */\n readonly onRetry?: () => void;\n /**\n * A save refused as `staleRevision` was answered with \"keep my changes\": the\n * host forgets the failure so the form is ready for the next, explicit, Save.\n */\n readonly onConflictResolved?: () => void;\n /**\n * A save refused as `staleRevision` was answered with \"load the current\n * record\": the host drops the draft and the failure and loads it again.\n */\n readonly onLoadCurrent?: () => void;\n readonly onSave: (entity: TEntity) => void;\n /** Omitted for a create — there is nothing to delete yet. */\n readonly onDelete?: () => void;\n /** How Delete is made safe — see `EntityCrudOptions.delete`. */\n readonly deletePolicy?: 'confirm' | 'undo' | 'typed';\n readonly backHref: string;\n /** Renders the Back link; see `useCrudRenderLink`. */\n readonly renderLink?: RenderLink;\n /**\n * Where to autosave this form's draft. Omitted by a route host, which is what\n * keeps a plain route ephemeral; the workspace tab host supplies one.\n */\n readonly draft?: EntityDraftStore;\n /**\n * Where this caller's affordances come from. Absent keeps the pre-ADR-0026\n * behaviour: Save and Delete render unconditionally and no declared verb\n * appears — which is what every generated catalog did before it existed.\n */\n readonly metadataSource?: EntityMetadataSource;\n /** Runs a declared `entity`-bound verb on this record, by its key. */\n readonly onUseCase?: (key: string) => void;\n}\n\n/**\n * The generated create/update form. A thin wrapper over the agnostic\n * {@link EntityForm}: every field, label and validation rule comes from the\n * entity's own accessor metadata, and `reconstructEntity` derives the submit\n * rebuild from that same metadata — so nothing here is per-entity but the\n * constructor, the catalog key and the hidden-field list.\n *\n * A hidden member still round-trips. `code` is assigned by the create\n * transaction and never shown, but it is a plain writable member, so the rebuild\n * picks it out of the seeded draft; dropping it from the rendered fields is not\n * dropping it from the draft.\n *\n * `useEntityForm` owns the draft and seeds it once, so the page keys this\n * component by the record id to reseed when the record arrives.\n */\nexport function EntityCrudForm<TEntity extends Entity>({\n entityConstructor,\n catalogKey,\n hiddenFields,\n links,\n entity,\n isLoading = false,\n isSaving = false,\n isPending = false,\n isDeleting = false,\n error,\n onRetry,\n onConflictResolved,\n onLoadCurrent,\n onSave,\n onDelete,\n deletePolicy,\n backHref,\n renderLink,\n draft,\n metadataSource,\n onUseCase,\n}: EntityCrudFormProps<TEntity>) {\n const et = useT('entity');\n\n // A runtime-key translator, so a message names the field by its catalog word\n // (`labelKey`) and a schema's keyed message resolves at all. Without it both\n // fell back to untranslated text inside an otherwise Spanish sentence.\n const translateKey = useTranslateKey();\n\n const form = useEntityForm<TEntity>({\n entityConstructor,\n entity,\n translateKey,\n draft,\n onSubmit: values =>\n onSave(\n reconstructEntity(entityConstructor, values, { existing: entity }),\n ),\n });\n\n const linkSources = useEntityLinkSources(links, {\n values: form.values,\n selection: form.links,\n });\n\n // Refill the relation sidecar from the ids the draft did keep.\n //\n // A draft is JSON, so it holds ids and nothing else; the instances behind them\n // die with the page. Each picker already resolves its id — that is how a\n // restored draft shows a brand's name instead of its key — so the instance is\n // in hand and only has to be handed back. Without this, a member declared\n // `linkSerialization: 'embedded'` reaches `applyEntityLinks` with an id and no\n // target, which it refuses rather than writing the wrong wire shape.\n //\n // `hydrateLink`, not `setLink`: this is a lookup landing, not a pick, so it\n // must leave the draft — and the form's dirty flag — alone.\n const { links: selection, hydrateLink } = form;\n useEffect(() => {\n for (const [field, source] of Object.entries(linkSources)) {\n const resolved = source.selected.entity;\n if (resolved !== undefined && selection[field] === undefined) {\n hydrateLink(field, resolved);\n }\n }\n }, [linkSources, selection, hydrateLink]);\n\n // A save refused because the record moved on (ADR 0032). Keeping the typed\n // values is what this form already does; \"keep mine\" only takes the newer\n // revision as the one the next save names, and nothing here saves.\n const staleCurrent =\n error?.code === 'staleRevision'\n ? (error as { current?: unknown }).current\n : undefined;\n const keepMine =\n typeof staleCurrent === 'number' && onConflictResolved !== undefined\n ? () => {\n form.setField(REVISION_KEY, String(staleCurrent));\n onConflictResolved();\n }\n : undefined;\n\n const affordances = useEntityAffordances(entityConstructor, metadataSource);\n\n /**\n * May this caller write the record in front of them?\n *\n * The **same authority that withholds Save**, applied one step earlier.\n * Absent metadata keeps the pre-ADR-0026 behaviour, so an un-migrated call\n * site is untouched; present metadata is authoritative, because it is what\n * the service already decided.\n *\n * ⚠️ Without this the form rendered inputs nobody could submit. Measured on\n * the stock surface: `stock-item` answers `[\"read\"]` — no role holds\n * `stock-item:write` and there is no save route — so Save was correctly\n * absent while `onHand` and `reserved` still rendered as **enabled number\n * inputs**. A vendor could type a new quantity into a field that is only ever\n * moved by a ledger, and nothing would happen and nothing would say why.\n *\n * A create is exempt: there is no record yet, so there is nothing to read and\n * a `read` mode would render an empty form with no way to fill it.\n */\n const mayWrite =\n entity === undefined ||\n affordances.metadata === undefined ||\n affordances.metadata.actions.includes('write');\n\n return (\n <EntityForm<TEntity>\n entityConstructor={entityConstructor}\n entity={entity}\n // Driven by the served descriptor rather than fixed: `edit` for a caller\n // who may write, `read` for one who may not. Passing it at all is what\n // suppresses the built-in Ver/Editar toggle, which would otherwise offer\n // a way back into inputs the service will refuse.\n mode={mayWrite ? 'edit' : 'read'}\n values={form.values}\n onFieldChange={form.setField}\n linkSources={linkSources}\n onLinkChange={form.setLink}\n errors={form.errors}\n formError={form.formError}\n onSubmit={form.submit}\n onDelete={onDelete}\n deletePolicy={deletePolicy}\n {...affordances}\n onUseCase={onUseCase}\n isLoading={isLoading}\n isSaving={isSaving}\n isPending={isPending}\n isDeleting={isDeleting}\n error={error}\n onRetry={onRetry}\n onKeepMine={keepMine}\n onLoadCurrent={onLoadCurrent}\n backHref={backHref}\n renderLink={renderLink}\n // `entity` is undefined until the record lands, so testing it alone\n // titled a loading edit form \"New\" and then relabelled it.\n title={et(\n entity || isLoading\n ? `${catalogKey}.form.editTitle`\n : `${catalogKey}.form.newTitle`,\n )}\n >\n {hiddenFields.map(field => (\n <EntityField<TEntity> key={field} field={field} hidden />\n ))}\n </EntityForm>\n );\n}\n"],"names":["reconstructEntity","REVISION_KEY","EntityField","EntityForm","useT","useTranslateKey","useEntityForm","useEffect","useEntityAffordances","useEntityLinkSources","EntityCrudForm","entityConstructor","catalogKey","hiddenFields","links","entity","isLoading","isSaving","isPending","isDeleting","error","onRetry","onConflictResolved","onLoadCurrent","onSave","onDelete","deletePolicy","backHref","renderLink","draft","metadataSource","onUseCase","et","translateKey","form","onSubmit","values","existing","linkSources","selection","hydrateLink","field","source","Object","entries","resolved","selected","undefined","staleCurrent","code","current","keepMine","setField","String","affordances","mayWrite","metadata","actions","includes","mode","onFieldChange","onLinkChange","setLink","errors","formError","submit","onKeepMine","title","map","hidden"],"mappings":"AAAA;;;AAEA,SAKEA,iBAAiB,EACjBC,YAA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AW,eAAe,CAAC,GAC9B,GAAGA,WAAW,cAAc,CAAC;kBAGlCC,aAAauD,GAAG,CAAC3B,CAAAA,sBAChB,KAACvC;gBAAiCuC,OAAOA;gBAAO4B,MAAM;eAA3B5B;;AAInC"}
1
+ {"version":3,"sources":["../../../src/lib/crud/entity-crud-form.tsx"],"sourcesContent":["'use client';\n\nimport {\n type EntifixFailure,\n type Entity,\n type EntityConstructor,\n type EntityMetadataSource,\n reconstructEntity,\n REVISION_KEY,\n} from '@entifix/core';\nimport {\n EntityField,\n EntityForm,\n type RenderLink,\n useT,\n useTranslateKey,\n} from '@entifix/react-controls';\nimport {\n type EntityDraftStore,\n useEntityForm,\n} from '@entifix/react-integration';\nimport { useEffect } from 'react';\n\nimport type {\n EntityCatalogKey,\n EntityCrudLinkSource,\n} from './make-entity-crud.types.js';\nimport { useEntityAffordances } from './use-entity-affordances.js';\nimport { useEntityLinkSources } from './use-entity-link-sources.js';\n\nexport interface EntityCrudFormProps<TEntity extends Entity> {\n readonly entityConstructor: EntityConstructor<TEntity>;\n readonly catalogKey: EntityCatalogKey;\n readonly hiddenFields: readonly string[];\n readonly links: readonly EntityCrudLinkSource[];\n /** The record being edited; `undefined` means this is a create. */\n readonly entity?: TEntity;\n readonly isLoading?: boolean;\n readonly isSaving?: boolean;\n /** A write handed to a flow that has not settled: the form waits, keeping its input. */\n readonly isPending?: boolean;\n readonly isDeleting?: boolean;\n readonly error?: EntifixFailure;\n /** Loads the record again — offered as Retry on a failed load. */\n readonly onRetry?: () => void;\n /**\n * A save refused as `staleRevision` was answered with \"keep my changes\": the\n * host forgets the failure so the form is ready for the next, explicit, Save.\n */\n readonly onConflictResolved?: () => void;\n /**\n * A save refused as `staleRevision` was answered with \"load the current\n * record\": the host drops the draft and the failure and loads it again.\n */\n readonly onLoadCurrent?: () => void;\n /**\n * Told whenever the draft starts or stops differing from the record it was\n * seeded from. The host uses it to hold a refetched record back while there\n * is unsaved input (ADR 0032 §8): a newer record must not reseed over it.\n */\n readonly onDirtyChange?: (dirty: boolean) => void;\n readonly onSave: (entity: TEntity) => void;\n /** Omitted for a create — there is nothing to delete yet. */\n readonly onDelete?: () => void;\n /** How Delete is made safe — see `EntityCrudOptions.delete`. */\n readonly deletePolicy?: 'confirm' | 'undo' | 'typed';\n readonly backHref: string;\n /** Renders the Back link; see `useCrudRenderLink`. */\n readonly renderLink?: RenderLink;\n /**\n * Where to autosave this form's draft. Omitted by a route host, which is what\n * keeps a plain route ephemeral; the workspace tab host supplies one.\n */\n readonly draft?: EntityDraftStore;\n /**\n * Where this caller's affordances come from. Absent keeps the pre-ADR-0026\n * behaviour: Save and Delete render unconditionally and no declared verb\n * appears — which is what every generated catalog did before it existed.\n */\n readonly metadataSource?: EntityMetadataSource;\n /** Runs a declared `entity`-bound verb on this record, by its key. */\n readonly onUseCase?: (key: string) => void;\n}\n\n/**\n * The generated create/update form. A thin wrapper over the agnostic\n * {@link EntityForm}: every field, label and validation rule comes from the\n * entity's own accessor metadata, and `reconstructEntity` derives the submit\n * rebuild from that same metadata — so nothing here is per-entity but the\n * constructor, the catalog key and the hidden-field list.\n *\n * A hidden member still round-trips. `code` is assigned by the create\n * transaction and never shown, but it is a plain writable member, so the rebuild\n * picks it out of the seeded draft; dropping it from the rendered fields is not\n * dropping it from the draft.\n *\n * `useEntityForm` owns the draft and seeds it once, so the page keys this\n * component by the record id to reseed when the record arrives.\n */\nexport function EntityCrudForm<TEntity extends Entity>({\n entityConstructor,\n catalogKey,\n hiddenFields,\n links,\n entity,\n isLoading = false,\n isSaving = false,\n isPending = false,\n isDeleting = false,\n error,\n onRetry,\n onConflictResolved,\n onLoadCurrent,\n onDirtyChange,\n onSave,\n onDelete,\n deletePolicy,\n backHref,\n renderLink,\n draft,\n metadataSource,\n onUseCase,\n}: EntityCrudFormProps<TEntity>) {\n const et = useT('entity');\n\n // A runtime-key translator, so a message names the field by its catalog word\n // (`labelKey`) and a schema's keyed message resolves at all. Without it both\n // fell back to untranslated text inside an otherwise Spanish sentence.\n const translateKey = useTranslateKey();\n\n const form = useEntityForm<TEntity>({\n entityConstructor,\n entity,\n translateKey,\n draft,\n onSubmit: values =>\n onSave(\n reconstructEntity(entityConstructor, values, { existing: entity }),\n ),\n });\n\n const { isDirty } = form;\n useEffect(() => {\n onDirtyChange?.(isDirty);\n }, [isDirty, onDirtyChange]);\n\n const linkSources = useEntityLinkSources(links, {\n values: form.values,\n selection: form.links,\n });\n\n // Refill the relation sidecar from the ids the draft did keep.\n //\n // A draft is JSON, so it holds ids and nothing else; the instances behind them\n // die with the page. Each picker already resolves its id — that is how a\n // restored draft shows a brand's name instead of its key — so the instance is\n // in hand and only has to be handed back. Without this, a member declared\n // `linkSerialization: 'embedded'` reaches `applyEntityLinks` with an id and no\n // target, which it refuses rather than writing the wrong wire shape.\n //\n // `hydrateLink`, not `setLink`: this is a lookup landing, not a pick, so it\n // must leave the draft — and the form's dirty flag — alone.\n const { links: selection, hydrateLink } = form;\n useEffect(() => {\n for (const [field, source] of Object.entries(linkSources)) {\n const resolved = source.selected.entity;\n if (resolved !== undefined && selection[field] === undefined) {\n hydrateLink(field, resolved);\n }\n }\n }, [linkSources, selection, hydrateLink]);\n\n // A save refused because the record moved on (ADR 0032). Keeping the typed\n // values is what this form already does; \"keep mine\" only takes the newer\n // revision as the one the next save names, and nothing here saves.\n const staleCurrent =\n error?.code === 'staleRevision'\n ? (error as { current?: unknown }).current\n : undefined;\n const keepMine =\n typeof staleCurrent === 'number' && onConflictResolved !== undefined\n ? () => {\n form.setField(REVISION_KEY, String(staleCurrent));\n onConflictResolved();\n }\n : undefined;\n\n const affordances = useEntityAffordances(entityConstructor, metadataSource);\n\n /**\n * May this caller write the record in front of them?\n *\n * The **same authority that withholds Save**, applied one step earlier.\n * Absent metadata keeps the pre-ADR-0026 behaviour, so an un-migrated call\n * site is untouched; present metadata is authoritative, because it is what\n * the service already decided.\n *\n * ⚠️ Without this the form rendered inputs nobody could submit. Measured on\n * the stock surface: `stock-item` answers `[\"read\"]` — no role holds\n * `stock-item:write` and there is no save route — so Save was correctly\n * absent while `onHand` and `reserved` still rendered as **enabled number\n * inputs**. A vendor could type a new quantity into a field that is only ever\n * moved by a ledger, and nothing would happen and nothing would say why.\n *\n * A create is exempt: there is no record yet, so there is nothing to read and\n * a `read` mode would render an empty form with no way to fill it.\n */\n const mayWrite =\n entity === undefined ||\n affordances.metadata === undefined ||\n affordances.metadata.actions.includes('write');\n\n return (\n <EntityForm<TEntity>\n entityConstructor={entityConstructor}\n entity={entity}\n // Driven by the served descriptor rather than fixed: `edit` for a caller\n // who may write, `read` for one who may not. Passing it at all is what\n // suppresses the built-in Ver/Editar toggle, which would otherwise offer\n // a way back into inputs the service will refuse.\n mode={mayWrite ? 'edit' : 'read'}\n values={form.values}\n onFieldChange={form.setField}\n linkSources={linkSources}\n onLinkChange={form.setLink}\n errors={form.errors}\n formError={form.formError}\n onSubmit={form.submit}\n onDelete={onDelete}\n deletePolicy={deletePolicy}\n {...affordances}\n onUseCase={onUseCase}\n isLoading={isLoading}\n isSaving={isSaving}\n isPending={isPending}\n isDeleting={isDeleting}\n error={error}\n onRetry={onRetry}\n onKeepMine={keepMine}\n onLoadCurrent={onLoadCurrent}\n backHref={backHref}\n renderLink={renderLink}\n // `entity` is undefined until the record lands, so testing it alone\n // titled a loading edit form \"New\" and then relabelled it.\n title={et(\n entity || isLoading\n ? `${catalogKey}.form.editTitle`\n : `${catalogKey}.form.newTitle`,\n )}\n >\n {hiddenFields.map(field => (\n <EntityField<TEntity> key={field} field={field} hidden />\n ))}\n </EntityForm>\n );\n}\n"],"names":["reconstructEntity","REVISION_KEY","EntityField","EntityForm","useT","useTranslateKey","useEntityForm","useEffect","useEntityAffordances","useEntityLinkSources","EntityCrudForm","entityConstructor","catalogKey","hiddenFields","links","entity","isLoading","isSaving","isPending","isDeleting","error","onRetry","onConflictResolved","onLoadCurrent","onDirtyChange","onSave","onDelete","deletePolicy","backHref","renderLink","draft","metadataSource","onUseCase","et","translateKey","form","onSubmit","values","existing","isDirty","linkSources","selection","hydrateLink","field","source","Object","entries","resolved","selected","undefined","staleCurrent","code","current","keepMine","setField","String","affordances","mayWrite","metadata","actions","includes","mode","onFieldChange","onLinkChange","setLink","errors","formError","submit","onKeepMine","title","map","hidden"],"mappings":"AAAA;;;AAEA,SAKEA,iBAAiB,EACjBC,YAAY,QACP,gBAAgB;AACvB,SACEC,WAAW,EACXC,UAAU,EAEVC,IAAI,EACJC,eAAe,QACV,0BAA0B;AACjC,SAEEC,aAAa,QACR,6BAA6B;AACpC,SAASC,SAAS,QAAQ,QAAQ;AAMlC,SAASC,oBAAoB,QAAQ,8BAA8B;AACnE,SAASC,oBAAoB,QAAQ,+BAA+B;AAwDpE;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,eAAuC,EACrDC,iBAAiB,EACjBC,UAAU,EACVC,YAAY,EACZC,KAAK,EACLC,MAAM,EACNC,YAAY,KAAK,EACjBC,WAAW,KAAK,EAChBC,YAAY,KAAK,EACjBC,aAAa,KAAK,EAClBC,KAAK,EACLC,OAAO,EACPC,kBAAkB,EAClBC,aAAa,EACbC,aAAa,EACbC,MAAM,EACNC,QAAQ,EACRC,YAAY,EACZC,QAAQ,EACRC,UAAU,EACVC,KAAK,EACLC,cAAc,EACdC,SAAS,EACoB;IAC7B,MAAMC,KAAK7B,KAAK;IAEhB,6EAA6E;IAC7E,6EAA6E;IAC7E,uEAAuE;IACvE,MAAM8B,eAAe7B;IAErB,MAAM8B,OAAO7B,cAAuB;QAClCK;QACAI;QACAmB;QACAJ;QACAM,UAAUC,CAAAA,SACRZ,OACEzB,kBAAkBW,mBAAmB0B,QAAQ;gBAAEC,UAAUvB;YAAO;IAEtE;IAEA,MAAM,EAAEwB,OAAO,EAAE,GAAGJ;IACpB5B,UAAU;QACRiB,iCAAAA,cAAgBe;IAClB,GAAG;QAACA;QAASf;KAAc;IAE3B,MAAMgB,cAAc/B,qBAAqBK,OAAO;QAC9CuB,QAAQF,KAAKE,MAAM;QACnBI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CAAC,GAC7C,UAAU,CAAC,OAAO,CAAC,CAyrBrB"}
1
+ {"version":3,"file":"make-entity-crud.d.ts","sourceRoot":"","sources":["../../../src/lib/crud/make-entity-crud.tsx"],"names":[],"mappings":"AAEA,OAAO,EAIL,KAAK,mBAAmB,EAKzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAIL,KAAK,MAAM,EACX,KAAK,iBAAiB,EAkBvB,MAAM,eAAe,CAAC;AAmBvB,OAAO,EAAS,OAAO,EAAgB,MAAM,QAAQ,CAAC;AAQtD,OAAO,KAAK,EAEV,UAAU,EAGV,iBAAiB,EAGlB,MAAM,6BAA6B,CAAC;AAuBrC;;;;GAIG;AACH,MAAM,MAAM,WAAW,GAAG,mBAAmB,CAAC;AAE9C;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,SAAS,EACrC,QAAQ,EAAE,SAAS,EACnB,UAAU,EAAE,MAAM,SAAS,GAC1B,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,CAE9B;AAsID,wBAAgB,cAAc,CAAC,OAAO,SAAS,MAAM,EAAE,SAAS,EAC9D,iBAAiB,EAAE,iBAAiB,CAAC,OAAO,CAAC,EAC7C,OAAO,EAAE,iBAAiB,CAAC,SAAS,EAAE,OAAO,CAAC,GAC7C,UAAU,CAAC,OAAO,CAAC,CAmtBrB"}
@@ -8,7 +8,7 @@ import { entityQueryScope, useDataLoading, useEntityRecord, useFacetCounts, useO
8
8
  import { useQueryClient } from '@tanstack/react-query';
9
9
  import { Cause, Context, Effect, Exit } from 'effect';
10
10
  import { useParams, useRouter, useSearchParams } from 'next/navigation';
11
- import { useEffect, useId, useMemo, useRef } from 'react';
11
+ import { useEffect, useId, useMemo, useRef, useState } from 'react';
12
12
  import { useBreadcrumbLabel } from '../back-office/breadcrumb-labels.js';
13
13
  import { useLocaleHref } from '../i18n/index.js';
14
14
  import { useEntityNavHost } from '../workspace/entity-nav.js';
@@ -442,6 +442,23 @@ export function makeEntityCrud(entityConstructor, options) {
442
442
  ctx,
443
443
  id
444
444
  });
445
+ /**
446
+ * The record the form was seeded from, which is not always the one the
447
+ * query holds now (ADR 0032 §8).
448
+ *
449
+ * A query refetches on its own — on focus, on reconnect, after a verb — and
450
+ * a newer revision used to remount the form and reseed it, so input typed
451
+ * in another tab's shadow was replaced without a word and the save that
452
+ * should have answered `staleRevision` named the newer revision and went
453
+ * through. While the draft differs from its seed, the newer record is held
454
+ * beside the form instead: the save still names the revision the person
455
+ * read, the service refuses it, and the conflict alert offers the choice.
456
+ * A clean form takes the refetch, and so does a different record.
457
+ */ const [isDirty, setDirty] = useState(false);
458
+ const [seeded, setSeeded] = useState(entity);
459
+ const holds = isDirty && seeded !== undefined && seeded.id === (entity == null ? void 0 : entity.id);
460
+ if (seeded !== entity && !holds) setSeeded(entity);
461
+ const shown = holds ? seeded : entity;
445
462
  // Against the record as loaded, not the draft: the rule is about which
446
463
  // record this is, not what the operator has typed into it.
447
464
  const linkFilters = useLinkFilters(linkPlans, entity);
@@ -498,6 +515,7 @@ export function makeEntityCrud(entityConstructor, options) {
498
515
  }),
499
516
  confirm: ()=>{
500
517
  draft == null ? void 0 : draft.clear();
518
+ setDirty(false);
501
519
  void refreshList();
502
520
  if (mounted.current) afterSave();
503
521
  }
@@ -521,6 +539,8 @@ export function makeEntityCrud(entityConstructor, options) {
521
539
  // completed.
522
540
  if ((result == null ? void 0 : result._tag) !== 'settled') return;
523
541
  draft == null ? void 0 : draft.clear();
542
+ // The input is the record now: the next refetch reseeds the form.
543
+ setDirty(false);
524
544
  void refreshList();
525
545
  // Said in the toast region every route shares, so it survives the
526
546
  // navigation that follows (ADR 0028).
@@ -602,7 +622,8 @@ export function makeEntityCrud(entityConstructor, options) {
602
622
  metadataSource: metadataSource,
603
623
  hiddenFields: hiddenFields,
604
624
  links: linkSources,
605
- entity: entity,
625
+ entity: shown,
626
+ onDirtyChange: setDirty,
606
627
  isLoading: isLoading,
607
628
  isSaving: saveMutation.status === 'running',
608
629
  isPending: [
@@ -617,8 +638,10 @@ export function makeEntityCrud(entityConstructor, options) {
617
638
  onConflictResolved: saveMutation.reset,
618
639
  onLoadCurrent: id == null ? undefined : ()=>{
619
640
  // What was typed is given up on purpose: its draft goes, so
620
- // the reseed shows the record as it now stands.
641
+ // the reseed shows the record as it now stands — and nothing
642
+ // holds the newer record back any more.
621
643
  draft == null ? void 0 : draft.clear();
644
+ setDirty(false);
622
645
  saveMutation.reset();
623
646
  void reload();
624
647
  },
@@ -628,7 +651,7 @@ export function makeEntityCrud(entityConstructor, options) {
628
651
  backHref: withLocale(basePath),
629
652
  renderLink: renderLink,
630
653
  draft: formDraft
631
- }, `${String((_ref2 = entity == null ? void 0 : entity.id) != null ? _ref2 : CATALOG_NEW_SLUG)}:${(_readRevision = readRevision(entity)) != null ? _readRevision : ''}`);
654
+ }, `${String((_ref2 = shown == null ? void 0 : shown.id) != null ? _ref2 : CATALOG_NEW_SLUG)}:${(_readRevision = readRevision(shown)) != null ? _readRevision : ''}`);
632
655
  // The records that refer to this one, under its form: an existing record
633
656
  // only, since a record being created has nothing referring to it yet.
634
657
  if (regions === undefined || id == null || entity === undefined) return form;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/crud/make-entity-crud.tsx"],"sourcesContent":["'use client';\n\nimport {\n deleteUCFactory,\n type EntityFacetCounterTag,\n EntityIdTag,\n type EntityRepositoryTag,\n EntityTag,\n getUCFactory,\n loadUCFactory,\n saveUCFactory,\n} from '@entifix/business';\nimport {\n coerceFiltering,\n describeEntityColumns,\n type EntifixFailure,\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityMetadataSource,\n type EntitySelection,\n type EntityUseCaseRunner,\n type EntityWriter,\n envelopeEntityName,\n extractMetaEntity,\n type FilterGroup,\n Internal,\n isFailure,\n parseRsql,\n parseSort,\n readRevision,\n serializeRsql,\n serializeSort,\n settled,\n type UseCaseDescriptor,\n} from '@entifix/core';\nimport {\n EntityTable,\n useCasesForSurface,\n useFocusOnArrival,\n useRecordLabel,\n useT,\n useToasts,\n useTranslateKey,\n} from '@entifix/react-controls';\nimport {\n entityQueryScope,\n type OptimisticMutation,\n useDataLoading,\n useEntityRecord,\n useFacetCounts,\n useOptimisticMutation,\n} from '@entifix/react-integration';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { Cause, Context, Effect, Exit } from 'effect';\nimport { useParams, useRouter, useSearchParams } from 'next/navigation';\nimport { useEffect, useId, useMemo, useRef } from 'react';\n\nimport { useBreadcrumbLabel } from '../back-office/breadcrumb-labels.js';\nimport { useLocaleHref } from '../i18n/index.js';\nimport { useEntityNavHost } from '../workspace/entity-nav.js';\nimport { EntityCrudForm } from './entity-crud-form.js';\nimport type {\n AnyFilterGroup,\n EntityCrud,\n EntityCrudLinkSource,\n EntityCrudListView,\n EntityCrudOptions,\n EntityCrudRelatedListProps,\n EntityCrudSingleViewProps,\n} from './make-entity-crud.types.js';\nimport {\n PREFILL_PARAM,\n readPrefill,\n RecordRegions,\n useRegion,\n} from './regions.js';\nimport {\n planRelated,\n useRelatedColumns,\n useSuppliedRepositories,\n} from './related-columns.js';\nimport { CATALOG_NEW_SLUG, slugToEntityId } from './slug.js';\nimport { useCrudRenderLink } from './use-crud-render-link.js';\nimport { useEntityAffordances } from './use-entity-affordances.js';\nimport { useEntityBulk } from './use-entity-bulk.js';\n\n/** What a picker defaults to reading off its target. */\nconst TARGET_NAME_PROPERTY = 'name';\n\n/** A prefilled create with no host draft store keeps nothing between visits. */\nconst ignoreDraft = () => undefined;\n\n/**\n * What the generated pages' use-cases run against: one repository adapter.\n * Exported because a hand-built screen — a wizard reading records and\n * resolving pickers — runs against exactly the same.\n */\nexport type CrudContext = EntityRepositoryTag;\n\n/**\n * One repository adapter, by its key, as the context the use-cases run\n * against.\n *\n * The cast is the price of naming adapters by key: `AdapterKey` narrows which\n * names may be *offered*, but TypeScript will not carry that narrowing through\n * an index access on a generic record.\n */\nexport function crudContextOf<TAdapters>(\n adapters: TAdapters,\n repository: keyof TAdapters,\n): Context.Context<CrudContext> {\n return adapters[repository] as Context.Context<EntityRepositoryTag>;\n}\n\n/**\n * Builds the list page and the single-record page for one entity.\n *\n * Every catalog entity used to cost ~10 files and ~300 lines whose only variable\n * was a class name: two organisms with a `.types.ts` each, two client pages, two\n * route files. The route files stay (Next needs a module per path); everything\n * between them is derived from the entity's own metadata, so a new reference\n * entity is this call plus a nav entry.\n *\n * Two things are checked here rather than at the call site, because both fail\n * silently otherwise. The catalog key must be the entity's own `@entity({ key })`\n * — they are the same string by convention, and a drifted one titles the form\n * after a different entity in a way only a reader of both catalogs would catch.\n * And a `links` entry must name a real member — a picker aimed at nothing renders\n * identically to a read-only field.\n *\n * **Serves compile-time `@entity()` classes only.** Operator reference data ships\n * with the code, so making this spec-driven would trade type safety for nothing;\n * a vendor-authored `EntitySpecification` renders through a separate path.\n */\n/**\n * A rejected write, as something the form's error slot can render.\n *\n * A typed failure is kept as it is: `useErrorMessage` translates its own code,\n * a business refusal and an outage alike. Anything else is a bug that reached\n * the screen, and is shown as `Internal` — never with its own text, which\n * nobody wrote for a user.\n */\nfunction asFailure(failure: unknown): EntifixFailure {\n return isFailure(failure) ? failure : new Internal();\n}\n\n/**\n * What a write failed with *synchronously* — before any flow took it — or\n * `undefined`. A flow's own failure is toasted by the `PendingFlowsProvider`\n * that settles it, so showing it in the error slot too would tell the operator\n * twice.\n */\nfunction syncFailure(\n mutation: OptimisticMutation<never, unknown>,\n): EntifixFailure | undefined {\n return mutation.status === 'failed' && mutation.flowId === undefined\n ? asFailure(mutation.failure)\n : undefined;\n}\n\n/**\n * A runner's verbs, looked up by the key the served `$metadata` named. A\n * single verb answers either settle mode, so it is run through the optimistic\n * API; a bulk run reports per row and is awaited as a promise whose rejection\n * carries the failure itself.\n */\nfunction verbsOf(\n runner: EntityUseCaseRunner | undefined,\n served: readonly UseCaseDescriptor[] | undefined,\n) {\n if (runner === undefined) return undefined;\n // The key always comes from the served document, so it names a verb in it.\n const descriptor = (key: string) =>\n served?.find(candidate => candidate.key === key) as UseCaseDescriptor;\n return {\n run: (key: string, id: EntityId) => runner.run(descriptor(key), id),\n bulk: (key: string, selection: EntitySelection<Entity>) =>\n Effect.runPromiseExit(runner.bulk(descriptor(key), selection)).then(\n exit =>\n Exit.isSuccess(exit)\n ? exit.value\n : Promise.reject(Cause.squash(exit.cause)),\n ),\n };\n}\n\ntype Verbs = NonNullable<ReturnType<typeof verbsOf>>;\n\n/**\n * One verb on one record, through the optimistic API: `done` runs once the\n * verb took effect — at once when it settled, or when the flow it was handed\n * to completed.\n */\nfunction useVerb(verbs: Verbs | undefined, done: () => void) {\n const verb = useOptimisticMutation<\n { readonly key: string; readonly id: EntityId },\n unknown\n >({\n // Only ever sent from a handler that exists because `verbs` does.\n write: ({ key, id }) => (verbs as Verbs).run(key, id),\n confirm: done,\n });\n const run = (key: string, id: EntityId) => {\n void verb.mutate({ key, id }).then(\n result => {\n if (result._tag === 'settled') done();\n },\n // Shown through `syncFailure`, from the mutation's own state.\n () => undefined,\n );\n };\n return { verb, run };\n}\n\n/** Whether the component is still mounted: a flow can settle after it left. */\nfunction useMounted() {\n const mounted = useRef(true);\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n };\n }, []);\n return mounted;\n}\n\n/**\n * Runs each link's `useBaseFiltering` against the record being edited, in link\n * order, with `undefined` for a link that declares none.\n *\n * Legal for the reason `useEntityLinkSources` gives: the links are a\n * factory-time array, and whether a link carries a rule is fixed with it, so\n * the same hooks run in the same order on every render. The lint rule cannot\n * see a hook called through a member, so there is nothing for it to flag.\n */\nfunction useLinkFilters<TEntity extends Entity>(\n links: readonly {\n readonly useBaseFiltering?: (\n record: TEntity | undefined,\n ) => AnyFilterGroup | undefined;\n }[],\n record: TEntity | undefined,\n): (AnyFilterGroup | undefined)[] {\n return links.map(link => link.useBaseFiltering?.(record));\n}\n\nexport function makeEntityCrud<TEntity extends Entity, TAdapters>(\n entityConstructor: EntityConstructor<TEntity>,\n options: EntityCrudOptions<TAdapters, TEntity>,\n): EntityCrud<TEntity> {\n const {\n useAdapters,\n basePath,\n catalogKey,\n repository,\n hiddenFields = [],\n columns,\n toolbar,\n pageSize,\n initialFiltering,\n initialSorting,\n useListView,\n links = [],\n related = [],\n regions,\n metadataSource: givenMetadataSource,\n metadata,\n useCases,\n write,\n delete: deletePolicy = 'confirm',\n facets,\n } = options;\n\n if (givenMetadataSource !== undefined && metadata !== undefined) {\n throw new Error(\n `${entityConstructor.name} was given both metadataSource and metadata; pass one`,\n );\n }\n // An adapter value, so it is resolved per render from the same `useAdapters()`\n // the records come from — the host's composition, never the caller's module.\n const metadataSourceOf = (adapters: TAdapters) =>\n metadata === undefined\n ? givenMetadataSource\n : (adapters[metadata] as EntityMetadataSource);\n\n // Through the service's own trust boundary rather than a second walk of the\n // tree: serialized the way a load request carries it, then coerced against\n // the entity's `filterable` allowlist exactly as a service coerces a query.\n // Whatever would answer `400` on the wire throws here instead, when the\n // screen is generated, naming the member.\n // An emptied group serializes to nothing and filters nothing, so there is\n // nothing to check.\n const initialRsql =\n initialFiltering === undefined ? '' : serializeRsql([initialFiltering]);\n if (initialRsql !== '') {\n coerceFiltering(entityConstructor, parseRsql(initialRsql));\n }\n // The same posture for the order it opens in: parsed back through the\n // allowlist a service applies to a `sort` parameter.\n if (initialSorting !== undefined) {\n parseSort(entityConstructor, serializeSort([initialSorting]));\n }\n\n const meta = extractMetaEntity(entityConstructor);\n if (meta.key !== catalogKey) {\n throw new Error(\n `${entityConstructor.name} declares key \"${String(meta.key)}\" but was given catalog key \"${catalogKey}\"`,\n );\n }\n // Read off `@entity()` rather than rebuilt from `catalogKey`. Both spellings\n // produce the same string today, and that is exactly the problem: a second\n // place that knows how an entity's catalog subtree is laid out is a second\n // place to fix when one moves. `MetaEntityOptions` makes them optional, so an\n // entity that never declared them fails here — where a screen is generated —\n // rather than on the render that first tries to title a tab with `undefined`.\n const { labelKey: entityLabelKey, pluralKey: entityPluralKey } = meta;\n if (entityLabelKey === undefined || entityPluralKey === undefined) {\n throw new Error(\n `${entityConstructor.name} must declare labelKey and pluralKey on @entity() to be generated`,\n );\n }\n // Narrowed once, for the closures below that TypeScript cannot follow.\n const pluralKey: string = entityPluralKey;\n\n // The host's reading of who is reading, or nobody in particular. Called the\n // same way on every render — whether there is a hook is fixed with the\n // factory — so it is a hook call the rules allow.\n const useReaderView = (): EntityCrudListView => useListView?.() ?? {};\n const useListTitleKey = (): string => useReaderView().titleKey ?? pluralKey;\n\n // Computed once: a descriptor is a property of the class, so nothing about it\n // depends on the record being edited. `linkLabelProperty`/`linkSearchProperty`\n // are overridden here because a scalar foreign key's `@accessor()` cannot name\n // the target's members — it may not import the target at all.\n // The wire name, which is also what a pending flow's intent records and what\n // `entityQueryScopeFor` keys on — one derivation, so the two can never\n // disagree about which entity they mean.\n const entityName = envelopeEntityName(entityConstructor);\n const descriptors = describeEntityColumns(entityConstructor);\n /** The members a filter panel offers choices for, and so counts. */\n const facetMembers = descriptors\n .filter(\n descriptor =>\n descriptor.filterable &&\n (descriptor.type === 'enum' || descriptor.type === 'boolean'),\n )\n .map(({ name, key }) => ({ name, key }));\n const relatedPlans = planRelated(\n entityConstructor as EntityConstructor<Entity>,\n descriptors,\n related,\n );\n const linkPlans = links.map(link => {\n const descriptor = descriptors.find(entry => entry.name === link.field);\n if (descriptor === undefined) {\n throw new Error(\n `${entityConstructor.name} has no member \"${link.field}\" for a link source`,\n );\n }\n return {\n ...link,\n descriptor: {\n ...descriptor,\n linkLabelProperty: link.labelProperty ?? TARGET_NAME_PROPERTY,\n linkSearchProperty: link.searchProperty ?? TARGET_NAME_PROPERTY,\n },\n };\n });\n\n /**\n * The generated list itself — the table, its reads, its verbs — shared by the\n * list page and by a related region on another record's page. A region holds\n * it to a fixed filter that is not a removable chip and keeps its pager in\n * component state, never in the URL.\n */\n function ListBody({\n baseFiltering,\n newHref: givenNewHref,\n listPageSize = pageSize,\n listInitialFiltering,\n onVerbSettled,\n }: {\n baseFiltering?: FilterGroup<TEntity>;\n newHref?: string;\n listPageSize?: number;\n listInitialFiltering?: FilterGroup<TEntity>;\n onVerbSettled?: () => void;\n }) {\n const adapters = useAdapters();\n const { hiddenColumns } = useReaderView();\n // Every internal href carries the locale. An unprefixed one still resolves —\n // the middleware redirects it — but the visitor pays a round trip per click.\n const withLocale = useLocaleHref();\n\n const queryClient = useQueryClient();\n const scope = entityQueryScope(entityConstructor);\n const metadataSource = metadataSourceOf(adapters);\n const affordances = useEntityAffordances(entityConstructor, metadataSource);\n const renderLink = useCrudRenderLink(catalogKey);\n\n const pager = useDataLoading<TEntity, CrudContext>({\n uc: loadUCFactory<TEntity>(),\n ctx: crudContextOf(adapters, repository),\n // Scoped rather than left to the per-instance fallback, which is correct\n // but unshared: with the entity's own scope one invalidation refreshes\n // every page and filter of it, which is what a bulk run needs — and it is\n // the same prefix `useReactiveInvalidation`already targets, so a generated\n // list now also refreshes on a reactive change event.\n queryKey: scope,\n ...(listPageSize === undefined ? {} : { initialPageSize: listPageSize }),\n ...(listInitialFiltering === undefined\n ? {}\n : { initialFiltering: listInitialFiltering }),\n ...(initialSorting === undefined ? {} : { initialSorting }),\n ...(baseFiltering === undefined ? {} : { baseFiltering }),\n });\n\n // Values that live in another entity, one read per column per page.\n const supplied = useSuppliedRepositories(relatedPlans);\n const relatedColumns = useRelatedColumns<TAdapters, TEntity>(\n relatedPlans,\n pager.items,\n (plan, index) =>\n supplied[index] ??\n crudContextOf(adapters, plan.repository as keyof TAdapters),\n );\n\n const facetCounts = useFacetCounts<TEntity>({\n ctx:\n facets === undefined\n ? undefined\n : (adapters[facets] as Context.Context<EntityFacetCounterTag>),\n members: facetMembers,\n filtering: pager.filtering,\n scope,\n });\n\n // Only when this caller may actually run something over a selection.\n //\n // Measured live: an `admin` holds `catalog-reference:*:read` and no\n // `retire`, so the service filters the verb out of `$metadata` — but the\n // selection column still rendered, offering a set that no action could be\n // taken on. A checkbox that can lead nowhere is worse than no checkbox: it\n // reads as a permission the user does not have.\n //\n // Decided from the served document rather than from the runner, because\n // the runner is a property of the *shell* (it knows the route) and the\n // grant is a property of the *caller*. The column therefore appears when\n // the document lands, which is the asynchrony serving affordances accepts\n // for every action surface.\n const canRunBulk =\n useCasesForSurface('bulk-bar', affordances.metadata?.useCases).length > 0;\n\n const verbs = verbsOf(\n useCases === undefined\n ? undefined\n : (adapters[useCases] as EntityUseCaseRunner),\n affordances.metadata?.useCases,\n );\n\n const bulk = useEntityBulk<TEntity>({\n run:\n canRunBulk && verbs !== undefined\n ? (key, selection) =>\n verbs.bulk(key, selection as EntitySelection<Entity>)\n : undefined,\n // A bulk write changed the rows underneath the listing, so the page is\n // re-read; the selection deliberately survives it (\"the selection\n // is still there afterwards\"), because the operator's next act is usually\n // to retry the failures or run a second verb on the same rows.\n onCompleted: () => {\n void queryClient.invalidateQueries({ queryKey: scope });\n },\n });\n\n // What a row's overflow menu runs, and the one place the list reports a\n // verb that failed.\n //\n // ⚠️ **A row verb and the form's are the same runner with different\n // arguments.** `EntityTable` hands back the whole record, because that is\n // what it has; the runner takes an id, because that is what a route needs.\n // The list has no error slot of its own, so a failure lands in the\n // table's own error region — the same one a failed page read uses.\n const rowVerb = useVerb(verbs, () => {\n void queryClient.invalidateQueries({ queryKey: scope });\n onVerbSettled?.();\n });\n // Called unconditionally and the *result* gated, the way the surfaces are\n // read in `EntityForm`: the name begins with `use`, so short-circuiting it\n // reads to `react-hooks/rules-of-hooks` as a conditional hook.\n const rowUseCases = useCasesForSurface(\n 'row-menu',\n affordances.metadata?.useCases,\n );\n const canRunRowUseCase = verbs !== undefined && rowUseCases.length > 0;\n\n const handleRowUseCase = canRunRowUseCase\n ? (key: string, item: TEntity) => {\n if (item.id == null) return;\n rowVerb.run(key, item.id);\n }\n : undefined;\n\n return (\n <EntityTable\n entityConstructor={entityConstructor}\n {...(hiddenColumns === undefined ? {} : { hiddenColumns })}\n {...pager}\n items={pager.items}\n totalItems={pager.totalItems}\n hrefFor={id => withLocale(`${basePath}/${String(id)}`)}\n newHref={withLocale(givenNewHref ?? `${basePath}/${CATALOG_NEW_SLUG}`)}\n renderLink={renderLink}\n {...affordances}\n {...bulk.tableProps}\n onUseCase={handleRowUseCase}\n onRetry={pager.refetch}\n facets={facetCounts}\n error={syncFailure(rowVerb.verb) ?? pager.error}\n >\n {columns}\n {relatedColumns}\n {/* After the host's own: a host column for the same member wins. */}\n {toolbar}\n </EntityTable>\n );\n }\n\n function ListPage() {\n // The list's heading, and where focus lands when a save or a delete\n // brings the reader back here rather than falling to `<body>`.\n const heading = useRef<HTMLHeadingElement>(null);\n useFocusOnArrival(heading);\n const et = useT('entity');\n const titleKey = useListTitleKey();\n\n return (\n <div className=\"flex flex-col gap-s\">\n <h1\n ref={heading}\n tabIndex={-1}\n className=\"m-0 text-step-2 font-semibold text-content focus-ring\"\n >\n {et(titleKey.replace(/^entity:/, ''))}\n </h1>\n <ListBody\n {...(initialFiltering === undefined\n ? {}\n : { listInitialFiltering: initialFiltering })}\n />\n </div>\n );\n }\n\n /**\n * This entity's records that refer to another record, as a region of that\n * record's page\n * ([ADR 0030](../../../../../../docs/adr/0030-a-reference-names-its-target-through-the-owners-read-port.md)):\n * the generated list held to `filtering`, which is fixed and shown as no\n * chip, under its own `h2`, with its own states and its own writes. A verb\n * that settles inside it moves focus to that heading; nothing else on the\n * page is re-read or touched. `prefill` names the members a \"New\" from here\n * opens already set — the parent record's id.\n */\n function RelatedList({\n filtering,\n labelKey: headingKey,\n prefill,\n newHref,\n pageSize: regionPageSize,\n }: EntityCrudRelatedListProps<TEntity>) {\n const headingRef = useRef<HTMLHeadingElement>(null);\n const id = useId();\n const heading = useTranslateKey()(headingKey);\n useRegion(id, heading);\n const query = new URLSearchParams(\n Object.entries(prefill ?? {}).map(([member, value]): [string, string] => [\n `${PREFILL_PARAM}${member}`,\n value,\n ]),\n ).toString();\n return (\n <section\n id={id}\n aria-labelledby={`${id}-heading`}\n className=\"flex flex-col gap-s\"\n >\n <h2\n id={`${id}-heading`}\n ref={headingRef}\n tabIndex={-1}\n className=\"m-0 text-step-1 font-semibold text-content focus-ring\"\n >\n {heading}\n </h2>\n <ListBody\n baseFiltering={filtering}\n newHref={\n newHref ??\n `${basePath}/${CATALOG_NEW_SLUG}${query === '' ? '' : `?${query}`}`\n }\n {...(regionPageSize === undefined\n ? {}\n : { listPageSize: regionPageSize })}\n // The row's menu hands focus back to its trigger two frames after\n // the click, unless focus already sits on a tabbable element — and\n // this heading, at `tabIndex={-1}`, is not one. A verb that settles\n // inside those two frames would be focused and then taken back.\n // Frame callbacks run in the order they were asked for, and these\n // are asked for after the click's, so two frames from the settle\n // always run after the restore, never under it.\n onVerbSettled={() =>\n requestAnimationFrame(() =>\n requestAnimationFrame(() => headingRef.current?.focus()),\n )\n }\n />\n </section>\n );\n }\n\n /**\n * Dual-host: as a route it reads its slug from the URL and returns to the list\n * on save; in a workspace tab it takes the slug and the post-save action as\n * props.\n */\n function SingleViewPage({\n slug,\n onSaved,\n onDeleted,\n draft,\n }: EntityCrudSingleViewProps = {}) {\n const adapters = useAdapters();\n const metadataSource = metadataSourceOf(adapters);\n // The same served document the form reads its buttons from, so a key the\n // form hands back always names a verb in it.\n const affordances = useEntityAffordances(entityConstructor, metadataSource);\n const router = useRouter();\n const withLocale = useLocaleHref();\n const params = useParams<{ slug: string }>();\n const mounted = useMounted();\n const id = slugToEntityId(slug ?? params.slug);\n\n // A create opened from a related region starts with the parent record set:\n // `?prefill.<member>=<value>`, layered under any draft the host restores.\n const searchParams = useSearchParams();\n const prefill =\n id == null ? readPrefill(searchParams, descriptors) : undefined;\n const prefillKey = prefill === undefined ? '' : JSON.stringify(prefill);\n const formDraft = useMemo(\n () =>\n prefill === undefined\n ? draft\n : {\n draft: { ...prefill, ...draft?.draft },\n save: draft?.save ?? ignoreDraft,\n clear: draft?.clear ?? ignoreDraft,\n },\n // Keyed on the values, not the object a render builds them into.\n [draft, prefillKey],\n );\n\n const ctx = crudContextOf(adapters, repository);\n\n const {\n entity,\n isLoading,\n error: loadError,\n reload,\n } = useEntityRecord<TEntity, CrudContext>({\n uc: getUCFactory<TEntity>(),\n ctx,\n id,\n });\n\n // Against the record as loaded, not the draft: the rule is about which\n // record this is, not what the operator has typed into it.\n const linkFilters = useLinkFilters(linkPlans, entity);\n\n // Rebuilt inline on every render on purpose: `useEntityLinkSource` holds\n // these in a ref and keeps them out of its query keys, precisely so a caller\n // does not have to memoise them.\n const linkSources: EntityCrudLinkSource[] = linkPlans.map(\n (plan, index) => ({\n field: plan.field,\n descriptor: plan.descriptor,\n config: {\n entityConstructor: plan.entityConstructor,\n loadUc: loadUCFactory(),\n getUc: getUCFactory(),\n ctx: crudContextOf(adapters, plan.repository),\n // The config's target is erased to `Entity`, and the host's filter to\n // `any`; the two meet here, where neither type is the real target's.\n baseFiltering: linkFilters[index] as FilterGroup<Entity> | undefined,\n },\n }),\n );\n\n // Inside a workspace tab, \"back to the list\" is the list's tab, not a URL\n // that would leave the workspace. A host's own callbacks still win.\n const host = useEntityNavHost();\n const renderLink = useCrudRenderLink(catalogKey);\n const queryClient = useQueryClient();\n // The list this page returns to has its page cached, and it is no longer\n // true. Invalidated rather than patched: the service is the authority on\n // the row it stored.\n //\n // ⚠️ Invisible while every Open was a document load, which threw the cache\n // away anyway (#20): the first client-side navigation back to the list\n // showed the record as it was before the save.\n const refreshList = () =>\n queryClient.invalidateQueries({\n queryKey: entityQueryScope(entityConstructor),\n });\n const toList = () =>\n host === undefined\n ? router.push(withLocale(basePath))\n : host.toList(catalogKey);\n const afterSave = onSaved ?? toList;\n const afterDelete = onDeleted ?? toList;\n\n // Through the host's writer when it named one, which answers both settle\n // modes; otherwise through the repository, where every write settles.\n const writer =\n write === undefined ? undefined : (adapters[write] as EntityWriter);\n\n // The draft is spent once the write *commits*, and only here is that known:\n // `useEntityForm` neither fetches nor saves, so it cannot clear its own.\n // A failed write — or a failed flow — deliberately keeps the draft and the\n // form: the edit is still the user's only copy of what they typed.\n //\n // ⚠️ A flow can complete after the operator left this page, so leaving it\n // is guarded on still being here: a navigation from a form nobody is\n // looking at would pull them away from wherever they went.\n const saveMutation = useOptimisticMutation<TEntity, TEntity>({\n write: next =>\n writer === undefined\n ? Effect.map(\n Effect.provide(\n saveUCFactory<TEntity>(),\n ctx.pipe(Context.add(EntityTag, next)),\n ),\n settled,\n )\n : writer.save(next),\n intent: () => ({ entity: entityName, write: 'save' }),\n confirm: () => {\n draft?.clear();\n void refreshList();\n if (mounted.current) afterSave();\n },\n });\n const deleteMutation = useOptimisticMutation<EntityId, void>({\n write: target =>\n writer === undefined\n ? Effect.as(\n Effect.provide(\n deleteUCFactory<TEntity>(),\n ctx.pipe(Context.add(EntityIdTag, target)),\n ),\n settled(undefined),\n )\n : writer.delete(target),\n intent: () => ({ entity: entityName, write: 'delete' }),\n confirm: () => {\n draft?.clear();\n void refreshList();\n if (mounted.current) afterDelete();\n },\n });\n\n const handleSave = async (next: TEntity) => {\n const result = await saveMutation.mutate(next).catch(() => undefined);\n // Failed, or pending: the form stays, and the mutation says which. A\n // pending write leaves through the mutation's `confirm`, once its flow\n // completed.\n if (result?._tag !== 'settled') return;\n draft?.clear();\n void refreshList();\n // Said in the toast region every route shares, so it survives the\n // navigation that follows (ADR 0028).\n toasts?.show({\n tone: 'success',\n message: ct('state.saved', {\n object: recordNoun(next),\n }),\n });\n afterSave();\n };\n\n const toasts = useToasts();\n const ct = useT('controls');\n const nameOf = useRecordLabel();\n /**\n * What an announcement names: the record, through the one derivation every\n * surface shares, or the entity for one not loaded.\n */\n const recordNoun = (record: TEntity | undefined) =>\n nameOf(entityConstructor, record);\n // The breadcrumb for this page's segment names the record, never its id:\n // \"Nuevo\" for a create, the record once it has loaded.\n useBreadcrumbLabel(\n slug ?? params.slug,\n id == null ? ct('form.new') : entity && recordNoun(entity),\n );\n /**\n * Saves a deleted record back under its id: what Undo runs under the\n * `undo` policy.\n */\n const restore = (record: TEntity) =>\n Effect.runPromise(\n writer === undefined\n ? Effect.asVoid(\n Effect.provide(\n saveUCFactory<TEntity>(),\n ctx.pipe(Context.add(EntityTag, record)),\n ),\n )\n : Effect.asVoid(writer.save(record)),\n ).then(\n () => refreshList(),\n (failure: unknown) => {\n toasts?.show({ tone: 'failure', failure: asFailure(failure) });\n },\n );\n\n const handleDelete = async () => {\n const snapshot = entity;\n const result = await deleteMutation.mutate(id).catch(() => undefined);\n if (result?._tag !== 'settled') return;\n draft?.clear();\n void refreshList();\n // Said once, in the toast region every route shares, so it survives the\n // navigation back to the list.\n const object = recordNoun(snapshot);\n const message = ct('confirm.deleted', { object });\n if (deletePolicy === 'undo' && snapshot !== undefined)\n toasts?.show({\n tone: 'undo',\n message,\n action: {\n label: ct('confirm.undo'),\n onAction: () => void restore(snapshot),\n },\n });\n else toasts?.show({ tone: 'success', message });\n afterDelete();\n };\n\n /**\n * An `entity`-bound verb, on the record being shown.\n *\n * It **reloads** — once the verb took effect, which for one the server\n * handed to a flow is when the flow completed — rather than patching what it has: the service decides the\n * resulting state — a `publish` may land on `published` from four different\n * places — and a client that assumed the new value would show the wrong one\n * the first time the rule changed. `id == null` means the create form,\n * where there is no record to act on and the form renders no verbs anyway.\n *\n * ⚠️ The rejection is **caught and shown**, never left to the promise.\n * `EntityForm`'s `onUseCase` returns `void`, so an uncaught rejection here\n * reaches the console and nothing else — measured on an offering refusing\n * `unpublish` from `draft`: the service answered `409` with a coded body,\n * the record correctly did not move, and the operator saw a button that\n * appeared to do nothing at all.\n */\n const verbs = verbsOf(\n useCases === undefined\n ? undefined\n : (adapters[useCases] as EntityUseCaseRunner),\n affordances.metadata?.useCases,\n );\n const recordVerb = useVerb(verbs, () => void reload());\n const handleUseCase =\n verbs === undefined || id == null\n ? undefined\n : (key: string) => recordVerb.run(key, id);\n\n const form = (\n <EntityCrudForm<TEntity>\n // Remounts (and reseeds the fields) once the record arrives.\n // A newer revision remounts too, so \"load the current record\" reseeds.\n key={`${String(entity?.id ?? CATALOG_NEW_SLUG)}:${readRevision(entity) ?? ''}`}\n entityConstructor={entityConstructor}\n catalogKey={catalogKey}\n metadataSource={metadataSource}\n hiddenFields={hiddenFields}\n links={linkSources}\n entity={entity}\n isLoading={isLoading}\n isSaving={saveMutation.status === 'running'}\n isPending={[saveMutation, deleteMutation, recordVerb.verb].some(\n mutation => mutation.status === 'pending',\n )}\n isDeleting={deleteMutation.status === 'running'}\n error={\n loadError ??\n syncFailure(saveMutation) ??\n syncFailure(deleteMutation) ??\n syncFailure(recordVerb.verb)\n }\n onSave={handleSave}\n onRetry={loadError === undefined ? undefined : reload}\n onConflictResolved={saveMutation.reset}\n onLoadCurrent={\n id == null\n ? undefined\n : () => {\n // What was typed is given up on purpose: its draft goes, so\n // the reseed shows the record as it now stands.\n draft?.clear();\n saveMutation.reset();\n void reload();\n }\n }\n onDelete={id == null ? undefined : handleDelete}\n deletePolicy={deletePolicy}\n onUseCase={handleUseCase}\n backHref={withLocale(basePath)}\n renderLink={renderLink}\n draft={formDraft}\n />\n );\n // The records that refer to this one, under its form: an existing record\n // only, since a record being created has nothing referring to it yet.\n if (regions === undefined || id == null || entity === undefined)\n return form;\n return (\n <div className=\"flex flex-col gap-l\">\n {form}\n <RecordRegions>{regions(entity)}</RecordRegions>\n </div>\n );\n }\n\n return {\n entityConstructor,\n entityKey: catalogKey,\n entityLabelKey,\n entityPluralKey,\n useListTitleKey,\n basePath,\n ListPage,\n SingleViewPage,\n RelatedList,\n };\n}\n"],"names":["deleteUCFactory","EntityIdTag","EntityTag","getUCFactory","loadUCFactory","saveUCFactory","coerceFiltering","describeEntityColumns","envelopeEntityName","extractMetaEntity","Internal","isFailure","parseRsql","parseSort","readRevision","serializeRsql","serializeSort","settled","EntityTable","useCasesForSurface","useFocusOnArrival","useRecordLabel","useT","useToasts","useTranslateKey","entityQueryScope","useDataLoading","useEntityRecord","useFacetCounts","useOptimisticMutation","useQueryClient","Cause","Context","Effect","Exit","useParams","useRouter","useSearchParams","useEffect","useId","useMemo","useRef","useBreadcrumbLabel","useLocaleHref","useEntityNavHost","EntityCrudForm","PREFILL_PARAM","readPrefill","RecordRegions","useRegion","planRelated","useRelatedColumns","useSuppliedRepositories","CATALOG_NEW_SLUG","slugToEntityId","useCrudRenderLink","useEntityAffordances","useEntityBulk","TARGET_NAME_PROPERTY","ignoreDraft","undefined","crudContextOf","adapters","repository","asFailure","failure","syncFailure","mutation","status","flowId","verbsOf","runner","served","descriptor","key","find","candidate","run","id","bulk","selection","runPromiseExit","then","exit","isSuccess","value","Promise","reject","squash","cause","useVerb","verbs","done","verb","write","confirm","mutate","result","_tag","useMounted","mounted","current","useLinkFilters","links","record","map","link","useBaseFiltering","makeEntityCrud","entityConstructor","options","useAdapters","basePath","catalogKey","hiddenFields","columns","toolbar","pageSize","initialFiltering","initialSorting","useListView","related","regions","metadataSource","givenMetadataSource","metadata","useCases","delete","deletePolicy","facets","Error","name","metadataSourceOf","initialRsql","meta","String","labelKey","entityLabelKey","pluralKey","entityPluralKey","useReaderView","useListTitleKey","titleKey","entityName","descriptors","facetMembers","filter","filterable","type","relatedPlans","linkPlans","entry","field","linkLabelProperty","labelProperty","linkSearchProperty","searchProperty","ListBody","baseFiltering","newHref","givenNewHref","listPageSize","listInitialFiltering","onVerbSettled","affordances","hiddenColumns","withLocale","queryClient","scope","renderLink","pager","uc","ctx","queryKey","initialPageSize","supplied","relatedColumns","items","plan","index","facetCounts","members","filtering","canRunBulk","length","onCompleted","invalidateQueries","rowVerb","rowUseCases","canRunRowUseCase","handleRowUseCase","item","totalItems","hrefFor","tableProps","onUseCase","onRetry","refetch","error","ListPage","heading","et","div","className","h1","ref","tabIndex","replace","RelatedList","headingKey","prefill","regionPageSize","headingRef","query","URLSearchParams","Object","entries","member","toString","section","aria-labelledby","h2","requestAnimationFrame","focus","SingleViewPage","slug","onSaved","onDeleted","draft","loadError","router","params","searchParams","prefillKey","JSON","stringify","formDraft","save","clear","entity","isLoading","reload","linkFilters","linkSources","config","loadUc","getUc","host","refreshList","toList","push","afterSave","afterDelete","writer","saveMutation","next","provide","pipe","add","intent","deleteMutation","target","as","handleSave","catch","toasts","show","tone","message","ct","object","recordNoun","nameOf","restore","runPromise","asVoid","handleDelete","snapshot","action","label","onAction","recordVerb","handleUseCase","form","isSaving","isPending","some","isDeleting","onSave","onConflictResolved","reset","onLoadCurrent","onDelete","backHref","entityKey"],"mappings":"AAAA;;;AAEA,SACEA,eAAe,EAEfC,WAAW,EAEXC,SAAS,EACTC,YAAY,EACZC,aAAa,EACbC,aAAa,QACR,oBAAoB;AAC3B,SACEC,eAAe,EACfC,qBAAqB,EASrBC,kBAAkB,EAClBC,iBAAiB,EAEjBC,QAAQ,EACRC,SAAS,EACTC,SAAS,EACTC,SAAS,EACTC,YAAY,EACZC,aAAa,EACbC,aAAa,EACbC,OAAO,QAEF,gBAAgB;AACvB,SACEC,WAAW,EACXC,kBAAkB,EAClBC,iBAAiB,EACjBC,cAAc,EACdC,IAAI,EACJC,SAAS,EACTC,eAAe,QACV,0BAA0B;AACjC,SACEC,gBAAgB,EAEhBC,cAAc,EACdC,eAAe,EACfC,cAAc,EACdC,qBAAqB,QAChB,6BAA6B;AACpC,SAASC,cAAc,QAAQ,wBAAwB;AACvD,SAASC,KAAK,EAAEC,OAAO,EAAEC,MAAM,EAAEC,IAAI,QAAQ,SAAS;AACtD,SAASC,SAAS,EAAEC,SAAS,EAAEC,eAAe,QAAQ,kBAAkB;AACxE,SAASC,SAAS,EAAEC,KAAK,EAAEC,OAAO,EAAEC,MAAM,QAAQ,QAAQ;AAE1D,SAASC,kBAAkB,QAAQ,sCAAsC;AACzE,SAASC,aAAa,QAAQ,mBAAmB;AACjD,SAASC,gBAAgB,QAAQ,6BAA6B;AAC9D,SAASC,cAAc,QAAQ,wBAAwB;AAUvD,SACEC,aAAa,EACbC,WAAW,EACXC,aAAa,EACbC,SAAS,QACJ,eAAe;AACtB,SACEC,WAAW,EACXC,iBAAiB,EACjBC,uBAAuB,QAClB,uBAAuB;AAC9B,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,YAAY;AAC7D,SAASC,iBAAiB,QAAQ,4BAA4B;AA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,kBAAkB,CAAC,GAAEvC,gBAAAA,aAAaiO,mBAAbjO,gBAAwB,IAAI;QAyClF,yEAAyE;QACzE,sEAAsE;QACtE,IAAI4G,YAAY9D,aAAakB,MAAM,QAAQiK,WAAWnL,WACpD,OAAO+N;QACT,qBACE,MAACjF;YAAIC,WAAU;;gBACZgF;8BACD,KAAC3O;8BAAe0E,QAAQqH;;;;IAG9B;IAEA,OAAO;QACLlI;QACAyL,WAAWrL;QACXwB;QACAE;QACAE;QACA7B;QACAuF;QACAyB;QACAhB;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/lib/crud/make-entity-crud.tsx"],"sourcesContent":["'use client';\n\nimport {\n deleteUCFactory,\n type EntityFacetCounterTag,\n EntityIdTag,\n type EntityRepositoryTag,\n EntityTag,\n getUCFactory,\n loadUCFactory,\n saveUCFactory,\n} from '@entifix/business';\nimport {\n coerceFiltering,\n describeEntityColumns,\n type EntifixFailure,\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityMetadataSource,\n type EntitySelection,\n type EntityUseCaseRunner,\n type EntityWriter,\n envelopeEntityName,\n extractMetaEntity,\n type FilterGroup,\n Internal,\n isFailure,\n parseRsql,\n parseSort,\n readRevision,\n serializeRsql,\n serializeSort,\n settled,\n type UseCaseDescriptor,\n} from '@entifix/core';\nimport {\n EntityTable,\n useCasesForSurface,\n useFocusOnArrival,\n useRecordLabel,\n useT,\n useToasts,\n useTranslateKey,\n} from '@entifix/react-controls';\nimport {\n entityQueryScope,\n type OptimisticMutation,\n useDataLoading,\n useEntityRecord,\n useFacetCounts,\n useOptimisticMutation,\n} from '@entifix/react-integration';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { Cause, Context, Effect, Exit } from 'effect';\nimport { useParams, useRouter, useSearchParams } from 'next/navigation';\nimport { useEffect, useId, useMemo, useRef, useState } from 'react';\n\nimport { useBreadcrumbLabel } from '../back-office/breadcrumb-labels.js';\nimport { useLocaleHref } from '../i18n/index.js';\nimport { useEntityNavHost } from '../workspace/entity-nav.js';\nimport { EntityCrudForm } from './entity-crud-form.js';\nimport type {\n AnyFilterGroup,\n EntityCrud,\n EntityCrudLinkSource,\n EntityCrudListView,\n EntityCrudOptions,\n EntityCrudRelatedListProps,\n EntityCrudSingleViewProps,\n} from './make-entity-crud.types.js';\nimport {\n PREFILL_PARAM,\n readPrefill,\n RecordRegions,\n useRegion,\n} from './regions.js';\nimport {\n planRelated,\n useRelatedColumns,\n useSuppliedRepositories,\n} from './related-columns.js';\nimport { CATALOG_NEW_SLUG, slugToEntityId } from './slug.js';\nimport { useCrudRenderLink } from './use-crud-render-link.js';\nimport { useEntityAffordances } from './use-entity-affordances.js';\nimport { useEntityBulk } from './use-entity-bulk.js';\n\n/** What a picker defaults to reading off its target. */\nconst TARGET_NAME_PROPERTY = 'name';\n\n/** A prefilled create with no host draft store keeps nothing between visits. */\nconst ignoreDraft = () => undefined;\n\n/**\n * What the generated pages' use-cases run against: one repository adapter.\n * Exported because a hand-built screen — a wizard reading records and\n * resolving pickers — runs against exactly the same.\n */\nexport type CrudContext = EntityRepositoryTag;\n\n/**\n * One repository adapter, by its key, as the context the use-cases run\n * against.\n *\n * The cast is the price of naming adapters by key: `AdapterKey` narrows which\n * names may be *offered*, but TypeScript will not carry that narrowing through\n * an index access on a generic record.\n */\nexport function crudContextOf<TAdapters>(\n adapters: TAdapters,\n repository: keyof TAdapters,\n): Context.Context<CrudContext> {\n return adapters[repository] as Context.Context<EntityRepositoryTag>;\n}\n\n/**\n * Builds the list page and the single-record page for one entity.\n *\n * Every catalog entity used to cost ~10 files and ~300 lines whose only variable\n * was a class name: two organisms with a `.types.ts` each, two client pages, two\n * route files. The route files stay (Next needs a module per path); everything\n * between them is derived from the entity's own metadata, so a new reference\n * entity is this call plus a nav entry.\n *\n * Two things are checked here rather than at the call site, because both fail\n * silently otherwise. The catalog key must be the entity's own `@entity({ key })`\n * — they are the same string by convention, and a drifted one titles the form\n * after a different entity in a way only a reader of both catalogs would catch.\n * And a `links` entry must name a real member — a picker aimed at nothing renders\n * identically to a read-only field.\n *\n * **Serves compile-time `@entity()` classes only.** Operator reference data ships\n * with the code, so making this spec-driven would trade type safety for nothing;\n * a vendor-authored `EntitySpecification` renders through a separate path.\n */\n/**\n * A rejected write, as something the form's error slot can render.\n *\n * A typed failure is kept as it is: `useErrorMessage` translates its own code,\n * a business refusal and an outage alike. Anything else is a bug that reached\n * the screen, and is shown as `Internal` — never with its own text, which\n * nobody wrote for a user.\n */\nfunction asFailure(failure: unknown): EntifixFailure {\n return isFailure(failure) ? failure : new Internal();\n}\n\n/**\n * What a write failed with *synchronously* — before any flow took it — or\n * `undefined`. A flow's own failure is toasted by the `PendingFlowsProvider`\n * that settles it, so showing it in the error slot too would tell the operator\n * twice.\n */\nfunction syncFailure(\n mutation: OptimisticMutation<never, unknown>,\n): EntifixFailure | undefined {\n return mutation.status === 'failed' && mutation.flowId === undefined\n ? asFailure(mutation.failure)\n : undefined;\n}\n\n/**\n * A runner's verbs, looked up by the key the served `$metadata` named. A\n * single verb answers either settle mode, so it is run through the optimistic\n * API; a bulk run reports per row and is awaited as a promise whose rejection\n * carries the failure itself.\n */\nfunction verbsOf(\n runner: EntityUseCaseRunner | undefined,\n served: readonly UseCaseDescriptor[] | undefined,\n) {\n if (runner === undefined) return undefined;\n // The key always comes from the served document, so it names a verb in it.\n const descriptor = (key: string) =>\n served?.find(candidate => candidate.key === key) as UseCaseDescriptor;\n return {\n run: (key: string, id: EntityId) => runner.run(descriptor(key), id),\n bulk: (key: string, selection: EntitySelection<Entity>) =>\n Effect.runPromiseExit(runner.bulk(descriptor(key), selection)).then(\n exit =>\n Exit.isSuccess(exit)\n ? exit.value\n : Promise.reject(Cause.squash(exit.cause)),\n ),\n };\n}\n\ntype Verbs = NonNullable<ReturnType<typeof verbsOf>>;\n\n/**\n * One verb on one record, through the optimistic API: `done` runs once the\n * verb took effect — at once when it settled, or when the flow it was handed\n * to completed.\n */\nfunction useVerb(verbs: Verbs | undefined, done: () => void) {\n const verb = useOptimisticMutation<\n { readonly key: string; readonly id: EntityId },\n unknown\n >({\n // Only ever sent from a handler that exists because `verbs` does.\n write: ({ key, id }) => (verbs as Verbs).run(key, id),\n confirm: done,\n });\n const run = (key: string, id: EntityId) => {\n void verb.mutate({ key, id }).then(\n result => {\n if (result._tag === 'settled') done();\n },\n // Shown through `syncFailure`, from the mutation's own state.\n () => undefined,\n );\n };\n return { verb, run };\n}\n\n/** Whether the component is still mounted: a flow can settle after it left. */\nfunction useMounted() {\n const mounted = useRef(true);\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n };\n }, []);\n return mounted;\n}\n\n/**\n * Runs each link's `useBaseFiltering` against the record being edited, in link\n * order, with `undefined` for a link that declares none.\n *\n * Legal for the reason `useEntityLinkSources` gives: the links are a\n * factory-time array, and whether a link carries a rule is fixed with it, so\n * the same hooks run in the same order on every render. The lint rule cannot\n * see a hook called through a member, so there is nothing for it to flag.\n */\nfunction useLinkFilters<TEntity extends Entity>(\n links: readonly {\n readonly useBaseFiltering?: (\n record: TEntity | undefined,\n ) => AnyFilterGroup | undefined;\n }[],\n record: TEntity | undefined,\n): (AnyFilterGroup | undefined)[] {\n return links.map(link => link.useBaseFiltering?.(record));\n}\n\nexport function makeEntityCrud<TEntity extends Entity, TAdapters>(\n entityConstructor: EntityConstructor<TEntity>,\n options: EntityCrudOptions<TAdapters, TEntity>,\n): EntityCrud<TEntity> {\n const {\n useAdapters,\n basePath,\n catalogKey,\n repository,\n hiddenFields = [],\n columns,\n toolbar,\n pageSize,\n initialFiltering,\n initialSorting,\n useListView,\n links = [],\n related = [],\n regions,\n metadataSource: givenMetadataSource,\n metadata,\n useCases,\n write,\n delete: deletePolicy = 'confirm',\n facets,\n } = options;\n\n if (givenMetadataSource !== undefined && metadata !== undefined) {\n throw new Error(\n `${entityConstructor.name} was given both metadataSource and metadata; pass one`,\n );\n }\n // An adapter value, so it is resolved per render from the same `useAdapters()`\n // the records come from — the host's composition, never the caller's module.\n const metadataSourceOf = (adapters: TAdapters) =>\n metadata === undefined\n ? givenMetadataSource\n : (adapters[metadata] as EntityMetadataSource);\n\n // Through the service's own trust boundary rather than a second walk of the\n // tree: serialized the way a load request carries it, then coerced against\n // the entity's `filterable` allowlist exactly as a service coerces a query.\n // Whatever would answer `400` on the wire throws here instead, when the\n // screen is generated, naming the member.\n // An emptied group serializes to nothing and filters nothing, so there is\n // nothing to check.\n const initialRsql =\n initialFiltering === undefined ? '' : serializeRsql([initialFiltering]);\n if (initialRsql !== '') {\n coerceFiltering(entityConstructor, parseRsql(initialRsql));\n }\n // The same posture for the order it opens in: parsed back through the\n // allowlist a service applies to a `sort` parameter.\n if (initialSorting !== undefined) {\n parseSort(entityConstructor, serializeSort([initialSorting]));\n }\n\n const meta = extractMetaEntity(entityConstructor);\n if (meta.key !== catalogKey) {\n throw new Error(\n `${entityConstructor.name} declares key \"${String(meta.key)}\" but was given catalog key \"${catalogKey}\"`,\n );\n }\n // Read off `@entity()` rather than rebuilt from `catalogKey`. Both spellings\n // produce the same string today, and that is exactly the problem: a second\n // place that knows how an entity's catalog subtree is laid out is a second\n // place to fix when one moves. `MetaEntityOptions` makes them optional, so an\n // entity that never declared them fails here — where a screen is generated —\n // rather than on the render that first tries to title a tab with `undefined`.\n const { labelKey: entityLabelKey, pluralKey: entityPluralKey } = meta;\n if (entityLabelKey === undefined || entityPluralKey === undefined) {\n throw new Error(\n `${entityConstructor.name} must declare labelKey and pluralKey on @entity() to be generated`,\n );\n }\n // Narrowed once, for the closures below that TypeScript cannot follow.\n const pluralKey: string = entityPluralKey;\n\n // The host's reading of who is reading, or nobody in particular. Called the\n // same way on every render — whether there is a hook is fixed with the\n // factory — so it is a hook call the rules allow.\n const useReaderView = (): EntityCrudListView => useListView?.() ?? {};\n const useListTitleKey = (): string => useReaderView().titleKey ?? pluralKey;\n\n // Computed once: a descriptor is a property of the class, so nothing about it\n // depends on the record being edited. `linkLabelProperty`/`linkSearchProperty`\n // are overridden here because a scalar foreign key's `@accessor()` cannot name\n // the target's members — it may not import the target at all.\n // The wire name, which is also what a pending flow's intent records and what\n // `entityQueryScopeFor` keys on — one derivation, so the two can never\n // disagree about which entity they mean.\n const entityName = envelopeEntityName(entityConstructor);\n const descriptors = describeEntityColumns(entityConstructor);\n /** The members a filter panel offers choices for, and so counts. */\n const facetMembers = descriptors\n .filter(\n descriptor =>\n descriptor.filterable &&\n (descriptor.type === 'enum' || descriptor.type === 'boolean'),\n )\n .map(({ name, key }) => ({ name, key }));\n const relatedPlans = planRelated(\n entityConstructor as EntityConstructor<Entity>,\n descriptors,\n related,\n );\n const linkPlans = links.map(link => {\n const descriptor = descriptors.find(entry => entry.name === link.field);\n if (descriptor === undefined) {\n throw new Error(\n `${entityConstructor.name} has no member \"${link.field}\" for a link source`,\n );\n }\n return {\n ...link,\n descriptor: {\n ...descriptor,\n linkLabelProperty: link.labelProperty ?? TARGET_NAME_PROPERTY,\n linkSearchProperty: link.searchProperty ?? TARGET_NAME_PROPERTY,\n },\n };\n });\n\n /**\n * The generated list itself — the table, its reads, its verbs — shared by the\n * list page and by a related region on another record's page. A region holds\n * it to a fixed filter that is not a removable chip and keeps its pager in\n * component state, never in the URL.\n */\n function ListBody({\n baseFiltering,\n newHref: givenNewHref,\n listPageSize = pageSize,\n listInitialFiltering,\n onVerbSettled,\n }: {\n baseFiltering?: FilterGroup<TEntity>;\n newHref?: string;\n listPageSize?: number;\n listInitialFiltering?: FilterGroup<TEntity>;\n onVerbSettled?: () => void;\n }) {\n const adapters = useAdapters();\n const { hiddenColumns } = useReaderView();\n // Every internal href carries the locale. An unprefixed one still resolves —\n // the middleware redirects it — but the visitor pays a round trip per click.\n const withLocale = useLocaleHref();\n\n const queryClient = useQueryClient();\n const scope = entityQueryScope(entityConstructor);\n const metadataSource = metadataSourceOf(adapters);\n const affordances = useEntityAffordances(entityConstructor, metadataSource);\n const renderLink = useCrudRenderLink(catalogKey);\n\n const pager = useDataLoading<TEntity, CrudContext>({\n uc: loadUCFactory<TEntity>(),\n ctx: crudContextOf(adapters, repository),\n // Scoped rather than left to the per-instance fallback, which is correct\n // but unshared: with the entity's own scope one invalidation refreshes\n // every page and filter of it, which is what a bulk run needs — and it is\n // the same prefix `useReactiveInvalidation`already targets, so a generated\n // list now also refreshes on a reactive change event.\n queryKey: scope,\n ...(listPageSize === undefined ? {} : { initialPageSize: listPageSize }),\n ...(listInitialFiltering === undefined\n ? {}\n : { initialFiltering: listInitialFiltering }),\n ...(initialSorting === undefined ? {} : { initialSorting }),\n ...(baseFiltering === undefined ? {} : { baseFiltering }),\n });\n\n // Values that live in another entity, one read per column per page.\n const supplied = useSuppliedRepositories(relatedPlans);\n const relatedColumns = useRelatedColumns<TAdapters, TEntity>(\n relatedPlans,\n pager.items,\n (plan, index) =>\n supplied[index] ??\n crudContextOf(adapters, plan.repository as keyof TAdapters),\n );\n\n const facetCounts = useFacetCounts<TEntity>({\n ctx:\n facets === undefined\n ? undefined\n : (adapters[facets] as Context.Context<EntityFacetCounterTag>),\n members: facetMembers,\n filtering: pager.filtering,\n scope,\n });\n\n // Only when this caller may actually run something over a selection.\n //\n // Measured live: an `admin` holds `catalog-reference:*:read` and no\n // `retire`, so the service filters the verb out of `$metadata` — but the\n // selection column still rendered, offering a set that no action could be\n // taken on. A checkbox that can lead nowhere is worse than no checkbox: it\n // reads as a permission the user does not have.\n //\n // Decided from the served document rather than from the runner, because\n // the runner is a property of the *shell* (it knows the route) and the\n // grant is a property of the *caller*. The column therefore appears when\n // the document lands, which is the asynchrony serving affordances accepts\n // for every action surface.\n const canRunBulk =\n useCasesForSurface('bulk-bar', affordances.metadata?.useCases).length > 0;\n\n const verbs = verbsOf(\n useCases === undefined\n ? undefined\n : (adapters[useCases] as EntityUseCaseRunner),\n affordances.metadata?.useCases,\n );\n\n const bulk = useEntityBulk<TEntity>({\n run:\n canRunBulk && verbs !== undefined\n ? (key, selection) =>\n verbs.bulk(key, selection as EntitySelection<Entity>)\n : undefined,\n // A bulk write changed the rows underneath the listing, so the page is\n // re-read; the selection deliberately survives it (\"the selection\n // is still there afterwards\"), because the operator's next act is usually\n // to retry the failures or run a second verb on the same rows.\n onCompleted: () => {\n void queryClient.invalidateQueries({ queryKey: scope });\n },\n });\n\n // What a row's overflow menu runs, and the one place the list reports a\n // verb that failed.\n //\n // ⚠️ **A row verb and the form's are the same runner with different\n // arguments.** `EntityTable` hands back the whole record, because that is\n // what it has; the runner takes an id, because that is what a route needs.\n // The list has no error slot of its own, so a failure lands in the\n // table's own error region — the same one a failed page read uses.\n const rowVerb = useVerb(verbs, () => {\n void queryClient.invalidateQueries({ queryKey: scope });\n onVerbSettled?.();\n });\n // Called unconditionally and the *result* gated, the way the surfaces are\n // read in `EntityForm`: the name begins with `use`, so short-circuiting it\n // reads to `react-hooks/rules-of-hooks` as a conditional hook.\n const rowUseCases = useCasesForSurface(\n 'row-menu',\n affordances.metadata?.useCases,\n );\n const canRunRowUseCase = verbs !== undefined && rowUseCases.length > 0;\n\n const handleRowUseCase = canRunRowUseCase\n ? (key: string, item: TEntity) => {\n if (item.id == null) return;\n rowVerb.run(key, item.id);\n }\n : undefined;\n\n return (\n <EntityTable\n entityConstructor={entityConstructor}\n {...(hiddenColumns === undefined ? {} : { hiddenColumns })}\n {...pager}\n items={pager.items}\n totalItems={pager.totalItems}\n hrefFor={id => withLocale(`${basePath}/${String(id)}`)}\n newHref={withLocale(givenNewHref ?? `${basePath}/${CATALOG_NEW_SLUG}`)}\n renderLink={renderLink}\n {...affordances}\n {...bulk.tableProps}\n onUseCase={handleRowUseCase}\n onRetry={pager.refetch}\n facets={facetCounts}\n error={syncFailure(rowVerb.verb) ?? pager.error}\n >\n {columns}\n {relatedColumns}\n {/* After the host's own: a host column for the same member wins. */}\n {toolbar}\n </EntityTable>\n );\n }\n\n function ListPage() {\n // The list's heading, and where focus lands when a save or a delete\n // brings the reader back here rather than falling to `<body>`.\n const heading = useRef<HTMLHeadingElement>(null);\n useFocusOnArrival(heading);\n const et = useT('entity');\n const titleKey = useListTitleKey();\n\n return (\n <div className=\"flex flex-col gap-s\">\n <h1\n ref={heading}\n tabIndex={-1}\n className=\"m-0 text-step-2 font-semibold text-content focus-ring\"\n >\n {et(titleKey.replace(/^entity:/, ''))}\n </h1>\n <ListBody\n {...(initialFiltering === undefined\n ? {}\n : { listInitialFiltering: initialFiltering })}\n />\n </div>\n );\n }\n\n /**\n * This entity's records that refer to another record, as a region of that\n * record's page\n * ([ADR 0030](../../../../../../docs/adr/0030-a-reference-names-its-target-through-the-owners-read-port.md)):\n * the generated list held to `filtering`, which is fixed and shown as no\n * chip, under its own `h2`, with its own states and its own writes. A verb\n * that settles inside it moves focus to that heading; nothing else on the\n * page is re-read or touched. `prefill` names the members a \"New\" from here\n * opens already set — the parent record's id.\n */\n function RelatedList({\n filtering,\n labelKey: headingKey,\n prefill,\n newHref,\n pageSize: regionPageSize,\n }: EntityCrudRelatedListProps<TEntity>) {\n const headingRef = useRef<HTMLHeadingElement>(null);\n const id = useId();\n const heading = useTranslateKey()(headingKey);\n useRegion(id, heading);\n const query = new URLSearchParams(\n Object.entries(prefill ?? {}).map(([member, value]): [string, string] => [\n `${PREFILL_PARAM}${member}`,\n value,\n ]),\n ).toString();\n return (\n <section\n id={id}\n aria-labelledby={`${id}-heading`}\n className=\"flex flex-col gap-s\"\n >\n <h2\n id={`${id}-heading`}\n ref={headingRef}\n tabIndex={-1}\n className=\"m-0 text-step-1 font-semibold text-content focus-ring\"\n >\n {heading}\n </h2>\n <ListBody\n baseFiltering={filtering}\n newHref={\n newHref ??\n `${basePath}/${CATALOG_NEW_SLUG}${query === '' ? '' : `?${query}`}`\n }\n {...(regionPageSize === undefined\n ? {}\n : { listPageSize: regionPageSize })}\n // The row's menu hands focus back to its trigger two frames after\n // the click, unless focus already sits on a tabbable element — and\n // this heading, at `tabIndex={-1}`, is not one. A verb that settles\n // inside those two frames would be focused and then taken back.\n // Frame callbacks run in the order they were asked for, and these\n // are asked for after the click's, so two frames from the settle\n // always run after the restore, never under it.\n onVerbSettled={() =>\n requestAnimationFrame(() =>\n requestAnimationFrame(() => headingRef.current?.focus()),\n )\n }\n />\n </section>\n );\n }\n\n /**\n * Dual-host: as a route it reads its slug from the URL and returns to the list\n * on save; in a workspace tab it takes the slug and the post-save action as\n * props.\n */\n function SingleViewPage({\n slug,\n onSaved,\n onDeleted,\n draft,\n }: EntityCrudSingleViewProps = {}) {\n const adapters = useAdapters();\n const metadataSource = metadataSourceOf(adapters);\n // The same served document the form reads its buttons from, so a key the\n // form hands back always names a verb in it.\n const affordances = useEntityAffordances(entityConstructor, metadataSource);\n const router = useRouter();\n const withLocale = useLocaleHref();\n const params = useParams<{ slug: string }>();\n const mounted = useMounted();\n const id = slugToEntityId(slug ?? params.slug);\n\n // A create opened from a related region starts with the parent record set:\n // `?prefill.<member>=<value>`, layered under any draft the host restores.\n const searchParams = useSearchParams();\n const prefill =\n id == null ? readPrefill(searchParams, descriptors) : undefined;\n const prefillKey = prefill === undefined ? '' : JSON.stringify(prefill);\n const formDraft = useMemo(\n () =>\n prefill === undefined\n ? draft\n : {\n draft: { ...prefill, ...draft?.draft },\n save: draft?.save ?? ignoreDraft,\n clear: draft?.clear ?? ignoreDraft,\n },\n // Keyed on the values, not the object a render builds them into.\n [draft, prefillKey],\n );\n\n const ctx = crudContextOf(adapters, repository);\n\n const {\n entity,\n isLoading,\n error: loadError,\n reload,\n } = useEntityRecord<TEntity, CrudContext>({\n uc: getUCFactory<TEntity>(),\n ctx,\n id,\n });\n\n /**\n * The record the form was seeded from, which is not always the one the\n * query holds now (ADR 0032 §8).\n *\n * A query refetches on its own — on focus, on reconnect, after a verb — and\n * a newer revision used to remount the form and reseed it, so input typed\n * in another tab's shadow was replaced without a word and the save that\n * should have answered `staleRevision` named the newer revision and went\n * through. While the draft differs from its seed, the newer record is held\n * beside the form instead: the save still names the revision the person\n * read, the service refuses it, and the conflict alert offers the choice.\n * A clean form takes the refetch, and so does a different record.\n */\n const [isDirty, setDirty] = useState(false);\n const [seeded, setSeeded] = useState(entity);\n const holds = isDirty && seeded !== undefined && seeded.id === entity?.id;\n if (seeded !== entity && !holds) setSeeded(entity);\n const shown = holds ? seeded : entity;\n\n // Against the record as loaded, not the draft: the rule is about which\n // record this is, not what the operator has typed into it.\n const linkFilters = useLinkFilters(linkPlans, entity);\n\n // Rebuilt inline on every render on purpose: `useEntityLinkSource` holds\n // these in a ref and keeps them out of its query keys, precisely so a caller\n // does not have to memoise them.\n const linkSources: EntityCrudLinkSource[] = linkPlans.map(\n (plan, index) => ({\n field: plan.field,\n descriptor: plan.descriptor,\n config: {\n entityConstructor: plan.entityConstructor,\n loadUc: loadUCFactory(),\n getUc: getUCFactory(),\n ctx: crudContextOf(adapters, plan.repository),\n // The config's target is erased to `Entity`, and the host's filter to\n // `any`; the two meet here, where neither type is the real target's.\n baseFiltering: linkFilters[index] as FilterGroup<Entity> | undefined,\n },\n }),\n );\n\n // Inside a workspace tab, \"back to the list\" is the list's tab, not a URL\n // that would leave the workspace. A host's own callbacks still win.\n const host = useEntityNavHost();\n const renderLink = useCrudRenderLink(catalogKey);\n const queryClient = useQueryClient();\n // The list this page returns to has its page cached, and it is no longer\n // true. Invalidated rather than patched: the service is the authority on\n // the row it stored.\n //\n // ⚠️ Invisible while every Open was a document load, which threw the cache\n // away anyway (#20): the first client-side navigation back to the list\n // showed the record as it was before the save.\n const refreshList = () =>\n queryClient.invalidateQueries({\n queryKey: entityQueryScope(entityConstructor),\n });\n const toList = () =>\n host === undefined\n ? router.push(withLocale(basePath))\n : host.toList(catalogKey);\n const afterSave = onSaved ?? toList;\n const afterDelete = onDeleted ?? toList;\n\n // Through the host's writer when it named one, which answers both settle\n // modes; otherwise through the repository, where every write settles.\n const writer =\n write === undefined ? undefined : (adapters[write] as EntityWriter);\n\n // The draft is spent once the write *commits*, and only here is that known:\n // `useEntityForm` neither fetches nor saves, so it cannot clear its own.\n // A failed write — or a failed flow — deliberately keeps the draft and the\n // form: the edit is still the user's only copy of what they typed.\n //\n // ⚠️ A flow can complete after the operator left this page, so leaving it\n // is guarded on still being here: a navigation from a form nobody is\n // looking at would pull them away from wherever they went.\n const saveMutation = useOptimisticMutation<TEntity, TEntity>({\n write: next =>\n writer === undefined\n ? Effect.map(\n Effect.provide(\n saveUCFactory<TEntity>(),\n ctx.pipe(Context.add(EntityTag, next)),\n ),\n settled,\n )\n : writer.save(next),\n intent: () => ({ entity: entityName, write: 'save' }),\n confirm: () => {\n draft?.clear();\n setDirty(false);\n void refreshList();\n if (mounted.current) afterSave();\n },\n });\n const deleteMutation = useOptimisticMutation<EntityId, void>({\n write: target =>\n writer === undefined\n ? Effect.as(\n Effect.provide(\n deleteUCFactory<TEntity>(),\n ctx.pipe(Context.add(EntityIdTag, target)),\n ),\n settled(undefined),\n )\n : writer.delete(target),\n intent: () => ({ entity: entityName, write: 'delete' }),\n confirm: () => {\n draft?.clear();\n void refreshList();\n if (mounted.current) afterDelete();\n },\n });\n\n const handleSave = async (next: TEntity) => {\n const result = await saveMutation.mutate(next).catch(() => undefined);\n // Failed, or pending: the form stays, and the mutation says which. A\n // pending write leaves through the mutation's `confirm`, once its flow\n // completed.\n if (result?._tag !== 'settled') return;\n draft?.clear();\n // The input is the record now: the next refetch reseeds the form.\n setDirty(false);\n void refreshList();\n // Said in the toast region every route shares, so it survives the\n // navigation that follows (ADR 0028).\n toasts?.show({\n tone: 'success',\n message: ct('state.saved', {\n object: recordNoun(next),\n }),\n });\n afterSave();\n };\n\n const toasts = useToasts();\n const ct = useT('controls');\n const nameOf = useRecordLabel();\n /**\n * What an announcement names: the record, through the one derivation every\n * surface shares, or the entity for one not loaded.\n */\n const recordNoun = (record: TEntity | undefined) =>\n nameOf(entityConstructor, record);\n // The breadcrumb for this page's segment names the record, never its id:\n // \"Nuevo\" for a create, the record once it has loaded.\n useBreadcrumbLabel(\n slug ?? params.slug,\n id == null ? ct('form.new') : entity && recordNoun(entity),\n );\n /**\n * Saves a deleted record back under its id: what Undo runs under the\n * `undo` policy.\n */\n const restore = (record: TEntity) =>\n Effect.runPromise(\n writer === undefined\n ? Effect.asVoid(\n Effect.provide(\n saveUCFactory<TEntity>(),\n ctx.pipe(Context.add(EntityTag, record)),\n ),\n )\n : Effect.asVoid(writer.save(record)),\n ).then(\n () => refreshList(),\n (failure: unknown) => {\n toasts?.show({ tone: 'failure', failure: asFailure(failure) });\n },\n );\n\n const handleDelete = async () => {\n const snapshot = entity;\n const result = await deleteMutation.mutate(id).catch(() => undefined);\n if (result?._tag !== 'settled') return;\n draft?.clear();\n void refreshList();\n // Said once, in the toast region every route shares, so it survives the\n // navigation back to the list.\n const object = recordNoun(snapshot);\n const message = ct('confirm.deleted', { object });\n if (deletePolicy === 'undo' && snapshot !== undefined)\n toasts?.show({\n tone: 'undo',\n message,\n action: {\n label: ct('confirm.undo'),\n onAction: () => void restore(snapshot),\n },\n });\n else toasts?.show({ tone: 'success', message });\n afterDelete();\n };\n\n /**\n * An `entity`-bound verb, on the record being shown.\n *\n * It **reloads** — once the verb took effect, which for one the server\n * handed to a flow is when the flow completed — rather than patching what it has: the service decides the\n * resulting state — a `publish` may land on `published` from four different\n * places — and a client that assumed the new value would show the wrong one\n * the first time the rule changed. `id == null` means the create form,\n * where there is no record to act on and the form renders no verbs anyway.\n *\n * ⚠️ The rejection is **caught and shown**, never left to the promise.\n * `EntityForm`'s `onUseCase` returns `void`, so an uncaught rejection here\n * reaches the console and nothing else — measured on an offering refusing\n * `unpublish` from `draft`: the service answered `409` with a coded body,\n * the record correctly did not move, and the operator saw a button that\n * appeared to do nothing at all.\n */\n const verbs = verbsOf(\n useCases === undefined\n ? undefined\n : (adapters[useCases] as EntityUseCaseRunner),\n affordances.metadata?.useCases,\n );\n const recordVerb = useVerb(verbs, () => void reload());\n const handleUseCase =\n verbs === undefined || id == null\n ? undefined\n : (key: string) => recordVerb.run(key, id);\n\n const form = (\n <EntityCrudForm<TEntity>\n // Remounts (and reseeds the fields) once the record arrives.\n // A newer revision remounts too, so \"load the current record\" reseeds.\n // Held back while the draft is dirty — see `seeded` above.\n key={`${String(shown?.id ?? CATALOG_NEW_SLUG)}:${readRevision(shown) ?? ''}`}\n entityConstructor={entityConstructor}\n catalogKey={catalogKey}\n metadataSource={metadataSource}\n hiddenFields={hiddenFields}\n links={linkSources}\n entity={shown}\n onDirtyChange={setDirty}\n isLoading={isLoading}\n isSaving={saveMutation.status === 'running'}\n isPending={[saveMutation, deleteMutation, recordVerb.verb].some(\n mutation => mutation.status === 'pending',\n )}\n isDeleting={deleteMutation.status === 'running'}\n error={\n loadError ??\n syncFailure(saveMutation) ??\n syncFailure(deleteMutation) ??\n syncFailure(recordVerb.verb)\n }\n onSave={handleSave}\n onRetry={loadError === undefined ? undefined : reload}\n onConflictResolved={saveMutation.reset}\n onLoadCurrent={\n id == null\n ? undefined\n : () => {\n // What was typed is given up on purpose: its draft goes, so\n // the reseed shows the record as it now stands — and nothing\n // holds the newer record back any more.\n draft?.clear();\n setDirty(false);\n saveMutation.reset();\n void reload();\n }\n }\n onDelete={id == null ? undefined : handleDelete}\n deletePolicy={deletePolicy}\n onUseCase={handleUseCase}\n backHref={withLocale(basePath)}\n renderLink={renderLink}\n draft={formDraft}\n />\n );\n // The records that refer to this one, under its form: an existing record\n // only, since a record being created has nothing referring to it yet.\n if (regions === undefined || id == null || entity === undefined)\n return form;\n return (\n <div className=\"flex flex-col gap-l\">\n {form}\n <RecordRegions>{regions(entity)}</RecordRegions>\n </div>\n );\n }\n\n return {\n entityConstructor,\n entityKey: catalogKey,\n entityLabelKey,\n entityPluralKey,\n useListTitleKey,\n basePath,\n ListPage,\n SingleViewPage,\n RelatedList,\n };\n}\n"],"names":["deleteUCFactory","EntityIdTag","EntityTag","getUCFactory","loadUCFactory","saveUCFactory","coerceFiltering","describeEntityColumns","envelopeEntityName","extractMetaEntity","Internal","isFailure","parseRsql","parseSort","readRevision","serializeRsql","serializeSort","settled","EntityTable","useCasesForSurface","useFocusOnArrival","useRecordLabel","useT","useToasts","useTranslateKey","entityQueryScope","useDataLoading","useEntityRecord","useFacetCounts","useOptimisticMutation","useQueryClient","Cause","Context","Effect","Exit","useParams","useRouter","useSearchParams","useEffect","useId","useMemo","useRef","useState","useBreadcrumbLabel","useLocaleHref","useEntityNavHost","EntityCrudForm","PREFILL_PARAM","readPrefill","RecordRegions","useRegion","planRelated","useRelatedColumns","useSuppliedRepositories","CATALOG_NEW_SLUG","slugToEntityId","useCrudRenderLink","useEntityAffordances","useEntityBulk","TARGET_NAME_PROPERTY","ignoreDraft","undefined","crudContextOf","adapters","repository","asFailure","failure","syncFailure","mutation","status","flowId","verbsOf","runner","served","descriptor","key","find","candidate","run","id","bulk","selection","runPromiseExit","then","exit","isSuccess","value","Promise","reject","squash","cause","useVerb","verbs","done","verb","write","confirm","mutate","result","_tag","useMounted","mounted","current","useLinkFilters","links","record","map","link","useBaseFiltering","makeEntityCrud","entityConstructor","options","useAdapters","basePath","catalogKey","hiddenFields","columns","toolbar","pageSize","initialFiltering","initialSorting","useListView","related","regions","metadataSource","givenMetadataSource","metadata","useCases","delete","deletePolicy","facets","Error","name","metadataSourceOf","initialRsql","meta","String","labelKey","entityLabelKey","pluralKey","entityPluralKey","useReaderView","useListTitleKey","titleKey","entityName","descriptors","facetMembers","filter","filterable","type","relatedPlans","linkPlans","entry","field","linkLabelProperty","labelProperty","linkSearchProperty","searchProperty","ListBody","baseFiltering","newHref","givenNewHref","listPageSize","listInitialFiltering","onVerbSettled","affordances","hiddenColumns","withLocale","queryClient","scope","renderLink","pager","uc","ctx","queryKey","initialPageSize","supplied","relatedColumns","items","plan","index","facetCounts","members","filtering","canRunBulk","length","onCompleted","invalidateQueries","rowVerb","rowUseCases","canRunRowUseCase","handleRowUseCase","item","totalItems","hrefFor","tableProps","onUseCase","onRetry","refetch","error","ListPage","heading","et","div","className","h1","ref","tabIndex","replace","RelatedList","headingKey","prefill","regionPageSize","headingRef","query","URLSearchParams","Object","entries","member","toString","section","aria-labelledby","h2","requestAnimationFrame","focus","SingleViewPage","slug","onSaved","onDeleted","draft","loadError","router","params","searchParams","prefillKey","JSON","stringify","formDraft","save","clear","entity","isLoading","reload","isDirty","setDirty","seeded","setSeeded","holds","shown","linkFilters","linkSources","config","loadUc","getUc","host","refreshList","toList","push","afterSave","afterDelete","writer","saveMutation","next","provide","pipe","add","intent","deleteMutation","target","as","handleSave","catch","toasts","show","tone","message","ct","object","recordNoun","nameOf","restore","runPromise","asVoid","handleDelete","snapshot","action","label","onAction","recordVerb","handleUseCase","form","onDirtyChange","isSaving","isPending","some","isDeleting","onSave","onConflictResolved","reset","onLoadCurrent","onDelete","backHref","entityKey"],"mappings":"AAAA;;;AAEA,SACEA,eAAe,EAEfC,WAAW,EAEXC,SAAS,EACTC,YAAY,EACZC,aAAa,EACbC,aAAa,QACR,oBAAoB;AAC3B,SACEC,eAAe,EACfC,qBAAqB,EASrBC,kBAAkB,EAClBC,iBAAiB,EAEjBC,QAAQ,EACRC,SAAS,EACTC,SAAS,EACTC,SAAS,EACTC,YAAY,EACZC,aAAa,EACbC,aAAa,EACbC,OAAO,QAEF,gBAAgB;AACvB,SACEC,WAAW,EACXC,kBAAkB,EAClBC,iBAAiB,EACjBC,cAAc,EACdC,IAAI,EACJC,SAAS,EACTC,eAAe,QACV,0BAA0B;AACjC,SACEC,gBAAgB,EAEhBC,cAAc,EACdC,eAAe,EACfC,cAAc,EACdC,qBAAqB,QAChB,6BAA6B;AACpC,SAASC,cAAc,QAAQ,wBAAwB;AACvD,SAASC,KAAK,EAAEC,OAAO,EAAEC,MAAM,EAAEC,IAAI,QAAQ,SAAS;AACtD,SAASC,SAAS,EAAEC,SAAS,EAAEC,eAAe,QAAQ,kBAAkB;AACxE,SAASC,SAAS,EAAEC,KAAK,EAAEC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAQ;AAEpE,SAASC,kBAAkB,QAAQ,sCAAsC;AACzE,SAASC,aAAa,QAAQ,mBAAmB;AACjD,SAASC,gBAAgB,QAAQ,6BAA6B;AAC9D,SAASC,cAAc,QAA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ASC,MAAM,KAAK;YAElCkO,YAAY5B,eAAetM,MAAM,KAAK;YACtCkI,KAAK,GACH+B,QAAAA,QAAAA,oBAAAA,YACAnK,YAAYkM,yBADZ/B,QAEAnK,YAAYwM,2BAFZrC,OAGAnK,YAAY6N,WAAWlM,IAAI;YAE7B0M,QAAQ1B;YACRzE,SAASiC,cAAczK,YAAYA,YAAYqL;YAC/CuD,oBAAoBpC,aAAaqC,KAAK;YACtCC,eACE5N,MAAM,OACFlB,YACA;gBACE,4DAA4D;gBAC5D,6DAA6D;gBAC7D,wCAAwC;gBACxCwK,yBAAAA,MAAOU,KAAK;gBACZK,SAAS;gBACTiB,aAAaqC,KAAK;gBAClB,KAAKxD;YACP;YAEN0D,UAAU7N,MAAM,OAAOlB,YAAY8N;YACnC1J,cAAcA;YACdmE,WAAW6F;YACXY,UAAUtI,WAAWtD;YACrByD,YAAYA;YACZ2D,OAAOQ;WAzCF,GAAGrG,gBAAOgH,yBAAAA,MAAOzK,EAAE,oBAAIzB,kBAAkB,CAAC,GAAExC,gBAAAA,aAAa0O,kBAAb1O,gBAAuB,IAAI;QA4ChF,yEAAyE;QACzE,sEAAsE;QACtE,IAAI6G,YAAY9D,aAAakB,MAAM,QAAQiK,WAAWnL,WACpD,OAAOqO;QACT,qBACE,MAACvF;YAAIC,WAAU;;gBACZsF;8BACD,KAACjP;8BAAe0E,QAAQqH;;;;IAG9B;IAEA,OAAO;QACLlI;QACAgM,WAAW5L;QACXwB;QACAE;QACAE;QACA7B;QACAuF;QACAyB;QACAhB;IACF;AACF"}
package/package.json CHANGED
@@ -21,7 +21,7 @@
21
21
  }
22
22
  }
23
23
  },
24
- "version": "0.23.1",
24
+ "version": "0.23.3",
25
25
  "description": "Next.js application shell: back-office chrome, workspace tabs, CRUD screens derived from entity metadata, and session and proxy routes.",
26
26
  "license": "MIT",
27
27
  "repository": {
@@ -57,17 +57,17 @@
57
57
  "react": "19.3.1",
58
58
  "react-dom": "19.3.1",
59
59
  "zustand": "^5.1.0",
60
- "@entifix/testing-unit": "0.23.1"
60
+ "@entifix/testing-unit": "0.23.3"
61
61
  },
62
62
  "dependencies": {
63
63
  "idb": "^8.0.4",
64
- "@entifix/authz": "0.23.1",
65
- "@entifix/core": "0.23.1",
66
- "@entifix/i18n": "0.23.1",
67
- "@entifix/react-controls": "0.23.1",
68
- "@entifix/react-integration": "0.23.1",
69
- "@entifix/transactions": "0.23.1",
70
- "@entifix/business": "0.23.1"
64
+ "@entifix/authz": "0.23.3",
65
+ "@entifix/business": "0.23.3",
66
+ "@entifix/core": "0.23.3",
67
+ "@entifix/react-controls": "0.23.3",
68
+ "@entifix/i18n": "0.23.3",
69
+ "@entifix/react-integration": "0.23.3",
70
+ "@entifix/transactions": "0.23.3"
71
71
  },
72
72
  "files": [
73
73
  "dist",