@cosmicdrift/kumiko-renderer 0.328.0 → 0.328.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (259) hide show
  1. package/dist/app/action-form-shim.d.ts +14 -0
  2. package/{src/app/action-form-shim.ts → dist/app/action-form-shim.js} +26 -46
  3. package/dist/app/app-features-context.d.ts +8 -0
  4. package/dist/app/app-features-context.js +16 -0
  5. package/dist/app/column-renderers.d.ts +30 -0
  6. package/dist/app/column-renderers.js +34 -0
  7. package/dist/app/config-edit-shim.d.ts +11 -0
  8. package/{src/app/config-edit-shim.ts → dist/app/config-edit-shim.js} +12 -25
  9. package/dist/app/content-editors.d.ts +38 -0
  10. package/dist/app/content-editors.js +26 -0
  11. package/dist/app/content-preview.d.ts +11 -0
  12. package/dist/app/content-preview.js +30 -0
  13. package/dist/app/custom-screens.d.ts +11 -0
  14. package/dist/app/custom-screens.js +20 -0
  15. package/dist/app/dashboard-body.d.ts +16 -0
  16. package/dist/app/dashboard-body.js +11 -0
  17. package/dist/app/extension-form-submit.d.ts +32 -0
  18. package/dist/app/extension-form-submit.js +73 -0
  19. package/dist/app/extension-sections.d.ts +72 -0
  20. package/dist/app/extension-sections.js +34 -0
  21. package/dist/app/feature-schema.d.ts +4 -0
  22. package/{src/app/feature-schema.ts → dist/app/feature-schema.js} +12 -22
  23. package/dist/app/form-schema.d.ts +4 -0
  24. package/dist/app/form-schema.js +85 -0
  25. package/dist/app/kumiko-screen.d.ts +43 -0
  26. package/dist/app/kumiko-screen.js +2206 -0
  27. package/dist/app/layout-fields.d.ts +3 -0
  28. package/dist/app/layout-fields.js +20 -0
  29. package/dist/app/list-facets.d.ts +48 -0
  30. package/dist/app/list-facets.js +185 -0
  31. package/dist/app/nav.d.ts +61 -0
  32. package/dist/app/nav.js +139 -0
  33. package/dist/app/projection-detail-shim.d.ts +8 -0
  34. package/dist/app/projection-detail-shim.js +71 -0
  35. package/dist/app/projection-list-shim.d.ts +13 -0
  36. package/{src/app/projection-list-shim.ts → dist/app/projection-list-shim.js} +26 -41
  37. package/dist/app/qn.d.ts +7 -0
  38. package/{src/app/qn.ts → dist/app/qn.js} +9 -11
  39. package/dist/app/qualify-screen-id.d.ts +2 -0
  40. package/{src/app/qualify-screen-id.ts → dist/app/qualify-screen-id.js} +5 -6
  41. package/dist/app/reference-facet-bridge.d.ts +10 -0
  42. package/dist/app/reference-facet-bridge.js +22 -0
  43. package/dist/app/return-to.d.ts +31 -0
  44. package/dist/app/return-to.js +188 -0
  45. package/dist/app/row-actions.d.ts +77 -0
  46. package/dist/app/row-actions.js +416 -0
  47. package/dist/app/screen-access.d.ts +8 -0
  48. package/dist/app/screen-access.js +48 -0
  49. package/dist/app/secret-mint-body.d.ts +10 -0
  50. package/dist/app/secret-mint-body.js +140 -0
  51. package/dist/app/secrets-edit-body.d.ts +8 -0
  52. package/dist/app/secrets-edit-body.js +76 -0
  53. package/dist/app/use-embedded-screen.d.ts +6 -0
  54. package/dist/app/use-embedded-screen.js +19 -0
  55. package/dist/app/variable-chips.d.ts +7 -0
  56. package/dist/app/variable-chips.js +16 -0
  57. package/dist/app/write-failed-error.d.ts +6 -0
  58. package/dist/app/write-failed-error.js +21 -0
  59. package/dist/components/embedded-list-field.d.ts +10 -0
  60. package/dist/components/embedded-list-field.js +259 -0
  61. package/dist/components/grid-cell-for-field.d.ts +25 -0
  62. package/dist/components/grid-cell-for-field.js +31 -0
  63. package/dist/components/multi-select-checkboxes.d.ts +14 -0
  64. package/dist/components/multi-select-checkboxes.js +36 -0
  65. package/dist/components/reference-create-dialog.d.ts +13 -0
  66. package/dist/components/reference-create-dialog.js +46 -0
  67. package/dist/components/related-list-section.d.ts +25 -0
  68. package/dist/components/related-list-section.js +273 -0
  69. package/dist/components/render-edit-action-button.d.ts +22 -0
  70. package/dist/components/render-edit-action-button.js +43 -0
  71. package/dist/components/render-edit-logic.d.ts +6 -0
  72. package/dist/components/render-edit-logic.js +63 -0
  73. package/dist/components/render-edit-types.d.ts +209 -0
  74. package/dist/components/render-edit-types.js +1 -0
  75. package/dist/components/render-edit.d.ts +6 -0
  76. package/dist/components/render-edit.js +1169 -0
  77. package/dist/components/render-field.d.ts +38 -0
  78. package/dist/components/render-field.js +544 -0
  79. package/dist/components/render-list.d.ts +117 -0
  80. package/dist/components/render-list.js +232 -0
  81. package/dist/components/write-form-section.d.ts +17 -0
  82. package/dist/components/write-form-section.js +104 -0
  83. package/dist/context/dispatcher-context.d.ts +10 -0
  84. package/{src/context/dispatcher-context.tsx → dist/context/dispatcher-context.js} +16 -29
  85. package/dist/context/draft-storage-context.d.ts +12 -0
  86. package/dist/context/draft-storage-context.js +18 -0
  87. package/dist/context/user-roles-context.d.ts +7 -0
  88. package/{src/context/user-roles-context.tsx → dist/context/user-roles-context.js} +7 -15
  89. package/dist/format-when.d.ts +1 -0
  90. package/{src/format-when.ts → dist/format-when.js} +7 -7
  91. package/dist/hooks/reference-limits.d.ts +3 -0
  92. package/{src/hooks/reference-limits.ts → dist/hooks/reference-limits.js} +0 -1
  93. package/dist/hooks/use-ai-text.d.ts +52 -0
  94. package/dist/hooks/use-ai-text.js +90 -0
  95. package/dist/hooks/use-disclosure.d.ts +7 -0
  96. package/dist/hooks/use-disclosure.js +8 -0
  97. package/dist/hooks/use-form.d.ts +7 -0
  98. package/dist/hooks/use-form.js +36 -0
  99. package/dist/hooks/use-list-url-state.d.ts +43 -0
  100. package/dist/hooks/use-list-url-state.js +131 -0
  101. package/dist/hooks/use-mutation.d.ts +9 -0
  102. package/dist/hooks/use-mutation.js +37 -0
  103. package/dist/hooks/use-query.d.ts +14 -0
  104. package/dist/hooks/use-query.js +118 -0
  105. package/dist/hooks/use-reference-lookup.d.ts +14 -0
  106. package/dist/hooks/use-reference-lookup.js +63 -0
  107. package/dist/hooks/use-store.d.ts +3 -0
  108. package/dist/hooks/use-store.js +38 -0
  109. package/dist/hooks/use-stream-handler.d.ts +14 -0
  110. package/dist/hooks/use-stream-handler.js +93 -0
  111. package/dist/i18n-defaults.d.ts +2 -0
  112. package/dist/i18n-defaults.js +201 -0
  113. package/dist/i18n.d.ts +64 -0
  114. package/dist/i18n.js +166 -0
  115. package/dist/index.d.ts +77 -0
  116. package/dist/index.js +55 -0
  117. package/dist/inside-drawer.d.ts +2 -0
  118. package/{src/inside-drawer.ts → dist/inside-drawer.js} +2 -5
  119. package/dist/page-header-slot.d.ts +2 -0
  120. package/{src/page-header-slot.ts → dist/page-header-slot.js} +2 -5
  121. package/dist/primitives.d.ts +1351 -0
  122. package/dist/primitives.js +73 -0
  123. package/dist/screen-fills-height.d.ts +3 -0
  124. package/dist/screen-fills-height.js +3 -0
  125. package/dist/share-links.d.ts +4 -0
  126. package/dist/share-links.js +11 -0
  127. package/dist/sort-by-accessor.d.ts +5 -0
  128. package/dist/sort-by-accessor.js +16 -0
  129. package/dist/sse/live-events.d.ts +23 -0
  130. package/dist/sse/live-events.js +28 -0
  131. package/dist/tokens.d.ts +83 -0
  132. package/dist/tokens.js +80 -0
  133. package/package.json +16 -9
  134. package/src/__tests__/error-i18n-defaults.test.ts +0 -82
  135. package/src/__tests__/format-when.test.ts +0 -12
  136. package/src/__tests__/i18n.test.tsx +0 -283
  137. package/src/__tests__/merge-search-params-into-initial.test.ts +0 -525
  138. package/src/__tests__/qn.test.ts +0 -83
  139. package/src/__tests__/share-links.test.ts +0 -26
  140. package/src/__tests__/sort-by-accessor.test.ts +0 -48
  141. package/src/__tests__/stringify-nav-params.test.ts +0 -33
  142. package/src/__tests__/use-list-url-state.test.tsx +0 -250
  143. package/src/app/__tests__/action-form-field-labels.test.tsx +0 -92
  144. package/src/app/__tests__/action-form-shim.test.ts +0 -137
  145. package/src/app/__tests__/build-list-query-payload.test.ts +0 -107
  146. package/src/app/__tests__/config-edit-shim.test.ts +0 -57
  147. package/src/app/__tests__/content-editors.test.tsx +0 -128
  148. package/src/app/__tests__/content-preview.test.tsx +0 -184
  149. package/src/app/__tests__/entity-edit-create-search-params.test.tsx +0 -236
  150. package/src/app/__tests__/entity-edit-fill-height.test.tsx +0 -118
  151. package/src/app/__tests__/entity-edit-jsonb-embedded-submit.test.tsx +0 -239
  152. package/src/app/__tests__/entity-list-create-singleton.test.tsx +0 -128
  153. package/src/app/__tests__/entity-list-row-action-entity-target.test.tsx +0 -424
  154. package/src/app/__tests__/entity-list-row-action-icon.test.tsx +0 -248
  155. package/src/app/__tests__/entity-list-row-action-kumiko-actions-view.test.tsx +0 -162
  156. package/src/app/__tests__/entity-list-row-action-refetch.test.tsx +0 -401
  157. package/src/app/__tests__/entity-list-screen-padding.test.tsx +0 -128
  158. package/src/app/__tests__/feature-schema.test.ts +0 -40
  159. package/src/app/__tests__/form-schema.test.ts +0 -247
  160. package/src/app/__tests__/list-daterange-facet.test.ts +0 -165
  161. package/src/app/__tests__/list-filter-facets.test.tsx +0 -521
  162. package/src/app/__tests__/nav.test.ts +0 -198
  163. package/src/app/__tests__/projection-detail-actions.test.tsx +0 -719
  164. package/src/app/__tests__/projection-detail-reference-field.test.tsx +0 -165
  165. package/src/app/__tests__/projection-detail-shim.test.ts +0 -188
  166. package/src/app/__tests__/projection-detail-singleton.test.tsx +0 -191
  167. package/src/app/__tests__/projection-list-bad-shape.test.tsx +0 -152
  168. package/src/app/__tests__/projection-list-reference-column.test.tsx +0 -219
  169. package/src/app/__tests__/projection-list-search-sort.test.tsx +0 -212
  170. package/src/app/__tests__/qualified-names.test.ts +0 -37
  171. package/src/app/__tests__/return-to.test.ts +0 -396
  172. package/src/app/__tests__/row-actions-navigate-tab.test.ts +0 -223
  173. package/src/app/__tests__/row-default-edit-action.test.tsx +0 -324
  174. package/src/app/__tests__/screen-access-allows.test.ts +0 -34
  175. package/src/app/__tests__/secret-mint-body.test.tsx +0 -404
  176. package/src/app/__tests__/variable-chips.test.tsx +0 -70
  177. package/src/app/app-features-context.tsx +0 -25
  178. package/src/app/column-renderers.tsx +0 -68
  179. package/src/app/content-editors.tsx +0 -85
  180. package/src/app/content-preview.tsx +0 -67
  181. package/src/app/custom-screens.tsx +0 -29
  182. package/src/app/dashboard-body.tsx +0 -33
  183. package/src/app/extension-form-submit.tsx +0 -123
  184. package/src/app/extension-sections.tsx +0 -111
  185. package/src/app/form-schema.ts +0 -91
  186. package/src/app/kumiko-screen.tsx +0 -3801
  187. package/src/app/layout-fields.ts +0 -31
  188. package/src/app/list-facets.ts +0 -259
  189. package/src/app/nav.tsx +0 -258
  190. package/src/app/projection-detail-shim.ts +0 -86
  191. package/src/app/reference-facet-bridge.tsx +0 -58
  192. package/src/app/return-to.tsx +0 -234
  193. package/src/app/row-actions.ts +0 -640
  194. package/src/app/screen-access.ts +0 -63
  195. package/src/app/secret-mint-body.tsx +0 -259
  196. package/src/app/secrets-edit-body.tsx +0 -194
  197. package/src/app/use-embedded-screen.ts +0 -27
  198. package/src/app/variable-chips.tsx +0 -39
  199. package/src/app/write-failed-error.ts +0 -27
  200. package/src/components/__tests__/embedded-list-field.test.tsx +0 -531
  201. package/src/components/__tests__/multi-select-checkboxes.test.tsx +0 -162
  202. package/src/components/__tests__/related-list-section-empty-state.test.tsx +0 -143
  203. package/src/components/__tests__/related-list-section.test.tsx +0 -1733
  204. package/src/components/__tests__/render-edit-action-button.test.tsx +0 -205
  205. package/src/components/__tests__/render-edit-hidden-section.test.tsx +0 -128
  206. package/src/components/__tests__/render-edit-logic.test.ts +0 -314
  207. package/src/components/__tests__/render-edit-screen-description.test.tsx +0 -152
  208. package/src/components/__tests__/render-edit-submit-actions.test.tsx +0 -460
  209. package/src/components/__tests__/render-field-app-locale.test.tsx +0 -142
  210. package/src/components/__tests__/render-field-enum-option.test.tsx +0 -99
  211. package/src/components/__tests__/render-field-icon-derivation.test.tsx +0 -119
  212. package/src/components/__tests__/render-field-json-format.test.tsx +0 -164
  213. package/src/components/__tests__/render-field-money-embedded-list-consistency.test.tsx +0 -212
  214. package/src/components/__tests__/render-field-money-roundtrip.test.tsx +0 -217
  215. package/src/components/__tests__/render-field-number-grouping.test.tsx +0 -76
  216. package/src/components/__tests__/render-field-number-unit.test.tsx +0 -227
  217. package/src/components/__tests__/render-field-password-format.test.tsx +0 -101
  218. package/src/components/__tests__/render-field-select-display.test.tsx +0 -134
  219. package/src/components/__tests__/render-field-unit-format.test.tsx +0 -107
  220. package/src/components/__tests__/render-field-unsupported-types.test.tsx +0 -195
  221. package/src/components/__tests__/render-list-toolbar-icon-only.test.tsx +0 -146
  222. package/src/components/__tests__/write-form-section.test.tsx +0 -375
  223. package/src/components/embedded-list-field.tsx +0 -354
  224. package/src/components/grid-cell-for-field.tsx +0 -88
  225. package/src/components/multi-select-checkboxes.tsx +0 -93
  226. package/src/components/reference-create-dialog.tsx +0 -91
  227. package/src/components/related-list-section.tsx +0 -491
  228. package/src/components/render-edit-action-button.tsx +0 -109
  229. package/src/components/render-edit-logic.ts +0 -85
  230. package/src/components/render-edit-types.ts +0 -226
  231. package/src/components/render-edit.tsx +0 -1871
  232. package/src/components/render-field.tsx +0 -951
  233. package/src/components/render-list.tsx +0 -593
  234. package/src/components/write-form-section.tsx +0 -198
  235. package/src/context/draft-storage-context.tsx +0 -39
  236. package/src/hooks/__tests__/use-ai-text.test.tsx +0 -177
  237. package/src/hooks/__tests__/use-disclosure.test.tsx +0 -25
  238. package/src/hooks/__tests__/use-form.test.tsx +0 -65
  239. package/src/hooks/__tests__/use-mutation.test.tsx +0 -77
  240. package/src/hooks/__tests__/use-query.test.tsx +0 -149
  241. package/src/hooks/__tests__/use-stream-handler.test.tsx +0 -107
  242. package/src/hooks/use-ai-text.ts +0 -172
  243. package/src/hooks/use-disclosure.ts +0 -20
  244. package/src/hooks/use-form.ts +0 -78
  245. package/src/hooks/use-list-url-state.ts +0 -207
  246. package/src/hooks/use-mutation.ts +0 -61
  247. package/src/hooks/use-query.ts +0 -166
  248. package/src/hooks/use-reference-lookup.ts +0 -76
  249. package/src/hooks/use-store.ts +0 -48
  250. package/src/hooks/use-stream-handler.ts +0 -134
  251. package/src/i18n-defaults.ts +0 -240
  252. package/src/i18n.tsx +0 -286
  253. package/src/index.ts +0 -279
  254. package/src/primitives.tsx +0 -1567
  255. package/src/screen-fills-height.ts +0 -3
  256. package/src/share-links.ts +0 -12
  257. package/src/sort-by-accessor.ts +0 -20
  258. package/src/sse/live-events.tsx +0 -56
  259. package/src/tokens.tsx +0 -170
@@ -1,3801 +0,0 @@
1
- import type { ConfigCascade } from "@cosmicdrift/kumiko-framework/engine";
2
- import type {
3
- ActionFormRedirect,
4
- ActionFormScreenDefinition,
5
- ConfigEditScreenDefinition,
6
- DashboardScreenDefinition,
7
- EntityDefinition,
8
- EntityEditScreenDefinition,
9
- EntityListScreenDefinition,
10
- MetricNavigate,
11
- MetricSpec,
12
- ProjectionDetailScreenDefinition,
13
- ProjectionListScreenDefinition,
14
- RowAction,
15
- RowActionDrawer,
16
- RowActionNavigate,
17
- ScreenDefinition,
18
- ToolbarAction,
19
- } from "@cosmicdrift/kumiko-framework/ui-types";
20
- import {
21
- evalFieldCondition,
22
- isWriteFormEditSection,
23
- metricField,
24
- parseRefTarget,
25
- } from "@cosmicdrift/kumiko-framework/ui-types";
26
- import type {
27
- Command,
28
- FormSnapshot,
29
- FormValues,
30
- ListRowViewModel,
31
- SubmitResult,
32
- Translate,
33
- } from "@cosmicdrift/kumiko-headless";
34
- import { fieldLabelKey, fieldOptionLabelKey, isSafeHref } from "@cosmicdrift/kumiko-headless";
35
- import { resolveActionIcon } from "@cosmicdrift/kumiko-types/action-icon";
36
- import { TENANT_CURRENCY_CONFIG_KEY } from "@cosmicdrift/kumiko-types/fields";
37
- import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
38
- import { extractCreatedId, extractIdField } from "../components/reference-create-dialog";
39
- import {
40
- RenderEdit,
41
- type RenderEditAction,
42
- type RenderEditControls,
43
- } from "../components/render-edit";
44
- import {
45
- needsActionConfirm,
46
- RenderEditActionButton,
47
- RenderEditActionConfirmDialog,
48
- } from "../components/render-edit-action-button";
49
- import { RenderList } from "../components/render-list";
50
- import { useDispatcher, useOptionalDispatcher } from "../context/dispatcher-context";
51
- import { useUserRoles } from "../context/user-roles-context";
52
- import { type ListSort, PAGE_SIZE_OPTIONS, useListUrlState } from "../hooks/use-list-url-state";
53
- import { type UseQueryResult, useQuery } from "../hooks/use-query";
54
- import { useLocale, useOptionalTimeZone, useTranslation } from "../i18n";
55
- import { InsideDrawerProvider, useInsideDrawer } from "../inside-drawer";
56
- import { PageHeaderSlotAvailableProvider, usePageHeaderSlotAvailable } from "../page-header-slot";
57
- import {
58
- type DataTableDateRangeFacet,
59
- type DataTableFacet,
60
- type DataTableRowAction,
61
- type StatusTone,
62
- statusToneForOptionTone,
63
- statusToneForValue,
64
- usePrimitives,
65
- } from "../primitives";
66
- import { screenFillsHeight } from "../screen-fills-height";
67
- import { synthesizeActionFormEntity, synthesizeActionFormScreen } from "./action-form-shim";
68
- import { useAppFeatures } from "./app-features-context";
69
- import { synthesizeConfigEditEntity, synthesizeConfigEditScreen } from "./config-edit-shim";
70
- import { useCustomScreenComponent } from "./custom-screens";
71
- import { useDashboardBody } from "./dashboard-body";
72
- import type { FeatureSchema } from "./feature-schema";
73
- import { buildFormSchema } from "./form-schema";
74
- import { layoutFieldNames } from "./layout-fields";
75
- import {
76
- buildDateRangePayload,
77
- buildFilterFacets,
78
- buildFilterPayload,
79
- clampDateRange,
80
- mergeReferenceFacetOptions,
81
- type ResolvedFacetSpec,
82
- readDateRange,
83
- resolveDateRangeFacets,
84
- resolveProjectionFacetSpecs,
85
- } from "./list-facets";
86
- import { type NavApi, type ScreenTarget, useInitialValuesHandoff, useNav } from "./nav";
87
- import {
88
- synthesizeProjectionDetailEntity,
89
- synthesizeProjectionDetailScreen,
90
- } from "./projection-detail-shim";
91
- import { synthesizeProjectionEntity, synthesizeProjectionScreen } from "./projection-list-shim";
92
- import { lastSegment, toKebab } from "./qn";
93
- import { featureNameFromQualifiedScreenId, qualifyScreenId } from "./qualify-screen-id";
94
- import { ReferenceFacetBridges, type ReferenceFacetOption } from "./reference-facet-bridge";
95
- import {
96
- navigateToReturn,
97
- navigateToReturnOr,
98
- navigateWithReturnTo,
99
- type ReturnHost,
100
- ReturnHostProvider,
101
- useReturnHost,
102
- useReturnTarget,
103
- } from "./return-to";
104
- import {
105
- buildDefaultEditRowAction,
106
- buildProjectionRowActions,
107
- buildProjectionToolbarActions,
108
- buildRecordActions,
109
- evalRowExtractor,
110
- isWriteHandlerRowAction,
111
- navigateActionSearchParams,
112
- refetchAfterWrite,
113
- runProjectionRowNavigate,
114
- } from "./row-actions";
115
- import { findEditScreenFor, navigateTargetAllows, screenAccessAllows } from "./screen-access";
116
- import { SecretMintBody } from "./secret-mint-body";
117
- import { SecretsEditBody } from "./secrets-edit-body";
118
- import { dispatcherErrorText, WriteFailedError } from "./write-failed-error";
119
-
120
- // KumikoScreen picks up a ScreenDefinition from the schema by qn and
121
- // routes it to the right renderer based on `screen.type`. Command
122
- // qualification (`<feature>:write:<entity>:create` etc.) happens here
123
- // so the renderers stay command-agnostic — consistent with how the
124
- // server-side dispatcher resolves QNs from ScreenDefinition + feature.
125
- //
126
- // The discriminator is `screen.type`, not a component-registry lookup
127
- // with feature-provided overrides — that's M4's r.uiComponent feature.
128
-
129
- export type KumikoScreenProps = {
130
- readonly schema: FeatureSchema;
131
- readonly qn: string;
132
- readonly translate?: Translate;
133
- // Optional entity-id / row-id. Meaningful for entityEdit screens — when
134
- // set, the edit screen loads the existing record via the detail query and
135
- // submits an update command (`write:<entity>:update`) instead of a create.
136
- // Also required for projectionDetail screens (which row to fetch — no
137
- // create mode exists there). For entityList/custom screens it's ignored.
138
- readonly entityId?: string;
139
- // Fires when the user clicks a row on an entityList screen. The
140
- // second argument is the screen's entity name, threaded through so
141
- // the caller's handler can navigate to `<edit screen for this
142
- // entity>/{row.id}` without re-deriving it. Default wiring in
143
- // createKumikoApp does exactly that; override to open a drawer,
144
- // inline-expand, etc.
145
- readonly onRowClick?: (row: ListRowViewModel, entityName: string) => void;
146
- // Copy-Link-Action auf entityEdit-Update-Screens (Issue #912). Bereits
147
- // vollständig gebunden (URL-Bau + Clipboard) — createKumikoApp/RoutedScreen
148
- // liefert die Default-Impl, dieses platform-neutrale Package baut selbst
149
- // keine URLs/Clipboard-Calls (guard-renderer-boundaries). Nur in
150
- // update-mode sichtbar (entityId muss gesetzt sein).
151
- readonly onCopyLink?: () => Promise<void> | void;
152
- };
153
-
154
- export { qualifyScreenId };
155
-
156
- /** Mirrors qualifyScreenId for nav QNs (registry form `<feature>:nav:<short-id>`).
157
- * Callers building QNs (e.g. the WorkspaceShell resolver) should use this instead of string-concat, so a QN-schema change only touches one place. */
158
- export function qualifyNavId(featureName: string, navId: string): string {
159
- return `${featureName}:nav:${navId}`;
160
- }
161
-
162
- export { screenAccessAllows };
163
-
164
- export function KumikoScreen({
165
- schema,
166
- qn,
167
- translate,
168
- entityId,
169
- onRowClick,
170
- onCopyLink,
171
- }: KumikoScreenProps): ReactNode {
172
- const { Banner, Text } = usePrimitives();
173
- const userRoles = useUserRoles();
174
- const outerHost = useReturnHost();
175
- const screen = useMemo(
176
- () =>
177
- schema.screens.find(
178
- (s: ScreenDefinition) => qualifyScreenId(schema.featureName, s.id) === qn,
179
- ),
180
- [schema.featureName, schema.screens, qn],
181
- );
182
- // Computed before the early returns below — hooks must run unconditionally.
183
- const ownHost = useMemo(
184
- (): ReturnHost => ({
185
- screenId: screen !== undefined ? lastSegment(screen.id) : "",
186
- ...(entityId !== undefined && { entityId }),
187
- }),
188
- [screen, entityId],
189
- );
190
-
191
- if (!screen) {
192
- return (
193
- <Banner padded variant="error" testId="kumiko-screen-not-found">
194
- Screen not found: <Text variant="code">{qn}</Text>
195
- </Banner>
196
- );
197
- }
198
-
199
- if (!screenAccessAllows(screen.access, userRoles)) {
200
- return (
201
- <Banner padded variant="error" testId="kumiko-screen-access-denied">
202
- Access denied: <Text variant="code">{qn}</Text>
203
- </Banner>
204
- );
205
- }
206
-
207
- const body = renderScreenBody({ schema, screen, translate, entityId, onRowClick, onCopyLink });
208
- // An embedded screen (e.g. a dashboard panel) keeps its parent's host and
209
- // must not portal its page header into the shell that hosts the outer screen.
210
- if (outerHost !== undefined) {
211
- return <PageHeaderSlotAvailableProvider value={false}>{body}</PageHeaderSlotAvailableProvider>;
212
- }
213
- return <ReturnHostProvider value={ownHost}>{body}</ReturnHostProvider>;
214
- }
215
-
216
- function renderScreenBody({
217
- schema,
218
- screen,
219
- translate,
220
- entityId,
221
- onRowClick,
222
- onCopyLink,
223
- }: {
224
- readonly schema: FeatureSchema;
225
- readonly screen: ScreenDefinition;
226
- readonly translate?: Translate;
227
- readonly entityId?: string;
228
- readonly onRowClick?: (row: ListRowViewModel, entityName: string) => void;
229
- readonly onCopyLink?: () => Promise<void> | void;
230
- }): ReactNode {
231
- switch (screen.type) {
232
- case "entityEdit":
233
- return (
234
- <EntityEditScreen
235
- schema={schema}
236
- screen={screen}
237
- translate={translate}
238
- {...(entityId !== undefined && { entityId })}
239
- {...(onCopyLink !== undefined && { onCopyLink })}
240
- />
241
- );
242
- case "entityList":
243
- return (
244
- <EntityListScreen
245
- schema={schema}
246
- screen={screen}
247
- translate={translate}
248
- {...(onRowClick !== undefined && { onRowClick })}
249
- />
250
- );
251
- case "projectionList":
252
- return (
253
- <ProjectionListBody
254
- schema={schema}
255
- screen={screen}
256
- translate={translate}
257
- {...(onRowClick !== undefined && { onRowClick })}
258
- />
259
- );
260
- case "projectionDetail":
261
- return (
262
- // key on the record identifier alone (never the active tab, see
263
- // ProjectionDetailBody's own hideSectionTitles/tab handling) forces
264
- // a full remount when navigating from one record to the next —
265
- // without it React keeps the RenderEdit form controller alive and
266
- // the screen briefly shows the PREVIOUS record's fields (fw#2518).
267
- <ProjectionDetailBody
268
- key={entityId ?? "no-entity"}
269
- schema={schema}
270
- screen={screen}
271
- translate={translate}
272
- {...(entityId !== undefined && { entityId })}
273
- />
274
- );
275
- case "dashboard":
276
- return (
277
- <DashboardScreenBody
278
- featureName={schema.featureName}
279
- screen={screen}
280
- translate={translate}
281
- />
282
- );
283
- case "actionForm":
284
- return <ActionFormBody schema={schema} screen={screen} translate={translate} />;
285
- case "secretMint":
286
- return <SecretMintBody schema={schema} screen={screen} translate={translate} />;
287
- case "configEdit":
288
- return <ConfigEditBody schema={schema} screen={screen} translate={translate} />;
289
- case "secretsEdit":
290
- return <SecretsEditBody screen={screen} translate={translate} />;
291
- case "custom":
292
- return <CustomScreenBody screenId={screen.id} featureName={schema.featureName} />;
293
- }
294
- }
295
-
296
- // Injection-Body für dashboard-Screens: die Panel-Implementierung (StatCard,
297
- // Charts) ist plattform-spezifisch und kommt aus dem DashboardBody-Context
298
- // (renderer-web registriert die Web-Variante in createKumikoApp).
299
- function DashboardScreenBody({
300
- featureName,
301
- screen,
302
- translate,
303
- }: {
304
- readonly featureName: string;
305
- readonly screen: DashboardScreenDefinition;
306
- readonly translate?: Translate;
307
- }): ReactNode {
308
- const { Banner, Text } = usePrimitives();
309
- const Body = useDashboardBody();
310
- if (Body === undefined) {
311
- return (
312
- <Banner padded variant="info" testId="kumiko-screen-dashboard-placeholder">
313
- Dashboard screen <Text variant="code">{screen.id}</Text> — kein Dashboard-Body registriert
314
- (createKumikoApp aus <Text variant="code">kumiko-renderer-web</Text> wired ihn automatisch).
315
- </Banner>
316
- );
317
- }
318
- return (
319
- <Body
320
- featureName={featureName}
321
- screen={screen}
322
- {...(translate !== undefined && { translate })}
323
- />
324
- );
325
- }
326
-
327
- // Lookup-Body für custom-screens: schaut die Component aus dem
328
- // CustomScreens-Context (gefüttert von clientFeatures.components in
329
- // createKumikoApp). Wenn weder Provider gemounted noch screenId
330
- // registriert ist, fällt es auf einen error-Banner zurück statt leer zu
331
- // rendern — der Screen ist per URL erreichbar sobald das Server-Feature
332
- // gemountet ist, unabhängig davon ob ein Client-Plugin existiert
333
- // (kumiko-framework#2025).
334
- function CustomScreenBody({
335
- screenId,
336
- featureName,
337
- }: {
338
- readonly screenId: string;
339
- readonly featureName: string;
340
- }): ReactNode {
341
- const { Banner, Text } = usePrimitives();
342
- const Component = useCustomScreenComponent(screenId);
343
- if (Component === undefined) {
344
- return (
345
- <Banner padded variant="error" testId="kumiko-screen-custom-placeholder">
346
- Custom screen <Text variant="code">{screenId}</Text> (Feature{" "}
347
- <Text variant="code">{featureName}</Text>) hat keine Component in{" "}
348
- <Text variant="code">clientFeatures.components</Text> — das Web-Client-Plugin des Features
349
- (siehe <Text variant="code">{featureName}/web/client-plugin.tsx</Text>) fehlt in{" "}
350
- <Text variant="code">clientFeatures</Text>.
351
- </Banner>
352
- );
353
- }
354
- return <Component />;
355
- }
356
-
357
- // ---- entity-edit ----
358
-
359
- // Derives `<feature>:write:<entity>:<verb>` from the screen's entity
360
- // and the schema's feature name. Matches qualifyEntityName / toKebab in
361
- // packages/framework/src/engine/qualified-name.ts so camelCase entity
362
- // ids (e.g. driverModel) resolve to server QNs (driver-model:create).
363
- function entityWriteCommand(
364
- featureName: string,
365
- entity: string,
366
- verb: "create" | "update" | "delete",
367
- ): string {
368
- return `${toKebab(featureName)}:write:${toKebab(entity)}:${verb}`;
369
- }
370
-
371
- // Default "success → zurück zur Liste"-Navigation. Findet den ersten
372
- // entityList-Screen für die Entity und navigiert dahin. Wird von
373
- // Create/Update/Delete genauso verwendet — alle drei haben "fertig
374
- // editiert, raus hier" als sinnvolles Default-Verhalten.
375
- function useNavigateToListAfter(schema: FeatureSchema, entityName: string): () => void {
376
- const nav = useNav();
377
- return useCallback(() => {
378
- const list = schema.screens.find(
379
- (s: ScreenDefinition) => s.type === "entityList" && s.entity === entityName,
380
- );
381
- if (!list) return;
382
- // schema.screens.id ist QN-form (registry-stamped); nav.navigate
383
- // erwartet Short-Form. Sonst landet die URL doppelt-qualifiziert.
384
- nav.navigate({ screenId: lastSegment(list.id) });
385
- }, [nav, schema.screens, entityName]);
386
- }
387
-
388
- // Default "+ Neu"-Navigation für die List-Toolbar: findet den ersten
389
- // entityEdit-Screen ohne entityId-Anhang und navigiert dorthin.
390
- // Returns undefined wenn kein Edit-Screen registriert ist — RenderList
391
- // rendert dann keinen + Neu Button.
392
- //
393
- // Schema-Screens kommen mit qualifizierten ids ("publicstatus:screen:
394
- // component-edit") aus der Registry; lastSegment strippt den Prefix
395
- // für nav.navigate (siehe ./qn.ts für Doku).
396
- function pageSizeOptionsFor(currentLimit: number): readonly number[] {
397
- return PAGE_SIZE_OPTIONS.includes(currentLimit)
398
- ? PAGE_SIZE_OPTIONS
399
- : [...PAGE_SIZE_OPTIONS, currentLimit].sort((a, b) => a - b);
400
- }
401
-
402
- function useNavigateToCreateFor(
403
- schema: FeatureSchema,
404
- entityName: string,
405
- ): (() => void) | undefined {
406
- const nav = useNav();
407
- const host = useReturnHost();
408
- const editScreenId = useMemo(() => {
409
- // allowCreate:false = update-only Edit-Screen (Create läuft über einen
410
- // Lifecycle-Write) — der zählt nicht als „+ Neu"-Ziel. singleton:true
411
- // öffnet ohne entityId den vorhandenen Record (EntityEditSingletonBody)
412
- // statt eines leeren Create-Forms — zählt aus demselben Grund nicht.
413
- const edit = schema.screens.find(
414
- (s: ScreenDefinition) =>
415
- s.type === "entityEdit" &&
416
- s.entity === entityName &&
417
- s.allowCreate !== false &&
418
- s.singleton !== true,
419
- );
420
- return edit !== undefined ? lastSegment(edit.id) : undefined;
421
- }, [schema.screens, entityName]);
422
- const navigate = useCallback(() => {
423
- if (editScreenId !== undefined) navigateWithReturnTo(nav, { screenId: editScreenId }, host);
424
- }, [nav, editScreenId, host]);
425
- return editScreenId !== undefined ? navigate : undefined;
426
- }
427
-
428
- // `defaultCurrency` is entityEdit-only — it enables the `{amount, currency}`
429
- // write shape (fw#1923); config-edit's plain-number contract needs bare `0`.
430
- // `moneyCurrencyOverrides` (fw#2933) replaces `defaultCurrency` per field name
431
- // — used for a `money` field that declares `currency: { kind: "tenant" }`, so
432
- // its empty initial value carries the tenant's own currency instead of the
433
- // entity-wide default.
434
- export function buildInitialValues(
435
- fields: Readonly<Record<string, unknown>>,
436
- defaultCurrency?: string,
437
- moneyCurrencyOverrides?: Readonly<Record<string, string>>,
438
- ): Readonly<Record<string, unknown>> {
439
- const out: Record<string, unknown> = {};
440
- for (const [name, def] of Object.entries(fields)) {
441
- const shape = def as { type?: string; default?: unknown; multiple?: boolean };
442
- if (shape.default !== undefined) {
443
- out[name] = shape.default;
444
- continue;
445
- }
446
- if (shape.type === "embedded" && shape.multiple === true) {
447
- out[name] = [];
448
- continue;
449
- }
450
- if (shape.type === "money") {
451
- const currency = moneyCurrencyOverrides?.[name] ?? defaultCurrency;
452
- if (currency !== undefined) {
453
- out[name] = { amount: 0, currency };
454
- continue;
455
- }
456
- }
457
- out[name] =
458
- shape.type === "boolean"
459
- ? false
460
- : shape.type === "number" || shape.type === "money"
461
- ? 0
462
- : shape.type === "multiSelect"
463
- ? []
464
- : "";
465
- }
466
- return out;
467
- }
468
-
469
- // A `money` field opts a currently-empty value into the tenant-settings
470
- // bundle's per-tenant currency (fw#2933) via `currency: { kind: "tenant" }`
471
- // on its FieldDefinition. Read structurally — renderer only depends on the
472
- // client-safe FieldDefinition subset, not the concrete MoneyFieldDef/
473
- // MoneyCurrencySource types, same idiom as the other field-shape narrowings
474
- // in this file (PrefillFieldShape etc.).
475
- function tenantCurrencyMoneyFieldNames(
476
- fields: Readonly<Record<string, unknown>>,
477
- ): readonly string[] {
478
- const names: string[] = [];
479
- for (const [name, def] of Object.entries(fields)) {
480
- const shape = def as { readonly type?: string; readonly currency?: { readonly kind?: string } };
481
- if (shape.type === "money" && shape.currency?.kind === "tenant") names.push(name);
482
- }
483
- return names;
484
- }
485
-
486
- type TenantConfigValuesResponse = Readonly<
487
- Record<string, { readonly value: string | number | boolean | undefined }>
488
- >;
489
-
490
- type TenantCurrencyResolution =
491
- | { readonly status: "not-needed" }
492
- | { readonly status: "loading" }
493
- | { readonly status: "ready"; readonly currency: string };
494
-
495
- // Resolves what a tenant-declared money field's currency should be, from the
496
- // same `config:query:values` query ConfigEditBody already uses. Never falls
497
- // back to "EUR" while the query is genuinely still in flight (fw#2933) — a
498
- // screen with no tenant-declared money field, or a query that errored or
499
- // returned no value for the key, resolves immediately instead of blocking.
500
- function resolveTenantCurrency(
501
- fieldNames: readonly string[],
502
- query: UseQueryResult<TenantConfigValuesResponse>,
503
- fallback: string,
504
- ): TenantCurrencyResolution {
505
- if (fieldNames.length === 0) return { status: "not-needed" };
506
- if (query.error) return { status: "ready", currency: fallback };
507
- if (query.data === null) return { status: "loading" };
508
- const raw = query.data[TENANT_CURRENCY_CONFIG_KEY]?.value;
509
- return { status: "ready", currency: typeof raw === "string" && raw !== "" ? raw : fallback };
510
- }
511
-
512
- // An entity-less form screen has no `entity.defaultCurrency` to fall back on,
513
- // so a tenant-declared field whose config query errors or returns no value
514
- // lands here — same last resort as the entityEdit path's `?? "EUR"`.
515
- const ACTION_FORM_CURRENCY_FALLBACK = "EUR";
516
-
517
- // Shared by the update payload shape and the server-error path prefix so both can't drift.
518
- const UPDATE_CHANGES_KEY = "changes";
519
-
520
- // A money field naming a fixed ISO code (`currency: { kind: "literal", code }`,
521
- // fw#2839) resolves with no query at all. Read structurally, same idiom as
522
- // tenantCurrencyMoneyFieldNames above.
523
- export function literalCurrencyOverrides(
524
- fields: Readonly<Record<string, unknown>>,
525
- ): Readonly<Record<string, string>> {
526
- const out: Record<string, string> = {};
527
- for (const [name, def] of Object.entries(fields)) {
528
- const shape = def as {
529
- readonly type?: string;
530
- readonly currency?: { readonly kind?: string; readonly code?: string };
531
- };
532
- const code = shape.currency?.code;
533
- if (shape.type === "money" && shape.currency?.kind === "literal" && code !== undefined) {
534
- out[name] = code;
535
- }
536
- }
537
- return out;
538
- }
539
-
540
- // Per-field currency for the money fields that declare their own source: a
541
- // literal code resolves synchronously (fw#2839), a `{ kind: "tenant" }` field
542
- // needs the tenant-settings config query and makes the caller hold the form
543
- // until it lands (fw#2933) — seeding the fallback meanwhile would render, and
544
- // on a fast click submit, the wrong currency. Callers pass the tenant field
545
- // names themselves because an edit form only needs the fetch for fields the
546
- // record has no stored value for.
547
- function useMoneyCurrencyOverrides(
548
- fields: Readonly<Record<string, unknown>>,
549
- tenantFieldNames: readonly string[],
550
- fallback: string,
551
- ): {
552
- readonly overrides: Readonly<Record<string, string>> | undefined;
553
- readonly loading: boolean;
554
- } {
555
- const query = useQuery<TenantConfigValuesResponse>(
556
- "config:query:values",
557
- {},
558
- { enabled: tenantFieldNames.length > 0 },
559
- );
560
- const resolution = resolveTenantCurrency(tenantFieldNames, query, fallback);
561
- const resolvedTenantCurrency = resolution.status === "ready" ? resolution.currency : undefined;
562
- const overrides = useMemo(() => {
563
- const out: Record<string, string> = { ...literalCurrencyOverrides(fields) };
564
- if (resolvedTenantCurrency !== undefined) {
565
- for (const name of tenantFieldNames) out[name] = resolvedTenantCurrency;
566
- }
567
- return Object.keys(out).length > 0 ? out : undefined;
568
- }, [fields, tenantFieldNames, resolvedTenantCurrency]);
569
- return { overrides, loading: resolution.status === "loading" };
570
- }
571
-
572
- function multiSelectOptionValues(shape: {
573
- readonly options?: readonly (string | { readonly value: string })[];
574
- }): ReadonlySet<string> | undefined {
575
- if (shape.options === undefined || shape.options.length === 0) return undefined;
576
- return new Set(shape.options.map((o) => (typeof o === "string" ? o : o.value)));
577
- }
578
-
579
- type MoneyValue = { readonly amount: number; readonly currency: string };
580
-
581
- // The currency now comes from a user-controlled URL param and reaches
582
- // `Intl.NumberFormat`, which throws a RangeError on a malformed code — reject
583
- // it here instead of crashing the form render.
584
- const CURRENCY_CODE_PATTERN = /^[A-Za-z]{3}$/;
585
-
586
- function isMoneyValue(value: unknown): value is MoneyValue {
587
- if (typeof value !== "object" || value === null) return false;
588
- const { amount, currency } = value as Partial<MoneyValue>;
589
- return (
590
- typeof amount === "number" &&
591
- Number.isFinite(amount) &&
592
- typeof currency === "string" &&
593
- CURRENCY_CODE_PATTERN.test(currency)
594
- );
595
- }
596
-
597
- const ISO_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
598
-
599
- function formatSummaryValue(value: unknown, locale: string): string {
600
- if (isMoneyValue(value)) {
601
- return new Intl.NumberFormat(locale, { style: "currency", currency: value.currency }).format(
602
- value.amount,
603
- );
604
- }
605
- if (typeof value === "number") return value.toLocaleString(locale);
606
- if (typeof value === "string" && ISO_DATE_PATTERN.test(value)) {
607
- return new Date(`${value}T00:00:00Z`).toLocaleDateString(locale, {
608
- year: "numeric",
609
- month: "2-digit",
610
- day: "2-digit",
611
- timeZone: "UTC",
612
- });
613
- }
614
- return value === null || value === undefined ? "" : String(value);
615
- }
616
-
617
- function resolveActionFormSummary(
618
- summary: ActionFormScreenDefinition["summary"],
619
- prefill: Readonly<Record<string, unknown>> | undefined,
620
- translate: Translate,
621
- locale: string,
622
- ): { readonly title: string; readonly subtitle?: string } | undefined {
623
- if (summary === undefined) return undefined;
624
- const params = Object.fromEntries(
625
- Object.entries(prefill ?? {}).map(([name, value]) => [name, formatSummaryValue(value, locale)]),
626
- );
627
- return {
628
- title: translate(summary.title, params),
629
- ...(summary.subtitle !== undefined && { subtitle: translate(summary.subtitle, params) }),
630
- };
631
- }
632
-
633
- function parseJsonOrRaw(raw: string): unknown {
634
- try {
635
- return JSON.parse(raw);
636
- } catch {
637
- return raw;
638
- }
639
- }
640
-
641
- function warnPrefillParam(message: string): void {
642
- // biome-ignore lint/suspicious/noConsole: dev-warning for an authoring error
643
- console.warn(`[kumiko] ${message}`);
644
- }
645
-
646
- // An actionForm has no entity and thus no defaultCurrency, so a bare-number
647
- // prefill would stay a number the handler's zod schema rejects (fw#2763).
648
- function coerceMoneyValue(
649
- raw: unknown,
650
- fieldName: string,
651
- defaultCurrency?: string,
652
- ): MoneyValue | number | undefined {
653
- if (raw === null || raw === undefined) return undefined;
654
- const value = typeof raw === "string" ? parseJsonOrRaw(raw) : raw;
655
- if (value === null) return undefined;
656
- if (isMoneyValue(value)) return { amount: value.amount, currency: value.currency.toUpperCase() };
657
- if (typeof value === "object") {
658
- warnPrefillParam(
659
- `money field "${fieldName}" got an object without a usable {amount, currency} shape — the prefill is ignored.`,
660
- );
661
- return undefined;
662
- }
663
- const amount = Number(typeof value === "number" ? value : raw);
664
- if (!Number.isFinite(amount)) return undefined;
665
- if (defaultCurrency !== undefined) return { amount, currency: defaultCurrency };
666
- warnPrefillParam(
667
- `money field "${fieldName}" was prefilled with a bare number and no currency is available — pass {"amount":<number>,"currency":"<ISO code>"} as the param value, otherwise the handler's schema rejects the submit.`,
668
- );
669
- return amount;
670
- }
671
-
672
- type EmbeddedCellShape = { readonly type?: string; readonly options?: readonly string[] };
673
-
674
- const EMBEDDED_LIST_PREFILL_ROW_LIMIT = 500;
675
-
676
- function coerceEmbeddedCell(value: unknown, cell: EmbeddedCellShape): unknown {
677
- switch (cell.type) {
678
- case "number":
679
- case "decimal":
680
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
681
- case "money":
682
- // Row cells are signed minor units; the currency lives on the head, so a
683
- // top-level `{amount, currency}` in major units would land 100x off.
684
- return typeof value === "number" && Number.isSafeInteger(value) ? value : undefined;
685
- case "boolean":
686
- return typeof value === "boolean" ? value : undefined;
687
- case "select":
688
- return typeof value === "string" && (cell.options ?? []).includes(value) ? value : undefined;
689
- default:
690
- return typeof value === "string" ? value : undefined;
691
- }
692
- }
693
-
694
- // A partially coerced list is the hazard the prefill exists to avoid: the
695
- // handler replaces the list whole, so half a list overwrites the rest.
696
- function coerceEmbeddedListRows(
697
- raw: string,
698
- fieldName: string,
699
- schema: Readonly<Record<string, EmbeddedCellShape>>,
700
- maxItems?: number,
701
- ): readonly Readonly<Record<string, unknown>>[] | undefined {
702
- const parsed = parseJsonOrRaw(raw);
703
- if (!Array.isArray(parsed)) {
704
- warnPrefillParam(
705
- `embedded-list field "${fieldName}" was prefilled with something that is not a JSON array — the prefill is ignored.`,
706
- );
707
- return undefined;
708
- }
709
- if (parsed.length > (maxItems ?? EMBEDDED_LIST_PREFILL_ROW_LIMIT)) {
710
- warnPrefillParam(
711
- `embedded-list field "${fieldName}" was prefilled with ${parsed.length} rows, more than it accepts — the prefill is ignored.`,
712
- );
713
- return undefined;
714
- }
715
- const rows: Readonly<Record<string, unknown>>[] = [];
716
- for (const candidate of parsed) {
717
- if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate)) {
718
- warnPrefillParam(
719
- `embedded-list field "${fieldName}" was prefilled with a row that is not an object — the prefill is ignored.`,
720
- );
721
- return undefined;
722
- }
723
- const cellEntries: [string, unknown][] = [];
724
- for (const [cellName, cell] of Object.entries(schema)) {
725
- const cellValue = (candidate as Record<string, unknown>)[cellName];
726
- if (cellValue === undefined || cellValue === null) continue;
727
- const coerced = coerceEmbeddedCell(cellValue, cell);
728
- if (coerced === undefined) {
729
- warnPrefillParam(
730
- `embedded-list field "${fieldName}" was prefilled with a cell "${cellName}" the sub-schema rejects — the prefill is ignored.`,
731
- );
732
- return undefined;
733
- }
734
- cellEntries.push([cellName, coerced]);
735
- }
736
- rows.push(Object.fromEntries(cellEntries));
737
- }
738
- return rows;
739
- }
740
-
741
- type PrefillFieldShape = {
742
- readonly type?: string;
743
- readonly sensitive?: boolean;
744
- readonly format?: string;
745
- readonly options?: readonly (string | { readonly value: string })[];
746
- readonly multiple?: boolean;
747
- readonly schema?: Readonly<Record<string, EmbeddedCellShape>>;
748
- readonly maxItems?: number;
749
- };
750
-
751
- export type InitialValueSources = {
752
- readonly searchParams: Readonly<Record<string, string>>;
753
- // Only these URL query keys may prefill — the target screen's
754
- // `urlPrefillFields` from buildAppSchema. Absent means none: a crafted link
755
- // must not seed fields no declared navigate `params` names.
756
- readonly urlPrefillFields: readonly string[] | undefined;
757
- readonly renderableFields?: ReadonlySet<string>;
758
- readonly defaultCurrency?: string;
759
- // Per-field override of `defaultCurrency` for money fields declaring
760
- // `currency: { kind: "tenant" }` (fw#2933) — see buildInitialValues.
761
- readonly moneyCurrencyOverrides?: Readonly<Record<string, string>>;
762
- // Drawer-kind row actions (fw#2710) prefill from the clicked row's
763
- // already-typed values; wins over every other source.
764
- readonly drawerOverrides?: Readonly<Record<string, unknown>>;
765
- // useNavigateWithInitialValues — in-app only, never in the URL, so it
766
- // bypasses urlPrefillFields; string values get the URL coercion.
767
- readonly handoffValues?: Readonly<Record<string, unknown>>;
768
- };
769
-
770
- function coercePrefillString(
771
- raw: string,
772
- name: string,
773
- shape: PrefillFieldShape,
774
- fallback: unknown,
775
- defaultCurrency: string | undefined,
776
- moneyCurrencyOverrides: Readonly<Record<string, string>> | undefined,
777
- ): unknown {
778
- if (shape.type === "number") {
779
- const parsed = Number(raw);
780
- return Number.isNaN(parsed) ? fallback : parsed;
781
- }
782
- if (shape.type === "money") {
783
- const coerced = coerceMoneyValue(raw, name, moneyCurrencyOverrides?.[name] ?? defaultCurrency);
784
- return coerced === undefined ? fallback : coerced;
785
- }
786
- if (shape.type === "boolean") return raw === "true";
787
- if (shape.type === "multiSelect") {
788
- // Row-action navigate stringifies arrays via String(arr) → "a,b" (or
789
- // JSON when the navigate helper JSON.stringifies). Try JSON first
790
- // (even without a "[" prefix), then comma-split; filter against
791
- // field.options when present so unknown values never reach the form.
792
- const optionValues = multiSelectOptionValues(shape);
793
- const splitComma = (): string[] =>
794
- raw === ""
795
- ? []
796
- : raw
797
- .split(",")
798
- .map((s) => s.trim())
799
- .filter(Boolean);
800
- let values: string[];
801
- try {
802
- const parsed: unknown = JSON.parse(raw);
803
- if (Array.isArray(parsed)) {
804
- values = parsed.map((v) => String(v));
805
- } else if (typeof parsed === "string") {
806
- values = [parsed];
807
- } else {
808
- values = splitComma();
809
- }
810
- } catch {
811
- values = splitComma();
812
- }
813
- return optionValues !== undefined ? values.filter((v) => optionValues.has(v)) : values;
814
- }
815
- if (shape.type === "embedded" && shape.multiple === true) {
816
- return coerceEmbeddedListRows(raw, name, shape.schema ?? {}, shape.maxItems) ?? fallback;
817
- }
818
- return raw;
819
- }
820
-
821
- export function mergeSearchParamsIntoInitial(
822
- fields: Readonly<Record<string, unknown>>,
823
- sources: InitialValueSources,
824
- ): Record<string, unknown> {
825
- const {
826
- searchParams,
827
- renderableFields,
828
- defaultCurrency,
829
- moneyCurrencyOverrides,
830
- drawerOverrides,
831
- handoffValues,
832
- } = sources;
833
- const urlPrefillFields = new Set(sources.urlPrefillFields ?? []);
834
- const defaults = buildInitialValues(fields, defaultCurrency, moneyCurrencyOverrides) as Record<
835
- string,
836
- unknown
837
- >;
838
- const merged: Record<string, unknown> = { ...defaults };
839
- for (const [name, fieldDef] of Object.entries(fields)) {
840
- if (renderableFields !== undefined && !renderableFields.has(name)) continue;
841
- const shape = fieldDef as PrefillFieldShape;
842
- // Neither gate is lifted by an allowlist entry or a handoff.
843
- if (shape.sensitive === true) continue;
844
- if (shape.format === "password") continue;
845
- if (drawerOverrides !== undefined && name in drawerOverrides) {
846
- merged[name] = drawerOverrides[name];
847
- continue;
848
- }
849
- const handedOff =
850
- handoffValues !== undefined && Object.hasOwn(handoffValues, name)
851
- ? handoffValues[name]
852
- : undefined;
853
- if (handedOff !== undefined) {
854
- merged[name] =
855
- typeof handedOff === "string"
856
- ? coercePrefillString(
857
- handedOff,
858
- name,
859
- shape,
860
- defaults[name],
861
- defaultCurrency,
862
- moneyCurrencyOverrides,
863
- )
864
- : handedOff;
865
- continue;
866
- }
867
- if (!urlPrefillFields.has(name)) continue;
868
- const raw = searchParams[name];
869
- if (raw === undefined) continue;
870
- merged[name] = coercePrefillString(
871
- raw,
872
- name,
873
- shape,
874
- defaults[name],
875
- defaultCurrency,
876
- moneyCurrencyOverrides,
877
- );
878
- }
879
- return merged;
880
- }
881
-
882
- function EntityEditScreen({
883
- schema,
884
- screen,
885
- translate,
886
- entityId,
887
- onCopyLink,
888
- }: {
889
- readonly schema: FeatureSchema;
890
- readonly screen: EntityEditScreenDefinition;
891
- readonly translate?: Translate;
892
- readonly entityId?: string;
893
- readonly onCopyLink?: () => Promise<void> | void;
894
- }): ReactNode {
895
- const { Banner, Text } = usePrimitives();
896
- const entity = schema.entities[screen.entity];
897
- if (!entity) {
898
- return (
899
- <Banner padded variant="error" testId="kumiko-screen-entity-missing">
900
- Entity <Text variant="code">{screen.entity}</Text> referenced by screen{" "}
901
- <Text variant="code">{screen.id}</Text> not registered in the schema.
902
- </Banner>
903
- );
904
- }
905
- // Split into create-body / update-body so the update-only hooks
906
- // (useQuery(detail)) don't fire in create mode, and vice versa.
907
- // Same shape as EntityListScreen.
908
- if (entityId !== undefined) {
909
- return (
910
- <EntityEditUpdateBody
911
- schema={schema}
912
- screen={screen}
913
- entity={entity}
914
- entityId={entityId}
915
- {...(translate !== undefined && { translate })}
916
- {...(onCopyLink !== undefined && { onCopyLink })}
917
- />
918
- );
919
- }
920
- if (screen.singleton === true) {
921
- return (
922
- <EntityEditSingletonBody
923
- schema={schema}
924
- screen={screen}
925
- entity={entity}
926
- {...(translate !== undefined && { translate })}
927
- {...(onCopyLink !== undefined && { onCopyLink })}
928
- />
929
- );
930
- }
931
- return (
932
- <EntityEditCreateOrDisabled
933
- schema={schema}
934
- screen={screen}
935
- entity={entity}
936
- {...(translate !== undefined && { translate })}
937
- />
938
- );
939
- }
940
-
941
- function EntityEditCreateBody({
942
- schema,
943
- screen,
944
- entity,
945
- translate,
946
- onSaved,
947
- }: {
948
- readonly schema: FeatureSchema;
949
- readonly screen: EntityEditScreenDefinition;
950
- readonly entity: EntityDefinition;
951
- readonly translate?: Translate;
952
- // Singleton screens (kumiko-screen#1944) run without a wrapping
953
- // entityList screen, so `navigateToList` below is a silent no-op there —
954
- // without this callback, a successful create left the form stuck showing
955
- // the just-submitted values, and a second submit created a duplicate
956
- // record. Wired by EntityEditSingletonBody to re-run its list(limit:1)
957
- // query, which flips the branch to EntityEditUpdateBody once it sees the
958
- // new row.
959
- readonly onSaved?: () => void;
960
- }): ReactNode {
961
- const { Banner } = usePrimitives();
962
- const nav = useNav();
963
- const handoffValues = useInitialValuesHandoff(screen.id);
964
- const appFeatures = useAppFeatures();
965
- const returnTargetParam = useReturnTarget(screen.id);
966
- // A singleton stays on its own screen after saving (onSaved/refetch) —
967
- // returnTo would fight that.
968
- const returnTarget = screen.singleton === true ? undefined : returnTargetParam;
969
- const entityDefaultCurrency = entity.defaultCurrency ?? "EUR";
970
- // A money field declaring `currency: { kind: "tenant" }` (fw#2933) resolves
971
- // its empty-value currency from the tenant-settings config key instead of
972
- // entityDefaultCurrency — `enabled` keeps the query a no-op for entities
973
- // without any such field.
974
- const tenantCurrencyFieldNames = useMemo(
975
- () => tenantCurrencyMoneyFieldNames(entity.fields),
976
- [entity.fields],
977
- );
978
- const { overrides: moneyCurrencyOverrides, loading: currencyLoading } = useMoneyCurrencyOverrides(
979
- entity.fields,
980
- tenantCurrencyFieldNames,
981
- entityDefaultCurrency,
982
- );
983
- const initial = useMemo(
984
- () =>
985
- mergeSearchParamsIntoInitial(entity.fields, {
986
- searchParams: nav.searchParams,
987
- urlPrefillFields: screen.urlPrefillFields,
988
- renderableFields: layoutFieldNames(screen),
989
- defaultCurrency: entityDefaultCurrency,
990
- ...(moneyCurrencyOverrides !== undefined && { moneyCurrencyOverrides }),
991
- ...(handoffValues !== undefined && { handoffValues }),
992
- }) as FormValues,
993
- [
994
- entity.fields,
995
- nav.searchParams,
996
- screen,
997
- entityDefaultCurrency,
998
- moneyCurrencyOverrides,
999
- handoffValues,
1000
- ],
1001
- );
1002
- const formSchema = useMemo(() => buildFormSchema(entity, screen), [entity, screen]);
1003
- const writeCommand = entityWriteCommand(schema.featureName, screen.entity, "create");
1004
- const navigateToList = useNavigateToListAfter(schema, screen.entity);
1005
- const handleCancel = useCallback(
1006
- () => navigateToReturnOr(nav, returnTarget, navigateToList),
1007
- [nav, returnTarget, navigateToList],
1008
- );
1009
- // Create's write-handler success payload doesn't flatly expose a parent FK
1010
- // (`{ kind, id, data, … }`), so an object-form redirect's `idFrom` falls
1011
- // back to the values just submitted to the handler.
1012
- const controlsRef = useRef<RenderEditControls<FormValues> | null>(null);
1013
- const handleControlsReady = useCallback((controls: RenderEditControls<FormValues>) => {
1014
- controlsRef.current = controls;
1015
- }, []);
1016
- const handleSubmitted = useCallback(
1017
- (result: SubmitResult<unknown>) => {
1018
- if (!result.isSuccess) return;
1019
- const redirect = screen.redirect;
1020
- if (redirect !== undefined) {
1021
- if (returnToWinsOverRedirect(returnTarget, redirect, schema, appFeatures)) {
1022
- navigateToReturn(nav, returnTarget);
1023
- } else if (typeof redirect === "string") {
1024
- // String form unchanged: always carries the newly created
1025
- // record's own id, regardless of the target screen's type. The
1026
- // object form resolves like actionForm's — a child record's own id
1027
- // is useless for a parent-detail redirect.
1028
- const entityId = extractCreatedId(result.data);
1029
- nav.navigate({
1030
- screenId: lastSegment(redirect),
1031
- ...(entityId !== undefined && { entityId }),
1032
- });
1033
- } else {
1034
- const { screenId, entityId } = resolveRedirectTarget(
1035
- redirect,
1036
- result.data,
1037
- schema,
1038
- appFeatures,
1039
- controlsRef.current?.getValues(),
1040
- );
1041
- nav.navigate({ screenId, ...(entityId !== undefined && { entityId }) });
1042
- }
1043
- } else {
1044
- navigateToReturnOr(nav, returnTarget, navigateToList);
1045
- onSaved?.();
1046
- }
1047
- },
1048
- [nav, screen.redirect, schema, appFeatures, navigateToList, onSaved, returnTarget],
1049
- );
1050
- // Never seed a tenant-declared money field with entityDefaultCurrency while
1051
- // its real tenant currency is still in flight (fw#2933) — wait instead.
1052
- if (currencyLoading) {
1053
- return (
1054
- <Banner padded variant="loading" testId="kumiko-screen-loading">
1055
- Loading…
1056
- </Banner>
1057
- );
1058
- }
1059
- // Deliberately no `actions` prop here: `screen.actions` targets an
1060
- // EXISTING record (publish/archive/duplicate and friends), which the
1061
- // create branch has none of yet — see EntityEditUpdateForm for the
1062
- // wired-up counterpart.
1063
- return (
1064
- <RenderEdit
1065
- screen={screen}
1066
- entity={entity}
1067
- featureName={schema.featureName}
1068
- initial={initial}
1069
- schema={formSchema}
1070
- writeCommand={writeCommand}
1071
- onSubmit={handleSubmitted}
1072
- onControlsReady={handleControlsReady}
1073
- onCancel={handleCancel}
1074
- {...(screenFillsHeight(screen) && { fillScreenHeight: true })}
1075
- {...(screen.submitLabel !== undefined && { submitLabel: screen.submitLabel })}
1076
- {...(translate !== undefined && { translate })}
1077
- />
1078
- );
1079
- }
1080
-
1081
- // Update body: loads the existing record via `<feature>:query:<entity>:detail`,
1082
- // then mounts a form pre-filled with the server values and dispatches
1083
- // `<feature>:write:<entity>:update` on submit. `buildPayload` shapes the
1084
- // snapshot into Kumiko's update-event envelope `{ id, version, changes }`.
1085
- function EntityEditUpdateBody({
1086
- schema,
1087
- screen,
1088
- entity,
1089
- entityId,
1090
- translate,
1091
- onCopyLink,
1092
- autoReloadOnSave,
1093
- onDeleted,
1094
- }: {
1095
- readonly schema: FeatureSchema;
1096
- readonly screen: EntityEditScreenDefinition;
1097
- readonly entity: EntityDefinition;
1098
- readonly entityId: string;
1099
- readonly translate?: Translate;
1100
- readonly onCopyLink?: () => Promise<void> | void;
1101
- // Singleton screens (kumiko-screen#1944): `navigateToList` below is a
1102
- // no-op there (no wrapping entityList screen), so a successful update
1103
- // left the form holding the now-stale `recordVersion` it captured at
1104
- // mount — the next submit hit a version conflict. Set by
1105
- // EntityEditSingletonBody to re-fetch this body's own detail query after
1106
- // a successful save, remounting the form (via the version-keyed `key`
1107
- // below) with the fresh version.
1108
- readonly autoReloadOnSave?: boolean;
1109
- // Wired by EntityEditSingletonBody to re-run its list(limit:1) query
1110
- // after a successful delete, so the branch flips back to the create form
1111
- // instead of the update form continuing to display the deleted record.
1112
- readonly onDeleted?: () => void;
1113
- }): ReactNode {
1114
- const { Banner, Text } = usePrimitives();
1115
- const t = useTranslation();
1116
- const effectiveTranslate = translate ?? t;
1117
- const detailQn = `${toKebab(schema.featureName)}:query:${toKebab(screen.entity)}:detail`;
1118
- const detailQuery = useQuery<Readonly<Record<string, unknown>>>(detailQn, { id: entityId });
1119
-
1120
- if (detailQuery.loading && detailQuery.data === null) {
1121
- return (
1122
- <Banner padded variant="loading" testId="kumiko-screen-loading">
1123
- Loading…
1124
- </Banner>
1125
- );
1126
- }
1127
- if (detailQuery.error) {
1128
- return (
1129
- <Banner padded variant="error" testId="kumiko-screen-error">
1130
- {dispatcherErrorText(detailQuery.error, effectiveTranslate)}
1131
- </Banner>
1132
- );
1133
- }
1134
- const record = detailQuery.data;
1135
- if (!record) {
1136
- return (
1137
- <Banner padded variant="error" testId="kumiko-screen-record-missing">
1138
- Record <Text variant="code">{entityId}</Text> not found.
1139
- </Banner>
1140
- );
1141
- }
1142
- // Record-version als React-key: bei "Neu laden" refetched detail,
1143
- // liefert neue version, und das Form remountet komplett. Ohne den
1144
- // Key-Wechsel bliebe der useForm-Controller lifetime-scoped auf
1145
- // der ursprünglichen version sitzen — der buildPayload würde
1146
- // weiter die stale version stampen und der Konflikt-Recovery wäre
1147
- // kaputt.
1148
- const recordKey = (record as { version?: number }).version ?? 1;
1149
- return (
1150
- <EntityEditUpdateForm
1151
- key={`${entityId}:${recordKey}`}
1152
- schema={schema}
1153
- screen={screen}
1154
- entity={entity}
1155
- entityId={entityId}
1156
- record={record}
1157
- onReload={detailQuery.refetch}
1158
- {...(translate !== undefined && { translate })}
1159
- {...(onCopyLink !== undefined && { onCopyLink })}
1160
- {...(autoReloadOnSave === true && { onSaved: () => void detailQuery.refetch() })}
1161
- {...(onDeleted !== undefined && { onDeleted })}
1162
- />
1163
- );
1164
- }
1165
-
1166
- function EntityEditUpdateForm({
1167
- schema,
1168
- screen,
1169
- entity,
1170
- entityId,
1171
- record,
1172
- onReload,
1173
- translate,
1174
- onCopyLink,
1175
- onSaved,
1176
- onDeleted,
1177
- }: {
1178
- readonly schema: FeatureSchema;
1179
- readonly screen: EntityEditScreenDefinition;
1180
- readonly entity: EntityDefinition;
1181
- readonly entityId: string;
1182
- readonly record: Readonly<Record<string, unknown>>;
1183
- readonly onReload: () => Promise<void> | void;
1184
- readonly translate?: Translate;
1185
- readonly onCopyLink?: () => Promise<void> | void;
1186
- // See EntityEditUpdateBody's autoReloadOnSave/onDeleted docs — both are
1187
- // no-ops unless the caller (singleton screens) wires them.
1188
- readonly onSaved?: () => void;
1189
- readonly onDeleted?: () => void;
1190
- }): ReactNode {
1191
- const { Banner } = usePrimitives();
1192
- // Seed the form with the server values for the entity's declared
1193
- // fields; anything else (id, tenant_id, created_at…) stays out of
1194
- // the form and lives in the closure. The record's `version` is
1195
- // captured once and stamped into every update payload — if a
1196
- // concurrent writer bumps it, the server returns a version-conflict
1197
- // error and the user reloads.
1198
- const recordVersion = (record as { version?: number }).version ?? 1;
1199
- const entityDefaultCurrency = entity.defaultCurrency ?? "EUR";
1200
- // A money field declaring `currency: { kind: "tenant" }` (fw#2933) resolves
1201
- // its empty-value currency from the tenant-settings config key instead of
1202
- // entityDefaultCurrency — `enabled` keeps the query a no-op for entities
1203
- // without any such field. A record's own stored value (below) always wins
1204
- // over this, regardless of the declaration.
1205
- //
1206
- // Only fields the record itself has no value for need the fetch at all —
1207
- // an already-set tenant-declared field keeps its own stored currency and
1208
- // must never block the form on this query.
1209
- const tenantCurrencyFieldNames = useMemo(
1210
- () =>
1211
- tenantCurrencyMoneyFieldNames(entity.fields).filter(
1212
- (name) => record[name] === null || record[name] === undefined,
1213
- ),
1214
- [entity.fields, record],
1215
- );
1216
- const { overrides: moneyCurrencyOverrides, loading: currencyLoading } = useMoneyCurrencyOverrides(
1217
- entity.fields,
1218
- tenantCurrencyFieldNames,
1219
- entityDefaultCurrency,
1220
- );
1221
- const initial = useMemo(() => {
1222
- const out: Record<string, unknown> = {};
1223
- for (const name of Object.keys(entity.fields)) {
1224
- out[name] =
1225
- record[name] ??
1226
- buildInitialValues(
1227
- { [name]: entity.fields[name] },
1228
- entityDefaultCurrency,
1229
- moneyCurrencyOverrides,
1230
- )[name];
1231
- }
1232
- return out as FormValues;
1233
- }, [entity.fields, entityDefaultCurrency, moneyCurrencyOverrides, record]);
1234
-
1235
- const formSchema = useMemo(() => buildFormSchema(entity, screen), [entity, screen]);
1236
-
1237
- // Extension-Werte (z.B. customFields-jsonb) an extension-sections geben,
1238
- // damit sie beim Edit den Bestand zeigen statt write-only zu sein.
1239
- const extensionInitialValues = useMemo((): Readonly<Record<string, unknown>> | undefined => {
1240
- const cf = record["customFields"];
1241
- return cf !== null && typeof cf === "object" && !Array.isArray(cf)
1242
- ? (cf as Record<string, unknown>)
1243
- : undefined;
1244
- }, [record]);
1245
-
1246
- const writeCommand = entityWriteCommand(schema.featureName, screen.entity, "update");
1247
- const deleteCommand = entityWriteCommand(schema.featureName, screen.entity, "delete");
1248
- const buildPayload = useMemo(
1249
- () =>
1250
- (snap: { readonly changes: Readonly<Record<string, unknown>> }): unknown => ({
1251
- id: entityId,
1252
- version: recordVersion,
1253
- [UPDATE_CHANGES_KEY]: snap.changes,
1254
- }),
1255
- [entityId, recordVersion],
1256
- );
1257
-
1258
- const nav = useNav();
1259
- const appFeatures = useAppFeatures();
1260
- const dispatcher = useDispatcher();
1261
- const t = useTranslation();
1262
- const effectiveTranslate = translate ?? t;
1263
- const navigateToList = useNavigateToListAfter(schema, screen.entity);
1264
- const userRoles = useUserRoles();
1265
- const host = useReturnHost();
1266
- const returnTargetParam = useReturnTarget(screen.id);
1267
- // A singleton stays on its own screen after saving (onSaved/refetch) —
1268
- // returnTo would fight that.
1269
- const returnTarget = screen.singleton === true ? undefined : returnTargetParam;
1270
- const { drawerAction, drawerScreen, drawerInitialValues, openDrawer, closeDrawer } =
1271
- useDrawerAction(schema);
1272
- // Header action buttons (fw entityEdit-actions) — same shape/dispatch
1273
- // pattern as ProjectionDetailBody.headerActions above (the edited record
1274
- // stands in for the "row"), minus the cross-feature defaultEditAction
1275
- // lookup that doesn't apply here (this screen already IS the edit form).
1276
- const buildSectionActions = useCallback(
1277
- (actions: readonly RowAction[]): readonly RenderEditAction[] | undefined =>
1278
- buildRecordActions({
1279
- actions,
1280
- record,
1281
- translate: effectiveTranslate,
1282
- nav,
1283
- host,
1284
- dispatcher,
1285
- openDrawer,
1286
- onWriteSuccess: onReload,
1287
- defaultScreenTargetEntityId: entityId,
1288
- }),
1289
- [record, effectiveTranslate, nav, host, dispatcher, openDrawer, onReload, entityId],
1290
- );
1291
- const headerActions = useMemo(
1292
- (): readonly RenderEditAction[] | undefined => buildSectionActions(screen.actions ?? []),
1293
- [buildSectionActions, screen.actions],
1294
- );
1295
- const handleSubmitted = useCallback(
1296
- (result: SubmitResult<unknown>) => {
1297
- if (!result.isSuccess) return;
1298
- const redirect = screen.redirect;
1299
- if (redirect !== undefined) {
1300
- if (returnToWinsOverRedirect(returnTarget, redirect, schema, appFeatures)) {
1301
- navigateToReturn(nav, returnTarget);
1302
- } else if (typeof redirect === "string") {
1303
- // String form unchanged: navigates without an entityId, same as
1304
- // before the object form existed. The object form resolves like
1305
- // actionForm's — the update handler's success payload usually
1306
- // reports only this record's own id (event-store-executor-write.ts),
1307
- // so a parent FK named by `idFrom` falls back to the already-loaded
1308
- // `record`.
1309
- nav.navigate({ screenId: lastSegment(redirect) });
1310
- } else {
1311
- const { screenId, entityId: targetEntityId } = resolveRedirectTarget(
1312
- redirect,
1313
- result.data,
1314
- schema,
1315
- appFeatures,
1316
- record,
1317
- );
1318
- nav.navigate({
1319
- screenId,
1320
- ...(targetEntityId !== undefined && { entityId: targetEntityId }),
1321
- });
1322
- }
1323
- } else {
1324
- navigateToReturnOr(nav, returnTarget, navigateToList);
1325
- onSaved?.();
1326
- }
1327
- },
1328
- [nav, screen.redirect, schema, appFeatures, record, navigateToList, onSaved, returnTarget],
1329
- );
1330
- const handleCancel = useCallback(
1331
- () => navigateToReturnOr(nav, returnTarget, navigateToList),
1332
- [nav, returnTarget, navigateToList],
1333
- );
1334
- const handleDelete = useCallback(async () => {
1335
- const res = await dispatcher.write(deleteCommand, { id: entityId });
1336
- if (res.isSuccess) {
1337
- // Never return onto the just-deleted record.
1338
- const target = returnTarget?.entityId !== entityId ? returnTarget : undefined;
1339
- navigateToReturnOr(nav, target, navigateToList);
1340
- onDeleted?.();
1341
- }
1342
- }, [dispatcher, deleteCommand, entityId, navigateToList, onDeleted, returnTarget, nav]);
1343
-
1344
- // Never seed a tenant-declared money field with entityDefaultCurrency while
1345
- // its real tenant currency is still in flight (fw#2933) — wait instead. A
1346
- // stored (non-empty) value is unaffected — it never reaches this branch's
1347
- // fallback because `initial` above already prefers `record[name]`.
1348
- if (currencyLoading) {
1349
- return (
1350
- <Banner padded variant="loading" testId="kumiko-screen-loading">
1351
- Loading…
1352
- </Banner>
1353
- );
1354
- }
1355
-
1356
- return (
1357
- <>
1358
- <RenderEdit
1359
- screen={screen}
1360
- entity={entity}
1361
- featureName={schema.featureName}
1362
- initial={initial}
1363
- // Real route id for the extension section (set-value UI): the update
1364
- // form deliberately keeps `id` out of the form values, so the section
1365
- // needs it explicitly — otherwise it renders in create mode.
1366
- entityId={entityId}
1367
- // Stored customFields for the extension section, so editing shows the
1368
- // persisted values instead of behaving write-only.
1369
- extensionInitialValues={extensionInitialValues}
1370
- schema={formSchema}
1371
- writeCommand={writeCommand}
1372
- payloadMode="changes"
1373
- buildPayload={buildPayload}
1374
- serverFieldPathPrefix={`${UPDATE_CHANGES_KEY}.`}
1375
- onSubmit={handleSubmitted}
1376
- // allowDelete:false marks an entity without a CRUD delete (history is
1377
- // kept) — without this gate the button dispatched against an
1378
- // unregistered `<entity>:delete` handler.
1379
- {...(screen.allowDelete !== false && { onDelete: handleDelete })}
1380
- onCancel={handleCancel}
1381
- onReload={() => void onReload()}
1382
- {...(screenFillsHeight(screen) && { fillScreenHeight: true })}
1383
- {...(screen.submitLabel !== undefined && { submitLabel: screen.submitLabel })}
1384
- {...(translate !== undefined && { translate })}
1385
- {...(onCopyLink !== undefined && { onCopyLink })}
1386
- {...(headerActions !== undefined && { actions: headerActions })}
1387
- buildSectionActions={buildSectionActions}
1388
- />
1389
- <DrawerHost
1390
- schema={schema}
1391
- drawerAction={drawerAction}
1392
- drawerScreen={drawerScreen}
1393
- {...(drawerInitialValues !== undefined && { drawerInitialValues })}
1394
- userRoles={userRoles}
1395
- {...(translate !== undefined && { translate })}
1396
- onClose={closeDrawer}
1397
- onSuccess={() => {
1398
- closeDrawer();
1399
- void onReload();
1400
- }}
1401
- />
1402
- </>
1403
- );
1404
- }
1405
-
1406
- // Singleton entities (`singleton: true`, exactly one record per tenant):
1407
- // EntityEditScreen reaches here only without an entityId. Resolve the
1408
- // existing record via list(limit:1) before deciding create vs update —
1409
- // otherwise every visit without an id would create another record.
1410
- function EntityEditSingletonBody({
1411
- schema,
1412
- screen,
1413
- entity,
1414
- translate,
1415
- onCopyLink,
1416
- }: {
1417
- readonly schema: FeatureSchema;
1418
- readonly screen: EntityEditScreenDefinition;
1419
- readonly entity: EntityDefinition;
1420
- readonly translate?: Translate;
1421
- readonly onCopyLink?: () => Promise<void> | void;
1422
- }): ReactNode {
1423
- const { Banner } = usePrimitives();
1424
- const t = useTranslation();
1425
- const effectiveTranslate = translate ?? t;
1426
- const listQn = entityQueryCommand(schema.featureName, screen.entity, "list");
1427
- const listQuery = useQuery<PagedRows>(listQn, { limit: 1 });
1428
-
1429
- if (listQuery.loading && listQuery.data === null) {
1430
- return (
1431
- <Banner padded variant="loading" testId="kumiko-screen-loading">
1432
- Loading…
1433
- </Banner>
1434
- );
1435
- }
1436
- if (listQuery.error) {
1437
- return (
1438
- <Banner padded variant="error" testId="kumiko-screen-error">
1439
- {dispatcherErrorText(listQuery.error, effectiveTranslate)}
1440
- </Banner>
1441
- );
1442
- }
1443
- const rawExistingId = listQuery.data?.rows[0]?.["id"];
1444
- const existingId = typeof rawExistingId === "string" ? rawExistingId : undefined;
1445
- if (existingId !== undefined) {
1446
- return (
1447
- <EntityEditUpdateBody
1448
- schema={schema}
1449
- screen={screen}
1450
- entity={entity}
1451
- entityId={existingId}
1452
- {...(translate !== undefined && { translate })}
1453
- {...(onCopyLink !== undefined && { onCopyLink })}
1454
- autoReloadOnSave
1455
- onDeleted={() => void listQuery.refetch()}
1456
- />
1457
- );
1458
- }
1459
- return (
1460
- <EntityEditCreateOrDisabled
1461
- schema={schema}
1462
- screen={screen}
1463
- entity={entity}
1464
- {...(translate !== undefined && { translate })}
1465
- onSaved={() => void listQuery.refetch()}
1466
- />
1467
- );
1468
- }
1469
-
1470
- // Shared no-entityId tail for both the plain create path and the
1471
- // singleton path's empty-table fallback: `allowCreate: false` blocks
1472
- // both the same way, since a create submit there would hit an
1473
- // unregistered `<entity>:create` handler.
1474
- function EntityEditCreateOrDisabled({
1475
- schema,
1476
- screen,
1477
- entity,
1478
- translate,
1479
- onSaved,
1480
- }: {
1481
- readonly schema: FeatureSchema;
1482
- readonly screen: EntityEditScreenDefinition;
1483
- readonly entity: EntityDefinition;
1484
- readonly translate?: Translate;
1485
- readonly onSaved?: () => void;
1486
- }): ReactNode {
1487
- const { Banner, Text } = usePrimitives();
1488
- if (screen.allowCreate === false) {
1489
- return (
1490
- <Banner padded variant="error" testId="kumiko-screen-create-disabled">
1491
- Screen <Text variant="code">{screen.id}</Text> is update-only (allowCreate: false) — open it
1492
- from a row action with an entity id.
1493
- </Banner>
1494
- );
1495
- }
1496
- return (
1497
- <EntityEditCreateBody
1498
- schema={schema}
1499
- screen={screen}
1500
- entity={entity}
1501
- {...(translate !== undefined && { translate })}
1502
- {...(onSaved !== undefined && { onSaved })}
1503
- />
1504
- );
1505
- }
1506
-
1507
- // ---- entity-list ----
1508
-
1509
- function entityQueryCommand(featureName: string, entity: string, verb: "list"): string {
1510
- return `${toKebab(featureName)}:query:${toKebab(entity)}:${verb}`;
1511
- }
1512
-
1513
- // Server-side entity-query-handlers return the paged envelope
1514
- // `{ rows, nextCursor, total? }`. Narrow the useQuery generic to that
1515
- // shape so RenderList gets plain rows. `total` ist optional — Server
1516
- // liefert es nur wenn der Caller `totalCount: true` setzt.
1517
- type PagedRows = {
1518
- readonly rows: Readonly<Record<string, unknown>>[];
1519
- readonly nextCursor: string | null;
1520
- readonly total?: number;
1521
- };
1522
-
1523
- // Payload for the server-side list query handler (LIST_PAYLOAD_SCHEMA):
1524
- // search/sort/sortDirection/limit + offset/totalCount for pager mode OR
1525
- // cursor for infinite scroll. Shared by EntityListBody and
1526
- // ProjectionListBody so the two branches can't drift on this shape
1527
- // (fw#2165) — entity-only additions (screen.filter, faceted filters) are
1528
- // layered on top by the caller instead of living in here.
1529
- export function buildListQueryPayload(state: {
1530
- readonly limit: number;
1531
- readonly search: string;
1532
- readonly sort: ListSort | null;
1533
- readonly usePager: boolean;
1534
- readonly page: number;
1535
- readonly useInfinite: boolean;
1536
- readonly cursor: string | undefined;
1537
- }): Record<string, unknown> {
1538
- const payload: Record<string, unknown> = { limit: state.limit };
1539
- if (state.search !== "") payload["search"] = state.search;
1540
- if (state.sort !== null) {
1541
- payload["sort"] = state.sort.field;
1542
- payload["sortDirection"] = state.sort.dir;
1543
- }
1544
- if (state.usePager) {
1545
- // page=1 → offset=0, page=2 → offset=limit, etc. Server clamps itself
1546
- // when offset >= total.
1547
- const offset = (state.page - 1) * state.limit;
1548
- if (offset > 0) payload["offset"] = offset;
1549
- // totalCount: extra COUNT(*) so the pager can render "Page X of Y".
1550
- payload["totalCount"] = true;
1551
- } else if (state.useInfinite && state.cursor !== undefined) {
1552
- payload["cursor"] = state.cursor;
1553
- }
1554
- return payload;
1555
- }
1556
-
1557
- // entityList adapter — one DataTableFacet per filterable select/boolean
1558
- // entity field, labels via the standard field/option i18n convention.
1559
- function resolveEntityFacetSpecs(
1560
- fields: Readonly<Record<string, unknown>>,
1561
- featureName: string,
1562
- entityName: string,
1563
- translate: Translate,
1564
- ): ResolvedFacetSpec[] {
1565
- const out: ResolvedFacetSpec[] = [];
1566
- for (const [field, rawDef] of Object.entries(fields)) {
1567
- // entity.fields ist am Renderer-Layer schwach getypt (Record<string,
1568
- // unknown>, vom Schema deserialisiert) — Boundary-Cast wie buildInitialValues.
1569
- const def = rawDef as {
1570
- type?: string;
1571
- filterable?: boolean;
1572
- options?: readonly string[];
1573
- entity?: string;
1574
- labelField?: string;
1575
- };
1576
- if (def.filterable !== true) continue;
1577
- const label = translate(fieldLabelKey(featureName, entityName, field));
1578
- if (def.type === "select" && Array.isArray(def.options)) {
1579
- out.push({
1580
- field,
1581
- type: "select",
1582
- label,
1583
- options: def.options.map((value) => ({
1584
- value,
1585
- label: translate(fieldOptionLabelKey(featureName, entityName, field, value)),
1586
- })),
1587
- });
1588
- } else if (def.type === "boolean") {
1589
- out.push({
1590
- field,
1591
- type: "boolean",
1592
- label,
1593
- options: [
1594
- {
1595
- value: "true",
1596
- label: translate(fieldOptionLabelKey(featureName, entityName, field, "true")),
1597
- },
1598
- {
1599
- value: "false",
1600
- label: translate(fieldOptionLabelKey(featureName, entityName, field, "false")),
1601
- },
1602
- ],
1603
- });
1604
- } else if (def.type === "reference" && def.entity !== undefined) {
1605
- const target = parseRefTarget(def.entity, featureName);
1606
- out.push({
1607
- field,
1608
- type: "reference",
1609
- label,
1610
- options: [],
1611
- reference: {
1612
- refEntity: target.entityName,
1613
- refFeature: target.featureName,
1614
- labelField: def.labelField ?? "id",
1615
- },
1616
- });
1617
- }
1618
- }
1619
- return out;
1620
- }
1621
-
1622
- // ---- drawer-kind actions: ToolbarAction (fw#2225) + RowAction (fw#2710) ----
1623
- //
1624
- // Shared across EntityListBody, ProjectionListBody, ProjectionDetailBody and
1625
- // EntityEditUpdateForm: state for "which drawer-kind action is currently
1626
- // open" plus a host component that mounts the referenced actionForm inside
1627
- // the Drawer primitive. Reuses ActionFormBody (no second, parallel form
1628
- // renderer) with onSuccess/onCancelOverride so submit-success closes the
1629
- // drawer + refetches the host screen instead of navigating, mirroring what
1630
- // a full-page actionForm would do via `redirect`. The only difference
1631
- // between the toolbar and row variants is prefill: a row action extracts
1632
- // `initialValues` from the clicked row (see buildProjectionRowActions /
1633
- // EntityListBody's rowActions builder); the toolbar variant has none.
1634
- type DrawerLikeAction = Extract<ToolbarAction, { kind: "drawer" }> | RowActionDrawer;
1635
-
1636
- function useDrawerAction(schema: FeatureSchema): {
1637
- readonly drawerAction: DrawerLikeAction | null;
1638
- readonly drawerScreen: ActionFormScreenDefinition | undefined;
1639
- readonly drawerInitialValues: Readonly<Record<string, unknown>> | undefined;
1640
- readonly openDrawer: (
1641
- action: DrawerLikeAction,
1642
- initialValues?: Readonly<Record<string, unknown>>,
1643
- ) => void;
1644
- readonly closeDrawer: () => void;
1645
- } {
1646
- const [drawerState, setDrawerState] = useState<{
1647
- readonly action: DrawerLikeAction;
1648
- readonly initialValues: Readonly<Record<string, unknown>> | undefined;
1649
- } | null>(null);
1650
- const drawerAction = drawerState?.action ?? null;
1651
- const drawerScreen = useMemo(() => {
1652
- if (drawerAction === null) return undefined;
1653
- // Same same-feature, short-id resolution as runNavigate — the drawer's
1654
- // `screen` reference is scoped to schema.screens, not cross-feature.
1655
- return schema.screens.find(
1656
- (s): s is ActionFormScreenDefinition =>
1657
- s.type === "actionForm" && lastSegment(s.id) === drawerAction.screen,
1658
- );
1659
- }, [drawerAction, schema.screens]);
1660
- const openDrawer = useCallback(
1661
- (action: DrawerLikeAction, initialValues?: Readonly<Record<string, unknown>>) =>
1662
- setDrawerState({ action, initialValues }),
1663
- [],
1664
- );
1665
- const closeDrawer = useCallback(() => setDrawerState(null), []);
1666
- return {
1667
- drawerAction,
1668
- drawerScreen,
1669
- drawerInitialValues: drawerState?.initialValues,
1670
- openDrawer,
1671
- closeDrawer,
1672
- };
1673
- }
1674
-
1675
- function DrawerHost({
1676
- schema,
1677
- drawerAction,
1678
- drawerScreen,
1679
- drawerInitialValues,
1680
- userRoles,
1681
- translate,
1682
- onClose,
1683
- onSuccess,
1684
- }: {
1685
- readonly schema: FeatureSchema;
1686
- readonly drawerAction: DrawerLikeAction | null;
1687
- readonly drawerScreen: ActionFormScreenDefinition | undefined;
1688
- readonly drawerInitialValues?: Readonly<Record<string, unknown>>;
1689
- readonly userRoles: readonly string[] | undefined;
1690
- readonly translate?: Translate;
1691
- readonly onClose: () => void;
1692
- readonly onSuccess: () => void;
1693
- }): ReactNode {
1694
- const { Drawer, Banner, Text, Dialog } = usePrimitives();
1695
- const t = useTranslation();
1696
- const effectiveTranslate = translate ?? t;
1697
- const [hasUnsavedInput, setHasUnsavedInput] = useState(false);
1698
- const [confirmDiscardOpen, setConfirmDiscardOpen] = useState(false);
1699
- const closeAndReset = useCallback(() => {
1700
- setHasUnsavedInput(false);
1701
- setConfirmDiscardOpen(false);
1702
- onClose();
1703
- }, [onClose]);
1704
- const requestClose = useCallback(() => {
1705
- if (hasUnsavedInput) setConfirmDiscardOpen(true);
1706
- else closeAndReset();
1707
- }, [hasUnsavedInput, closeAndReset]);
1708
- // Drawer is an optional Core-Primitive (additive rollout) — same "skip +
1709
- // warn once" precedent as rowActions without a mounted DispatcherProvider
1710
- // above, instead of crashing when a web app hasn't upgraded its
1711
- // createKumikoApp wiring yet.
1712
- useEffect(() => {
1713
- if (drawerAction !== null && Drawer === undefined) {
1714
- // biome-ignore lint/suspicious/noConsole: dev-warning for a setup error
1715
- console.warn(
1716
- `[kumiko] toolbarAction "${drawerAction.id}" is kind:"drawer", but no <Drawer> primitive is registered — it will not open. createKumikoApp() from kumiko-renderer-web wires it automatically.`,
1717
- );
1718
- }
1719
- }, [drawerAction, Drawer]);
1720
-
1721
- if (drawerAction === null || Drawer === undefined) return null;
1722
-
1723
- // Access mirrors kind:"navigate" exactly: the toolbar button itself stays
1724
- // visible either way (same as navigate — access is enforced at the
1725
- // target, not by hiding the trigger), but the drawer shows the same
1726
- // "Access denied" state KumikoScreen's top-level gate would show for a
1727
- // direct hit on that screen, never the form.
1728
- const allowed = screenAccessAllows(drawerScreen?.access, userRoles);
1729
-
1730
- return (
1731
- <>
1732
- <Drawer
1733
- open={true}
1734
- onOpenChange={(open) => {
1735
- if (!open) requestClose();
1736
- }}
1737
- title={effectiveTranslate(drawerAction.label)}
1738
- testId={`toolbar-drawer-${drawerAction.id}`}
1739
- >
1740
- <PageHeaderSlotAvailableProvider value={false}>
1741
- <InsideDrawerProvider value={true}>
1742
- {drawerScreen === undefined ? (
1743
- <Banner padded variant="error" testId="kumiko-toolbar-drawer-not-found">
1744
- Screen not found: <Text variant="code">{drawerAction.screen}</Text>
1745
- </Banner>
1746
- ) : !allowed ? (
1747
- <Banner padded variant="error" testId="kumiko-toolbar-drawer-access-denied">
1748
- Access denied: <Text variant="code">{drawerAction.screen}</Text>
1749
- </Banner>
1750
- ) : (
1751
- <ActionFormBody
1752
- schema={schema}
1753
- screen={drawerScreen}
1754
- {...(translate !== undefined && { translate })}
1755
- {...(drawerInitialValues !== undefined && {
1756
- initialOverrides: drawerInitialValues,
1757
- })}
1758
- onSuccess={() => {
1759
- setHasUnsavedInput(false);
1760
- onSuccess();
1761
- }}
1762
- onCancelOverride={requestClose}
1763
- onDirtyChange={setHasUnsavedInput}
1764
- submitLabelFallback={drawerAction.label}
1765
- />
1766
- )}
1767
- </InsideDrawerProvider>
1768
- </PageHeaderSlotAvailableProvider>
1769
- </Drawer>
1770
- <Dialog
1771
- open={confirmDiscardOpen}
1772
- onOpenChange={setConfirmDiscardOpen}
1773
- title={t("kumiko.drawer.discard.title")}
1774
- description={t("kumiko.drawer.discard.body")}
1775
- confirmLabel={t("kumiko.drawer.discard.confirm")}
1776
- cancelLabel={t("kumiko.drawer.discard.cancel")}
1777
- variant="danger"
1778
- initialFocus="cancel"
1779
- onConfirm={closeAndReset}
1780
- testId="drawer-discard-dialog"
1781
- />
1782
- </>
1783
- );
1784
- }
1785
-
1786
- function EntityListScreen({
1787
- schema,
1788
- screen,
1789
- translate,
1790
- onRowClick,
1791
- }: {
1792
- readonly schema: FeatureSchema;
1793
- readonly screen: EntityListScreenDefinition;
1794
- readonly translate?: Translate;
1795
- readonly onRowClick?: (row: ListRowViewModel, entityName: string) => void;
1796
- }): ReactNode {
1797
- const { Banner, Text } = usePrimitives();
1798
- const entity = schema.entities[screen.entity];
1799
- if (!entity) {
1800
- return (
1801
- <Banner padded variant="error" testId="kumiko-screen-entity-missing">
1802
- Entity <Text variant="code">{screen.entity}</Text> referenced by screen{" "}
1803
- <Text variant="code">{screen.id}</Text> not registered in the schema.
1804
- </Banner>
1805
- );
1806
- }
1807
- // Entity resolved — mount the inner component so useQuery only fires
1808
- // when there's actually something to render. A missing entity is a
1809
- // dev-error state; no point hitting the server for it.
1810
- return (
1811
- <EntityListBody
1812
- schema={schema}
1813
- screen={screen}
1814
- entity={entity}
1815
- {...(translate !== undefined && { translate })}
1816
- {...(onRowClick !== undefined && { onRowClick })}
1817
- />
1818
- );
1819
- }
1820
-
1821
- function EntityListBody({
1822
- schema,
1823
- screen,
1824
- entity,
1825
- translate,
1826
- onRowClick,
1827
- }: {
1828
- readonly schema: FeatureSchema;
1829
- readonly screen: EntityListScreenDefinition;
1830
- readonly entity: EntityDefinition;
1831
- readonly translate?: Translate;
1832
- readonly onRowClick?: (row: ListRowViewModel, entityName: string) => void;
1833
- }): ReactNode {
1834
- const featureName = schema.featureName;
1835
- const onCreate = useNavigateToCreateFor(schema, screen.entity);
1836
- const { Banner } = usePrimitives();
1837
- const queryType = entityQueryCommand(featureName, screen.entity, "list");
1838
- const nav = useNav();
1839
- const host = useReturnHost();
1840
- const userRoles = useUserRoles();
1841
- const appFeatures = useAppFeatures();
1842
- const { drawerAction, drawerScreen, drawerInitialValues, openDrawer, closeDrawer } =
1843
- useDrawerAction(schema);
1844
- const defaultEditScreen = useMemo(
1845
- () => findEditScreenFor(screen.entity, appFeatures, userRoles),
1846
- [appFeatures, screen.entity, userRoles],
1847
- );
1848
-
1849
- // URL-State: sort/dir/q/page leben unter dem screen.id-Namespace
1850
- // (`/orders?orders.sort=createdAt&orders.dir=desc&orders.q=acme`),
1851
- // damit zwei Lists auf derselben Route nicht über dieselben
1852
- // Query-Keys streiten. Default-Sort aus der Screen-Def gewinnt nur
1853
- // wenn URL keinen sort hat — Author-Default vs User-Choice.
1854
- const urlState = useListUrlState(screen.id);
1855
- const effectiveSort = urlState.sort ?? screen.defaultSort ?? null;
1856
- const limit = urlState.pageSize ?? screen.pageSize ?? 50;
1857
- const paginationMode = screen.pagination ?? "pages";
1858
- const usePager = paginationMode === "pages";
1859
- const useInfinite = paginationMode === "infinite";
1860
-
1861
- // Infinite-Scroll: lokaler State akkumuliert rows über mehrere
1862
- // useQuery-Aufrufe (statt replacen wie bei Pager). cursor wechselt
1863
- // wenn der User den Bottom-Sentinel erreicht; bei sort/q-Change
1864
- // resetten wir alles, da die Insert-Order der akkumulierten Rows
1865
- // sonst inkonsistent ist mit der neuen Sortierung.
1866
- const [accumulated, setAccumulated] = useState<readonly Readonly<Record<string, unknown>>[]>([]);
1867
- const [cursor, setCursor] = useState<string | undefined>(undefined);
1868
- const [hasMore, setHasMore] = useState(true);
1869
- // Ref damit der useEffect-Cleanup nicht alten state sieht.
1870
- const sortQRef = useRef<string>("");
1871
- const sortQKey = `${urlState.q}|${effectiveSort?.field ?? ""}|${effectiveSort?.dir ?? ""}`;
1872
- // Bei sort/q-Wechsel rows + cursor reseten — vor dem nächsten useQuery
1873
- // damit der Reload mit cursor=undefined startet.
1874
- useEffect(() => {
1875
- if (!useInfinite) return;
1876
- if (sortQRef.current === sortQKey) return;
1877
- sortQRef.current = sortQKey;
1878
- setAccumulated([]);
1879
- setCursor(undefined);
1880
- setHasMore(true);
1881
- }, [useInfinite, sortQKey]);
1882
-
1883
- // User-gewählte Faceted-Filter aus dem URL-State → payload.filters.
1884
- // typeOf liest den Field-Type direkt aus entity.fields (nicht gated auf
1885
- // filterable — bewusst permissiv, siehe buildFilterPayload-Doc).
1886
- const filterPayload = useMemo(
1887
- () =>
1888
- buildFilterPayload(urlState.filters, (field) => {
1889
- // entity.fields ist am Renderer-Layer schwach getypt (vom Schema
1890
- // deserialisiert) — Boundary-Cast wie buildInitialValues.
1891
- const def = entity.fields[field] as { type?: string } | undefined;
1892
- return def?.type;
1893
- }),
1894
- [urlState.filters, entity.fields],
1895
- );
1896
-
1897
- // Entity-only additions (screen.filter, faceted filters) layer on top of
1898
- // the shared buildListQueryPayload — projectionList has neither.
1899
- const queryPayload = useMemo(() => {
1900
- const payload = buildListQueryPayload({
1901
- limit,
1902
- search: urlState.q,
1903
- sort: effectiveSort,
1904
- usePager,
1905
- page: urlState.page,
1906
- useInfinite,
1907
- cursor,
1908
- });
1909
- // Screen-Filter (Tier 2.7c) — vom Author am Schema deklariert,
1910
- // unabhängig vom User-q-Search. Mehrere Buckets derselben Entity
1911
- // ("Upcoming" / "Active" / "Past") nutzen unterschiedliche filter
1912
- // bei gleichem Query-Handler.
1913
- if (screen.filter !== undefined) {
1914
- payload["filter"] = screen.filter;
1915
- }
1916
- if (filterPayload.length > 0) {
1917
- payload["filters"] = filterPayload;
1918
- }
1919
- return payload;
1920
- }, [
1921
- limit,
1922
- urlState.q,
1923
- effectiveSort,
1924
- screen.filter,
1925
- filterPayload,
1926
- usePager,
1927
- urlState.page,
1928
- useInfinite,
1929
- cursor,
1930
- ]);
1931
-
1932
- const rowsQuery = useQuery<PagedRows>(queryType, queryPayload, { live: true });
1933
-
1934
- const refreshRowsAfterWrite = useCallback(async () => {
1935
- if (useInfinite) {
1936
- setAccumulated([]);
1937
- setCursor(undefined);
1938
- setHasMore(true);
1939
- return;
1940
- }
1941
- await refetchAfterWrite(rowsQuery.refetch);
1942
- }, [useInfinite, rowsQuery.refetch]);
1943
-
1944
- // Infinite-Scroll: bei jedem erfolgreichen Result die rows appenden +
1945
- // hasMore aus nextCursor ableiten. Live-Updates (postgres NOTIFY) und
1946
- // initiale Loads laufen beide hier durch — das useEffect-Dep-Array
1947
- // pinnt die Dedup auf dem letzten verarbeiteten data-Pointer.
1948
- const lastDataRef = useRef<PagedRows | null>(null);
1949
- useEffect(() => {
1950
- if (!useInfinite) return;
1951
- const data = rowsQuery.data;
1952
- if (data === null) return;
1953
- if (data === lastDataRef.current) return;
1954
- lastDataRef.current = data;
1955
- setAccumulated((prev) => {
1956
- // Wenn cursor undefined ist, ist das die erste Page nach
1957
- // sort/q-Change → komplett ersetzen statt anhängen. Sonst dedupe
1958
- // auf id falls Live-Updates einen Eintrag in der nächsten Page
1959
- // bringen die schon angehängt war.
1960
- if (cursor === undefined) return data.rows;
1961
- const seen = new Set(prev.map((r) => r["id"] as string));
1962
- const fresh = data.rows.filter((r) => !seen.has(r["id"] as string));
1963
- return [...prev, ...fresh];
1964
- });
1965
- setHasMore(data.nextCursor !== null);
1966
- }, [rowsQuery.data, useInfinite, cursor]);
1967
-
1968
- const loadMore = useCallback(() => {
1969
- if (!useInfinite) return;
1970
- if (rowsQuery.loading) return;
1971
- const data = rowsQuery.data;
1972
- if (data?.nextCursor === undefined || data.nextCursor === null) return;
1973
- setCursor(data.nextCursor);
1974
- }, [useInfinite, rowsQuery.loading, rowsQuery.data]);
1975
-
1976
- // RowActions: Schema-Form (handler-QN + i18n-Key) → Resolved-Form
1977
- // (dispatcher-Call + translated Strings). dispatcher.write kennt den
1978
- // User intern (JWT-Cookie). Schema kann sowohl raw-Strings als auch
1979
- // i18n-Keys enthalten — translate() returnt den Key wenn das Bundle
1980
- // ihn nicht kennt (Convention überall im Renderer).
1981
- // Hooks-Reihenfolge: ALLE Hooks vor early-return für loading/error,
1982
- // sonst kollidieren die Hook-Slots zwischen Renders.
1983
- const t = useTranslation();
1984
- const effectiveTranslate = translate ?? t;
1985
-
1986
- // Faceted-Filter: ein Dropdown pro filterable select/boolean/reference-Feld.
1987
- // Labels + select-Option-Labels über dieselbe i18n-Konvention wie die
1988
- // Spalten-Header (fieldLabelKey / :option:<value>); reference-Felder laden
1989
- // ihre Optionen asynchron über ReferenceFacetBridges.
1990
- const entityFacetSpecs = useMemo(
1991
- () => resolveEntityFacetSpecs(entity.fields, featureName, screen.entity, effectiveTranslate),
1992
- [entity.fields, featureName, screen.entity, effectiveTranslate],
1993
- );
1994
- const [entityReferenceFacetOptions, setEntityReferenceFacetOptions] = useState<
1995
- Record<string, readonly ReferenceFacetOption[]>
1996
- >({});
1997
- const handleEntityFacetOptions = useCallback(
1998
- (field: string, options: readonly ReferenceFacetOption[]) =>
1999
- setEntityReferenceFacetOptions((prev) =>
2000
- prev[field] === options ? prev : { ...prev, [field]: options },
2001
- ),
2002
- [],
2003
- );
2004
- const filterFacets = useMemo<DataTableFacet[]>(
2005
- () =>
2006
- buildFilterFacets(mergeReferenceFacetOptions(entityFacetSpecs, entityReferenceFacetOptions)),
2007
- [entityFacetSpecs, entityReferenceFacetOptions],
2008
- );
2009
-
2010
- // Soft-Dispatcher: in Tests die ohne DispatcherProvider mounten,
2011
- // bleibt rowActions undefined statt zu crashen. Echte Apps haben
2012
- // den Provider via createKumikoApp — wenn nicht, ist es vermutlich
2013
- // ein Setup-Fehler, also einmal warnen damit der Author das findet
2014
- // (sonst rendert die Action-Spalte still nichts und der "warum sind
2015
- // meine Buttons weg?"-Debug ist teuer).
2016
- const dispatcher = useOptionalDispatcher();
2017
- const hasRowActions = screen.rowActions !== undefined && screen.rowActions.length > 0;
2018
- useEffect(() => {
2019
- if (hasRowActions && dispatcher === undefined) {
2020
- // biome-ignore lint/suspicious/noConsole: dev-warning für Setup-Fehler
2021
- console.warn(
2022
- `[kumiko] Screen "${screen.id}" deklariert rowActions, aber kein <DispatcherProvider> ist mounted — die Action-Spalte wird nicht gerendert. createKumikoApp() wired den Provider automatisch.`,
2023
- );
2024
- }
2025
- }, [hasRowActions, dispatcher, screen.id]);
2026
- // Discriminated Union: writeHandler (default) dispatched einen Server-
2027
- // Handler, navigate ruft nav.navigate() ggf. mit URL-Search-Params aus
2028
- // params(row). nav lebt schon weiter unten in EntityListBody-Scope.
2029
- // Gemeinsame navigate-Ausführung: sowohl das "…"-Aktionsmenü (rowActions) als
2030
- // auch der Row-Body-Klick (rowClick) laufen hierdurch — ein Pfad, damit beide
2031
- // nicht auseinanderdriften.
2032
- const runNavigate = useCallback(
2033
- (action: RowActionNavigate, row: ListRowViewModel) => {
2034
- if (action.entity !== undefined) {
2035
- // Entity-Targets (fw#2228) lösen sich erst in der NavApi-Impl gegen
2036
- // ALLE Features auf (resolveTarget in renderer-web/nav.tsx) — dieses
2037
- // Package kennt nur `schema` (das eine aufrufende Feature) und kann
2038
- // detailFor cross-feature nicht selbst nachschlagen.
2039
- const explicit =
2040
- action.entityId !== undefined ? String(row.values[action.entityId] ?? "") : undefined;
2041
- // Same-entity only — cross-entity targets must declare entityId (boot-validator).
2042
- const fallback =
2043
- action.entity === screen.entity ? String(row.values["id"] ?? "") : undefined;
2044
- const id = explicit ?? fallback ?? "";
2045
- if (id === "") return;
2046
- const params = navigateActionSearchParams(action, row.values);
2047
- navigateWithReturnTo(nav, { entity: action.entity, id }, host, params);
2048
- } else if (action.screen !== undefined) {
2049
- // Default entityId für entityEdit-Targets: row["id"] wenn kein expliziter
2050
- // entityId-Feldname gesetzt ist. Nur für Targets DERSELBEN Entity — sonst
2051
- // bekäme ein Cross-Entity-Edit-Screen die falsche row.id injiziert.
2052
- const targetIsEntityEdit = schema.screens.some(
2053
- (s) =>
2054
- s.type === "entityEdit" &&
2055
- s.entity === screen.entity &&
2056
- lastSegment(s.id) === action.screen,
2057
- );
2058
- const explicit =
2059
- action.entityId !== undefined ? String(row.values[action.entityId] ?? "") : undefined;
2060
- const fallback = targetIsEntityEdit ? String(row.values["id"] ?? "") : undefined;
2061
- const entityId = explicit ?? fallback;
2062
- const target: ScreenTarget = {
2063
- screenId: action.screen,
2064
- ...(entityId !== undefined && entityId !== "" && { entityId }),
2065
- };
2066
- // setSearchParams nimmt string|null — komplexe Werte zu String (der Reader
2067
- // kennt via URL nur Strings). Known-edge: zielt die Action auf den
2068
- // AKTUELLEN pathname, mergen die Params auf den alten ?-String (für
2069
- // Row-Actions praktisch nicht erreichbar, Pfad differiert).
2070
- const params = navigateActionSearchParams(action, row.values);
2071
- navigateWithReturnTo(nav, target, host, params);
2072
- }
2073
- },
2074
- [nav, schema.screens, screen.entity, host],
2075
- );
2076
-
2077
- const rowActions = useMemo(() => {
2078
- const declared = screen.rowActions ?? [];
2079
- // Prepended unless a declared rowAction already has id "edit" — declared wins.
2080
- const declaredHasEdit = declared.some((a) => a.id === "edit");
2081
- const defaultEditRowAction = declaredHasEdit
2082
- ? undefined
2083
- : buildDefaultEditRowAction(defaultEditScreen);
2084
- const effectiveActions: readonly RowAction[] =
2085
- defaultEditRowAction !== undefined ? [defaultEditRowAction, ...declared] : declared;
2086
- if (effectiveActions.length === 0) return undefined;
2087
- return effectiveActions
2088
- .map((action: RowAction): DataTableRowAction | null => {
2089
- // navigate-Variante braucht keinen Dispatcher; nav ist
2090
- // immer da (Provider von createKumikoApp).
2091
- if (action.kind === "navigate") {
2092
- const navigateAction = action;
2093
- const actionVisible = action.visible;
2094
- const actionIcon = resolveActionIcon(action.id, action.icon);
2095
- return {
2096
- id: action.id,
2097
- label: effectiveTranslate(action.label),
2098
- ...(action.style !== undefined && { style: action.style }),
2099
- confirmRequired: false,
2100
- ...(navigateAction.rowClick === true && { rowClick: true }),
2101
- ...(actionIcon !== undefined && { icon: actionIcon }),
2102
- onTrigger: (row: ListRowViewModel) => runNavigate(navigateAction, row),
2103
- ...(actionVisible !== undefined && {
2104
- isVisible: (row: ListRowViewModel) => evalFieldCondition(actionVisible, row.values),
2105
- }),
2106
- };
2107
- }
2108
- if (action.kind === "drawer") {
2109
- const drawerAction = action;
2110
- const actionVisible = action.visible;
2111
- const actionIcon = resolveActionIcon(action.id, action.icon);
2112
- return {
2113
- id: action.id,
2114
- label: effectiveTranslate(action.label),
2115
- ...(action.style !== undefined && { style: action.style }),
2116
- confirmRequired: false,
2117
- ...(actionIcon !== undefined && { icon: actionIcon }),
2118
- onTrigger: (row: ListRowViewModel) => {
2119
- const initialValues =
2120
- drawerAction.params !== undefined
2121
- ? evalRowExtractor(drawerAction.params, row.values)
2122
- : undefined;
2123
- openDrawer(drawerAction, initialValues);
2124
- },
2125
- ...(actionVisible !== undefined && {
2126
- isVisible: (row: ListRowViewModel) => evalFieldCondition(actionVisible, row.values),
2127
- }),
2128
- };
2129
- }
2130
- if (dispatcher === undefined) return null;
2131
- if (!isWriteHandlerRowAction(action)) return null;
2132
- const writeAction = action;
2133
- const writeActionVisible = writeAction.visible;
2134
- return {
2135
- id: writeAction.id,
2136
- label: effectiveTranslate(writeAction.label),
2137
- style: writeAction.style,
2138
- icon: resolveActionIcon(writeAction.id, writeAction.icon),
2139
- confirm:
2140
- writeAction.confirm !== undefined ? effectiveTranslate(writeAction.confirm) : undefined,
2141
- confirmLabel:
2142
- writeAction.confirmLabel !== undefined
2143
- ? effectiveTranslate(writeAction.confirmLabel)
2144
- : undefined,
2145
- onTrigger: async (row: ListRowViewModel) => {
2146
- const buildPayload = writeAction.payload;
2147
- const payload =
2148
- buildPayload !== undefined
2149
- ? evalRowExtractor(buildPayload, row.values)
2150
- : { id: row.values["id"] };
2151
- const result = await dispatcher.write(writeAction.handler, payload);
2152
- // write() wirft nicht — Failure-Result MUSS hier zum Error
2153
- // werden, sonst schließt der Confirm-Dialog kommentarlos und
2154
- // der User sieht "nichts passiert" (Prod-Bug 2026-06-07).
2155
- if (!result.isSuccess) {
2156
- throw new WriteFailedError(
2157
- result.error,
2158
- dispatcherErrorText(result.error, effectiveTranslate),
2159
- );
2160
- }
2161
- await refreshRowsAfterWrite();
2162
- },
2163
- isVisible:
2164
- writeActionVisible !== undefined
2165
- ? (row: ListRowViewModel) => evalFieldCondition(writeActionVisible, row.values)
2166
- : undefined,
2167
- };
2168
- })
2169
- .filter((a: DataTableRowAction | null): a is DataTableRowAction => a !== null);
2170
- }, [
2171
- screen.rowActions,
2172
- defaultEditScreen,
2173
- effectiveTranslate,
2174
- dispatcher,
2175
- runNavigate,
2176
- refreshRowsAfterWrite,
2177
- openDrawer,
2178
- ]);
2179
-
2180
- // ToolbarActions: Schema → Resolved-Form (analog rowActions), shared with
2181
- // projectionList and relatedList sections via buildProjectionToolbarActions.
2182
- const toolbarActions = useMemo(
2183
- () =>
2184
- buildProjectionToolbarActions({
2185
- toolbarActions: screen.toolbarActions,
2186
- translate: effectiveTranslate,
2187
- dispatcher,
2188
- nav,
2189
- refetch: refreshRowsAfterWrite,
2190
- openDrawer,
2191
- host,
2192
- }),
2193
- [
2194
- screen.toolbarActions,
2195
- effectiveTranslate,
2196
- nav,
2197
- host,
2198
- dispatcher,
2199
- refreshRowsAfterWrite,
2200
- openDrawer,
2201
- ],
2202
- );
2203
-
2204
- if (rowsQuery.loading && rowsQuery.data === null) {
2205
- return (
2206
- <Banner padded variant="loading" testId="kumiko-screen-loading">
2207
- Loading…
2208
- </Banner>
2209
- );
2210
- }
2211
- if (rowsQuery.error) {
2212
- return (
2213
- <Banner padded variant="error" testId="kumiko-screen-error">
2214
- {dispatcherErrorText(rowsQuery.error, effectiveTranslate)}
2215
- </Banner>
2216
- );
2217
- }
2218
-
2219
- // RenderList's onRowClick is a 1-arg callback; KumikoScreen's
2220
- // 2-arg shape (row, entityName) is the public surface — thread the
2221
- // screen's entity through here so callers don't have to re-derive
2222
- // it.
2223
- // Row-Body-Klick: eine explizit als rowClick markierte navigate-rowAction
2224
- // gewinnt (deklarierte Author-Absicht "Klick auf die Zeile tut X"). Ohne Flag
2225
- // bleibt der Pfad unverändert — create-app's entityEdit-Default bzw. ein vom
2226
- // App-Author gesetztes onRowClick.
2227
- const rowClickAction = screen.rowActions?.find(
2228
- (a): a is RowActionNavigate => a.kind === "navigate" && a.rowClick === true,
2229
- );
2230
- const wrappedOnRowClick = rowClickAction
2231
- ? (row: ListRowViewModel) => runNavigate(rowClickAction, row)
2232
- : onRowClick !== undefined
2233
- ? (row: ListRowViewModel) => onRowClick(row, screen.entity)
2234
- : undefined;
2235
-
2236
- // Searchable default: explicit author choice wins, otherwise auto-on when
2237
- // the entity has searchable fields (dead toolbar slot otherwise — the
2238
- // server search index has nothing to filter). Gated on
2239
- // schema.searchAdapterMissing !== true regardless of source (explicit or
2240
- // auto) — a search bar the server can't serve would 422 at request-time
2241
- // (#2032); matches the boot-time check in api/server.ts (#2051).
2242
- const searchable =
2243
- schema.searchAdapterMissing !== true &&
2244
- (screen.searchable ??
2245
- Object.values(entity.fields).some((f) => "searchable" in f && f.searchable === true));
2246
-
2247
- // Pager-Props nur bei pagination="pages" zusammenstellen. Server-
2248
- // total kommt async — bis es da ist, rendert RenderList die Tabelle
2249
- // ohne Pager (Pager hat eine eigene total>0-Guard).
2250
- const total = rowsQuery.data?.total;
2251
- const pager =
2252
- usePager && total !== undefined
2253
- ? {
2254
- page: urlState.page,
2255
- limit,
2256
- total,
2257
- onPageChange: urlState.setPage,
2258
- pageSizeOptions: pageSizeOptionsFor(limit),
2259
- onPageSizeChange: urlState.setPageSize,
2260
- }
2261
- : undefined;
2262
-
2263
- // Bei Infinite-Mode: rows kommen aus accumulated (über mehrere
2264
- // useQuery-Calls gesammelt), bei pages/false aus dem aktuellen Result.
2265
- const renderRows = useInfinite ? accumulated : (rowsQuery.data?.rows ?? []);
2266
-
2267
- return (
2268
- <>
2269
- <ReferenceFacetBridges specs={entityFacetSpecs} onOptions={handleEntityFacetOptions} />
2270
- <RenderList
2271
- screen={screen}
2272
- entity={entity}
2273
- rows={renderRows}
2274
- featureName={featureName}
2275
- searchable={searchable}
2276
- searchValue={urlState.q}
2277
- onSearchChange={urlState.setQ}
2278
- sort={effectiveSort}
2279
- onSortChange={urlState.setSort}
2280
- screenPadding
2281
- {...(screenFillsHeight(screen) && { scrollBody: true })}
2282
- {...(pager !== undefined && { pager })}
2283
- {...(rowActions !== undefined && { rowActions })}
2284
- {...(toolbarActions !== undefined && toolbarActions.length > 0 && { toolbarActions })}
2285
- {...(useInfinite && {
2286
- onReachEnd: loadMore,
2287
- loadingMore: rowsQuery.loading,
2288
- hasMore,
2289
- })}
2290
- {...(onCreate !== undefined && { onCreate })}
2291
- {...(translate !== undefined && { translate })}
2292
- {...(wrappedOnRowClick !== undefined && { onRowClick: wrappedOnRowClick })}
2293
- {...(filterFacets.length > 0 && {
2294
- filterFacets,
2295
- filterValues: urlState.filters,
2296
- onFilterChange: urlState.setFilter,
2297
- onFilterReset: urlState.clearFilters,
2298
- })}
2299
- />
2300
- <DrawerHost
2301
- schema={schema}
2302
- drawerAction={drawerAction}
2303
- drawerScreen={drawerScreen}
2304
- {...(drawerInitialValues !== undefined && { drawerInitialValues })}
2305
- userRoles={userRoles}
2306
- {...(translate !== undefined && { translate })}
2307
- onClose={closeDrawer}
2308
- onSuccess={() => {
2309
- closeDrawer();
2310
- void rowsQuery.refetch();
2311
- }}
2312
- />
2313
- </>
2314
- );
2315
- }
2316
-
2317
- // ---- projection-list ----
2318
-
2319
- // Like entityList, but the list query comes DIRECTLY from `screen.query`
2320
- // (instead of being derived from an entity) — cross-feature capable.
2321
- // search/sort/pagination reuse the same URL-state + buildListQueryPayload
2322
- // wiring as EntityListBody; which of them are actually offered is derived
2323
- // from the query handler's Zod schema at buildAppSchema time (fw#2165), not
2324
- // declared here. Pages-mode pagination only — infinite-scroll accumulation
2325
- // isn't wired for projectionList.
2326
- function ProjectionListBody({
2327
- schema,
2328
- screen,
2329
- translate,
2330
- onRowClick,
2331
- }: {
2332
- readonly schema: FeatureSchema;
2333
- readonly screen: ProjectionListScreenDefinition;
2334
- readonly translate?: Translate;
2335
- readonly onRowClick?: (row: ListRowViewModel, entityName: string) => void;
2336
- }): ReactNode {
2337
- const { Banner, Text } = usePrimitives();
2338
- const t = useTranslation();
2339
- const nav = useNav();
2340
- const host = useReturnHost();
2341
- const dispatcher = useOptionalDispatcher();
2342
- const effectiveTranslate = translate ?? t;
2343
- const userRoles = useUserRoles();
2344
- const appFeatures = useAppFeatures();
2345
- const { drawerAction, drawerScreen, drawerInitialValues, openDrawer, closeDrawer } =
2346
- useDrawerAction(schema);
2347
- const defaultEditScreen = useMemo(() => {
2348
- const detailFor = screen.detailFor;
2349
- if (detailFor === undefined) return undefined;
2350
- return findEditScreenFor(detailFor, appFeatures, userRoles);
2351
- }, [appFeatures, screen.detailFor, userRoles]);
2352
-
2353
- // searchable/sortable/paginated are derived at buildAppSchema time from the
2354
- // query handler's Zod schema (fw#2165) — not authored on the screen.
2355
- const searchable = screen.searchable ?? false;
2356
- const sortable = screen.sortable ?? false;
2357
- const paginated = screen.paginated ?? false;
2358
- const entity = useMemo(
2359
- () => synthesizeProjectionEntity(screen.columns, sortable),
2360
- [screen.columns, sortable],
2361
- );
2362
- const listScreen = useMemo(() => synthesizeProjectionScreen(screen), [screen]);
2363
-
2364
- const urlState = useListUrlState(screen.id);
2365
- // Gated on the derived capability, not just on whether URL-state happens to
2366
- // carry a value — a stale/hand-crafted URL (?…q=x on a non-searchable
2367
- // screen) must not smuggle a param the query's Zod schema doesn't accept.
2368
- const activeSearch = searchable ? urlState.q : "";
2369
- const activeSort = sortable ? (urlState.sort ?? screen.defaultSort ?? null) : null;
2370
- const limit = urlState.pageSize ?? screen.pageSize ?? 50;
2371
- // Pages-mode only (see header comment) — an author-set pagination:
2372
- // "infinite" on a paginated projectionList is silently a no-op today.
2373
- const usePager = paginated && (screen.pagination ?? "pages") === "pages";
2374
-
2375
- // Facets (fw#2224) — a projectionList has no entity, so screen.facets is
2376
- // the only field inventory; resolveProjectionFacetSpecs reshapes +
2377
- // translates its explicit labels into the same ResolvedFacetSpec the
2378
- // entityList adapter produces, so both feed the same
2379
- // buildFilterFacets/buildFilterPayload.
2380
- const facetSpecs = useMemo(
2381
- () => resolveProjectionFacetSpecs(screen.facets, effectiveTranslate, schema.featureName),
2382
- [screen.facets, effectiveTranslate, schema.featureName],
2383
- );
2384
- const [projectionReferenceFacetOptions, setProjectionReferenceFacetOptions] = useState<
2385
- Record<string, readonly ReferenceFacetOption[]>
2386
- >({});
2387
- const handleProjectionFacetOptions = useCallback(
2388
- (field: string, options: readonly ReferenceFacetOption[]) =>
2389
- setProjectionReferenceFacetOptions((prev) =>
2390
- prev[field] === options ? prev : { ...prev, [field]: options },
2391
- ),
2392
- [],
2393
- );
2394
- const resolvedFacetSpecs = useMemo(
2395
- () => mergeReferenceFacetOptions(facetSpecs, projectionReferenceFacetOptions),
2396
- [facetSpecs, projectionReferenceFacetOptions],
2397
- );
2398
- const filterPayload = useMemo(
2399
- () =>
2400
- buildFilterPayload(
2401
- urlState.filters,
2402
- (field) => facetSpecs.find((spec) => spec.field === field)?.type,
2403
- ),
2404
- [urlState.filters, facetSpecs],
2405
- );
2406
-
2407
- // dateRange facets (fw#3104) bypass `filters` entirely — their two bounds
2408
- // become the top-level query params the facet declares, resolved from a
2409
- // calendar date to an instant in the viewer's zone.
2410
- const timeZone = useOptionalTimeZone();
2411
- const dateRangeSpecs = useMemo(
2412
- () => resolveDateRangeFacets(screen.facets, effectiveTranslate),
2413
- [screen.facets, effectiveTranslate],
2414
- );
2415
- const dateRangePayload = useMemo(
2416
- () => buildDateRangePayload(dateRangeSpecs, urlState.filters, timeZone),
2417
- [dateRangeSpecs, urlState.filters, timeZone],
2418
- );
2419
-
2420
- const queryPayload = useMemo(() => {
2421
- const payload = buildListQueryPayload({
2422
- limit,
2423
- search: activeSearch,
2424
- sort: activeSort,
2425
- usePager,
2426
- page: urlState.page,
2427
- useInfinite: false,
2428
- cursor: undefined,
2429
- });
2430
- // Gated on screen.filter/screen.facets being declared (not just on
2431
- // urlState/filterPayload happening to carry a value) — same rule as
2432
- // activeSearch/activeSort above: a stale URL must not smuggle a param
2433
- // the bound query's Zod schema doesn't accept (fw#2165 pattern).
2434
- if (screen.filter !== undefined) {
2435
- payload["filter"] = screen.filter;
2436
- }
2437
- if (screen.facets !== undefined && filterPayload.length > 0) {
2438
- payload["filters"] = filterPayload;
2439
- }
2440
- Object.assign(payload, dateRangePayload);
2441
- return payload;
2442
- }, [
2443
- limit,
2444
- activeSearch,
2445
- activeSort,
2446
- usePager,
2447
- urlState.page,
2448
- screen.filter,
2449
- screen.facets,
2450
- filterPayload,
2451
- dateRangePayload,
2452
- ]);
2453
-
2454
- const rowsQuery = useQuery<PagedRows>(screen.query, queryPayload, { live: true });
2455
-
2456
- const filterFacets = useMemo<DataTableFacet[]>(
2457
- () => buildFilterFacets(resolvedFacetSpecs),
2458
- [resolvedFacetSpecs],
2459
- );
2460
- const dateRangeFacets = useMemo<DataTableDateRangeFacet[]>(
2461
- () =>
2462
- dateRangeSpecs.map((spec) => ({
2463
- field: spec.field,
2464
- label: spec.label,
2465
- ...readDateRange(urlState.filters, spec.field),
2466
- })),
2467
- [dateRangeSpecs, urlState.filters],
2468
- );
2469
- const handleDateRangeChange = useCallback(
2470
- (field: string, bound: "from" | "to", value: string) => {
2471
- urlState.setDateRange(
2472
- field,
2473
- clampDateRange(readDateRange(urlState.filters, field), bound, value),
2474
- );
2475
- },
2476
- [urlState.setDateRange, urlState.filters],
2477
- );
2478
-
2479
- // Entity-Targets (fw#2228) — see EntityListBody.runNavigate for why the
2480
- // resolution happens in the NavApi impl. Unlike there: NO row["id"]
2481
- // fallback — projectionList rows come from an arbitrary query projection
2482
- // with no guaranteed "id" field. The boot validator therefore enforces an
2483
- // explicit entityId for projectionList entity targets. Same helper
2484
- // relatedList's rowActions reuse (related-list-section.tsx) — a
2485
- // projectionDetail relatedList row has the identical "no guaranteed id"
2486
- // shape.
2487
- const runNavigate = useCallback(
2488
- (action: RowActionNavigate, row: ListRowViewModel) =>
2489
- runProjectionRowNavigate(nav, action, row, host),
2490
- [nav, host],
2491
- );
2492
-
2493
- const defaultEditRowAction = useMemo(
2494
- () => buildDefaultEditRowAction(defaultEditScreen),
2495
- [defaultEditScreen],
2496
- );
2497
-
2498
- const rowActions = useMemo(
2499
- () =>
2500
- buildProjectionRowActions({
2501
- rowActions: screen.rowActions,
2502
- translate: effectiveTranslate,
2503
- dispatcher,
2504
- nav,
2505
- refetch: rowsQuery.refetch,
2506
- openDrawer,
2507
- defaultEditRowAction,
2508
- host,
2509
- }),
2510
- [
2511
- screen.rowActions,
2512
- effectiveTranslate,
2513
- dispatcher,
2514
- nav,
2515
- rowsQuery.refetch,
2516
- openDrawer,
2517
- defaultEditRowAction,
2518
- host,
2519
- ],
2520
- );
2521
-
2522
- const toolbarActions = useMemo(
2523
- () =>
2524
- buildProjectionToolbarActions({
2525
- toolbarActions: screen.toolbarActions,
2526
- translate: effectiveTranslate,
2527
- dispatcher,
2528
- nav,
2529
- refetch: rowsQuery.refetch,
2530
- openDrawer,
2531
- host,
2532
- }),
2533
- [
2534
- screen.toolbarActions,
2535
- effectiveTranslate,
2536
- nav,
2537
- host,
2538
- dispatcher,
2539
- rowsQuery.refetch,
2540
- openDrawer,
2541
- ],
2542
- );
2543
-
2544
- if (rowsQuery.loading && rowsQuery.data === null) {
2545
- return (
2546
- <Banner padded variant="loading" testId="kumiko-screen-loading">
2547
- Loading…
2548
- </Banner>
2549
- );
2550
- }
2551
- if (rowsQuery.error) {
2552
- return (
2553
- <Banner padded variant="error" testId="kumiko-screen-error">
2554
- {dispatcherErrorText(rowsQuery.error, effectiveTranslate)}
2555
- </Banner>
2556
- );
2557
- }
2558
-
2559
- // rowsQuery.data is typed as PagedRows but the query handler is free to
2560
- // return anything at runtime (fw#2216: a bare array silently rendered an
2561
- // empty table instead of surfacing the mismatch); a system-boundary cast
2562
- // is needed to inspect the actual wire shape before trusting it.
2563
- const rawRowsData = rowsQuery.data as unknown as { readonly rows?: unknown } | null;
2564
- if (rawRowsData !== null && !Array.isArray(rawRowsData.rows)) {
2565
- return (
2566
- <Banner padded variant="error" testId="kumiko-screen-projection-list-bad-shape">
2567
- Screen <Text variant="code">{screen.id}</Text> query{" "}
2568
- <Text variant="code">{screen.query}</Text> did not return a PagedRows envelope; a
2569
- projectionList query must return <Text variant="code">{"{ rows, nextCursor }"}</Text>.
2570
- </Banner>
2571
- );
2572
- }
2573
-
2574
- const rowClickAction = screen.rowActions?.find(
2575
- (a): a is RowActionNavigate => a.kind === "navigate" && a.rowClick === true,
2576
- );
2577
- const wrappedOnRowClick = rowClickAction
2578
- ? (row: ListRowViewModel) => runNavigate(rowClickAction, row)
2579
- : onRowClick !== undefined
2580
- ? (row: ListRowViewModel) => onRowClick(row, listScreen.entity)
2581
- : undefined;
2582
-
2583
- // Same pager-construction as EntityListBody: no Pager UI until the
2584
- // server-provided `total` arrives (guards pagination="pages" without
2585
- // totalCount support, see fw#2165 report on solon's leaseOverviewHandler).
2586
- const total = rowsQuery.data?.total;
2587
- const pager =
2588
- usePager && total !== undefined
2589
- ? {
2590
- page: urlState.page,
2591
- limit,
2592
- total,
2593
- onPageChange: urlState.setPage,
2594
- pageSizeOptions: pageSizeOptionsFor(limit),
2595
- onPageSizeChange: urlState.setPageSize,
2596
- }
2597
- : undefined;
2598
-
2599
- return (
2600
- <>
2601
- <ReferenceFacetBridges specs={facetSpecs} onOptions={handleProjectionFacetOptions} />
2602
- <RenderList
2603
- screen={listScreen}
2604
- entity={entity}
2605
- rows={rowsQuery.data?.rows ?? []}
2606
- featureName={schema.featureName}
2607
- searchable={searchable}
2608
- searchValue={urlState.q}
2609
- onSearchChange={urlState.setQ}
2610
- sort={activeSort}
2611
- onSortChange={urlState.setSort}
2612
- screenPadding
2613
- {...(screenFillsHeight(listScreen) && { scrollBody: true })}
2614
- {...(pager !== undefined && { pager })}
2615
- {...(rowActions !== undefined && { rowActions })}
2616
- {...(toolbarActions !== undefined && { toolbarActions })}
2617
- {...(translate !== undefined && { translate })}
2618
- {...(wrappedOnRowClick !== undefined && { onRowClick: wrappedOnRowClick })}
2619
- {...(filterFacets.length > 0 && {
2620
- filterFacets,
2621
- onFilterChange: urlState.setFilter,
2622
- })}
2623
- {...(dateRangeFacets.length > 0 && {
2624
- dateRangeFacets,
2625
- onDateRangeChange: handleDateRangeChange,
2626
- })}
2627
- {...((filterFacets.length > 0 || dateRangeFacets.length > 0) && {
2628
- filterValues: urlState.filters,
2629
- onFilterReset: urlState.clearFilters,
2630
- })}
2631
- />
2632
- <DrawerHost
2633
- schema={schema}
2634
- drawerAction={drawerAction}
2635
- drawerScreen={drawerScreen}
2636
- {...(drawerInitialValues !== undefined && { drawerInitialValues })}
2637
- userRoles={userRoles}
2638
- {...(translate !== undefined && { translate })}
2639
- onClose={closeDrawer}
2640
- onSuccess={() => {
2641
- closeDrawer();
2642
- void rowsQuery.refetch();
2643
- }}
2644
- />
2645
- </>
2646
- );
2647
- }
2648
-
2649
- function metricLabelKey(
2650
- metric: MetricSpec,
2651
- fieldLabels: Readonly<Record<string, string>> | undefined,
2652
- ): string | undefined {
2653
- if (typeof metric !== "string" && metric.label !== undefined) return metric.label;
2654
- return fieldLabels?.[metricField(metric)];
2655
- }
2656
-
2657
- function metricNavigateSpec(metric: MetricSpec): MetricNavigate | undefined {
2658
- return typeof metric === "string" ? undefined : metric.navigate;
2659
- }
2660
-
2661
- // Reuses runProjectionRowNavigate (row-actions.ts) instead of re-deriving
2662
- // navigate execution — a metric click has the same entity/screen/params
2663
- // shape as a RowActionNavigate, minus the fields (id, label, style) that
2664
- // function never reads.
2665
- function runMetricNavigate(
2666
- nav: NavApi,
2667
- navigate: MetricNavigate,
2668
- record: Readonly<Record<string, unknown>>,
2669
- host: ReturnHost | undefined,
2670
- ): void {
2671
- // tab alone (no screen/entity) stays on the current record and just
2672
- // activates that tab — no route change, so runProjectionRowNavigate
2673
- // (which always navigates) doesn't apply here.
2674
- if (navigate.screen === undefined && navigate.entity === undefined) {
2675
- if (navigate.tab !== undefined) nav.setSearchParams({ tab: navigate.tab });
2676
- return;
2677
- }
2678
- const base = { kind: "navigate" as const, id: "metric-navigate", label: "" };
2679
- const action: RowActionNavigate | undefined =
2680
- navigate.entity !== undefined
2681
- ? {
2682
- ...base,
2683
- entity: navigate.entity,
2684
- ...(navigate.entityId !== undefined && { entityId: navigate.entityId }),
2685
- ...(navigate.params !== undefined && { params: navigate.params }),
2686
- ...(navigate.tab !== undefined && { tab: navigate.tab }),
2687
- }
2688
- : navigate.screen !== undefined
2689
- ? {
2690
- ...base,
2691
- screen: navigate.screen,
2692
- ...(navigate.entityId !== undefined && { entityId: navigate.entityId }),
2693
- ...(navigate.params !== undefined && { params: navigate.params }),
2694
- ...(navigate.tab !== undefined && { tab: navigate.tab }),
2695
- }
2696
- : undefined;
2697
- if (action === undefined) return;
2698
- runProjectionRowNavigate(nav, action, { id: "", values: record }, host);
2699
- }
2700
-
2701
- // Absolute http(s) check for RecordHeaderSpec.subtitleHref — deliberately
2702
- // stricter than isSafeHref (which also allows relative paths and mailto:),
2703
- // since a relative/mailto value here should render as plain text, not a
2704
- // "_blank" external link.
2705
- function isAbsoluteHttpUrl(value: string): boolean {
2706
- return /^https?:\/\//i.test(value) && isSafeHref(value);
2707
- }
2708
-
2709
- function headerStatusTone(
2710
- header: NonNullable<ProjectionDetailScreenDefinition["header"]>,
2711
- record: Readonly<Record<string, unknown>>,
2712
- ): StatusTone | undefined {
2713
- if (header.status === undefined) return undefined;
2714
- const value = String(record[header.status] ?? "");
2715
- const declared =
2716
- header.statusTones !== undefined && Object.hasOwn(header.statusTones, value)
2717
- ? header.statusTones[value]
2718
- : undefined;
2719
- return declared !== undefined ? statusToneForOptionTone(declared) : statusToneForValue(value);
2720
- }
2721
-
2722
- function resolveSubtitleHref(
2723
- header: ProjectionDetailScreenDefinition["header"],
2724
- record: Readonly<Record<string, unknown>>,
2725
- ): string | undefined {
2726
- if (header?.subtitleHref === undefined) return undefined;
2727
- const value = record[header.subtitleHref];
2728
- return typeof value === "string" && isAbsoluteHttpUrl(value) ? value : undefined;
2729
- }
2730
-
2731
- // Projection-Detail-Body — read-only single-row inspector über eine explizite
2732
- // Query statt einer Entity (siehe projection-detail-shim.ts für die Schulden-
2733
- // Doku). Fetcht selbst über `screen.query` + `idParam` (analog zu
2734
- // EntityEditUpdateBody, das die Query-QN aus der Entity-Convention ableitet —
2735
- // hier ist die QN Author-explizit, wie bei ProjectionListBody). Rendert über
2736
- // RenderEdit MIT customSubmit-No-Op statt writeCommand: hasEditableSection()
2737
- // blendet den Save-Button aus (jedes Feld ist readOnly), und selbst ein
2738
- // natives Form-Submit (Enter-Keypress) würde ohne customSubmit gegen
2739
- // controller.submit() ohne submit-config throwen — der No-Op macht diesen
2740
- // Pfad harmlos statt ihn dem Zufall zu überlassen.
2741
- // The primary header action always stays a visible text button — `edit` if
2742
- // declared, else the first `style: "primary"` action, else the first action
2743
- // at all. One step longer than row actions' `primaryRowAction` (renderer-web
2744
- // primitives/index.tsx): rows don't declare `style: "primary"`.
2745
- function primaryHeaderAction(actions: readonly RenderEditAction[]): RenderEditAction | undefined {
2746
- return (
2747
- actions.find((a) => a.id === "edit") ?? actions.find((a) => a.style === "primary") ?? actions[0]
2748
- );
2749
- }
2750
-
2751
- // Header actions bar (A7): <=2 actions render as plain buttons; >2 with an
2752
- // `ActionOverflowMenu` primitive collapse to the primary button plus a menu
2753
- // for the rest — same rule as RowActionsCell for table rows. Owns confirm
2754
- // state for menu items: RenderEditActionButton already owns a per-button
2755
- // confirm dialog for the always-visible primary action, but a menu item has
2756
- // no button of its own to carry one.
2757
- function HeaderActionsBar({
2758
- actions,
2759
- Button,
2760
- Dialog,
2761
- ActionOverflowMenu,
2762
- onError,
2763
- collapseAfterPrimary = false,
2764
- }: {
2765
- /** Header slot layout: only the primary action stays a button, the rest goes into the menu. */
2766
- readonly collapseAfterPrimary?: boolean;
2767
- readonly actions: readonly RenderEditAction[];
2768
- readonly Button: ReturnType<typeof usePrimitives>["Button"];
2769
- readonly Dialog: ReturnType<typeof usePrimitives>["Dialog"];
2770
- readonly ActionOverflowMenu: ReturnType<typeof usePrimitives>["ActionOverflowMenu"];
2771
- readonly onError: (text: string | null) => void;
2772
- }): ReactNode {
2773
- const t = useTranslation();
2774
- const [pendingAction, setPendingAction] = useState<RenderEditAction | null>(null);
2775
- const trigger = async (action: RenderEditAction): Promise<void> => {
2776
- onError(null);
2777
- try {
2778
- await action.onPress();
2779
- } catch (e) {
2780
- onError(e instanceof Error ? e.message : String(e));
2781
- }
2782
- };
2783
- const maxPlainButtons = collapseAfterPrimary ? 1 : 2;
2784
- if (actions.length <= maxPlainButtons || ActionOverflowMenu === undefined) {
2785
- return (
2786
- <>
2787
- {actions.map((action) => (
2788
- <RenderEditActionButton
2789
- key={action.id}
2790
- action={action}
2791
- Button={Button}
2792
- Dialog={Dialog}
2793
- hideIcon
2794
- onError={onError}
2795
- />
2796
- ))}
2797
- </>
2798
- );
2799
- }
2800
- const primary = primaryHeaderAction(actions);
2801
- const rest = actions.filter((a) => a.id !== primary?.id);
2802
- return (
2803
- <>
2804
- {primary !== undefined && (
2805
- <RenderEditActionButton
2806
- key={primary.id}
2807
- action={primary}
2808
- Button={Button}
2809
- Dialog={Dialog}
2810
- hideIcon
2811
- onError={onError}
2812
- />
2813
- )}
2814
- <ActionOverflowMenu
2815
- label={t("kumiko.list.row-actions.more")}
2816
- testId="kumiko-screen-projection-detail-actions-overflow"
2817
- items={rest.map((action) => ({
2818
- id: action.id,
2819
- label: action.label,
2820
- ...(action.icon !== undefined && { icon: action.icon }),
2821
- variant: action.style === "danger" ? ("danger" as const) : ("default" as const),
2822
- onSelect: () => {
2823
- if (needsActionConfirm(action)) {
2824
- setPendingAction(action);
2825
- } else {
2826
- void trigger(action);
2827
- }
2828
- },
2829
- }))}
2830
- />
2831
- {pendingAction !== null && (
2832
- <RenderEditActionConfirmDialog
2833
- action={pendingAction}
2834
- open={true}
2835
- onOpenChange={(open) => {
2836
- if (!open) setPendingAction(null);
2837
- }}
2838
- onConfirm={async () => {
2839
- const action = pendingAction;
2840
- setPendingAction(null);
2841
- await trigger(action);
2842
- }}
2843
- Dialog={Dialog}
2844
- />
2845
- )}
2846
- </>
2847
- );
2848
- }
2849
-
2850
- function ProjectionDetailBody({
2851
- schema,
2852
- screen,
2853
- translate,
2854
- entityId,
2855
- }: {
2856
- readonly schema: FeatureSchema;
2857
- // detailFor sits on the ScreenDefinition intersection, not on the
2858
- // projectionDetail variant itself (screen.ts:832) — widen the prop type
2859
- // to keep reading it here instead of re-deriving it from schema.screens.
2860
- readonly screen: ProjectionDetailScreenDefinition & { readonly detailFor?: string };
2861
- readonly translate?: Translate;
2862
- readonly entityId?: string;
2863
- }): ReactNode {
2864
- const {
2865
- Banner,
2866
- Button,
2867
- Dialog,
2868
- Text,
2869
- Grid,
2870
- GridCell,
2871
- Card,
2872
- Tabs,
2873
- StatusBadge,
2874
- Metric,
2875
- MetricBand,
2876
- PageHeader,
2877
- Link,
2878
- ActionOverflowMenu,
2879
- } = usePrimitives();
2880
- const t = useTranslation();
2881
- const pageHeaderSlotAvailable = usePageHeaderSlotAvailable();
2882
- const effectiveTranslate = translate ?? t;
2883
- const nav = useNav();
2884
- const idParam = screen.idParam ?? "id";
2885
- // Singleton screens ignore whatever id the path happens to carry — the
2886
- // server picks the row from session/context, so forwarding a path id
2887
- // (even a stray/spoofed one) into the query or into extension sections'
2888
- // entityId fallback (resolveExtensionEntityId in render-edit.tsx) would
2889
- // let a client-controlled value leak where none is meant to reach.
2890
- const effectiveEntityId = screen.singleton === true ? undefined : entityId;
2891
- const isTabsMode = screen.layout.mode === "tabs";
2892
- const activeSection = useMemo(() => {
2893
- if (!isTabsMode || Tabs === undefined) return undefined;
2894
- const tabParam = nav.searchParams["tab"];
2895
- return (
2896
- screen.layout.sections.find((section) => section.id === tabParam) ?? screen.layout.sections[0]
2897
- );
2898
- }, [isTabsMode, Tabs, screen.layout.sections, nav.searchParams]);
2899
- const hasTabs = isTabsMode && Tabs !== undefined && activeSection !== undefined;
2900
- // Tabs is an optional Core-Primitive: without it the screen falls back to
2901
- // the stacked all-sections layout instead of silently truncating to section 1.
2902
- useEffect(() => {
2903
- if (isTabsMode && Tabs === undefined) {
2904
- // biome-ignore lint/suspicious/noConsole: dev-warning for a setup error
2905
- console.warn(
2906
- `[kumiko] screen "${screen.id}" uses layout.mode: "tabs", but no <Tabs> primitive is registered — the tab strip will not render. createKumikoApp() from kumiko-renderer-web wires it automatically.`,
2907
- );
2908
- }
2909
- }, [isTabsMode, Tabs, screen.id]);
2910
- const entity = useMemo(() => synthesizeProjectionDetailEntity(screen.layout), [screen.layout]);
2911
- const detailScreen = useMemo(() => {
2912
- const source =
2913
- activeSection !== undefined
2914
- ? { ...screen, layout: { ...screen.layout, sections: [activeSection] } }
2915
- : screen;
2916
- return synthesizeProjectionDetailScreen(source);
2917
- }, [screen, activeSection]);
2918
- const detailQuery = useQuery<Readonly<Record<string, unknown>>>(
2919
- screen.query,
2920
- effectiveEntityId !== undefined ? { [idParam]: effectiveEntityId } : {},
2921
- );
2922
-
2923
- // A writeForm section's handler creates a new record (see EditWriteFormSection's
2924
- // doc) — both the outer record (header/metrics/other sections) and a sibling
2925
- // relatedList section's own independently-fetched rows must reflect it. A
2926
- // query refetch alone only refreshes `record` below; bumping this into
2927
- // <RenderEdit>'s `key` forces a full remount so RelatedListSection's own
2928
- // useQuery call re-runs too (it has no `live` subscription of its own).
2929
- const [reloadNonce, setReloadNonce] = useState(0);
2930
- const reloadDetail = useCallback(async () => {
2931
- await detailQuery.refetch();
2932
- setReloadNonce((n) => n + 1);
2933
- }, [detailQuery.refetch]);
2934
-
2935
- // Header actions render directly via RenderEditActionButton (fw#2713,
2936
- // headerActions moved out of RenderEdit's footer) — this component owns
2937
- // the failure-surfacing state RenderEdit used to own for them.
2938
- const [actionError, setActionError] = useState<string | null>(null);
2939
-
2940
- // Default edit action (fw#2166): resolved cross-feature over ALL mounted
2941
- // features, not just this feature's own schema — detailFor itself is
2942
- // resolved cross-feature by the boot-validator (detail-screens.ts), and
2943
- // the motivating case is a projectionDetail whose query belongs to one
2944
- // feature while the entity's entityEdit screen lives in another. Unlike
2945
- // useNavigateToCreateFor this must NOT filter on allowCreate/singleton —
2946
- // those gate create-targets, we're resolving an update-target by a
2947
- // known id.
2948
- const appFeatures = useAppFeatures();
2949
- const userRoles = useUserRoles();
2950
- const dispatcher = useOptionalDispatcher();
2951
- const host = useReturnHost();
2952
- const { drawerAction, drawerScreen, drawerInitialValues, openDrawer, closeDrawer } =
2953
- useDrawerAction(schema);
2954
- const editScreen = useMemo(() => {
2955
- const detailFor = screen.detailFor;
2956
- if (detailFor === undefined) return undefined;
2957
- return findEditScreenFor(detailFor, appFeatures, userRoles);
2958
- }, [appFeatures, screen.detailFor, userRoles]);
2959
- const defaultEditAction = useMemo((): RenderEditAction | undefined => {
2960
- if (editScreen === undefined) return undefined;
2961
- // editScreen.id is registry-qualified ("feature:screen:contact-edit");
2962
- // nav.navigate expects the short form (see useNavigateToCreateFor above).
2963
- const targetScreenId = lastSegment(editScreen.id);
2964
- return {
2965
- id: "edit",
2966
- label: effectiveTranslate("kumiko.actions.edit"),
2967
- icon: resolveActionIcon("edit"),
2968
- onPress: () => {
2969
- const target: ScreenTarget = {
2970
- screenId: targetScreenId,
2971
- ...(effectiveEntityId !== undefined && { entityId: effectiveEntityId }),
2972
- };
2973
- navigateWithReturnTo(nav, target, host);
2974
- },
2975
- };
2976
- }, [editScreen, effectiveTranslate, nav, effectiveEntityId, host]);
2977
-
2978
- // a navigate-screen action targeting an entityEdit screen for the
2979
- // SAME entity this projectionDetail shows (screen.detailFor) defaults its
2980
- // entityId to the shown record's own id — without this fallback the target
2981
- // opens an empty create-form instead of the shown record, silently.
2982
- // Searched cross-feature, consistent with editScreen above.
2983
- const sameEntityScreenId = useCallback(
2984
- (targetScreen: string): string | undefined => {
2985
- const record = detailQuery.data ?? {};
2986
- const targetIsEntityEditSameEntity =
2987
- screen.detailFor !== undefined &&
2988
- appFeatures.some((feature) =>
2989
- feature.screens.some(
2990
- (s) =>
2991
- s.type === "entityEdit" &&
2992
- s.entity === screen.detailFor &&
2993
- lastSegment(s.id) === targetScreen,
2994
- ),
2995
- );
2996
- return targetIsEntityEditSameEntity ? String(record["id"] ?? "") : undefined;
2997
- },
2998
- [detailQuery.data, screen.detailFor, appFeatures],
2999
- );
3000
- const buildSectionActions = useCallback(
3001
- (actions: readonly RowAction[]): readonly RenderEditAction[] | undefined =>
3002
- buildRecordActions({
3003
- actions,
3004
- record: detailQuery.data ?? {},
3005
- translate: effectiveTranslate,
3006
- nav,
3007
- host,
3008
- dispatcher,
3009
- openDrawer,
3010
- onWriteSuccess: detailQuery.refetch,
3011
- sameEntityScreenId,
3012
- }),
3013
- [
3014
- detailQuery.data,
3015
- detailQuery.refetch,
3016
- effectiveTranslate,
3017
- nav,
3018
- host,
3019
- dispatcher,
3020
- openDrawer,
3021
- sameEntityScreenId,
3022
- ],
3023
- );
3024
- const headerActions = useMemo((): readonly RenderEditAction[] | undefined => {
3025
- const declaredHasEdit = screen.actions?.some((a) => a.id === "edit") === true;
3026
- const resolved = buildRecordActions({
3027
- actions: screen.actions ?? [],
3028
- record: detailQuery.data ?? {},
3029
- translate: effectiveTranslate,
3030
- nav,
3031
- host,
3032
- dispatcher,
3033
- openDrawer,
3034
- onWriteSuccess: detailQuery.refetch,
3035
- sameEntityScreenId,
3036
- });
3037
- if (defaultEditAction === undefined || declaredHasEdit) return resolved;
3038
- return [defaultEditAction, ...(resolved ?? [])];
3039
- }, [
3040
- screen.actions,
3041
- defaultEditAction,
3042
- effectiveTranslate,
3043
- nav,
3044
- host,
3045
- dispatcher,
3046
- detailQuery.data,
3047
- detailQuery.refetch,
3048
- openDrawer,
3049
- sameEntityScreenId,
3050
- ]);
3051
-
3052
- if (effectiveEntityId === undefined && screen.singleton !== true) {
3053
- return (
3054
- <Banner padded variant="error" testId="kumiko-screen-projection-detail-missing-id">
3055
- Screen <Text variant="code">{screen.id}</Text> (projectionDetail) needs a row id in the path
3056
- — open it from a row action.
3057
- </Banner>
3058
- );
3059
- }
3060
- if (detailQuery.loading && detailQuery.data === null) {
3061
- return (
3062
- <Banner padded variant="loading" testId="kumiko-screen-loading">
3063
- Loading…
3064
- </Banner>
3065
- );
3066
- }
3067
- if (detailQuery.error) {
3068
- return (
3069
- <Banner padded variant="error" testId="kumiko-screen-error">
3070
- {dispatcherErrorText(detailQuery.error, effectiveTranslate)}
3071
- </Banner>
3072
- );
3073
- }
3074
- const record = detailQuery.data;
3075
- if (!record) {
3076
- return (
3077
- <Banner padded variant="error" testId="kumiko-screen-record-missing">
3078
- {screen.singleton === true ? (
3079
- "Record not found."
3080
- ) : (
3081
- <>
3082
- Record <Text variant="code">{entityId}</Text> not found.
3083
- </>
3084
- )}
3085
- </Banner>
3086
- );
3087
- }
3088
- const hasHeader = screen.header !== undefined;
3089
- const hasMetrics = screen.metrics !== undefined && screen.metrics.length > 0;
3090
- // ?? [] rather than threading `headerActions !== undefined` through every
3091
- // use below — an empty array is a safe no-op for .map/.length.
3092
- const headerActionsList = headerActions ?? [];
3093
- const hasHeaderActions = headerActionsList.length > 0;
3094
- // Grouped into the head Card alongside title/status/metrics (fw#2713):
3095
- // these are actions on the record the head shows, not on whichever tab is
3096
- // open, so they must stay in place across tab switches instead of
3097
- // trailing the active tab's content in the card footer.
3098
- const headerActionsContent = hasHeaderActions && (
3099
- <Grid columns="auto" testId="kumiko-screen-projection-detail-actions">
3100
- <HeaderActionsBar
3101
- actions={headerActionsList}
3102
- Button={Button}
3103
- Dialog={Dialog}
3104
- ActionOverflowMenu={ActionOverflowMenu}
3105
- onError={setActionError}
3106
- />
3107
- </Grid>
3108
- );
3109
- const hasHeaderCard = hasHeader || hasMetrics || hasHeaderActions;
3110
- // Rendered as RenderEdit's headerRegion (not as JSX siblings before it) so
3111
- // this shares the same page padding/width as the record's edit card below
3112
- // it, instead of sitting flush against the screen edge (fw record-screen
3113
- // header polish).
3114
- const header = screen.header;
3115
- const subtitleHref = resolveSubtitleHref(header, record);
3116
- // Plain Text, not Heading — the Card title slot already renders as its own
3117
- // heading element (h3); nesting another heading (h1) inside it is invalid HTML.
3118
- const headerTitleSlot =
3119
- header !== undefined ? (
3120
- header.status !== undefined ? (
3121
- <Grid columns="auto">
3122
- <Text testId="kumiko-screen-projection-detail-title">
3123
- {String(record[header.title] ?? "")}
3124
- </Text>
3125
- {StatusBadge !== undefined ? (
3126
- <StatusBadge
3127
- value={String(record[header.status] ?? "")}
3128
- tone={headerStatusTone(header, record)}
3129
- testId="kumiko-screen-projection-detail-status"
3130
- />
3131
- ) : (
3132
- <Text testId="kumiko-screen-projection-detail-status">
3133
- {String(record[header.status] ?? "")}
3134
- </Text>
3135
- )}
3136
- </Grid>
3137
- ) : (
3138
- <Text testId="kumiko-screen-projection-detail-title">
3139
- {String(record[header.title] ?? "")}
3140
- </Text>
3141
- )
3142
- ) : undefined;
3143
- const headerSubtitleSlot =
3144
- header?.subtitle !== undefined ? (
3145
- subtitleHref !== undefined ? (
3146
- <Link href={subtitleHref} target="_blank" testId="kumiko-screen-projection-detail-subtitle">
3147
- {String(record[header.subtitle] ?? "")}
3148
- </Link>
3149
- ) : (
3150
- <Text variant="muted" testId="kumiko-screen-projection-detail-subtitle">
3151
- {String(record[header.subtitle] ?? "")}
3152
- </Text>
3153
- )
3154
- ) : undefined;
3155
- // slots.header shares the header card with the actions (one card, actions
3156
- // top right) instead of rendering as an unframed block above it.
3157
- const metricItems = screen.metrics?.map((metric) => {
3158
- const field = metricField(metric);
3159
- const labelKey = metricLabelKey(metric, screen.fieldLabels);
3160
- const label = labelKey !== undefined ? effectiveTranslate(labelKey) : field;
3161
- const value = String(record[field] ?? "");
3162
- const testId = `kumiko-screen-projection-detail-metric-${field}`;
3163
- const navigate = metricNavigateSpec(metric);
3164
- const onPress =
3165
- navigate !== undefined && navigateTargetAllows(navigate, appFeatures, userRoles)
3166
- ? () => runMetricNavigate(nav, navigate, record, host)
3167
- : undefined;
3168
- return Metric !== undefined ? (
3169
- <Metric
3170
- key={field}
3171
- label={label}
3172
- value={value}
3173
- testId={testId}
3174
- {...(onPress !== undefined && { onPress })}
3175
- />
3176
- ) : (
3177
- <GridCell key={field}>
3178
- <Text variant="small" testId={`${testId}-label`}>
3179
- {label}
3180
- </Text>
3181
- <Text testId={`${testId}-value`}>{value}</Text>
3182
- </GridCell>
3183
- );
3184
- });
3185
- // Metrics are a dl band when the primitive exists; the old Grid stays as the fallback.
3186
- const metricsBlock = (subtitle?: ReactNode): ReactNode =>
3187
- MetricBand !== undefined ? (
3188
- <MetricBand testId="kumiko-screen-projection-detail-metrics" subtitle={subtitle}>
3189
- {metricItems}
3190
- </MetricBand>
3191
- ) : (
3192
- <Grid columns={screen.metrics?.length ?? 1} testId="kumiko-screen-projection-detail-metrics">
3193
- {metricItems}
3194
- </Grid>
3195
- );
3196
- const usesPageHeaderSlot = pageHeaderSlotAvailable && PageHeader !== undefined;
3197
- const actionErrorBanner = actionError !== null && (
3198
- <Banner variant="error" testId="render-edit-action-error">
3199
- {actionError}
3200
- </Banner>
3201
- );
3202
- const renderHeaderContent = (headerSlot: ReactNode | undefined): ReactNode => (
3203
- <>
3204
- {usesPageHeaderSlot && headerSlot === undefined ? (
3205
- <>
3206
- <PageHeader
3207
- {...(header !== undefined && { title: String(record[header.title] ?? "") })}
3208
- {...(header?.status !== undefined &&
3209
- StatusBadge !== undefined && {
3210
- status: (
3211
- <StatusBadge
3212
- value={String(record[header.status] ?? "")}
3213
- tone={headerStatusTone(header, record)}
3214
- testId="kumiko-screen-projection-detail-status"
3215
- />
3216
- ),
3217
- })}
3218
- {...(hasHeaderActions && {
3219
- actions: (
3220
- <Grid columns="auto" testId="kumiko-screen-projection-detail-actions">
3221
- <HeaderActionsBar
3222
- actions={headerActionsList}
3223
- Button={Button}
3224
- Dialog={Dialog}
3225
- ActionOverflowMenu={ActionOverflowMenu}
3226
- onError={setActionError}
3227
- collapseAfterPrimary
3228
- />
3229
- </Grid>
3230
- ),
3231
- })}
3232
- />
3233
- {(hasMetrics || headerSubtitleSlot !== undefined) &&
3234
- (MetricBand !== undefined || hasMetrics) &&
3235
- metricsBlock(headerSubtitleSlot)}
3236
- {actionErrorBanner}
3237
- </>
3238
- ) : (
3239
- (hasHeaderCard || headerSlot !== undefined) && (
3240
- <Card
3241
- slots={{
3242
- ...(headerTitleSlot !== undefined && { title: headerTitleSlot }),
3243
- ...(headerSubtitleSlot !== undefined && { subtitle: headerSubtitleSlot }),
3244
- ...(headerSlot !== undefined && { headerContent: headerSlot }),
3245
- ...(hasHeaderActions && { headerActions: headerActionsContent }),
3246
- }}
3247
- >
3248
- {hasMetrics && metricsBlock()}
3249
- {actionErrorBanner}
3250
- </Card>
3251
- )
3252
- )}
3253
- {hasTabs && activeSection !== undefined && (
3254
- <Tabs
3255
- testId="kumiko-screen-projection-detail-tabs"
3256
- items={screen.layout.sections.map((section) => {
3257
- const countField = isWriteFormEditSection(section) ? undefined : section.countField;
3258
- const countValue = countField !== undefined ? record[countField] : undefined;
3259
- const count =
3260
- typeof countValue === "number" && Number.isFinite(countValue)
3261
- ? countValue
3262
- : undefined;
3263
- return {
3264
- id: section.id ?? "",
3265
- label: effectiveTranslate(section.title ?? section.id ?? ""),
3266
- ...(count !== undefined && { count }),
3267
- };
3268
- })}
3269
- activeId={activeSection.id ?? ""}
3270
- onSelect={(id) => nav.setSearchParams({ tab: id })}
3271
- />
3272
- )}
3273
- </>
3274
- );
3275
- return (
3276
- <>
3277
- <RenderEdit
3278
- key={`${entityId}:${reloadNonce}`}
3279
- screen={detailScreen}
3280
- entity={entity}
3281
- featureName={schema.featureName}
3282
- initial={record as FormValues}
3283
- entityId={effectiveEntityId}
3284
- customSubmit={async () => ({ isSuccess: true, validationBlocked: false, data: undefined })}
3285
- onReload={reloadDetail}
3286
- onRelatedListDrawerAction={openDrawer}
3287
- {...(translate !== undefined && { translate })}
3288
- {...(hasTabs && { hideSectionTitles: true })}
3289
- {...(screenFillsHeight(screen) && { fillScreenHeight: true })}
3290
- {...((hasHeaderCard || hasTabs || screen.slots?.header !== undefined) && {
3291
- headerRegion: renderHeaderContent,
3292
- })}
3293
- buildSectionActions={buildSectionActions}
3294
- valueDisplay={screen.valueDisplay ?? "text"}
3295
- />
3296
- <DrawerHost
3297
- schema={schema}
3298
- drawerAction={drawerAction}
3299
- drawerScreen={drawerScreen}
3300
- {...(drawerInitialValues !== undefined && { drawerInitialValues })}
3301
- userRoles={userRoles}
3302
- {...(translate !== undefined && { translate })}
3303
- onClose={closeDrawer}
3304
- onSuccess={() => {
3305
- closeDrawer();
3306
- void reloadDetail();
3307
- }}
3308
- />
3309
- </>
3310
- );
3311
- }
3312
- // ---- actionForm (Tier 2.7d) ----
3313
-
3314
- function redirectScreenTarget(
3315
- redirect: NonNullable<ActionFormScreenDefinition["redirect"]>,
3316
- ): string {
3317
- return typeof redirect === "string" ? redirect : redirect.screen;
3318
- }
3319
-
3320
- // Checks this schema first, then every mounted feature — the target may live
3321
- // in another (cross-feature) feature than the redirect's own screen.
3322
- function findRedirectTargetScreen(
3323
- redirect: string | ActionFormRedirect,
3324
- schema: FeatureSchema,
3325
- appFeatures: readonly FeatureSchema[],
3326
- ): ScreenDefinition | undefined {
3327
- const redirectScreen = redirectScreenTarget(redirect);
3328
- const targetId = lastSegment(redirectScreen);
3329
- const targetFeatureName = featureNameFromQualifiedScreenId(redirectScreen);
3330
- return (
3331
- schema.screens.find((s) => lastSegment(s.id) === targetId) ??
3332
- (targetFeatureName !== undefined
3333
- ? appFeatures
3334
- .find((f) => f.featureName === targetFeatureName)
3335
- ?.screens.find((s) => lastSegment(s.id) === targetId)
3336
- : appFeatures.flatMap((f) => f.screens).find((s) => lastSegment(s.id) === targetId))
3337
- );
3338
- }
3339
-
3340
- // A redirect to a record screen ("show the result") is a deliberate forward
3341
- // navigation and keeps precedence over returnTo.
3342
- function redirectTargetsRecord(
3343
- redirect: string | ActionFormRedirect,
3344
- schema: FeatureSchema,
3345
- appFeatures: readonly FeatureSchema[],
3346
- ): boolean {
3347
- const target = findRedirectTargetScreen(redirect, schema, appFeatures);
3348
- return (
3349
- target !== undefined && (target.type === "entityEdit" || target.type === "projectionDetail")
3350
- );
3351
- }
3352
-
3353
- // Type-guard form narrows `returnTarget` for the caller's subsequent
3354
- // navigateToReturn(nav, returnTarget) call.
3355
- function returnToWinsOverRedirect(
3356
- returnTarget: ScreenTarget | undefined,
3357
- redirect: string | ActionFormRedirect,
3358
- schema: FeatureSchema,
3359
- appFeatures: readonly FeatureSchema[],
3360
- ): returnTarget is ScreenTarget {
3361
- return returnTarget !== undefined && !redirectTargetsRecord(redirect, schema, appFeatures);
3362
- }
3363
-
3364
- // Resolves an object-form redirect to a nav target — shared by
3365
- // actionForm and entityEdit (create + update) so the id
3366
- // carries over identically regardless of which screen type triggered it.
3367
- // `carriesId` gates entityId on the TARGET screen type: a redirect to a
3368
- // list screen never gets an id attached, matching actionForm's original
3369
- // behavior. The id itself prefers the write-handler's success payload
3370
- // (`submittedData`) and falls back to `fallbackRecord` — the entityEdit
3371
- // update path's already-loaded record, or the create path's just-submitted
3372
- // form values — both of which carry fields (e.g. a parent FK) the CRUD
3373
- // write executor's success payload doesn't flatly expose.
3374
- function resolveRedirectTarget(
3375
- redirect: string | ActionFormRedirect,
3376
- submittedData: unknown,
3377
- schema: FeatureSchema,
3378
- appFeatures: readonly FeatureSchema[],
3379
- fallbackRecord?: Readonly<Record<string, unknown>>,
3380
- ): { readonly screenId: string; readonly entityId: string | undefined } {
3381
- const redirectScreen = redirectScreenTarget(redirect);
3382
- const idField = typeof redirect === "string" ? "id" : redirect.idFrom;
3383
- const targetId = lastSegment(redirectScreen);
3384
- const target = findRedirectTargetScreen(redirect, schema, appFeatures);
3385
- const carriesId =
3386
- target !== undefined && (target.type === "entityEdit" || target.type === "projectionDetail");
3387
- if (!carriesId) return { screenId: targetId, entityId: undefined };
3388
- const entityId =
3389
- extractIdField(submittedData, idField) ??
3390
- (fallbackRecord !== undefined ? extractIdField(fallbackRecord, idField) : undefined);
3391
- return { screenId: targetId, entityId };
3392
- }
3393
-
3394
- // Action-Form-Body — non-CRUD Write-Handler-driven Form. Re-uses
3395
- // RenderEdit über synthetisierte EntityDefinition + EntityEditScreen-
3396
- // Definition (siehe action-form-shim.ts für die Schulden-Doku). Die
3397
- // Form-Mechanik (useForm, RenderEdit, DefaultInput, Banner, Submit-
3398
- // Button) ist identisch zu entityEdit, nur der Submit-Pfad wechselt
3399
- // vom CRUD-verb auf den Author-deklarierten handler-QN +
3400
- // payloadMode="values" (alle Form-Werte schicken statt nur Changes).
3401
- function ActionFormBody({
3402
- schema,
3403
- screen,
3404
- translate,
3405
- initialOverrides,
3406
- onSuccess,
3407
- onCancelOverride,
3408
- onDirtyChange,
3409
- submitLabelFallback,
3410
- }: {
3411
- readonly schema: FeatureSchema;
3412
- readonly screen: ActionFormScreenDefinition;
3413
- readonly translate?: Translate;
3414
- /** Row-drawer usage (RowAction kind:"drawer", fw#2710): prefill extracted
3415
- * from the clicked row, applied on top of searchParams through the same
3416
- * renderableFields/sensitive gates (see mergeSearchParamsIntoInitial). */
3417
- readonly initialOverrides?: Readonly<Record<string, unknown>>;
3418
- /** Drawer-hosted usage (toolbarAction kind:"drawer", fw#2225): called
3419
- * instead of the redirect-based navigation on successful submit, so the
3420
- * host closes the drawer + refetches its list regardless of whether
3421
- * `screen.redirect` is set — a full-page redirect would navigate away
3422
- * from the list the drawer sits on top of. */
3423
- readonly onSuccess?: () => void;
3424
- /** Drawer-hosted usage: replaces the cancelTarget/redirect-based Cancel
3425
- * handler so Cancel closes the drawer instead of navigating. */
3426
- readonly onCancelOverride?: () => void;
3427
- /** Drawer-hosted usage: reports unsaved input so the host can confirm
3428
- * before discarding it. */
3429
- readonly onDirtyChange?: (dirty: boolean) => void;
3430
- /** Drawer-hosted usage: submit label when the screen declares none (the opening action's label). */
3431
- readonly submitLabelFallback?: string;
3432
- }): ReactNode {
3433
- const nav = useNav();
3434
- const appFeatures = useAppFeatures();
3435
- const insideDrawer = useInsideDrawer();
3436
- const locale = useLocale().locale();
3437
- const { Banner } = usePrimitives();
3438
- // Unused when drawer-hosted — onSuccess/onCancelOverride win below first.
3439
- const returnTarget = useReturnTarget(screen.id);
3440
- const synthEntity = useMemo(() => synthesizeActionFormEntity(screen.fields), [screen.fields]);
3441
- const synthScreen = useMemo(() => synthesizeActionFormScreen(screen), [screen]);
3442
- const pendingHandoff = useInitialValuesHandoff(screen.id);
3443
- // A drawer-hosted form is not a navigation target, so it never takes a handoff.
3444
- const handoffValues = onSuccess === undefined ? pendingHandoff : undefined;
3445
- // This screen has no entity, so a money field here declares its own currency
3446
- // source (fw#2839, boot-enforced) — without one the form would seed a bare
3447
- // `0` the handler's schema rejects. ACTION_FORM_CURRENCY_FALLBACK only
3448
- // applies when a tenant-declared field's config query errors or holds no
3449
- // value, matching the entityEdit path's behaviour (fw#2937).
3450
- const tenantCurrencyFieldNames = useMemo(
3451
- () => tenantCurrencyMoneyFieldNames(screen.fields),
3452
- [screen.fields],
3453
- );
3454
- const { overrides: moneyCurrencyOverrides, loading: currencyLoading } = useMoneyCurrencyOverrides(
3455
- screen.fields,
3456
- tenantCurrencyFieldNames,
3457
- ACTION_FORM_CURRENCY_FALLBACK,
3458
- );
3459
- const initial = useMemo(
3460
- () =>
3461
- mergeSearchParamsIntoInitial(screen.fields, {
3462
- searchParams: nav.searchParams,
3463
- urlPrefillFields: screen.urlPrefillFields,
3464
- renderableFields: layoutFieldNames(synthScreen),
3465
- ...(moneyCurrencyOverrides !== undefined && { moneyCurrencyOverrides }),
3466
- ...(initialOverrides !== undefined && { drawerOverrides: initialOverrides }),
3467
- ...(handoffValues !== undefined && { handoffValues }),
3468
- }) as FormValues,
3469
- [
3470
- screen.fields,
3471
- screen.urlPrefillFields,
3472
- nav.searchParams,
3473
- synthScreen,
3474
- moneyCurrencyOverrides,
3475
- initialOverrides,
3476
- handoffValues,
3477
- ],
3478
- );
3479
- const t = useTranslation();
3480
- const effectiveTranslate = translate ?? t;
3481
- const summary = useMemo(
3482
- () => resolveActionFormSummary(screen.summary, initialOverrides, effectiveTranslate, locale),
3483
- [screen.summary, initialOverrides, effectiveTranslate, locale],
3484
- );
3485
- const handleSubmitted = useCallback(
3486
- (result: SubmitResult<unknown>) => {
3487
- if (!result.isSuccess) return;
3488
- if (onSuccess !== undefined) {
3489
- onSuccess();
3490
- return;
3491
- }
3492
- // Without a redirect the form stays put; returnTo only replaces an existing
3493
- // navigation, and never one to a record screen (see redirectTargetsRecord).
3494
- if (screen.redirect !== undefined) {
3495
- if (returnToWinsOverRedirect(returnTarget, screen.redirect, schema, appFeatures)) {
3496
- navigateToReturn(nav, returnTarget);
3497
- } else {
3498
- const { screenId, entityId } = resolveRedirectTarget(
3499
- screen.redirect,
3500
- result.data,
3501
- schema,
3502
- appFeatures,
3503
- );
3504
- nav.navigate({ screenId, ...(entityId !== undefined && { entityId }) });
3505
- }
3506
- }
3507
- },
3508
- [nav, screen.redirect, onSuccess, schema, appFeatures, returnTarget],
3509
- );
3510
- // Cancel ist nur sinnvoll wenn ein Navigations-Ziel existiert —
3511
- // sonst hätte der Button nirgendwo hin zu navigieren. cancelTarget
3512
- // gewinnt über redirect; `false` schaltet den Button explizit ab
3513
- // (Single-Action-Screens, wo Cancel nur Submit-ohne-Senden wäre).
3514
- // returnTo wins over the declared target when both are present.
3515
- const handleCancel = useMemo<(() => void) | undefined>(() => {
3516
- if (onCancelOverride !== undefined) return onCancelOverride;
3517
- const target =
3518
- screen.cancelTarget ??
3519
- (screen.redirect !== undefined ? redirectScreenTarget(screen.redirect) : undefined);
3520
- if (target === undefined || target === false) return undefined;
3521
- return () =>
3522
- navigateToReturnOr(nav, returnTarget, () => nav.navigate({ screenId: lastSegment(target) }));
3523
- }, [nav, screen.redirect, screen.cancelTarget, onCancelOverride, returnTarget]);
3524
- // Rendering the form before a tenant-declared currency lands would show the
3525
- // fallback and, on a fast click, submit it (fw#2933) — hold instead.
3526
- if (currencyLoading) {
3527
- return (
3528
- <Banner padded variant="loading" testId="kumiko-screen-loading">
3529
- Loading…
3530
- </Banner>
3531
- );
3532
- }
3533
- return (
3534
- <RenderEdit
3535
- screen={synthScreen}
3536
- entity={synthEntity}
3537
- featureName={schema.featureName}
3538
- initial={initial}
3539
- // Extension-Sections im actionForm sehen die initialen Form-Values
3540
- // (inkl. searchParams-Prefill, z.B. ?incidentId=…) als initialValues
3541
- // — anders als im entityEdit gibt es hier keinen record, aus dem
3542
- // sie Kontext ziehen könnten.
3543
- extensionInitialValues={initial}
3544
- writeCommand={screen.handler}
3545
- payloadMode="values"
3546
- onSubmit={handleSubmitted}
3547
- {...(handleCancel !== undefined && { onCancel: handleCancel })}
3548
- {...(onDirtyChange !== undefined && { onDirtyChange })}
3549
- {...((insideDrawer || screenFillsHeight(screen)) && { fillScreenHeight: true })}
3550
- {...((screen.submitLabel ?? submitLabelFallback) !== undefined && {
3551
- submitLabel: screen.submitLabel ?? submitLabelFallback,
3552
- })}
3553
- {...(screen.submitStyle !== undefined && { submitVariant: screen.submitStyle })}
3554
- {...(summary !== undefined && { summary })}
3555
- {...(translate !== undefined && { translate })}
3556
- />
3557
- );
3558
- }
3559
-
3560
- // ---- config-edit ----
3561
- //
3562
- // Settings-Form gegen das bundled config-Feature. Liest beim Mount
3563
- // `config:query:values` (returned ALLE Keys die der User lesen darf
3564
- // als `{ [qualifiedKey]: { value, scope } }`); schreibt beim Save
3565
- // pro geändertem Feld einen `config:write:set` Call. Singleton-pro-
3566
- // Tenant kommt by-design vom config-feature (key+tenantId Unique-
3567
- // Constraint) — kein Bridge-Hack, keine extra Aggregate.
3568
- //
3569
- // Parallel-Aufbau zu ActionFormBody: synthesisierte Entity + EntityEdit-
3570
- // Screen damit RenderEdit reused werden kann; Layout/Field-Rendering/
3571
- // Banner/Submit-Button-State sind identisch zu entityEdit. Der einzige
3572
- // Pfad-Unterschied ist customSubmit das mehrere config:write:set-Calls
3573
- // orchestriert.
3574
- //
3575
- // Response enthält seit config-seeding auch `source` (z.B. "system-row")
3576
- // für das ConfigSourceBadge. Type wird lokal gehalten da er nur hier
3577
- // relevant ist — kein eigener Export nötig.
3578
- type ConfigValueResponse = Readonly<
3579
- Record<string, { value: string | number | boolean | undefined; scope: string; source: string }>
3580
- >;
3581
-
3582
- // A money-typed config-edit field renders through RenderField's entityEdit
3583
- // `{amount, currency}` payload shape (render-field.tsx, #1923), but
3584
- // `ConfigKeyType` (write-helpers.ts validateType) only ever knows
3585
- // number/boolean/text/select — a config value is always a bare scalar.
3586
- // Unwrap back to the amount before it hits config:write:set.
3587
- function unwrapMoneyValue(value: unknown): unknown {
3588
- if (typeof value === "object" && value !== null && "amount" in value) {
3589
- const amount = (value as { amount?: unknown }).amount;
3590
- if (typeof amount === "number") return amount;
3591
- }
3592
- return value;
3593
- }
3594
-
3595
- function ConfigEditBody({
3596
- schema,
3597
- screen,
3598
- translate,
3599
- }: {
3600
- readonly schema: FeatureSchema;
3601
- readonly screen: ConfigEditScreenDefinition;
3602
- readonly translate?: Translate;
3603
- }): ReactNode {
3604
- const { Banner, ConfigCascadeView } = usePrimitives();
3605
- const t = useTranslation();
3606
- const effectiveTranslate = translate ?? t;
3607
- const dispatcher = useDispatcher();
3608
-
3609
- // Detail-Load: config:query:values returnt ALLE Keys des Tenants.
3610
- // Wir mappen via screen.configKeys von short → qualified-name auf
3611
- // unsere Form-Field-Werte.
3612
- const valuesQuery = useQuery<ConfigValueResponse>("config:query:values", {});
3613
-
3614
- const cascadeQuery = useQuery<Record<string, ConfigCascade>>("config:query:cascade", {});
3615
-
3616
- const synthEntity = useMemo(() => synthesizeConfigEditEntity(screen.fields), [screen.fields]);
3617
- const synthScreen = useMemo(() => synthesizeConfigEditScreen(screen), [screen]);
3618
-
3619
- // Initial-Values: pro Field-Name den Wert aus `values[qualifiedKey]`
3620
- // abholen. Fehlt der Key auf dem Server (= noch nie gesetzt), nutzen
3621
- // wir den Field-Default (createTextField/createNumberField/...).
3622
- // String-coerce nur für Text-Fields; andere Types sollten in der
3623
- // Response bereits Native-Type sein.
3624
- const initial = useMemo<FormValues | null>(() => {
3625
- if (valuesQuery.data === null) return null;
3626
- const out: Record<string, unknown> = {};
3627
- const defaults = buildInitialValues(screen.fields) as Record<string, unknown>; // @cast-boundary render-helper
3628
- for (const [shortName, fieldDef] of Object.entries(screen.fields)) {
3629
- const qualified = screen.configKeys[shortName];
3630
- if (qualified === undefined) {
3631
- // Author hat ein Field deklariert ohne Mapping — nimm Default.
3632
- // Boot-Validator pinnt das, sollte nie zur Runtime greifen.
3633
- out[shortName] = defaults[shortName];
3634
- continue;
3635
- }
3636
- const stored = valuesQuery.data[qualified]?.value;
3637
- if (stored === undefined) {
3638
- out[shortName] = defaults[shortName];
3639
- continue;
3640
- }
3641
- const ftype = (fieldDef as { type?: string }).type;
3642
- // Field-Type-Coercion: config-Werte sind string|number|boolean,
3643
- // aber der Form-State erwartet das passende Field-Native-Type.
3644
- if (ftype === "number" || ftype === "money") {
3645
- out[shortName] = typeof stored === "number" ? stored : Number(stored);
3646
- } else if (ftype === "boolean") {
3647
- out[shortName] = typeof stored === "boolean" ? stored : stored === "true";
3648
- } else {
3649
- out[shortName] = typeof stored === "string" ? stored : String(stored);
3650
- }
3651
- }
3652
- return out as FormValues;
3653
- }, [valuesQuery.data, screen.fields, screen.configKeys]);
3654
-
3655
- // Cascade-Lookup: qualifiedKey → ConfigCascade für die
3656
- // Cascade-Anzeige unter jedem Feld. Defensive `levels`-Shape-Check
3657
- // damit fremde Query-Mocks (z.B. configEdit-Unit-Tests die nur
3658
- // `config:query:values` mocken) nicht durch das Cascade-Rendering
3659
- // crashen.
3660
- const cascades = useMemo<Record<string, ConfigCascade>>(() => {
3661
- if (!cascadeQuery.data) return {};
3662
- const out: Record<string, ConfigCascade> = {};
3663
- for (const [shortName, qualified] of Object.entries(screen.configKeys)) {
3664
- const cascade = cascadeQuery.data[qualified];
3665
- if (cascade && Array.isArray(cascade.levels)) out[shortName] = cascade;
3666
- }
3667
- return out;
3668
- }, [cascadeQuery.data, screen.configKeys]);
3669
-
3670
- // Multi-Write Submit: ein einzelner /api/batch Call mit N
3671
- // config:write:set Commands. Server-side ist batch atomic
3672
- // (transaktional: alle Writes in einer DB-TX, all-or-nothing) und
3673
- // browser-side ist es genau eine HTTP-Roundtrip — kein Race zwischen
3674
- // mehreren in-flight fetches die der Browser bei page.reload mid-
3675
- // submit aborten könnte. Promise.all von N separaten dispatcher.write-
3676
- // Calls war fragil: server bekommt + commited alle N, aber das
3677
- // Browser-Connection-Pool gibt sporadisch "Failed to fetch" für
3678
- // einzelne Responses zurück, customSubmit returnt failure obwohl der
3679
- // Write durch ist, das Form bleibt dirty.
3680
- const customSubmit = useCallback(
3681
- async (snapshot: FormSnapshot<FormValues>): Promise<SubmitResult<unknown>> => {
3682
- const commands: Command[] = [];
3683
- for (const [shortName, value] of Object.entries(snapshot.changes)) {
3684
- const qualified = screen.configKeys[shortName];
3685
- if (qualified === undefined) continue;
3686
- const ftype = (screen.fields[shortName] as { type?: string } | undefined)?.type;
3687
- commands.push({
3688
- type: "config:write:set",
3689
- payload: {
3690
- key: qualified,
3691
- value: ftype === "money" ? unwrapMoneyValue(value) : value,
3692
- scope: screen.scope,
3693
- },
3694
- });
3695
- }
3696
- if (commands.length === 0) {
3697
- return { validationBlocked: false, isSuccess: true, data: undefined };
3698
- }
3699
- const result = await dispatcher.batch(commands);
3700
- if (!result.isSuccess) {
3701
- return { validationBlocked: false, isSuccess: false, error: result.error };
3702
- }
3703
- // Cascade-Disclosure + Maskenwerte nach dem Write nachziehen, sonst
3704
- // bleibt die Anzeige stale bis Reload — gleiche refetch-Calls wie onReset.
3705
- // allSettled: der Write ist schon committed, ein gescheitertes Refetch
3706
- // (stale Anzeige) darf das Erfolgsergebnis nicht in einen Fehler kippen.
3707
- await Promise.allSettled([valuesQuery.refetch?.(), cascadeQuery.refetch?.()]);
3708
- return { validationBlocked: false, isSuccess: true, data: undefined };
3709
- },
3710
- [
3711
- dispatcher,
3712
- screen.configKeys,
3713
- screen.fields,
3714
- screen.scope,
3715
- valuesQuery.refetch,
3716
- cascadeQuery.refetch,
3717
- ],
3718
- );
3719
-
3720
- // Cascade-Disclosure (#429): Trigger sitzt in der Label-Row, das Panel
3721
- // unter dem Input — zwei getrennte Render-Slots teilen sich den
3722
- // expanded-State, der daher hier (pro Feld) statt in der Komponente lebt.
3723
- const [expandedFields, setExpandedFields] = useState<ReadonlySet<string>>(new Set());
3724
- const toggleExpanded = useCallback((fieldName: string) => {
3725
- setExpandedFields((prev) => {
3726
- const next = new Set(prev);
3727
- if (next.has(fieldName)) next.delete(fieldName);
3728
- else next.add(fieldName);
3729
- return next;
3730
- });
3731
- }, []);
3732
-
3733
- if (valuesQuery.loading && valuesQuery.data === null) {
3734
- return (
3735
- <Banner padded variant="loading" testId="kumiko-screen-loading">
3736
- Loading…
3737
- </Banner>
3738
- );
3739
- }
3740
- if (valuesQuery.error) {
3741
- return (
3742
- <Banner padded variant="error" testId="kumiko-screen-error">
3743
- {dispatcherErrorText(valuesQuery.error, effectiveTranslate)}
3744
- </Banner>
3745
- );
3746
- }
3747
- if (initial === null) {
3748
- return (
3749
- <Banner padded variant="loading" testId="kumiko-screen-loading">
3750
- Loading…
3751
- </Banner>
3752
- );
3753
- }
3754
- return (
3755
- <RenderEdit
3756
- screen={synthScreen}
3757
- entity={synthEntity}
3758
- featureName={schema.featureName}
3759
- initial={initial}
3760
- customSubmit={customSubmit}
3761
- {...(screen.submitLabel !== undefined && { submitLabel: screen.submitLabel })}
3762
- {...(translate !== undefined && { translate })}
3763
- labelAppendix={(fieldName: string) => {
3764
- const cascade = cascades[fieldName];
3765
- if (cascade === undefined) return undefined;
3766
- return (
3767
- <ConfigCascadeView
3768
- slot="trigger"
3769
- cascade={cascade}
3770
- screenScope={screen.scope}
3771
- expanded={expandedFields.has(fieldName)}
3772
- onToggle={() => toggleExpanded(fieldName)}
3773
- />
3774
- );
3775
- }}
3776
- fieldAppendix={(fieldName: string) => {
3777
- const cascade = cascades[fieldName];
3778
- // Panel nur rendern wenn aufgeklappt — sonst kein leerer Abstand
3779
- // unter dem Input.
3780
- if (cascade === undefined || !expandedFields.has(fieldName)) return undefined;
3781
- return (
3782
- <ConfigCascadeView
3783
- slot="panel"
3784
- cascade={cascade}
3785
- screenScope={screen.scope}
3786
- expanded
3787
- qualifiedKey={screen.configKeys[fieldName]}
3788
- onReset={async (key, scope) => {
3789
- await dispatcher.write("config:write:reset", { key, scope });
3790
- await Promise.allSettled([valuesQuery.refetch?.(), cascadeQuery.refetch?.()]);
3791
- }}
3792
- />
3793
- );
3794
- }}
3795
- />
3796
- );
3797
- }
3798
-
3799
- // Re-export the ScreenDefinition type so callers don't reach into
3800
- // framework/ui-types for a prop-type they need to narrow on.
3801
- export type { ScreenDefinition };