@entifix/next-shell 0.22.0 → 0.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  The Next.js application shell. `makeEntityCrud` derives the list, detail and edit screens for an entity from its metadata; `BackOfficeShell` and `WorkspaceShell` provide the chrome, sidebar navigation, breadcrumbs, workspace tabs and command palette around them. Drafts and pending writes persist in IndexedDB.
4
4
 
5
- `makeEntityCrud` takes a `delete` policy (`confirm`, `undo` or `typed`) and a `facets` adapter, announces saves and deletions, names a record in its rows, toasts and breadcrumb rather than by its id, and keeps focus on a heading after every write. `ConfirmAction` asks before a Server Action acts, with or without JavaScript; the action guards itself with `whenConfirmed`. `AccountMenu` offers theme and density.
5
+ `makeEntityCrud` takes a `delete` policy (`confirm`, `undo` or `typed`), a `facets` adapter, the filter and order a list opens on (`initialFiltering`, `initialSorting`) and a `useListView` hook that titles the list and withholds columns for whoever is reading it, announces saves and deletions, names a record in its rows, toasts and breadcrumb rather than by its id, and keeps focus on a heading after every write. `ConfirmAction` asks before a Server Action acts, with or without JavaScript; the action guards itself with `whenConfirmed`. `AccountMenu` offers theme and density.
6
6
 
7
7
  The `server` entry holds the route handlers a Next backend needs: a same-origin proxy to your services, session refresh and cookies, health, and record search across services — and `whenConfirmed` and `readThemeCookies`.
8
8
 
@@ -21,6 +21,8 @@ const REFERENCE_LABELS: ReferenceLabelRegistration[] = [
21
21
 
22
22
  Every screen then shows the target's name where it would have shown the key, read in one request per target entity per page and cached per id, so a record's page reuses what its list read. A target's `id` must be `filterable`. An entity no registration reads shows its raw id, muted, and `onUnregistered` is told its key once, for the host to warn about in development.
23
23
 
24
+ Record search follows the same references. A source declared with `reference: { entityConstructor, baseUrl }` is searched through the record its `searchProperty` refers to — a stock level by its product's name — and labelled by it; a source with no `labelProperty` names each record as every other screen does, and one nothing names reads as its noun and short id.
25
+
24
26
  ## Install
25
27
 
26
28
  ```sh
@@ -1 +1 @@
1
- {"version":3,"file":"use-records-source.d.ts","sourceRoot":"","sources":["../../../src/lib/command-palette/use-records-source.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAEV,aAAa,EAGd,MAAM,eAAe,CAAC;AA0CvB;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,OAAO,GACf,aAAa,CAiJf"}
1
+ {"version":3,"file":"use-records-source.d.ts","sourceRoot":"","sources":["../../../src/lib/command-palette/use-records-source.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAEV,aAAa,EAGd,MAAM,eAAe,CAAC;AA0CvB;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,OAAO,GACf,aAAa,CA0Jf"}
@@ -41,6 +41,7 @@ const NOTHING_YET = {
41
41
  * searchable here at all.
42
42
  */ export function useRecordsSource(term, enabled) {
43
43
  const t = useT('shell');
44
+ const controls = useT();
44
45
  const translateKey = useTranslateKey();
45
46
  const locale = useLocale();
46
47
  const withLocale = useLocaleHref();
@@ -150,7 +151,12 @@ const NOTHING_YET = {
150
151
  label: translateKey(group.labelKey),
151
152
  options: group.items.map((item)=>_extends({
152
153
  id: `record:${group.source}:${item.id}`,
153
- label: item.label
154
+ // A record nothing names reads as a table names it: the entity's noun
155
+ // and its short id, never the bare id.
156
+ label: item.unnamed === true ? controls('reference.unresolved', {
157
+ noun: translateKey(`entity:${item.entity}.label`),
158
+ id: item.label
159
+ }) : item.label
154
160
  }, item.sublabel === undefined ? {} : {
155
161
  sublabel: item.sublabel
156
162
  }, {
@@ -184,6 +190,7 @@ const NOTHING_YET = {
184
190
  };
185
191
  }, [
186
192
  active,
193
+ controls,
187
194
  enabled,
188
195
  state,
189
196
  term,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/command-palette/use-records-source.ts"],"sourcesContent":["'use client';\n\nimport type {\n CommandGroup,\n CommandSource,\n CommandUnavailableSeverity,\n FailureCategory,\n} from '@entifix/core';\nimport { useLocale, useT, useTranslateKey } from '@entifix/react-controls';\nimport { useEffect, useMemo, useRef, useState } from 'react';\n\nimport { useLocaleHref } from '../i18n/index.js';\nimport type { RecordSearchResponse } from '../search/record-search.types.js';\nimport { searchRecords } from '../search/search-records.js';\nimport {\n RECORD_SEARCH_DEBOUNCE_MS,\n RECORD_SEARCH_MIN_TERM,\n} from './palette-command.js';\n\n/**\n * Which reasons are the caller's ordinary state, and which mean something broke.\n *\n * The split is the record search's, restated as severity because that is what the palette\n * renders. An operator holds no membership, so every tenant-plane source answers\n * `409` on every keystroke — painting that as an outage teaches them to ignore\n * the row entirely, and then the `timeout` that does matter goes unread too.\n */\nconst SCOPE_CODES: ReadonlySet<string> = new Set(['noActiveOrganization']);\n\nconst severityOf = (degraded: {\n readonly reason: string;\n readonly category: FailureCategory;\n}): CommandUnavailableSeverity =>\n degraded.category === 'unauthenticated' ||\n degraded.category === 'forbidden' ||\n SCOPE_CODES.has(degraded.reason)\n ? 'scope'\n : 'reachability';\n\n/** What the browser is currently showing for records. */\ninterface RecordsState {\n /** The term this answer is for, so a stale response cannot overwrite a newer one. */\n readonly term: string;\n readonly response?: RecordSearchResponse;\n readonly failed: boolean;\n}\n\nconst NOTHING_YET: RecordsState = { term: '', failed: false };\n\n/**\n * Records matching the term, one group per source, in the order the host\n * declared them.\n *\n * The whole of the *keystroke* policy lives here rather than in `searchRecords`,\n * which is deliberately a bare typed `fetch`: the palette is the thing that\n * knows a keystroke is not a query. So this owns the debounce, the abort and the\n * two-character floor, while the route owns the fan-out, the per-source timeout\n * and the authorization.\n *\n * **No index, ever.** Every option here came back from `/api/search` for this\n * principal and this organization, on this keystroke. A prefetched client index\n * is the shape that surfaces another organization's record the first time a\n * session's scope moves under it, so there is none, ever.\n *\n * Below the two-character floor the group is present and **says why** rather\n * than being empty or absent: empty would claim nothing matched a search that\n * never ran, and absent would leave someone wondering whether records are\n * searchable here at all.\n */\nexport function useRecordsSource(\n term: string,\n enabled: boolean,\n): CommandSource {\n const t = useT('shell');\n const translateKey = useTranslateKey();\n const locale = useLocale();\n const withLocale = useLocaleHref();\n\n const [state, setState] = useState<RecordsState>(NOTHING_YET);\n // The term the request in flight is for. A ref, not state: it changes on every\n // keystroke and nothing renders from it.\n const pending = useRef<string | null>(null);\n\n const active = enabled && term.length >= RECORD_SEARCH_MIN_TERM;\n\n useEffect(() => {\n // Nothing is cleared here on purpose. A `setState` in an effect body is a\n // cascading render, and there is nothing to clear: the memo below returns no\n // groups while inactive, so a previous answer is unreachable rather than\n // stale — and the host empties the term when it opens the palette.\n if (!active) {\n pending.current = null;\n return;\n }\n\n const controller = new AbortController();\n pending.current = term;\n\n const timer = setTimeout(() => {\n void searchRecords(term, { signal: controller.signal, locale })\n .then(response => {\n if (pending.current !== term) return;\n setState({ term, response, failed: false });\n })\n .catch(() => {\n // An abort lands here too and must not be shown: the term moved on,\n // so there is nothing to report about the request that did not finish.\n if (controller.signal.aborted || pending.current !== term) return;\n setState({ term, failed: true });\n });\n }, RECORD_SEARCH_DEBOUNCE_MS);\n\n return () => {\n clearTimeout(timer);\n controller.abort();\n };\n }, [active, locale, term]);\n\n return useMemo(() => {\n const heading = t('commandPalette.groups.records');\n\n if (!active) {\n // Someone who has typed one character is mid-word, not looking at an\n // answer. Saying so is better than both alternatives: an empty group would\n // claim nothing matched a search that never ran, and an absent one would\n // leave them wondering whether records are searchable at all.\n if (!enabled || term.length === 0) return { key: 'records', groups: [] };\n return {\n key: 'records',\n groups: [\n {\n key: 'records',\n label: heading,\n options: [],\n isLoading: false,\n unavailable: {\n message: t('commandPalette.typeMore', {\n count: RECORD_SEARCH_MIN_TERM,\n }),\n severity: 'scope',\n },\n },\n ],\n };\n }\n // A newer term is in flight. The previous answer stays on screen with its\n // groups marked loading rather than blanking: a list that empties between\n // keystrokes flickers, and the rows it drops were correct a moment ago.\n const isLoading = state.term !== term;\n\n if (state.response === undefined) {\n return {\n key: 'records',\n groups: [\n {\n key: 'records',\n label: heading,\n options: [],\n isLoading: !state.failed,\n // The whole endpoint failed — a lapsed session or a `400`, both of\n // which arrive as a rejection rather than inside a `200`. It is\n // named for the same reason a single degraded source is.\n ...(state.failed\n ? {\n unavailable: {\n message: t('commandPalette.unavailableReach', {\n reason: translateKey('errors:unexpected'),\n }),\n severity: 'reachability' as const,\n },\n }\n : {}),\n },\n ],\n };\n }\n\n const groups: CommandGroup[] = state.response.groups.map(group => ({\n key: `record:${group.source}`,\n // The entity's own `pluralKey`, so record search introduces no copy of\n // its own and a group is titled exactly as its screen is.\n label: translateKey(group.labelKey),\n options: group.items.map(item => ({\n id: `record:${group.source}:${item.id}`,\n label: item.label,\n ...(item.sublabel === undefined ? {} : { sublabel: item.sublabel }),\n href: withLocale(item.href),\n })),\n total: group.total,\n isLoading,\n }));\n\n for (const degraded of state.response.unavailable) {\n const severity = severityOf(degraded);\n groups.push({\n key: `record:${degraded.source}`,\n // Derived from the entity rather than from the source key, which is an\n // identifier and would render as `product-specification`. Every\n // searchable entity declares a `pluralKey` — `catalogSurface` throws\n // without one — so this always resolves.\n label: translateKey(`entity:${degraded.entity}.plural`),\n options: [],\n isLoading: false,\n unavailable: {\n message: t(\n severity === 'scope'\n ? 'commandPalette.unavailableScope'\n : 'commandPalette.unavailableReach',\n { reason: translateKey(`errors:${degraded.reason}`) },\n ),\n severity,\n },\n });\n }\n\n return { key: 'records', groups };\n }, [active, enabled, state, term, t, translateKey, withLocale]);\n}\n"],"names":["useLocale","useT","useTranslateKey","useEffect","useMemo","useRef","useState","useLocaleHref","searchRecords","RECORD_SEARCH_DEBOUNCE_MS","RECORD_SEARCH_MIN_TERM","SCOPE_CODES","Set","severityOf","degraded","category","has","reason","NOTHING_YET","term","failed","useRecordsSource","enabled","t","translateKey","locale","withLocale","state","setState","pending","active","length","current","controller","AbortController","timer","setTimeout","signal","then","response","catch","aborted","clearTimeout","abort","heading","key","groups","label","options","isLoading","unavailable","message","count","severity","undefined","map","group","source","labelKey","items","item","id","sublabel","href","total","push","entity"],"mappings":"AAAA;;AAQA,SAASA,SAAS,EAAEC,IAAI,EAAEC,eAAe,QAAQ,0BAA0B;AAC3E,SAASC,SAAS,EAAEC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAQ;AAE7D,SAASC,aAAa,QAAQ,mBAAmB;AAEjD,SAASC,aAAa,QAAQ,8BAA8B;AAC5D,SACEC,yBAAyB,EACzBC,sBAAsB,QACjB,uBAAuB;AAE9B;;;;;;;CAOC,GACD,MAAMC,cAAmC,IAAIC,IAAI;IAAC;CAAuB;AAEzE,MAAMC,aAAa,CAACC,WAIlBA,SAASC,QAAQ,KAAK,qBACtBD,SAASC,QAAQ,KAAK,eACtBJ,YAAYK,GAAG,CAACF,SAASG,MAAM,IAC3B,UACA;AAUN,MAAMC,cAA4B;IAAEC,MAAM;IAAIC,QAAQ;AAAM;AAE5D;;;;;;;;;;;;;;;;;;;CAmBC,GACD,OAAO,SAASC,iBACdF,IAAY,EACZG,OAAgB;IAEhB,MAAMC,IAAItB,KAAK;IACf,MAAMuB,eAAetB;IACrB,MAAMuB,SAASzB;IACf,MAAM0B,aAAanB;IAEnB,MAAM,CAACoB,OAAOC,SAAS,GAAGtB,SAAuBY;IACjD,+EAA+E;IAC/E,yCAAyC;IACzC,MAAMW,UAAUxB,OAAsB;IAEtC,MAAMyB,SAASR,WAAWH,KAAKY,MAAM,IAAIrB;IAEzCP,UAAU;QACR,0EAA0E;QAC1E,6EAA6E;QAC7E,yEAAyE;QACzE,mEAAmE;QACnE,IAAI,CAAC2B,QAAQ;YACXD,QAAQG,OAAO,GAAG;YAClB;QACF;QAEA,MAAMC,aAAa,IAAIC;QACvBL,QAAQG,OAAO,GAAGb;QAElB,MAAMgB,QAAQC,WAAW;YACvB,KAAK5B,cAAcW,MAAM;gBAAEkB,QAAQJ,WAAWI,MAAM;gBAAEZ;YAAO,GAC1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lib/command-palette/use-records-source.ts"],"sourcesContent":["'use client';\n\nimport type {\n CommandGroup,\n CommandSource,\n CommandUnavailableSeverity,\n FailureCategory,\n} from '@entifix/core';\nimport { useLocale, useT, useTranslateKey } from '@entifix/react-controls';\nimport { useEffect, useMemo, useRef, useState } from 'react';\n\nimport { useLocaleHref } from '../i18n/index.js';\nimport type { RecordSearchResponse } from '../search/record-search.types.js';\nimport { searchRecords } from '../search/search-records.js';\nimport {\n RECORD_SEARCH_DEBOUNCE_MS,\n RECORD_SEARCH_MIN_TERM,\n} from './palette-command.js';\n\n/**\n * Which reasons are the caller's ordinary state, and which mean something broke.\n *\n * The split is the record search's, restated as severity because that is what the palette\n * renders. An operator holds no membership, so every tenant-plane source answers\n * `409` on every keystroke — painting that as an outage teaches them to ignore\n * the row entirely, and then the `timeout` that does matter goes unread too.\n */\nconst SCOPE_CODES: ReadonlySet<string> = new Set(['noActiveOrganization']);\n\nconst severityOf = (degraded: {\n readonly reason: string;\n readonly category: FailureCategory;\n}): CommandUnavailableSeverity =>\n degraded.category === 'unauthenticated' ||\n degraded.category === 'forbidden' ||\n SCOPE_CODES.has(degraded.reason)\n ? 'scope'\n : 'reachability';\n\n/** What the browser is currently showing for records. */\ninterface RecordsState {\n /** The term this answer is for, so a stale response cannot overwrite a newer one. */\n readonly term: string;\n readonly response?: RecordSearchResponse;\n readonly failed: boolean;\n}\n\nconst NOTHING_YET: RecordsState = { term: '', failed: false };\n\n/**\n * Records matching the term, one group per source, in the order the host\n * declared them.\n *\n * The whole of the *keystroke* policy lives here rather than in `searchRecords`,\n * which is deliberately a bare typed `fetch`: the palette is the thing that\n * knows a keystroke is not a query. So this owns the debounce, the abort and the\n * two-character floor, while the route owns the fan-out, the per-source timeout\n * and the authorization.\n *\n * **No index, ever.** Every option here came back from `/api/search` for this\n * principal and this organization, on this keystroke. A prefetched client index\n * is the shape that surfaces another organization's record the first time a\n * session's scope moves under it, so there is none, ever.\n *\n * Below the two-character floor the group is present and **says why** rather\n * than being empty or absent: empty would claim nothing matched a search that\n * never ran, and absent would leave someone wondering whether records are\n * searchable here at all.\n */\nexport function useRecordsSource(\n term: string,\n enabled: boolean,\n): CommandSource {\n const t = useT('shell');\n const controls = useT();\n const translateKey = useTranslateKey();\n const locale = useLocale();\n const withLocale = useLocaleHref();\n\n const [state, setState] = useState<RecordsState>(NOTHING_YET);\n // The term the request in flight is for. A ref, not state: it changes on every\n // keystroke and nothing renders from it.\n const pending = useRef<string | null>(null);\n\n const active = enabled && term.length >= RECORD_SEARCH_MIN_TERM;\n\n useEffect(() => {\n // Nothing is cleared here on purpose. A `setState` in an effect body is a\n // cascading render, and there is nothing to clear: the memo below returns no\n // groups while inactive, so a previous answer is unreachable rather than\n // stale — and the host empties the term when it opens the palette.\n if (!active) {\n pending.current = null;\n return;\n }\n\n const controller = new AbortController();\n pending.current = term;\n\n const timer = setTimeout(() => {\n void searchRecords(term, { signal: controller.signal, locale })\n .then(response => {\n if (pending.current !== term) return;\n setState({ term, response, failed: false });\n })\n .catch(() => {\n // An abort lands here too and must not be shown: the term moved on,\n // so there is nothing to report about the request that did not finish.\n if (controller.signal.aborted || pending.current !== term) return;\n setState({ term, failed: true });\n });\n }, RECORD_SEARCH_DEBOUNCE_MS);\n\n return () => {\n clearTimeout(timer);\n controller.abort();\n };\n }, [active, locale, term]);\n\n return useMemo(() => {\n const heading = t('commandPalette.groups.records');\n\n if (!active) {\n // Someone who has typed one character is mid-word, not looking at an\n // answer. Saying so is better than both alternatives: an empty group would\n // claim nothing matched a search that never ran, and an absent one would\n // leave them wondering whether records are searchable at all.\n if (!enabled || term.length === 0) return { key: 'records', groups: [] };\n return {\n key: 'records',\n groups: [\n {\n key: 'records',\n label: heading,\n options: [],\n isLoading: false,\n unavailable: {\n message: t('commandPalette.typeMore', {\n count: RECORD_SEARCH_MIN_TERM,\n }),\n severity: 'scope',\n },\n },\n ],\n };\n }\n // A newer term is in flight. The previous answer stays on screen with its\n // groups marked loading rather than blanking: a list that empties between\n // keystrokes flickers, and the rows it drops were correct a moment ago.\n const isLoading = state.term !== term;\n\n if (state.response === undefined) {\n return {\n key: 'records',\n groups: [\n {\n key: 'records',\n label: heading,\n options: [],\n isLoading: !state.failed,\n // The whole endpoint failed — a lapsed session or a `400`, both of\n // which arrive as a rejection rather than inside a `200`. It is\n // named for the same reason a single degraded source is.\n ...(state.failed\n ? {\n unavailable: {\n message: t('commandPalette.unavailableReach', {\n reason: translateKey('errors:unexpected'),\n }),\n severity: 'reachability' as const,\n },\n }\n : {}),\n },\n ],\n };\n }\n\n const groups: CommandGroup[] = state.response.groups.map(group => ({\n key: `record:${group.source}`,\n // The entity's own `pluralKey`, so record search introduces no copy of\n // its own and a group is titled exactly as its screen is.\n label: translateKey(group.labelKey),\n options: group.items.map(item => ({\n id: `record:${group.source}:${item.id}`,\n // A record nothing names reads as a table names it: the entity's noun\n // and its short id, never the bare id.\n label:\n item.unnamed === true\n ? controls('reference.unresolved', {\n noun: translateKey(`entity:${item.entity}.label`),\n id: item.label,\n })\n : item.label,\n ...(item.sublabel === undefined ? {} : { sublabel: item.sublabel }),\n href: withLocale(item.href),\n })),\n total: group.total,\n isLoading,\n }));\n\n for (const degraded of state.response.unavailable) {\n const severity = severityOf(degraded);\n groups.push({\n key: `record:${degraded.source}`,\n // Derived from the entity rather than from the source key, which is an\n // identifier and would render as `product-specification`. Every\n // searchable entity declares a `pluralKey` — `catalogSurface` throws\n // without one — so this always resolves.\n label: translateKey(`entity:${degraded.entity}.plural`),\n options: [],\n isLoading: false,\n unavailable: {\n message: t(\n severity === 'scope'\n ? 'commandPalette.unavailableScope'\n : 'commandPalette.unavailableReach',\n { reason: translateKey(`errors:${degraded.reason}`) },\n ),\n severity,\n },\n });\n }\n\n return { key: 'records', groups };\n }, [active, controls, enabled, state, term, t, translateKey, withLocale]);\n}\n"],"names":["useLocale","useT","useTranslateKey","useEffect","useMemo","useRef","useState","useLocaleHref","searchRecords","RECORD_SEARCH_DEBOUNCE_MS","RECORD_SEARCH_MIN_TERM","SCOPE_CODES","Set","severityOf","degraded","category","has","reason","NOTHING_YET","term","failed","useRecordsSource","enabled","t","controls","translateKey","locale","withLocale","state","setState","pending","active","length","current","controller","AbortController","timer","setTimeout","signal","then","response","catch","aborted","clearTimeout","abort","heading","key","groups","label","options","isLoading","unavailable","message","count","severity","undefined","map","group","source","labelKey","items","item","id","unnamed","noun","entity","sublabel","href","total","push"],"mappings":"AAAA;;AAQA,SAASA,SAAS,EAAEC,IAAI,EAAEC,eAAe,QAAQ,0BAA0B;AAC3E,SAASC,SAAS,EAAEC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAQ;AAE7D,SAASC,aAAa,QAAQ,mBAAmB;AAEjD,SAASC,aAAa,QAAQ,8BAA8B;AAC5D,SACEC,yBAAyB,EACzBC,sBAAsB,QACjB,uBAAuB;AAE9B;;;;;;;CAOC,GACD,MAAMC,cAAmC,IAAIC,IAAI;IAAC;CAAuB;AAEzE,MAAMC,aAAa,CAACC,WAIlBA,SAASC,QAAQ,KAAK,qBACtBD,SAASC,QAAQ,KAAK,eACtBJ,YAAYK,GAAG,CAACF,SAASG,MAAM,IAC3B,UACA;AAUN,MAAMC,cAA4B;IAAEC,MAAM;IAAIC,QAAQ;AAAM;AAE5D;;;;;;;;;;;;;;;;;;;CAmBC,GACD,OAAO,SAASC,iBACdF,IAAY,EACZG,OAAgB;IAEhB,MAAMC,IAAItB,KAAK;IACf,MAAMuB,WAAWvB;IACjB,MAAMwB,eAAevB;IACrB,MAAMwB,SAAS1B;IACf,MAAM2B,aAAapB;IAEnB,MAAM,CAACqB,OAAOC,SAAS,GAAGvB,SAAuBY;IACjD,+EAA+E;IAC/E,yCAAyC;IACzC,MAAMY,UAAUzB,OAAsB;IAEtC,MAAM0B,SAAST,WAAWH,KAAKa,MAAM,IAAItB;IAEzCP,UAAU;QACR,0EAA0E;QAC1E,6EAA6E;QAC7E,yEAAyE;QACzE,mEAAmE;QACnE,IAAI,CAAC4B,QAAQ;Y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AAOvB,aAAa,CAAC,OAAO,EAAEX,SAASmD,MAAM,CAAC,OAAO,CAAC;gBACtDhB,SAAS,EAAE;gBACXC,WAAW;gBACXC,aAAa;oBACXC,SAAS7B,EACP+B,aAAa,UACT,oCACA,mCACJ;wBAAErC,QAAQQ,aAAa,CAAC,OAAO,EAAEX,SAASG,MAAM,EAAE;oBAAE;oBAEtDqC;gBACF;YACF;QACF;QAEA,OAAO;YAAER,KAAK;YAAWC;QAAO;IAClC,GAAG;QAAChB;QAAQP;QAAUF;QAASM;QAAOT;QAAMI;QAAGE;QAAcE;KAAW;AAC1E"}
@@ -1 +1 @@
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,EAevB,MAAM,eAAe,CAAC;AAmBvB,OAAO,EAAS,OAAO,EAAgB,MAAM,QAAQ,CAAC;AAQtD,OAAO,KAAK,EAEV,UAAU,EAEV,iBAAiB,EAGlB,MAAM,6BAA6B,CAAC;AAmBrC;;;;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,CAipBrB"}
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,EAiBvB,MAAM,eAAe,CAAC;AAmBvB,OAAO,EAAS,OAAO,EAAgB,MAAM,QAAQ,CAAC;AAQtD,OAAO,KAAK,EAEV,UAAU,EAGV,iBAAiB,EAGlB,MAAM,6BAA6B,CAAC;AAmBrC;;;;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,CAyqBrB"}
@@ -2,7 +2,7 @@
2
2
  import { _ as _extends } from "@swc/helpers/_/_extends";
3
3
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
4
4
  import { deleteUCFactory, EntityIdTag, EntityTag, getUCFactory, loadUCFactory, saveUCFactory } from '@entifix/business';
5
- import { coerceFiltering, describeEntityColumns, envelopeEntityName, extractMetaEntity, Internal, isFailure, parseRsql, serializeRsql, settled } from '@entifix/core';
5
+ import { coerceFiltering, describeEntityColumns, envelopeEntityName, extractMetaEntity, Internal, isFailure, parseRsql, parseSort, serializeRsql, serializeSort, settled } from '@entifix/core';
6
6
  import { EntityTable, useCasesForSurface, useFocusOnArrival, useRecordLabel, useT, useToasts, useTranslateKey } from '@entifix/react-controls';
7
7
  import { entityQueryScope, useDataLoading, useEntityRecord, useFacetCounts, useOptimisticMutation } from '@entifix/react-integration';
8
8
  import { useQueryClient } from '@tanstack/react-query';
@@ -128,7 +128,7 @@ import { useEntityBulk } from './use-entity-bulk.js';
128
128
  return links.map((link)=>link.useBaseFiltering == null ? void 0 : link.useBaseFiltering.call(link, record));
129
129
  }
130
130
  export function makeEntityCrud(entityConstructor, options) {
131
- const { useAdapters, basePath, catalogKey, repository, hiddenFields = [], columns, toolbar, pageSize, initialFiltering, links = [], related = [], regions, metadataSource: givenMetadataSource, metadata, useCases, write, delete: deletePolicy = 'confirm', facets } = options;
131
+ const { useAdapters, basePath, catalogKey, repository, hiddenFields = [], columns, toolbar, pageSize, initialFiltering, initialSorting, useListView, links = [], related = [], regions, metadataSource: givenMetadataSource, metadata, useCases, write, delete: deletePolicy = 'confirm', facets } = options;
132
132
  if (givenMetadataSource !== undefined && metadata !== undefined) {
133
133
  throw new Error(`${entityConstructor.name} was given both metadataSource and metadata; pass one`);
134
134
  }
@@ -148,6 +148,13 @@ export function makeEntityCrud(entityConstructor, options) {
148
148
  if (initialRsql !== '') {
149
149
  coerceFiltering(entityConstructor, parseRsql(initialRsql));
150
150
  }
151
+ // The same posture for the order it opens in: parsed back through the
152
+ // allowlist a service applies to a `sort` parameter.
153
+ if (initialSorting !== undefined) {
154
+ parseSort(entityConstructor, serializeSort([
155
+ initialSorting
156
+ ]));
157
+ }
151
158
  const meta = extractMetaEntity(entityConstructor);
152
159
  if (meta.key !== catalogKey) {
153
160
  throw new Error(`${entityConstructor.name} declares key "${String(meta.key)}" but was given catalog key "${catalogKey}"`);
@@ -164,6 +171,17 @@ export function makeEntityCrud(entityConstructor, options) {
164
171
  }
165
172
  // Narrowed once, for the closures below that TypeScript cannot follow.
166
173
  const pluralKey = entityPluralKey;
174
+ // The host's reading of who is reading, or nobody in particular. Called the
175
+ // same way on every render — whether there is a hook is fixed with the
176
+ // factory — so it is a hook call the rules allow.
177
+ const useReaderView = ()=>{
178
+ var _ref;
179
+ return (_ref = useListView == null ? void 0 : useListView()) != null ? _ref : {};
180
+ };
181
+ const useListTitleKey = ()=>{
182
+ var _useReaderView_titleKey;
183
+ return (_useReaderView_titleKey = useReaderView().titleKey) != null ? _useReaderView_titleKey : pluralKey;
184
+ };
167
185
  // Computed once: a descriptor is a property of the class, so nothing about it
168
186
  // depends on the record being edited. `linkLabelProperty`/`linkSearchProperty`
169
187
  // are overridden here because a scalar foreign key's `@accessor()` cannot name
@@ -200,6 +218,7 @@ export function makeEntityCrud(entityConstructor, options) {
200
218
  var _syncFailure;
201
219
  var _affordances_metadata, _affordances_metadata1, _affordances_metadata2;
202
220
  const adapters = useAdapters();
221
+ const { hiddenColumns } = useReaderView();
203
222
  // Every internal href carries the locale. An unprefixed one still resolves —
204
223
  // the middleware redirects it — but the visitor pays a round trip per click.
205
224
  const withLocale = useLocaleHref();
@@ -221,6 +240,8 @@ export function makeEntityCrud(entityConstructor, options) {
221
240
  initialPageSize: listPageSize
222
241
  }, listInitialFiltering === undefined ? {} : {
223
242
  initialFiltering: listInitialFiltering
243
+ }, initialSorting === undefined ? {} : {
244
+ initialSorting
224
245
  }, baseFiltering === undefined ? {} : {
225
246
  baseFiltering
226
247
  }));
@@ -284,6 +305,8 @@ export function makeEntityCrud(entityConstructor, options) {
284
305
  } : undefined;
285
306
  return /*#__PURE__*/ _jsxs(EntityTable, _extends({
286
307
  entityConstructor: entityConstructor
308
+ }, hiddenColumns === undefined ? {} : {
309
+ hiddenColumns
287
310
  }, pager, {
288
311
  items: pager.items,
289
312
  totalItems: pager.totalItems,
@@ -308,6 +331,7 @@ export function makeEntityCrud(entityConstructor, options) {
308
331
  const heading = useRef(null);
309
332
  useFocusOnArrival(heading);
310
333
  const et = useT('entity');
334
+ const titleKey = useListTitleKey();
311
335
  return /*#__PURE__*/ _jsxs("div", {
312
336
  className: "flex flex-col gap-s",
313
337
  children: [
@@ -315,7 +339,7 @@ export function makeEntityCrud(entityConstructor, options) {
315
339
  ref: heading,
316
340
  tabIndex: -1,
317
341
  className: "m-0 text-step-2 font-semibold text-content focus-ring",
318
- children: et(pluralKey.replace(/^entity:/, ''))
342
+ children: et(titleKey.replace(/^entity:/, ''))
319
343
  }),
320
344
  /*#__PURE__*/ _jsx(ListBody, _extends({}, initialFiltering === undefined ? {} : {
321
345
  listInitialFiltering: initialFiltering
@@ -359,13 +383,17 @@ export function makeEntityCrud(entityConstructor, options) {
359
383
  }, regionPageSize === undefined ? {} : {
360
384
  listPageSize: regionPageSize
361
385
  }, {
362
- // The row's menu hands focus back to its trigger as it closes, and
363
- // a verb that settles fast settles before that. Focusing on the
364
- // next frame lands after the menu's restore, never under it.
365
- onVerbSettled: ()=>requestAnimationFrame(()=>{
366
- var _headingRef_current;
367
- return (_headingRef_current = headingRef.current) == null ? void 0 : _headingRef_current.focus();
368
- })
386
+ // The row's menu hands focus back to its trigger two frames after
387
+ // the click, unless focus already sits on a tabbable element — and
388
+ // this heading, at `tabIndex={-1}`, is not one. A verb that settles
389
+ // inside those two frames would be focused and then taken back.
390
+ // Frame callbacks run in the order they were asked for, and these
391
+ // are asked for after the click's, so two frames from the settle
392
+ // always run after the restore, never under it.
393
+ onVerbSettled: ()=>requestAnimationFrame(()=>requestAnimationFrame(()=>{
394
+ var _headingRef_current;
395
+ return (_headingRef_current = headingRef.current) == null ? void 0 : _headingRef_current.focus();
396
+ }))
369
397
  }))
370
398
  ]
371
399
  });
@@ -607,6 +635,7 @@ export function makeEntityCrud(entityConstructor, options) {
607
635
  entityKey: catalogKey,
608
636
  entityLabelKey,
609
637
  entityPluralKey,
638
+ useListTitleKey,
610
639
  basePath,
611
640
  ListPage,
612
641
  SingleViewPage,
@@ -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 serializeRsql,\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 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 { planRelated, useRelatedColumns } 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 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\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 // 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 // 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 ...(baseFiltering === undefined ? {} : { baseFiltering }),\n });\n\n // Values that live in another entity, one read per column per page.\n const relatedColumns = useRelatedColumns<TAdapters, TEntity>(\n relatedPlans,\n pager.items,\n plan => crudContextOf(adapters, plan.repository),\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 {...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\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(pluralKey.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 as it closes, and\n // a verb that settles fast settles before that. Focusing on the\n // next frame lands after the menu's restore, never under it.\n onVerbSettled={() =>\n requestAnimationFrame(() => headingRef.current?.focus())\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 key={String(entity?.id ?? CATALOG_NEW_SLUG)}\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 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 basePath,\n ListPage,\n SingleViewPage,\n RelatedList,\n };\n}\n"],"names":["deleteUCFactory","EntityIdTag","EntityTag","getUCFactory","loadUCFactory","saveUCFactory","coerceFiltering","describeEntityColumns","envelopeEntityName","extractMetaEntity","Internal","isFailure","parseRsql","serializeRsql","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","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","related","regions","metadataSource","givenMetadataSource","metadata","useCases","delete","deletePolicy","facets","Error","name","metadataSourceOf","initialRsql","meta","String","labelKey","entityLabelKey","pluralKey","entityPluralKey","entityName","descriptors","facetMembers","filter","filterable","type","relatedPlans","linkPlans","entry","field","linkLabelProperty","labelProperty","linkSearchProperty","searchProperty","ListBody","baseFiltering","newHref","givenNewHref","listPageSize","listInitialFiltering","onVerbSettled","affordances","withLocale","queryClient","scope","renderLink","pager","uc","ctx","queryKey","initialPageSize","relatedColumns","items","plan","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","index","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","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,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,E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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 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 { planRelated, useRelatedColumns } 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 relatedColumns = useRelatedColumns<TAdapters, TEntity>(\n relatedPlans,\n pager.items,\n plan => crudContextOf(adapters, plan.repository),\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 key={String(entity?.id ?? CATALOG_NEW_SLUG)}\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 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","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","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","relatedColumns","items","plan","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","index","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","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,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,SAASC,WAAW,EAAEC,iBAAiB,QAAQ,uBAAuB;AACtE,S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;QACAqL,WAAWjL;QACXwB;QACAE;QACAE;QACA7B;QACAqF;QACAyB;QACAhB;IACF;AACF"}
@@ -1,5 +1,5 @@
1
1
  import type { EntityFacetCounterTag, EntityRepositoryTag } from '@entifix/business';
2
- import type { Entity, EntityConstructor, EntityFieldDescriptor, EntityMetadataSource, EntityUseCaseRunner, EntityWriter, FilterGroup } from '@entifix/core';
2
+ import type { Entity, EntityConstructor, EntityFieldDescriptor, EntityMetadataSource, EntitySorting, EntityUseCaseRunner, EntityWriter, FilterGroup } from '@entifix/core';
3
3
  import type { EntityDraftStore, EntityLinkSourceConfig } from '@entifix/react-integration';
4
4
  import type { Context } from 'effect/Context';
5
5
  import type { CustomTypeOptions } from 'i18next';
@@ -225,6 +225,27 @@ export interface EntityCrudOptions<TAdapters, TEntity extends Entity> {
225
225
  * wrong type, throws here rather than answering `400` on every first load.
226
226
  */
227
227
  readonly initialFiltering?: FilterGroup<TEntity>;
228
+ /**
229
+ * The order the list opens in — a worklist again: the stock that is out
230
+ * first, the oldest order first. The header reads as sorted by it, and a
231
+ * click on another column replaces it.
232
+ *
233
+ * Checked when the screen is generated against the `sortable` allowlist a
234
+ * service applies to a `sort` parameter: a member that is not `sortable`
235
+ * throws here rather than answering `400` on every first load.
236
+ */
237
+ readonly initialSorting?: EntitySorting<TEntity>;
238
+ /**
239
+ * How the list reads for whoever is reading it — a hook the host supplies,
240
+ * called on every render of the list page and of each `RelatedList`. A
241
+ * vendor reading their own statement gets "My payouts" over a list with no
242
+ * "Vendor" column, where an operator gets "Vendor payouts" and the column.
243
+ *
244
+ * Copy and presentation only. It decides nothing about what the reader may
245
+ * read: the service narrows the records, and a column withheld here is a
246
+ * column whose value the service still sends.
247
+ */
248
+ readonly useListView?: () => EntityCrudListView;
228
249
  /**
229
250
  * How the record page's Delete is made safe
230
251
  * ([ADR 0026](../../../../../../docs/adr/0026-actions-hierarchy-overflow-and-destructive-verbs.md)):
@@ -345,12 +366,33 @@ export interface EntityCrud<TEntity extends Entity> {
345
366
  readonly entityLabelKey: string;
346
367
  /** `@entity({ pluralKey })` — how the collection is named. A list tab's title. */
347
368
  readonly entityPluralKey: string;
369
+ /**
370
+ * The list's title for whoever is reading it: the `titleKey` the host's
371
+ * `useListView` answers, else {@link entityPluralKey}. A hook, so a host
372
+ * titles a list's tab exactly as the page titles itself.
373
+ */
374
+ readonly useListTitleKey: () => string;
348
375
  readonly basePath: string;
349
376
  readonly ListPage: () => ReactElement;
350
377
  readonly SingleViewPage: (props?: EntityCrudSingleViewProps) => ReactElement;
351
378
  /** This entity's records referring to another record, as a region of that record's page. */
352
379
  readonly RelatedList: (props: EntityCrudRelatedListProps<TEntity>) => ReactElement;
353
380
  }
381
+ /** What {@link EntityCrudOptions.useListView} answers for one reader. */
382
+ export interface EntityCrudListView {
383
+ /**
384
+ * The list's title, as a catalog key, in place of the entity's own
385
+ * `pluralKey`. Also what {@link EntityCrud.useListTitleKey} answers, so a
386
+ * host titles the list's tab the same way.
387
+ */
388
+ readonly titleKey?: string;
389
+ /**
390
+ * Columns this reader does not get, passed to `EntityTable` as
391
+ * `hiddenColumns`: gone from the header, the settings, the filters, the sort
392
+ * choices and the cards. A name that is not a column throws.
393
+ */
394
+ readonly hiddenColumns?: readonly string[];
395
+ }
354
396
  /**
355
397
  * A picker's transport with its context tags erased.
356
398
  *