@entifix/next-shell 0.20.3 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +16 -1
  2. package/dist/lib/command-palette/use-records-source.d.ts.map +1 -1
  3. package/dist/lib/command-palette/use-records-source.js +5 -2
  4. package/dist/lib/command-palette/use-records-source.js.map +1 -1
  5. package/dist/lib/crud/index.d.ts +2 -0
  6. package/dist/lib/crud/index.d.ts.map +1 -1
  7. package/dist/lib/crud/index.js +2 -0
  8. package/dist/lib/crud/index.js.map +1 -1
  9. package/dist/lib/crud/make-entity-crud.d.ts.map +1 -1
  10. package/dist/lib/crud/make-entity-crud.js +131 -58
  11. package/dist/lib/crud/make-entity-crud.js.map +1 -1
  12. package/dist/lib/crud/make-entity-crud.types.d.ts +68 -1
  13. package/dist/lib/crud/make-entity-crud.types.d.ts.map +1 -1
  14. package/dist/lib/crud/make-entity-crud.types.js.map +1 -1
  15. package/dist/lib/crud/reference-labels.d.ts +27 -0
  16. package/dist/lib/crud/reference-labels.d.ts.map +1 -0
  17. package/dist/lib/crud/reference-labels.js +159 -0
  18. package/dist/lib/crud/reference-labels.js.map +1 -0
  19. package/dist/lib/crud/regions.d.ts +25 -0
  20. package/dist/lib/crud/regions.d.ts.map +1 -0
  21. package/dist/lib/crud/regions.js +82 -0
  22. package/dist/lib/crud/regions.js.map +1 -0
  23. package/dist/lib/crud/related-columns.d.ts +29 -0
  24. package/dist/lib/crud/related-columns.d.ts.map +1 -0
  25. package/dist/lib/crud/related-columns.js +141 -0
  26. package/dist/lib/crud/related-columns.js.map +1 -0
  27. package/dist/lib/crud/use-entity-link-sources.d.ts.map +1 -1
  28. package/dist/lib/crud/use-entity-link-sources.js +5 -1
  29. package/dist/lib/crud/use-entity-link-sources.js.map +1 -1
  30. package/dist/lib/crud/use-entity-total.d.ts +27 -0
  31. package/dist/lib/crud/use-entity-total.d.ts.map +1 -0
  32. package/dist/lib/crud/use-entity-total.js +39 -0
  33. package/dist/lib/crud/use-entity-total.js.map +1 -0
  34. package/dist/lib/i18n/catalog/en.d.ts.map +1 -1
  35. package/dist/lib/i18n/catalog/en.js +6 -0
  36. package/dist/lib/i18n/catalog/en.js.map +1 -1
  37. package/dist/lib/i18n/catalog/es.d.ts +8 -0
  38. package/dist/lib/i18n/catalog/es.d.ts.map +1 -1
  39. package/dist/lib/i18n/catalog/es.js +7 -1
  40. package/dist/lib/i18n/catalog/es.js.map +1 -1
  41. package/dist/lib/i18n/catalog/index.d.ts +12 -0
  42. package/dist/lib/i18n/catalog/index.d.ts.map +1 -1
  43. package/dist/lib/search/record-search-route.d.ts +2 -0
  44. package/dist/lib/search/record-search-route.d.ts.map +1 -1
  45. package/dist/lib/search/record-search-route.js +21 -5
  46. package/dist/lib/search/record-search-route.js.map +1 -1
  47. package/dist/lib/search/record-search-source.d.ts +11 -4
  48. package/dist/lib/search/record-search-source.d.ts.map +1 -1
  49. package/dist/lib/search/record-search-source.js +17 -19
  50. package/dist/lib/search/record-search-source.js.map +1 -1
  51. package/dist/lib/search/record-search.types.d.ts +4 -3
  52. package/dist/lib/search/record-search.types.d.ts.map +1 -1
  53. package/dist/lib/search/record-search.types.js.map +1 -1
  54. package/dist/lib/search/search-records.d.ts +3 -1
  55. package/dist/lib/search/search-records.d.ts.map +1 -1
  56. package/dist/lib/search/search-records.js +2 -1
  57. package/dist/lib/search/search-records.js.map +1 -1
  58. package/package.json +9 -9
  59. package/dist/lib/crud/use-link-labels.d.ts +0 -32
  60. package/dist/lib/crud/use-link-labels.d.ts.map +0 -1
  61. package/dist/lib/crud/use-link-labels.js +0 -76
  62. package/dist/lib/crud/use-link-labels.js.map +0 -1
@@ -0,0 +1,159 @@
1
+ 'use client';
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { createReferenceLabels, ReferenceLabelsTag } from '@entifix/business';
4
+ import { extractMetaEntity } from '@entifix/core';
5
+ import { ReferenceLabelsProvider } from '@entifix/react-controls';
6
+ import { entityQueryScope } from '@entifix/react-integration';
7
+ import { useQueries, useQueryClient } from '@tanstack/react-query';
8
+ import { Context, Effect } from 'effect';
9
+ import { useMemo, useRef, useState } from 'react';
10
+ /**
11
+ * Reads the names of the records a screen refers to by id, and publishes them
12
+ * to the controls
13
+ * ([ADR 0030](../../../../../../docs/adr/0030-a-reference-names-its-target-through-the-owners-read-port.md)).
14
+ *
15
+ * Mounted **once by the host**, beside its other providers, with one
16
+ * registration per target entity — `[Constructor, repositoryContext,
17
+ * { labelProperty? }]` — because only the host has every target's adapter in
18
+ * reach. Keep `registrations` stable (a module constant or a `useMemo`).
19
+ *
20
+ * Every id a render asks for is collected and, after that commit, read in
21
+ * **one request per target entity**. Each label is cached per id under the
22
+ * target's own query scope, so a record's page reuses what its list read, and
23
+ * an invalidation of the target — a save, a pushed change — refreshes it.
24
+ *
25
+ * A reference to an entity no registration reads shows its raw id, muted, and
26
+ * `onUnregistered` is told its key once — the host decides whether that is a
27
+ * development warning; this mechanism does not log.
28
+ */ export function ReferenceLabelsHost({ registrations, onUnregistered, children }) {
29
+ const labels = useMemo(()=>Context.get(createReferenceLabels(registrations), ReferenceLabelsTag), [
30
+ registrations
31
+ ]);
32
+ const queryClient = useQueryClient();
33
+ /** Ids a render asked for that no batch holds yet, by entity key. */ const asked = useRef(new Map());
34
+ const [batches, setBatches] = useState([]);
35
+ const results = useQueries({
36
+ queries: batches.map((batch)=>{
37
+ const entityConstructor = labels.entities.get(batch.entityKey);
38
+ return {
39
+ queryKey: [
40
+ ...entityQueryScope(entityConstructor),
41
+ 'reference-label-batch',
42
+ batch.ids
43
+ ],
44
+ queryFn: ()=>Effect.runPromise(labels.resolve(batch.entityKey, batch.ids)).then((found)=>{
45
+ for (const id of batch.ids){
46
+ var _found_get;
47
+ queryClient.setQueryData(labelKey(entityConstructor, id), (_found_get = found.get(id)) != null ? _found_get : null);
48
+ }
49
+ return true;
50
+ })
51
+ };
52
+ })
53
+ });
54
+ /** The unregistered keys `onUnregistered` was already told about. */ const reported = useRef(new Set());
55
+ /** Whether a flush of what renders asked for is already queued. */ const scheduled = useRef(false);
56
+ /**
57
+ * Turns everything renders asked for into one batch per target entity. Run
58
+ * as a microtask once the render that asked has returned — a reader re-renders
59
+ * on its own when its rows arrive, without this host rendering at all, so
60
+ * waiting for this host's commit would wait forever. A render only asks for an
61
+ * id nothing has cached and no batch is reading or has failed on, so the same
62
+ * id is never read twice.
63
+ */ const flush = ()=>{
64
+ scheduled.current = false;
65
+ const next = [
66
+ ...asked.current
67
+ ].map(([entityKey, ids])=>({
68
+ entityKey,
69
+ ids: [
70
+ ...ids
71
+ ].sort()
72
+ }));
73
+ asked.current.clear();
74
+ setBatches((previous)=>[
75
+ ...previous,
76
+ ...next
77
+ ]);
78
+ };
79
+ const failedBatches = batches.filter((_, index)=>{
80
+ var _results_index;
81
+ return (_results_index = results[index]) == null ? void 0 : _results_index.isError;
82
+ });
83
+ const pendingBatches = batches.filter((_, index)=>{
84
+ var _results_index;
85
+ return ((_results_index = results[index]) == null ? void 0 : _results_index.isPending) !== false;
86
+ });
87
+ const dataStamp = results.map((result)=>`${result.status}${result.dataUpdatedAt}`).join(',');
88
+ const lookup = useMemo(()=>({
89
+ label (entityKey, id) {
90
+ const entityConstructor = labels.entities.get(entityKey);
91
+ if (entityConstructor === undefined) {
92
+ if (!reported.current.has(entityKey)) {
93
+ reported.current.add(entityKey);
94
+ onUnregistered == null ? void 0 : onUnregistered(entityKey);
95
+ }
96
+ return {
97
+ status: 'unregistered'
98
+ };
99
+ }
100
+ const cached = readLabel(queryClient, entityConstructor, id);
101
+ if (cached !== undefined) return cached;
102
+ const holds = (batch)=>batch.entityKey === entityKey && batch.ids.includes(id);
103
+ if (failedBatches.some(holds)) return {
104
+ status: 'failed'
105
+ };
106
+ if (pendingBatches.some(holds)) return {
107
+ status: 'resolving'
108
+ };
109
+ let ids = asked.current.get(entityKey);
110
+ if (ids === undefined) {
111
+ ids = new Set();
112
+ asked.current.set(entityKey, ids);
113
+ }
114
+ ids.add(id);
115
+ if (!scheduled.current) {
116
+ scheduled.current = true;
117
+ queueMicrotask(flush);
118
+ }
119
+ return {
120
+ status: 'resolving'
121
+ };
122
+ },
123
+ noun (entityKey) {
124
+ const entityConstructor = labels.entities.get(entityKey);
125
+ return entityConstructor === undefined ? undefined : extractMetaEntity(entityConstructor);
126
+ }
127
+ }), // A new lookup whenever a batch starts, lands or fails — what the stamp
128
+ // tracks — so every reader re-renders.
129
+ [
130
+ labels,
131
+ queryClient,
132
+ dataStamp,
133
+ batches,
134
+ onUnregistered
135
+ ]);
136
+ return /*#__PURE__*/ _jsx(ReferenceLabelsProvider, {
137
+ lookup: lookup,
138
+ children: children
139
+ });
140
+ }
141
+ function labelKey(entityConstructor, id) {
142
+ return [
143
+ ...entityQueryScope(entityConstructor),
144
+ 'reference-label',
145
+ id
146
+ ];
147
+ }
148
+ /** A cached label's state, or `undefined` when nothing is cached for the id yet. */ function readLabel(queryClient, entityConstructor, id) {
149
+ const state = queryClient.getQueryState(labelKey(entityConstructor, id));
150
+ if ((state == null ? void 0 : state.status) !== 'success') return undefined;
151
+ return state.data === null || state.data === undefined ? {
152
+ status: 'notFound'
153
+ } : {
154
+ status: 'named',
155
+ label: state.data
156
+ };
157
+ }
158
+
159
+ //# sourceMappingURL=reference-labels.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/lib/crud/reference-labels.tsx"],"sourcesContent":["'use client';\n\nimport {\n createReferenceLabels,\n type ReferenceLabel,\n type ReferenceLabelRegistration,\n ReferenceLabelsTag,\n} from '@entifix/business';\nimport { extractMetaEntity } from '@entifix/core';\nimport {\n type ReferenceLabelLookup,\n ReferenceLabelsProvider,\n type ReferenceLabelState,\n} from '@entifix/react-controls';\nimport { entityQueryScope } from '@entifix/react-integration';\nimport {\n type QueryClient,\n useQueries,\n useQueryClient,\n} from '@tanstack/react-query';\nimport { Context, Effect } from 'effect';\nimport { type ReactNode, useMemo, useRef, useState } from 'react';\n\n/** One read: the ids of one target entity a commit asked for and nothing had cached. */\ninterface Batch {\n readonly entityKey: string;\n readonly ids: readonly string[];\n}\n\n/**\n * What the per-id cache holds for a record: its label, or `null` for an id no\n * record answered — so a miss is remembered as one, not asked for again.\n */\ntype CachedLabel = ReferenceLabel | null;\n\n/**\n * Reads the names of the records a screen refers to by id, and publishes them\n * to the controls\n * ([ADR 0030](../../../../../../docs/adr/0030-a-reference-names-its-target-through-the-owners-read-port.md)).\n *\n * Mounted **once by the host**, beside its other providers, with one\n * registration per target entity — `[Constructor, repositoryContext,\n * { labelProperty? }]` — because only the host has every target's adapter in\n * reach. Keep `registrations` stable (a module constant or a `useMemo`).\n *\n * Every id a render asks for is collected and, after that commit, read in\n * **one request per target entity**. Each label is cached per id under the\n * target's own query scope, so a record's page reuses what its list read, and\n * an invalidation of the target — a save, a pushed change — refreshes it.\n *\n * A reference to an entity no registration reads shows its raw id, muted, and\n * `onUnregistered` is told its key once — the host decides whether that is a\n * development warning; this mechanism does not log.\n */\nexport function ReferenceLabelsHost({\n registrations,\n onUnregistered,\n children,\n}: {\n registrations: ReadonlyArray<ReferenceLabelRegistration>;\n onUnregistered?: (entityKey: string) => void;\n children: ReactNode;\n}) {\n const labels = useMemo(\n () => Context.get(createReferenceLabels(registrations), ReferenceLabelsTag),\n [registrations],\n );\n const queryClient = useQueryClient();\n /** Ids a render asked for that no batch holds yet, by entity key. */\n const asked = useRef(new Map<string, Set<string>>());\n const [batches, setBatches] = useState<readonly Batch[]>([]);\n\n const results = useQueries({\n queries: batches.map(batch => {\n const entityConstructor = labels.entities.get(batch.entityKey);\n return {\n queryKey: [\n ...entityQueryScope(entityConstructor as never),\n 'reference-label-batch',\n batch.ids,\n ],\n queryFn: () =>\n Effect.runPromise(labels.resolve(batch.entityKey, batch.ids)).then(\n found => {\n for (const id of batch.ids) {\n queryClient.setQueryData<CachedLabel>(\n labelKey(entityConstructor, id),\n found.get(id) ?? null,\n );\n }\n return true;\n },\n ),\n };\n }),\n });\n\n /** The unregistered keys `onUnregistered` was already told about. */\n const reported = useRef(new Set<string>());\n /** Whether a flush of what renders asked for is already queued. */\n const scheduled = useRef(false);\n /**\n * Turns everything renders asked for into one batch per target entity. Run\n * as a microtask once the render that asked has returned — a reader re-renders\n * on its own when its rows arrive, without this host rendering at all, so\n * waiting for this host's commit would wait forever. A render only asks for an\n * id nothing has cached and no batch is reading or has failed on, so the same\n * id is never read twice.\n */\n const flush = () => {\n scheduled.current = false;\n const next = [...asked.current].map(([entityKey, ids]) => ({\n entityKey,\n ids: [...ids].sort(),\n }));\n asked.current.clear();\n setBatches(previous => [...previous, ...next]);\n };\n\n const failedBatches = batches.filter((_, index) => results[index]?.isError);\n const pendingBatches = batches.filter(\n (_, index) => results[index]?.isPending !== false,\n );\n const dataStamp = results\n .map(result => `${result.status}${result.dataUpdatedAt}`)\n .join(',');\n\n const lookup = useMemo<ReferenceLabelLookup>(\n () => ({\n label(entityKey, id) {\n const entityConstructor = labels.entities.get(entityKey);\n if (entityConstructor === undefined) {\n if (!reported.current.has(entityKey)) {\n reported.current.add(entityKey);\n onUnregistered?.(entityKey);\n }\n return { status: 'unregistered' };\n }\n const cached = readLabel(queryClient, entityConstructor, id);\n if (cached !== undefined) return cached;\n const holds = (batch: Batch) =>\n batch.entityKey === entityKey && batch.ids.includes(id);\n if (failedBatches.some(holds)) return { status: 'failed' };\n if (pendingBatches.some(holds)) return { status: 'resolving' };\n let ids = asked.current.get(entityKey);\n if (ids === undefined) {\n ids = new Set();\n asked.current.set(entityKey, ids);\n }\n ids.add(id);\n if (!scheduled.current) {\n scheduled.current = true;\n queueMicrotask(flush);\n }\n return { status: 'resolving' };\n },\n noun(entityKey) {\n const entityConstructor = labels.entities.get(entityKey);\n return entityConstructor === undefined\n ? undefined\n : extractMetaEntity(entityConstructor);\n },\n }),\n // A new lookup whenever a batch starts, lands or fails — what the stamp\n // tracks — so every reader re-renders.\n [labels, queryClient, dataStamp, batches, onUnregistered],\n );\n\n return (\n <ReferenceLabelsProvider lookup={lookup}>\n {children}\n </ReferenceLabelsProvider>\n );\n}\n\nfunction labelKey(entityConstructor: unknown, id: string) {\n return [\n ...entityQueryScope(entityConstructor as never),\n 'reference-label',\n id,\n ];\n}\n\n/** A cached label's state, or `undefined` when nothing is cached for the id yet. */\nfunction readLabel(\n queryClient: QueryClient,\n entityConstructor: unknown,\n id: string,\n): ReferenceLabelState | undefined {\n const state = queryClient.getQueryState<CachedLabel>(\n labelKey(entityConstructor, id),\n );\n if (state?.status !== 'success') return undefined;\n return state.data === null || state.data === undefined\n ? { status: 'notFound' }\n : { status: 'named', label: state.data };\n}\n"],"names":["createReferenceLabels","ReferenceLabelsTag","extractMetaEntity","ReferenceLabelsProvider","entityQueryScope","useQueries","useQueryClient","Context","Effect","useMemo","useRef","useState","ReferenceLabelsHost","registrations","onUnregistered","children","labels","get","queryClient","asked","Map","batches","setBatches","results","queries","map","batch","entityConstructor","entities","entityKey","queryKey","ids","queryFn","runPromise","resolve","then","found","id","setQueryData","labelKey","reported","Set","scheduled","flush","current","next","sort","clear","previous","failedBatches","filter","_","index","isError","pendingBatches","isPending","dataStamp","result","status","dataUpdatedAt","join","lookup","label","undefined","has","add","cached","readLabel","holds","includes","some","set","queueMicrotask","noun","state","getQueryState","data"],"mappings":"AAAA;;AAEA,SACEA,qBAAqB,EAGrBC,kBAAkB,QACb,oBAAoB;AAC3B,SAASC,iBAAiB,QAAQ,gBAAgB;AAClD,SAEEC,uBAAuB,QAElB,0BAA0B;AACjC,SAASC,gBAAgB,QAAQ,6BAA6B;AAC9D,SAEEC,UAAU,EACVC,cAAc,QACT,wBAAwB;AAC/B,SAASC,OAAO,EAAEC,MAAM,QAAQ,SAAS;AACzC,SAAyBC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAQ;AAclE;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASC,oBAAoB,EAClCC,aAAa,EACbC,cAAc,EACdC,QAAQ,EAKT;IACC,MAAMC,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AUE,OAAO,GAAG;oBACpB4B,eAAe7B;gBACjB;gBACA,OAAO;oBAAEe,QAAQ;gBAAY;YAC/B;YACAe,MAAK5C,SAAS;gBACZ,MAAMF,oBAAoBX,OAAOY,QAAQ,CAACX,GAAG,CAACY;gBAC9C,OAAOF,sBAAsBoC,YACzBA,YACA7D,kBAAkByB;YACxB;QACF,CAAA,GACA,wEAAwE;IACxE,uCAAuC;IACvC;QAACX;QAAQE;QAAasC;QAAWnC;QAASP;KAAe;IAG3D,qBACE,KAACX;QAAwB0D,QAAQA;kBAC9B9C;;AAGP;AAEA,SAASwB,SAASZ,iBAA0B,EAAEU,EAAU;IACtD,OAAO;WACFjC,iBAAiBuB;QACpB;QACAU;KACD;AACH;AAEA,kFAAkF,GAClF,SAAS8B,UACPjD,WAAwB,EACxBS,iBAA0B,EAC1BU,EAAU;IAEV,MAAMqC,QAAQxD,YAAYyD,aAAa,CACrCpC,SAASZ,mBAAmBU;IAE9B,IAAIqC,CAAAA,yBAAAA,MAAOhB,MAAM,MAAK,WAAW,OAAOK;IACxC,OAAOW,MAAME,IAAI,KAAK,QAAQF,MAAME,IAAI,KAAKb,YACzC;QAAEL,QAAQ;IAAW,IACrB;QAAEA,QAAQ;QAASI,OAAOY,MAAME,IAAI;IAAC;AAC3C"}
@@ -0,0 +1,25 @@
1
+ import type { EntityDraft, EntityFieldDescriptor } from '@entifix/core';
2
+ import { type ReactNode } from 'react';
3
+ /**
4
+ * The query parameter prefix a create page reads a member's starting value
5
+ * from — `?prefill.customerId=c-1` — so a related region's "New" opens with
6
+ * the parent record already set.
7
+ */
8
+ export declare const PREFILL_PARAM = "prefill.";
9
+ /**
10
+ * A create page's starting values from its query string: only declared,
11
+ * writable members, and only as the strings a draft holds. Anything else in
12
+ * the query is ignored rather than written into a record.
13
+ */
14
+ export declare function readPrefill(params: URLSearchParams | null | undefined, descriptors: readonly EntityFieldDescriptor[]): EntityDraft | undefined;
15
+ /** Lists a region in the record page's section nav while it is mounted. */
16
+ export declare function useRegion(id: string, heading: string): void;
17
+ /**
18
+ * The regions under a record's form, and — once there are two or more — a
19
+ * section nav above them, a `nav` landmark whose anchors mark the region in
20
+ * view. Composes what exists: no new organism.
21
+ */
22
+ export declare function RecordRegions({ children }: {
23
+ children: ReactNode;
24
+ }): import("react").JSX.Element;
25
+ //# sourceMappingURL=regions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"regions.d.ts","sourceRoot":"","sources":["../../../src/lib/crud/regions.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAExE,OAAO,EAEL,KAAK,SAAS,EAMf,MAAM,OAAO,CAAC;AAEf;;;;GAIG;AACH,eAAO,MAAM,aAAa,aAAa,CAAC;AAExC;;;;GAIG;AACH,wBAAgB,WAAW,CACzB,MAAM,EAAE,eAAe,GAAG,IAAI,GAAG,SAAS,EAC1C,WAAW,EAAE,SAAS,qBAAqB,EAAE,GAC5C,WAAW,GAAG,SAAS,CAUzB;AAWD,2EAA2E;AAC3E,wBAAgB,SAAS,CAAC,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAG3D;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,EAAE,QAAQ,EAAE,EAAE;IAAE,QAAQ,EAAE,SAAS,CAAA;CAAE,+BAiClE"}
@@ -0,0 +1,82 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { ActiveSection, linkClassName, useT } from '@entifix/react-controls';
4
+ import { createContext, useCallback, useContext, useLayoutEffect, useMemo, useState } from 'react';
5
+ /**
6
+ * The query parameter prefix a create page reads a member's starting value
7
+ * from — `?prefill.customerId=c-1` — so a related region's "New" opens with
8
+ * the parent record already set.
9
+ */ export const PREFILL_PARAM = 'prefill.';
10
+ /**
11
+ * A create page's starting values from its query string: only declared,
12
+ * writable members, and only as the strings a draft holds. Anything else in
13
+ * the query is ignored rather than written into a record.
14
+ */ export function readPrefill(params, descriptors) {
15
+ const values = {};
16
+ for (const [name, value] of params != null ? params : []){
17
+ if (!name.startsWith(PREFILL_PARAM)) continue;
18
+ const member = name.slice(PREFILL_PARAM.length);
19
+ const descriptor = descriptors.find((entry)=>entry.name === member);
20
+ if (descriptor === undefined || descriptor.readonly) continue;
21
+ values[member] = value;
22
+ }
23
+ return Object.keys(values).length === 0 ? undefined : values;
24
+ }
25
+ const RegionsContext = /*#__PURE__*/ createContext(undefined);
26
+ /** Lists a region in the record page's section nav while it is mounted. */ export function useRegion(id, heading) {
27
+ const register = useContext(RegionsContext);
28
+ useLayoutEffect(()=>register == null ? void 0 : register({
29
+ id,
30
+ heading
31
+ }), [
32
+ register,
33
+ id,
34
+ heading
35
+ ]);
36
+ }
37
+ /**
38
+ * The regions under a record's form, and — once there are two or more — a
39
+ * section nav above them, a `nav` landmark whose anchors mark the region in
40
+ * view. Composes what exists: no new organism.
41
+ */ export function RecordRegions({ children }) {
42
+ const t = useT('shell');
43
+ const [regions, setRegions] = useState([]);
44
+ const register = useCallback((region)=>{
45
+ setRegions((current)=>[
46
+ ...current,
47
+ region
48
+ ]);
49
+ return ()=>setRegions((current)=>current.filter((entry)=>entry.id !== region.id));
50
+ }, []);
51
+ const ids = useMemo(()=>regions.map((region)=>region.id), [
52
+ regions
53
+ ]);
54
+ return /*#__PURE__*/ _jsxs(RegionsContext.Provider, {
55
+ value: register,
56
+ children: [
57
+ regions.length >= 2 && /*#__PURE__*/ _jsxs("nav", {
58
+ "aria-label": t('regions.nav'),
59
+ children: [
60
+ /*#__PURE__*/ _jsx("ul", {
61
+ role: "list",
62
+ className: "m-0 p-0 flex list-none flex-wrap gap-s",
63
+ children: regions.map((region)=>/*#__PURE__*/ _jsx("li", {
64
+ children: /*#__PURE__*/ _jsx("a", {
65
+ href: `#${region.id}`,
66
+ "data-section": region.id,
67
+ className: linkClassName,
68
+ children: region.heading
69
+ })
70
+ }, region.id))
71
+ }),
72
+ /*#__PURE__*/ _jsx(ActiveSection, {
73
+ sections: ids
74
+ })
75
+ ]
76
+ }),
77
+ children
78
+ ]
79
+ });
80
+ }
81
+
82
+ //# sourceMappingURL=regions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/lib/crud/regions.tsx"],"sourcesContent":["'use client';\n\nimport type { EntityDraft, EntityFieldDescriptor } from '@entifix/core';\nimport { ActiveSection, linkClassName, useT } from '@entifix/react-controls';\nimport {\n createContext,\n type ReactNode,\n useCallback,\n useContext,\n useLayoutEffect,\n useMemo,\n useState,\n} from 'react';\n\n/**\n * The query parameter prefix a create page reads a member's starting value\n * from — `?prefill.customerId=c-1` — so a related region's \"New\" opens with\n * the parent record already set.\n */\nexport const PREFILL_PARAM = 'prefill.';\n\n/**\n * A create page's starting values from its query string: only declared,\n * writable members, and only as the strings a draft holds. Anything else in\n * the query is ignored rather than written into a record.\n */\nexport function readPrefill(\n params: URLSearchParams | null | undefined,\n descriptors: readonly EntityFieldDescriptor[],\n): EntityDraft | undefined {\n const values: Record<string, string> = {};\n for (const [name, value] of params ?? []) {\n if (!name.startsWith(PREFILL_PARAM)) continue;\n const member = name.slice(PREFILL_PARAM.length);\n const descriptor = descriptors.find(entry => entry.name === member);\n if (descriptor === undefined || descriptor.readonly) continue;\n values[member] = value;\n }\n return Object.keys(values).length === 0 ? undefined : values;\n}\n\ninterface Region {\n readonly id: string;\n readonly heading: string;\n}\n\nconst RegionsContext = createContext<\n ((region: Region) => () => void) | undefined\n>(undefined);\n\n/** Lists a region in the record page's section nav while it is mounted. */\nexport function useRegion(id: string, heading: string): void {\n const register = useContext(RegionsContext);\n useLayoutEffect(() => register?.({ id, heading }), [register, id, heading]);\n}\n\n/**\n * The regions under a record's form, and — once there are two or more — a\n * section nav above them, a `nav` landmark whose anchors mark the region in\n * view. Composes what exists: no new organism.\n */\nexport function RecordRegions({ children }: { children: ReactNode }) {\n const t = useT('shell');\n const [regions, setRegions] = useState<readonly Region[]>([]);\n const register = useCallback((region: Region) => {\n setRegions(current => [...current, region]);\n return () =>\n setRegions(current => current.filter(entry => entry.id !== region.id));\n }, []);\n const ids = useMemo(() => regions.map(region => region.id), [regions]);\n\n return (\n <RegionsContext.Provider value={register}>\n {regions.length >= 2 && (\n <nav aria-label={t('regions.nav')}>\n <ul role=\"list\" className=\"m-0 p-0 flex list-none flex-wrap gap-s\">\n {regions.map(region => (\n <li key={region.id}>\n <a\n href={`#${region.id}`}\n data-section={region.id}\n className={linkClassName}\n >\n {region.heading}\n </a>\n </li>\n ))}\n </ul>\n <ActiveSection sections={ids} />\n </nav>\n )}\n {children}\n </RegionsContext.Provider>\n );\n}\n"],"names":["ActiveSection","linkClassName","useT","createContext","useCallback","useContext","useLayoutEffect","useMemo","useState","PREFILL_PARAM","readPrefill","params","descriptors","values","name","value","startsWith","member","slice","length","descriptor","find","entry","undefined","readonly","Object","keys","RegionsContext","useRegion","id","heading","register","RecordRegions","children","t","regions","setRegions","region","current","filter","ids","map","Provider","nav","aria-label","ul","role","className","li","a","href","data-section","sections"],"mappings":"AAAA;;AAGA,SAASA,aAAa,EAAEC,aAAa,EAAEC,IAAI,QAAQ,0BAA0B;AAC7E,SACEC,aAAa,EAEbC,WAAW,EACXC,UAAU,EACVC,eAAe,EACfC,OAAO,EACPC,QAAQ,QACH,QAAQ;AAEf;;;;CAIC,GACD,OAAO,MAAMC,gBAAgB,WAAW;AAExC;;;;CAIC,GACD,OAAO,SAASC,YACdC,MAA0C,EAC1CC,WAA6C;IAE7C,MAAMC,SAAiC,CAAC;IACxC,KAAK,MAAM,CAACC,MAAMC,MAAM,IAAIJ,iBAAAA,SAAU,EAAE,CAAE;QACxC,IAAI,CAACG,KAAKE,UAAU,CAACP,gBAAgB;QACrC,MAAMQ,SAASH,KAAKI,KAAK,CAACT,cAAcU,MAAM;QAC9C,MAAMC,aAAaR,YAAYS,IAAI,CAACC,CAAAA,QAASA,MAAMR,IAAI,KAAKG;QAC5D,IAAIG,eAAeG,a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5BP;;;AAGP"}
@@ -0,0 +1,29 @@
1
+ import { type EntityRepositoryTag } from '@entifix/business';
2
+ import { type Entity, type EntityConstructor, type EntityFieldDescriptor } from '@entifix/core';
3
+ import { Context } from 'effect';
4
+ import type { ReactElement } from 'react';
5
+ import type { EntityCrudRelated } from './make-entity-crud.types.js';
6
+ /**
7
+ * How many matches one related read asks for. A page names far fewer for a
8
+ * `via` column; a `match` column whose records hold more than this per page
9
+ * reads as the count of those it got.
10
+ */
11
+ export declare const RELATED_PAGE_SIZE = 200;
12
+ /** A related column, checked when the screen is generated. */
13
+ export interface RelatedPlan<TAdapters> extends EntityCrudRelated<TAdapters> {
14
+ /** The target member's descriptor: what a match's value reads as. */
15
+ readonly descriptor: EntityFieldDescriptor;
16
+ readonly entityKey: string;
17
+ }
18
+ /**
19
+ * Checks every related column against both entities' metadata, so a mistake
20
+ * throws when the screen is generated rather than answering `400` per page.
21
+ */
22
+ export declare function planRelated<TAdapters>(entityConstructor: EntityConstructor<Entity>, descriptors: readonly EntityFieldDescriptor[], related: readonly EntityCrudRelated<TAdapters>[]): RelatedPlan<TAdapters>[];
23
+ /**
24
+ * One column per related plan, its values read for the page's items in one
25
+ * request per column — keyed under the target's own query scope, so a write
26
+ * to the target refreshes it.
27
+ */
28
+ export declare function useRelatedColumns<TAdapters, TEntity extends Entity>(plans: readonly RelatedPlan<TAdapters>[], items: readonly TEntity[], repositoryOf: (plan: RelatedPlan<TAdapters>) => Context.Context<EntityRepositoryTag>): ReactElement[];
29
+ //# sourceMappingURL=related-columns.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"related-columns.d.ts","sourceRoot":"","sources":["../../../src/lib/crud/related-columns.tsx"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,mBAAmB,EAEzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAGL,KAAK,MAAM,EACX,KAAK,iBAAiB,EACtB,KAAK,qBAAqB,EAM3B,MAAM,eAAe,CAAC;AAUvB,OAAO,EAAE,OAAO,EAAU,MAAM,QAAQ,CAAC;AACzC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AAE1C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAErE;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,MAAM,CAAC;AAErC,8DAA8D;AAC9D,MAAM,WAAW,WAAW,CAAC,SAAS,CAAE,SAAQ,iBAAiB,CAAC,SAAS,CAAC;IAC1E,qEAAqE;IACrE,QAAQ,CAAC,UAAU,EAAE,qBAAqB,CAAC;IAC3C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;CAC5B;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,SAAS,EACnC,iBAAiB,EAAE,iBAAiB,CAAC,MAAM,CAAC,EAC5C,WAAW,EAAE,SAAS,qBAAqB,EAAE,EAC7C,OAAO,EAAE,SAAS,iBAAiB,CAAC,SAAS,CAAC,EAAE,GAC/C,WAAW,CAAC,SAAS,CAAC,EAAE,CAwC1B;AAQD;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,OAAO,SAAS,MAAM,EACjE,KAAK,EAAE,SAAS,WAAW,CAAC,SAAS,CAAC,EAAE,EACxC,KAAK,EAAE,SAAS,OAAO,EAAE,EACzB,YAAY,EAAE,CACZ,IAAI,EAAE,WAAW,CAAC,SAAS,CAAC,KACzB,OAAO,CAAC,OAAO,CAAC,mBAAmB,CAAC,GACxC,YAAY,EAAE,CAmGhB"}
@@ -0,0 +1,141 @@
1
+ 'use client';
2
+ import { _ as _extends } from "@swc/helpers/_/_extends";
3
+ import { jsx as _jsx } from "react/jsx-runtime";
4
+ import { EntityLoadRequestTag, loadUCFactory } from '@entifix/business';
5
+ import { coerceFiltering, describeEntityColumns, extractMetaEntity, parseRsql, serializeRsql } from '@entifix/core';
6
+ import { CellValue, EntityColumn, useEntityNoun, useT, useTranslateKey } from '@entifix/react-controls';
7
+ import { entityQueryScope } from '@entifix/react-integration';
8
+ import { useQueries } from '@tanstack/react-query';
9
+ import { Context, Effect } from 'effect';
10
+ /**
11
+ * How many matches one related read asks for. A page names far fewer for a
12
+ * `via` column; a `match` column whose records hold more than this per page
13
+ * reads as the count of those it got.
14
+ */ export const RELATED_PAGE_SIZE = 200;
15
+ /**
16
+ * Checks every related column against both entities' metadata, so a mistake
17
+ * throws when the screen is generated rather than answering `400` per page.
18
+ */ export function planRelated(entityConstructor, descriptors, related) {
19
+ return related.map((column)=>{
20
+ var _descriptors_find, _target_find;
21
+ const name = `${entityConstructor.name}'s related column "${column.key}"`;
22
+ if (column.via === undefined === (column.match === undefined)) {
23
+ throw new Error(`${name} needs exactly one of via and match.`);
24
+ }
25
+ if (column.via !== undefined && ((_descriptors_find = descriptors.find((entry)=>entry.name === column.via)) == null ? void 0 : _descriptors_find.references) === undefined) {
26
+ throw new Error(`${name} reads via "${column.via}", which is not a reference member of ${entityConstructor.name}.`);
27
+ }
28
+ const target = describeEntityColumns(column.target);
29
+ if (column.match !== undefined && ((_target_find = target.find((entry)=>entry.name === column.match)) == null ? void 0 : _target_find.filterable) !== true) {
30
+ throw new Error(`${name} matches on "${column.match}", which must be a filterable member of ${column.target.name}.`);
31
+ }
32
+ const descriptor = target.find((entry)=>entry.name === column.member);
33
+ if (descriptor === undefined) {
34
+ throw new Error(`${name} shows "${column.member}", which is not a member of ${column.target.name}.`);
35
+ }
36
+ // Through the target's own allowlist, as a service would coerce it.
37
+ const rsql = column.filtering === undefined ? '' : serializeRsql([
38
+ column.filtering
39
+ ]);
40
+ if (rsql !== '') coerceFiltering(column.target, parseRsql(rsql));
41
+ return _extends({}, column, {
42
+ descriptor,
43
+ entityKey: String(extractMetaEntity(column.target).key)
44
+ });
45
+ });
46
+ }
47
+ const valueOf = (record, member)=>record[member];
48
+ const present = (value)=>value !== undefined && value !== null && value !== '';
49
+ /**
50
+ * One column per related plan, its values read for the page's items in one
51
+ * request per column — keyed under the target's own query scope, so a write
52
+ * to the target refreshes it.
53
+ */ export function useRelatedColumns(plans, items, repositoryOf) {
54
+ const translateKey = useTranslateKey();
55
+ const t = useT('shell');
56
+ const noun = useEntityNoun();
57
+ const keysOf = (plan)=>[
58
+ ...new Set(items.map((item)=>{
59
+ var _plan_via;
60
+ return valueOf(item, (_plan_via = plan.via) != null ? _plan_via : 'id');
61
+ }).filter(present).map(String))
62
+ ].sort();
63
+ const results = useQueries({
64
+ queries: plans.map((plan)=>{
65
+ const keys = keysOf(plan);
66
+ const property = plan.via === undefined ? plan.match : 'id';
67
+ const filtering = {
68
+ operator: 'and',
69
+ values: [
70
+ {
71
+ property: property,
72
+ operator: 'in',
73
+ values: keys
74
+ },
75
+ ...plan.filtering === undefined ? [] : [
76
+ plan.filtering
77
+ ]
78
+ ]
79
+ };
80
+ const request = {
81
+ filtering: [
82
+ filtering
83
+ ],
84
+ page: 1,
85
+ pageSize: RELATED_PAGE_SIZE
86
+ };
87
+ return {
88
+ queryKey: [
89
+ ...entityQueryScope(plan.target),
90
+ 'related',
91
+ plan.key,
92
+ keys
93
+ ],
94
+ enabled: keys.length > 0,
95
+ queryFn: ()=>Effect.runPromise(Effect.provide(loadUCFactory(), repositoryOf(plan).pipe(Context.add(EntityLoadRequestTag, request)))).then((page)=>page.items)
96
+ };
97
+ })
98
+ });
99
+ return plans.map((plan, index)=>{
100
+ var _ref;
101
+ var _results_index;
102
+ const matches = (_ref = (_results_index = results[index]) == null ? void 0 : _results_index.data) != null ? _ref : [];
103
+ const matchesOf = (item)=>{
104
+ var _plan_via;
105
+ const key = valueOf(item, (_plan_via = plan.via) != null ? _plan_via : 'id');
106
+ if (!present(key)) return [];
107
+ return matches.filter((match)=>plan.via === undefined ? String(valueOf(match, plan.match)) === String(key) : String(match.id) === String(key));
108
+ };
109
+ const plural = noun(extractMetaEntity(plan.target), 'plural');
110
+ return /*#__PURE__*/ _jsx(EntityColumn, _extends({
111
+ field: plan.key,
112
+ label: translateKey(plan.labelKey),
113
+ type: plan.descriptor.type
114
+ }, plan.descriptor.minWidth === undefined ? {} : {
115
+ minWidth: plan.descriptor.minWidth
116
+ }, {
117
+ render: (item)=>{
118
+ const found = matchesOf(item);
119
+ const [only] = found;
120
+ if (only === undefined || found.length > 1) {
121
+ return found.length > 1 ? /*#__PURE__*/ _jsx("span", {
122
+ children: t('related.count', {
123
+ count: found.length,
124
+ noun: plural
125
+ })
126
+ }) : /*#__PURE__*/ _jsx("span", {
127
+ className: "text-content-muted",
128
+ children: "—"
129
+ });
130
+ }
131
+ return plan.render === undefined ? /*#__PURE__*/ _jsx(CellValue, {
132
+ value: valueOf(only, plan.member),
133
+ descriptor: plan.descriptor,
134
+ record: only
135
+ }) : plan.render(only);
136
+ }
137
+ }), plan.key);
138
+ });
139
+ }
140
+
141
+ //# sourceMappingURL=related-columns.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/lib/crud/related-columns.tsx"],"sourcesContent":["'use client';\n\nimport {\n EntityLoadRequestTag,\n type EntityRepositoryTag,\n loadUCFactory,\n} from '@entifix/business';\nimport {\n coerceFiltering,\n describeEntityColumns,\n type Entity,\n type EntityConstructor,\n type EntityFieldDescriptor,\n type EntityLoadRequest,\n extractMetaEntity,\n type FilterGroup,\n parseRsql,\n serializeRsql,\n} from '@entifix/core';\nimport {\n CellValue,\n EntityColumn,\n useEntityNoun,\n useT,\n useTranslateKey,\n} from '@entifix/react-controls';\nimport { entityQueryScope } from '@entifix/react-integration';\nimport { useQueries } from '@tanstack/react-query';\nimport { Context, Effect } from 'effect';\nimport type { ReactElement } from 'react';\n\nimport type { EntityCrudRelated } from './make-entity-crud.types.js';\n\n/**\n * How many matches one related read asks for. A page names far fewer for a\n * `via` column; a `match` column whose records hold more than this per page\n * reads as the count of those it got.\n */\nexport const RELATED_PAGE_SIZE = 200;\n\n/** A related column, checked when the screen is generated. */\nexport interface RelatedPlan<TAdapters> extends EntityCrudRelated<TAdapters> {\n /** The target member's descriptor: what a match's value reads as. */\n readonly descriptor: EntityFieldDescriptor;\n readonly entityKey: string;\n}\n\n/**\n * Checks every related column against both entities' metadata, so a mistake\n * throws when the screen is generated rather than answering `400` per page.\n */\nexport function planRelated<TAdapters>(\n entityConstructor: EntityConstructor<Entity>,\n descriptors: readonly EntityFieldDescriptor[],\n related: readonly EntityCrudRelated<TAdapters>[],\n): RelatedPlan<TAdapters>[] {\n return related.map(column => {\n const name = `${entityConstructor.name}'s related column \"${column.key}\"`;\n if ((column.via === undefined) === (column.match === undefined)) {\n throw new Error(`${name} needs exactly one of via and match.`);\n }\n if (\n column.via !== undefined &&\n descriptors.find(entry => entry.name === column.via)?.references ===\n undefined\n ) {\n throw new Error(\n `${name} reads via \"${column.via}\", which is not a reference member of ${entityConstructor.name}.`,\n );\n }\n const target = describeEntityColumns(column.target);\n if (\n column.match !== undefined &&\n target.find(entry => entry.name === column.match)?.filterable !== true\n ) {\n throw new Error(\n `${name} matches on \"${column.match}\", which must be a filterable member of ${column.target.name}.`,\n );\n }\n const descriptor = target.find(entry => entry.name === column.member);\n if (descriptor === undefined) {\n throw new Error(\n `${name} shows \"${column.member}\", which is not a member of ${column.target.name}.`,\n );\n }\n // Through the target's own allowlist, as a service would coerce it.\n const rsql =\n column.filtering === undefined ? '' : serializeRsql([column.filtering]);\n if (rsql !== '') coerceFiltering(column.target, parseRsql(rsql));\n return {\n ...column,\n descriptor,\n entityKey: String(extractMetaEntity(column.target).key),\n };\n });\n}\n\nconst valueOf = (record: Entity, member: string): unknown =>\n (record as unknown as Record<string, unknown>)[member];\n\nconst present = (value: unknown): value is string | number =>\n value !== undefined && value !== null && value !== '';\n\n/**\n * One column per related plan, its values read for the page's items in one\n * request per column — keyed under the target's own query scope, so a write\n * to the target refreshes it.\n */\nexport function useRelatedColumns<TAdapters, TEntity extends Entity>(\n plans: readonly RelatedPlan<TAdapters>[],\n items: readonly TEntity[],\n repositoryOf: (\n plan: RelatedPlan<TAdapters>,\n ) => Context.Context<EntityRepositoryTag>,\n): ReactElement[] {\n const translateKey = useTranslateKey();\n const t = useT('shell');\n const noun = useEntityNoun();\n\n const keysOf = (plan: RelatedPlan<TAdapters>) =>\n [\n ...new Set(\n items\n .map(item => valueOf(item, plan.via ?? 'id'))\n .filter(present)\n .map(String),\n ),\n ].sort();\n\n const results = useQueries({\n queries: plans.map(plan => {\n const keys = keysOf(plan);\n const property = plan.via === undefined ? (plan.match as string) : 'id';\n const filtering: FilterGroup<Entity> = {\n operator: 'and',\n values: [\n {\n property: property as never,\n operator: 'in',\n values: keys as never,\n },\n ...(plan.filtering === undefined\n ? []\n : [plan.filtering as FilterGroup<Entity>]),\n ],\n };\n const request: EntityLoadRequest = {\n filtering: [filtering],\n page: 1,\n pageSize: RELATED_PAGE_SIZE,\n };\n return {\n queryKey: [...entityQueryScope(plan.target), 'related', plan.key, keys],\n enabled: keys.length > 0,\n queryFn: () =>\n Effect.runPromise(\n Effect.provide(\n loadUCFactory<Entity>(),\n repositoryOf(plan).pipe(\n Context.add(EntityLoadRequestTag, request),\n ),\n ),\n ).then(page => page.items),\n };\n }),\n });\n\n return plans.map((plan, index) => {\n const matches = results[index]?.data ?? [];\n const matchesOf = (item: TEntity) => {\n const key = valueOf(item, plan.via ?? 'id');\n if (!present(key)) return [];\n return matches.filter(match =>\n plan.via === undefined\n ? String(valueOf(match, plan.match as string)) === String(key)\n : String(match.id) === String(key),\n );\n };\n const plural = noun(extractMetaEntity(plan.target), 'plural');\n return (\n <EntityColumn<TEntity>\n key={plan.key}\n field={plan.key}\n label={translateKey(plan.labelKey)}\n type={plan.descriptor.type}\n {...(plan.descriptor.minWidth === undefined\n ? {}\n : { minWidth: plan.descriptor.minWidth })}\n render={item => {\n const found = matchesOf(item);\n const [only] = found;\n if (only === undefined || found.length > 1) {\n return found.length > 1 ? (\n <span>\n {t('related.count', { count: found.length, noun: plural })}\n </span>\n ) : (\n <span className=\"text-content-muted\">—</span>\n );\n }\n return plan.render === undefined ? (\n <CellValue\n value={valueOf(only, plan.member)}\n descriptor={plan.descriptor}\n record={only as unknown as Record<string, unknown>}\n />\n ) : (\n plan.render(only)\n );\n }}\n />\n );\n });\n}\n"],"names":["EntityLoadRequestTag","loadUCFactory","coerceFiltering","describeEntityColumns","extractMetaEntity","parseRsql","serializeRsql","CellValue","EntityColumn","useEntityNoun","useT","useTranslateKey","entityQueryScope","useQueries","Context","Effect","RELATED_PAGE_SIZE","planRelated","entityConstructor","descriptors","related","map","column","target","name","key","via","undefined","match","Error","find","entry","references","filterable","descriptor","member","rsql","filtering","entityKey","String","valueOf","record","present","value","useRelatedColumns","plans","items","repositoryOf","translateKey","t","noun","keysOf","plan","Set","item","filter","sort","results","queries","keys","property","operator","values","request","page","pageSize","queryKey","enabled","length","queryFn","runPromise","provide","pipe","add","then","index","matches","data","matchesOf","id","plural","field","label","labelKey","type","minWidth","render","found","only","span","count","className"],"mappings":"AAAA;;;AAEA,SACEA,oBAAoB,EAEpBC,aAAa,QACR,oBAAoB;AAC3B,SACEC,eAAe,EACfC,qBAAqB,EAKrBC,iBAAiB,EAEjBC,SAAS,EACTC,aAAa,QACR,gBAAgB;AACvB,SACEC,SAAS,EACTC,YAAY,EACZC,aAAa,EACbC,IAAI,EACJC,eAAe,QACV,0BAA0B;AACjC,SAASC,gBAAgB,QAAQ,6BAA6B;AAC9D,SAASC,UAAU,QAAQ,wBAAwB;AACnD,SAASC,OAAO,EAAEC,MAAM,QAAQ,SAAS;AAKzC;;;;CAIC,GACD,OAAO,MAAMC,oBAAoB,IAAI;AASrC;;;CAGC,GACD,OAAO,SAASC,YACdC,iBAA4C,EAC5CC,WAA6C,EAC7CC,OAAgD;IAEhD,OAAOA,QAAQC,GAAG,CAACC,CAAAA;YAOfH,mBAUAI;QAhBF,MAAMC,OAAO,GAAGN,kBAAkBM,IAAI,CAAC,mBAAmB,EAAEF,OAAOG,GAAG,CAAC,CAAC,CAAC;QACzE,IAAI,AAACH,OAAOI,GAAG,KAAKC,cAAgBL,CAAAA,OAAOM,KAAK,KAAKD,SAAQ,GAAI;YAC/D,MAA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AKlB,UAAU;oBAC3BO,QAAQ+C;qBAGVpC,KAAKkC,MAAM,CAACE;YAEhB;YA5BKpC,KAAK3B,GAAG;IA+BnB;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"use-entity-link-sources.d.ts","sourceRoot":"","sources":["../../../src/lib/crud/use-entity-link-sources.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,KAAK,MAAM,EACX,KAAK,WAAW,EAChB,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EAEtB,MAAM,eAAe,CAAC;AAGvB,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AAExE,MAAM,WAAW,2BAA2B;IAC1C,oDAAoD;IACpD,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;IAC7B,yEAAyE;IACzE,QAAQ,CAAC,SAAS,EAAE,mBAAmB,CAAC;CACzC;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,SAAS,oBAAoB,EAAE,EACtC,EAAE,MAAM,EAAE,SAAS,EAAE,EAAE,2BAA2B,GACjD,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,MAAM,CAAC,CAAC,CAiB1C"}
1
+ {"version":3,"file":"use-entity-link-sources.d.ts","sourceRoot":"","sources":["../../../src/lib/crud/use-entity-link-sources.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,KAAK,MAAM,EACX,KAAK,WAAW,EAChB,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EAEtB,MAAM,eAAe,CAAC;AAIvB,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AAExE,MAAM,WAAW,2BAA2B;IAC1C,oDAAoD;IACpD,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;IAC7B,yEAAyE;IACzE,QAAQ,CAAC,SAAS,EAAE,mBAAmB,CAAC;CACzC;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,SAAS,oBAAoB,EAAE,EACtC,EAAE,MAAM,EAAE,SAAS,EAAE,EAAE,2BAA2B,GACjD,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,MAAM,CAAC,CAAC,CAoB1C"}
@@ -1,5 +1,6 @@
1
1
  'use client';
2
2
  import { readDraftString } from '@entifix/core';
3
+ import { useLocale } from '@entifix/react-controls';
3
4
  import { useEntityLinkSource } from '@entifix/react-integration';
4
5
  /**
5
6
  * Turns a fixed list of pickers into the `linkSources` map `EntityForm` takes.
@@ -16,6 +17,8 @@ import { useEntityLinkSource } from '@entifix/react-integration';
16
17
  * upward — would put the sources one render behind the draft that feeds them,
17
18
  * which is a stale suggestion list rather than a lint error.
18
19
  */ export function useEntityLinkSources(links, { values, selection }) {
20
+ // A localized member is searched and read in the reader's own locale.
21
+ const locale = useLocale();
19
22
  const sources = {};
20
23
  for (const link of links){
21
24
  // Read as a string: a relation's draft value is a foreign key, and a
@@ -28,7 +31,8 @@ import { useEntityLinkSource } from '@entifix/react-integration';
28
31
  // An empty draft entry is "unset", not an id. Nothing enforces the
29
32
  // reference across a store boundary, so `''` would be a dangling id.
30
33
  selectedId: held === '' ? undefined : held,
31
- selectedEntity: selection[link.field]
34
+ selectedEntity: selection[link.field],
35
+ locale
32
36
  });
33
37
  }
34
38
  return sources;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/crud/use-entity-link-sources.ts"],"sourcesContent":["'use client';\n\nimport {\n type Entity,\n type EntityDraft,\n type EntityLinkSelection,\n type EntityLinkSource,\n readDraftString,\n} from '@entifix/core';\nimport { useEntityLinkSource } from '@entifix/react-integration';\n\nimport type { EntityCrudLinkSource } from './make-entity-crud.types.js';\n\nexport interface UseEntityLinkSourcesOptions {\n /** The form's current draft — ids are the truth. */\n readonly values: EntityDraft;\n /** The picked-instance sidecar, so a chosen name needs no round trip. */\n readonly selection: EntityLinkSelection;\n}\n\n/**\n * Turns a fixed list of pickers into the `linkSources` map `EntityForm` takes.\n *\n * **Why the rule is disabled below.** `links` is built once, at factory time,\n * and closed over by the generated form — it is the same array object on every\n * render of a given component, so the hook count is fixed. That is exactly the\n * invariant `react-hooks/rules-of-hooks` exists to protect and exactly the one\n * it cannot see, because it reasons syntactically about the loop rather than\n * about the array's provenance. The loop is isolated in this module so the\n * disable is written once, with its reason, instead of once per generated form.\n *\n * The alternative — one child component per picker, reporting its source\n * upward — would put the sources one render behind the draft that feeds them,\n * which is a stale suggestion list rather than a lint error.\n */\nexport function useEntityLinkSources(\n links: readonly EntityCrudLinkSource[],\n { values, selection }: UseEntityLinkSourcesOptions,\n): Record<string, EntityLinkSource<Entity>> {\n const sources: Record<string, EntityLinkSource<Entity>> = {};\n for (const link of links) {\n // Read as a string: a relation's draft value is a foreign key, and a\n // member that came back from storage in any other shape must read as unset\n // rather than be handed to the picker as an id.\n const held = readDraftString(values, link.field);\n // eslint-disable-next-line react-hooks/rules-of-hooks -- fixed-length loop over a factory-time array; see the note above.\n sources[link.field] = useEntityLinkSource(link.config, {\n descriptor: link.descriptor,\n // An empty draft entry is \"unset\", not an id. Nothing enforces the\n // reference across a store boundary, so `''` would be a dangling id.\n selectedId: held === '' ? undefined : held,\n selectedEntity: selection[link.field],\n });\n }\n return sources;\n}\n"],"names":["readDraftString","useEntityLinkSource","useEntityLinkSources","links","values","selection","sources","link","held","field","config","descriptor","selectedId","undefined","selectedEntity"],"mappings":"AAAA;AAEA,SAKEA,eAAe,QACV,gBAAgB;AACvB,SAASC,mBAAmB,QAAQ,6BAA6B;AAWjE;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,qBACdC,KAAsC,EACtC,EAAEC,MAAM,EAAEC,SAAS,EAA+B;IAElD,MAAMC,UAAoD,CAAC;IAC3D,KAAK,MAAMC,QAAQJ,MAAO;QACxB,qEAAqE;QACrE,2EAA2E;QAC3E,gDAAgD;QAChD,MAAMK,OAAOR,gBAAgBI,QAAQG,KAAKE,KAAK;QAC/C,0HAA0H;QAC1HH,OAAO,CAACC,KAAKE,KAAK,CAAC,GAAGR,oBAAoBM,KAAKG,MAAM,EAAE;YACrDC,YAAYJ,KAAKI,UAAU;YAC3B,mEAAmE;YACnE,qEAAqE;YACrEC,YAAYJ,SAAS,KAAKK,YAAYL;YACtCM,gBAAgBT,SAAS,CAACE,KAAKE,KAAK,CAAC;QACvC;IACF;IACA,OAAOH;AACT"}
1
+ {"version":3,"sources":["../../../src/lib/crud/use-entity-link-sources.ts"],"sourcesContent":["'use client';\n\nimport {\n type Entity,\n type EntityDraft,\n type EntityLinkSelection,\n type EntityLinkSource,\n readDraftString,\n} from '@entifix/core';\nimport { useLocale } from '@entifix/react-controls';\nimport { useEntityLinkSource } from '@entifix/react-integration';\n\nimport type { EntityCrudLinkSource } from './make-entity-crud.types.js';\n\nexport interface UseEntityLinkSourcesOptions {\n /** The form's current draft — ids are the truth. */\n readonly values: EntityDraft;\n /** The picked-instance sidecar, so a chosen name needs no round trip. */\n readonly selection: EntityLinkSelection;\n}\n\n/**\n * Turns a fixed list of pickers into the `linkSources` map `EntityForm` takes.\n *\n * **Why the rule is disabled below.** `links` is built once, at factory time,\n * and closed over by the generated form — it is the same array object on every\n * render of a given component, so the hook count is fixed. That is exactly the\n * invariant `react-hooks/rules-of-hooks` exists to protect and exactly the one\n * it cannot see, because it reasons syntactically about the loop rather than\n * about the array's provenance. The loop is isolated in this module so the\n * disable is written once, with its reason, instead of once per generated form.\n *\n * The alternative — one child component per picker, reporting its source\n * upward — would put the sources one render behind the draft that feeds them,\n * which is a stale suggestion list rather than a lint error.\n */\nexport function useEntityLinkSources(\n links: readonly EntityCrudLinkSource[],\n { values, selection }: UseEntityLinkSourcesOptions,\n): Record<string, EntityLinkSource<Entity>> {\n // A localized member is searched and read in the reader's own locale.\n const locale = useLocale();\n const sources: Record<string, EntityLinkSource<Entity>> = {};\n for (const link of links) {\n // Read as a string: a relation's draft value is a foreign key, and a\n // member that came back from storage in any other shape must read as unset\n // rather than be handed to the picker as an id.\n const held = readDraftString(values, link.field);\n // eslint-disable-next-line react-hooks/rules-of-hooks -- fixed-length loop over a factory-time array; see the note above.\n sources[link.field] = useEntityLinkSource(link.config, {\n descriptor: link.descriptor,\n // An empty draft entry is \"unset\", not an id. Nothing enforces the\n // reference across a store boundary, so `''` would be a dangling id.\n selectedId: held === '' ? undefined : held,\n selectedEntity: selection[link.field],\n locale,\n });\n }\n return sources;\n}\n"],"names":["readDraftString","useLocale","useEntityLinkSource","useEntityLinkSources","links","values","selection","locale","sources","link","held","field","config","descriptor","selectedId","undefined","selectedEntity"],"mappings":"AAAA;AAEA,SAKEA,eAAe,QACV,gBAAgB;AACvB,SAASC,SAAS,QAAQ,0BAA0B;AACpD,SAASC,mBAAmB,QAAQ,6BAA6B;AAWjE;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,qBACdC,KAAsC,EACtC,EAAEC,MAAM,EAAEC,SAAS,EAA+B;IAElD,sEAAsE;IACtE,MAAMC,SAASN;IACf,MAAMO,UAAoD,CAAC;IAC3D,KAAK,MAAMC,QAAQL,MAAO;QACxB,qEAAqE;QACrE,2EAA2E;QAC3E,gDAAgD;QAChD,MAAMM,OAAOV,gBAAgBK,QAAQI,KAAKE,KAAK;QAC/C,0HAA0H;QAC1HH,OAAO,CAACC,KAAKE,KAAK,CAAC,GAAGT,oBAAoBO,KAAKG,MAAM,EAAE;YACrDC,YAAYJ,KAAKI,UAAU;YAC3B,mEAAmE;YACnE,qEAAqE;YACrEC,YAAYJ,SAAS,KAAKK,YAAYL;YACtCM,gBAAgBV,SAAS,CAACG,KAAKE,KAAK,CAAC;YACrCJ;QACF;IACF;IACA,OAAOC;AACT"}
@@ -0,0 +1,27 @@
1
+ import { type EntityRepositoryTag } from '@entifix/business';
2
+ import type { Entity, EntityConstructor, FilterGroup } from '@entifix/core';
3
+ import { Context } from 'effect';
4
+ export interface UseEntityTotalOptions<TEntity extends Entity> {
5
+ /** The entity counted; its query scope is the count's, so a push refreshes it. */
6
+ readonly entity: EntityConstructor<TEntity>;
7
+ /** Where its records are read. Without one nothing is counted and the count stays loading. */
8
+ readonly ctx: Context.Context<EntityRepositoryTag> | undefined;
9
+ /** Which records count — "awaiting dispatch". All of them when omitted. */
10
+ readonly filtering?: FilterGroup<TEntity>;
11
+ }
12
+ /** A count in the shape a summary tile takes it. */
13
+ export interface EntityTotal {
14
+ readonly state: 'loading' | 'ready' | 'failed';
15
+ /** How many records match, once read. */
16
+ readonly total: number | undefined;
17
+ /** Reads the count again. */
18
+ readonly retry: () => void;
19
+ }
20
+ /**
21
+ * How many records of an entity match a filtering, read as a one-record page
22
+ * whose `total` is the answer — the list's own read, so the same narrowing and
23
+ * the same authorization apply. Keyed under the entity's query scope: a pushed
24
+ * change to that entity, or a write through its list, refreshes the count.
25
+ */
26
+ export declare function useEntityTotal<TEntity extends Entity>({ entity, ctx, filtering, }: UseEntityTotalOptions<TEntity>): EntityTotal;
27
+ //# sourceMappingURL=use-entity-total.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-entity-total.d.ts","sourceRoot":"","sources":["../../../src/lib/crud/use-entity-total.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,mBAAmB,EAEzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EACV,MAAM,EACN,iBAAiB,EAGjB,WAAW,EACZ,MAAM,eAAe,CAAC;AAGvB,OAAO,EAAE,OAAO,EAAU,MAAM,QAAQ,CAAC;AAEzC,MAAM,WAAW,qBAAqB,CAAC,OAAO,SAAS,MAAM;IAC3D,kFAAkF;IAClF,QAAQ,CAAC,MAAM,EAAE,iBAAiB,CAAC,OAAO,CAAC,CAAC;IAC5C,8FAA8F;IAC9F,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC,OAAO,CAAC,mBAAmB,CAAC,GAAG,SAAS,CAAC;IAC/D,2EAA2E;IAC3E,QAAQ,CAAC,SAAS,CAAC,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC;CAC3C;AAED,oDAAoD;AACpD,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,KAAK,EAAE,SAAS,GAAG,OAAO,GAAG,QAAQ,CAAC;IAC/C,yCAAyC;IACzC,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;IACnC,6BAA6B;IAC7B,QAAQ,CAAC,KAAK,EAAE,MAAM,IAAI,CAAC;CAC5B;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,OAAO,SAAS,MAAM,EAAE,EACrD,MAAM,EACN,GAAG,EACH,SAAS,GACV,EAAE,qBAAqB,CAAC,OAAO,CAAC,GAAG,WAAW,CA4B9C"}