@cosmicdrift/kumiko-renderer 0.419.0 → 0.421.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/app/action-form-body.js +7 -3
  2. package/dist/app/action-form-preview.d.ts +1 -1
  3. package/dist/app/action-form-preview.js +1 -1
  4. package/dist/app/action-form-support.d.ts +2 -0
  5. package/dist/app/action-form-support.js +16 -2
  6. package/dist/app/content-editors.d.ts +2 -0
  7. package/dist/app/entity-edit-prefill.js +24 -26
  8. package/dist/app/projection-detail-body.js +22 -1
  9. package/dist/app/projection-detail-header-model.js +2 -6
  10. package/dist/app/projection-detail-header-region.js +32 -21
  11. package/dist/app/projection-detail-header.d.ts +1 -0
  12. package/dist/app/use-projection-detail-layout.d.ts +2 -0
  13. package/dist/app/use-projection-detail-layout.js +2 -2
  14. package/dist/components/document-field-editor.d.ts +7 -0
  15. package/dist/components/document-field-editor.js +9 -0
  16. package/dist/components/document-text.d.ts +3 -0
  17. package/dist/components/document-text.js +32 -0
  18. package/dist/components/page-help-button.d.ts +43 -0
  19. package/dist/components/page-help-button.js +84 -0
  20. package/dist/components/render-edit-field-grid.js +10 -6
  21. package/dist/components/render-edit-section-kinds.js +8 -2
  22. package/dist/components/render-edit-types.d.ts +2 -0
  23. package/dist/components/render-field-ai-assist.js +19 -5
  24. package/dist/components/render-field-control.js +25 -3
  25. package/dist/components/render-list-toolbar.d.ts +1 -1
  26. package/dist/components/render-list-toolbar.js +2 -2
  27. package/dist/components/render-list.js +12 -2
  28. package/dist/headless/form/index.d.ts +1 -1
  29. package/dist/headless/form/index.js +1 -1
  30. package/dist/headless/format/document-values.d.ts +3 -0
  31. package/dist/headless/format/document-values.js +19 -8
  32. package/dist/headless/format/index.d.ts +1 -1
  33. package/dist/headless/index.d.ts +3 -3
  34. package/dist/headless/index.js +2 -2
  35. package/dist/headless/view-model/edit.js +15 -0
  36. package/dist/headless/view-model/index.d.ts +1 -1
  37. package/dist/headless/view-model/index.js +1 -1
  38. package/dist/headless/view-model/list.d.ts +1 -0
  39. package/dist/headless/view-model/list.js +3 -0
  40. package/dist/headless/view-model/types.d.ts +8 -1
  41. package/dist/i18n-defaults.js +3 -0
  42. package/dist/primitives.d.ts +13 -1
  43. package/dist/primitives.js +1 -1
  44. package/dist/status-tone.d.ts +4 -0
  45. package/dist/status-tone.js +6 -0
  46. package/dist/web/icons.d.ts +1 -0
  47. package/dist/web/icons.js +2 -1
  48. package/dist/web/primitives/button.d.ts +1 -1
  49. package/dist/web/primitives/button.js +3 -3
  50. package/dist/web/primitives/dialog.d.ts +1 -1
  51. package/dist/web/primitives/dialog.js +2 -2
  52. package/dist/web/primitives/layout-elements.d.ts +1 -1
  53. package/dist/web/primitives/layout-elements.js +8 -1
  54. package/dist/web/primitives/page-header.d.ts +1 -1
  55. package/dist/web/primitives/page-header.js +5 -5
  56. package/package.json +5 -5
  57. package/src/changes.json +24 -0
@@ -305,6 +305,7 @@ export function ActionFormBody({ schema, screen, translate, entityId, initialOve
305
305
  return (_jsx(ActionFormLoadStatus, { state: loadState, screenId: screen.id, translate: effectiveTranslate }));
306
306
  }
307
307
  const { preview } = screen;
308
+ const renderPreview = (values) => preview === undefined ? null : (_jsx(ActionFormPreviewPanel, { preview: preview, fields: screen.fields, values: values, translate: effectiveTranslate, locale: locale }));
308
309
  return (_jsx(AiAssistPayloadProvider, { value: aiAssistPayload, children: _jsx(RenderEdit, { screen: synthScreen, entity: synthEntity, featureName: schema.featureName, initial: derivedInitial, ...(screen.derive !== undefined && { formDerivation: screen }), actionFormScreenQn: qualifyScreenId(schema.featureName, screen.id),
309
310
  // Extension sections in the actionForm see the initial form values
310
311
  // (incl. searchParams prefill, e.g. ?incidentId=...) as initialValues;
@@ -331,7 +332,10 @@ export function ActionFormBody({ schema, screen, translate, entityId, initialOve
331
332
  const { text, complete } = resolveFieldText(ref, values, effectiveTranslate);
332
333
  return complete ? text : undefined;
333
334
  },
334
- }), ...(summary !== undefined && { summary }), ...(preview !== undefined && {
335
- belowSections: (values) => (_jsx(ActionFormPreviewPanel, { preview: preview, fields: screen.fields, values: values, translate: effectiveTranslate, locale: locale })),
336
- }), ...(translate !== undefined && { translate }) }, formEpoch) }));
335
+ }), ...(summary !== undefined && { summary }), ...(preview !== undefined &&
336
+ (preview.section === undefined
337
+ ? { belowSections: renderPreview }
338
+ : {
339
+ afterSection: (sectionId, values) => sectionId === preview.section ? renderPreview(values) : undefined,
340
+ })), ...(translate !== undefined && { translate }) }, formEpoch) }));
337
341
  }
@@ -1,6 +1,6 @@
1
1
  import type { ActionFormPreview } from "@cosmicdrift/kumiko-framework/ui-types";
2
2
  import { type ReactNode } from "react";
3
- import type { Translate } from "../headless/index.ts";
3
+ import { type Translate } from "../headless/index.ts";
4
4
  type FormValueMap = Readonly<Record<string, unknown>>;
5
5
  /** Shows what the submit would do, from a query over the live form values. A failed query is a hint only. */
6
6
  export declare function ActionFormPreviewPanel({ preview, fields, values, translate, locale, }: {
@@ -1,7 +1,7 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { isPlainObject, propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
3
3
  import { useMemo } from "react";
4
- import { isCurrencyOnlyMoney } from "../headless/form/form-controller.js";
4
+ import { isCurrencyOnlyMoney, } from "../headless/index.js";
5
5
  import { REFERENCE_SEARCH_DEBOUNCE_MS } from "../hooks/reference-limits.js";
6
6
  import { useDebouncedValue } from "../hooks/use-debounced-value.js";
7
7
  import { useQuery } from "../hooks/use-query.js";
@@ -50,6 +50,8 @@ export type ResolvedSuccessFact = {
50
50
  readonly key: string;
51
51
  readonly label: string;
52
52
  readonly lines: readonly string[];
53
+ /** Set for a `file` fact: stored file ids shown as a file list instead of lines. */
54
+ readonly fileIds?: readonly string[];
53
55
  };
54
56
  export type ResolvedSuccessItem = {
55
57
  readonly key: string;
@@ -1,6 +1,7 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
3
3
  import { useMemo } from "react";
4
+ import { fileIdsOf } from "../file-ids-of.js";
4
5
  import { applyFormatSpec, formatMoneyValue, } from "../headless/index.js";
5
6
  import { useQuery } from "../hooks/use-query.js";
6
7
  import { usePrimitives } from "../primitives.js";
@@ -103,8 +104,16 @@ export function resolveSuccessFacts(facts, data, translate, locale) {
103
104
  const resolved = [];
104
105
  (facts ?? []).forEach((fact, index) => {
105
106
  const value = propertyOf(data, fact.field);
107
+ const valueType = fact.type;
108
+ if (valueType === "file") {
109
+ const fileIds = fileIdsOf(value);
110
+ if (fileIds.length > 0) {
111
+ resolved.push({ key: String(index), label: translate(fact.label), lines: [], fileIds });
112
+ }
113
+ return;
114
+ }
106
115
  const entries = Array.isArray(value) ? value : [value];
107
- const lines = entries.flatMap((entry) => formatTypedFact(entry, fact.type, locale) ?? factLine(entry, locale) ?? []);
116
+ const lines = entries.flatMap((entry) => formatTypedFact(entry, valueType, locale) ?? factLine(entry, locale) ?? []);
108
117
  if (lines.length > 0) {
109
118
  resolved.push({ key: String(index), label: translate(fact.label), lines });
110
119
  }
@@ -123,9 +132,14 @@ function SuccessItemHints({ items, }) {
123
132
  }
124
133
  /** One line per fact, a list of values as a block; shared by the success box and the preview panel. */
125
134
  export function ActionFormFacts({ testIdPrefix = "action-form-success-fact", facts, }) {
126
- const { Grid, Text } = usePrimitives();
135
+ const { FileValueList, Grid, Text } = usePrimitives();
127
136
  return facts.map((fact) => {
128
137
  const factTestId = `${testIdPrefix}-${fact.key}`;
138
+ if (fact.fileIds !== undefined) {
139
+ if (FileValueList === undefined)
140
+ return null;
141
+ return (_jsxs(Grid, { columns: 1, testId: factTestId, children: [_jsxs(Text, { children: [fact.label, ":"] }), _jsx(FileValueList, { fileIds: fact.fileIds, testId: `${factTestId}-files` })] }, fact.key));
142
+ }
129
143
  if (fact.lines.length === 1) {
130
144
  return (_jsxs(Text, { testId: factTestId, children: [fact.label, ": ", fact.lines[0]] }, fact.key));
131
145
  }
@@ -15,6 +15,8 @@ export type ContentEditorProps = {
15
15
  * here. */
16
16
  readonly variables: readonly string[];
17
17
  readonly readOnly: boolean;
18
+ /** "text" asks for plain text formatting only (bold, italic, lists, link): no images, tables or other blocks. Editors that cannot restrict themselves ignore it. */
19
+ readonly formatting?: "text";
18
20
  };
19
21
  export type ContentEditorComponent = ComponentType<ContentEditorProps>;
20
22
  /** Default id value for callers that don't generate their own (e.g. a
@@ -297,6 +297,27 @@ function coerceEmbeddedListRows(raw, fieldName, schema, maxItems) {
297
297
  }
298
298
  return rows;
299
299
  }
300
+ // Row-action navigate stringifies arrays via String(arr) → "a,b" (or JSON when the navigate helper
301
+ // JSON.stringifies); a single value is a one-element list. JSON first, then comma-split.
302
+ function parseListPrefill(raw) {
303
+ const splitComma = () => raw === ""
304
+ ? []
305
+ : raw
306
+ .split(",")
307
+ .map((s) => s.trim())
308
+ .filter(Boolean);
309
+ try {
310
+ const parsed = JSON.parse(raw);
311
+ if (Array.isArray(parsed))
312
+ return parsed.map((v) => String(v));
313
+ if (typeof parsed === "string")
314
+ return [parsed];
315
+ return splitComma();
316
+ }
317
+ catch {
318
+ return splitComma();
319
+ }
320
+ }
300
321
  function coercePrefillString(raw, name, shape, fallback, defaultCurrency, moneyCurrencyOverrides) {
301
322
  if (shape.type === "number") {
302
323
  if (raw.trim() === "")
@@ -310,34 +331,11 @@ function coercePrefillString(raw, name, shape, fallback, defaultCurrency, moneyC
310
331
  }
311
332
  if (shape.type === "boolean")
312
333
  return raw === "true";
334
+ if (shape.type === "reference" && shape.multiple === true)
335
+ return parseListPrefill(raw);
313
336
  if (shape.type === "multiSelect") {
314
- // Row-action navigate stringifies arrays via String(arr) → "a,b" (or
315
- // JSON when the navigate helper JSON.stringifies). Try JSON first
316
- // (even without a "[" prefix), then comma-split; filter against
317
- // field.options when present so unknown values never reach the form.
337
+ const values = parseListPrefill(raw);
318
338
  const optionValues = multiSelectOptionValues(shape);
319
- const splitComma = () => raw === ""
320
- ? []
321
- : raw
322
- .split(",")
323
- .map((s) => s.trim())
324
- .filter(Boolean);
325
- let values;
326
- try {
327
- const parsed = JSON.parse(raw);
328
- if (Array.isArray(parsed)) {
329
- values = parsed.map((v) => String(v));
330
- }
331
- else if (typeof parsed === "string") {
332
- values = [parsed];
333
- }
334
- else {
335
- values = splitComma();
336
- }
337
- }
338
- catch {
339
- values = splitComma();
340
- }
341
339
  return optionValues !== undefined ? values.filter((v) => optionValues.has(v)) : values;
342
340
  }
343
341
  if (shape.type === "embedded" && shape.multiple === true) {
@@ -1,6 +1,7 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { evalFieldCondition } from "@cosmicdrift/kumiko-framework/ui-types";
3
3
  import { useState } from "react";
4
+ import { pageHelpButtonOf } from "../components/page-help-button.js";
4
5
  import { RenderEdit } from "../components/render-edit.js";
5
6
  import { WriteFormRegistryProvider } from "../components/write-form-registry.js";
6
7
  import { useOptionalDispatcher } from "../context/dispatcher-context.js";
@@ -85,7 +86,8 @@ export function ProjectionDetailBody({ schema, screen, translate, entityId, }) {
85
86
  activeTabId: activeSection?.id,
86
87
  writeForms,
87
88
  });
88
- const { hasMetrics, headerActionsList, hasHeaderActions, hasHeaderCard, renderedDetailScreen } = useProjectionDetailLayout({ screen, headerActions, hasTabs, detailScreen });
89
+ const pageHelp = detailPageHelpOf(screen, visibleSections, schema, effectiveTranslate, appFeatures);
90
+ const { hasMetrics, headerActionsList, hasHeaderActions, hasHeaderCard, renderedDetailScreen } = useProjectionDetailLayout({ screen, headerActions, hasTabs, detailScreen, pageHelp });
89
91
  const recordId = detailQuery.data?.["id"];
90
92
  const tabCounts = useRelatedListTabCounts({
91
93
  sections: hasTabs ? visibleSections : [],
@@ -124,6 +126,7 @@ export function ProjectionDetailBody({ schema, screen, translate, entityId, }) {
124
126
  userRoles,
125
127
  host,
126
128
  headerActionsList,
129
+ ...(pageHelp !== undefined && { pageHelp }),
127
130
  setActionError,
128
131
  actionError,
129
132
  pageHeaderSlotAvailable,
@@ -164,3 +167,21 @@ export function ProjectionDetailBody({ schema, screen, translate, entityId, }) {
164
167
  refreshRows: reloadDetail,
165
168
  })] }));
166
169
  }
170
+ function detailPageHelpOf(screen, sections, schema, translate, appFeatures) {
171
+ const sectionSources = sections.flatMap((section) => "kind" in section && section.kind === "relatedList"
172
+ ? [
173
+ {
174
+ spec: section.pageHelp,
175
+ defaultEntity: section.entity ?? "",
176
+ scopeTitle: section.title,
177
+ },
178
+ ]
179
+ : []);
180
+ return pageHelpButtonOf([{ spec: screen.pageHelp, defaultEntity: "" }, ...sectionSources], {
181
+ featureName: schema.featureName,
182
+ screenId: screen.id,
183
+ ownEntities: schema.entities,
184
+ translate,
185
+ appFeatures,
186
+ });
187
+ }
@@ -1,17 +1,13 @@
1
1
  import { isFieldsEditSection, isFormatSpec, isWriteFormEditSection, normalizeEditField, sectionFieldSpecs, } from "@cosmicdrift/kumiko-framework/ui-types";
2
2
  import { applyFormatSpec } from "../headless/index.js";
3
- import { statusToneForOptionTone, statusToneForValue, } from "../primitives.js";
3
+ import { statusToneForOption } from "../primitives.js";
4
4
  import { isAbsoluteHttpUrl, withUiLocale } from "./projection-detail-navigation.js";
5
5
  export function headerStatusTone(header, record) {
6
6
  // skip: a header without status has no tone
7
7
  if (header.status === undefined)
8
8
  return undefined;
9
9
  const value = String(record[header.statusToneField ?? header.status] ?? "");
10
- const declared = header.statusTones !== undefined && Object.hasOwn(header.statusTones, value)
11
- ? header.statusTones[value]
12
- : undefined;
13
- const declaredTone = declared !== undefined ? statusToneForOptionTone(declared) : undefined;
14
- return declaredTone ?? statusToneForValue(value);
10
+ return statusToneForOption(value, header.statusTones);
15
11
  }
16
12
  function layoutStatusFormat(screen, statusField) {
17
13
  for (const section of screen.layout.sections) {
@@ -82,10 +82,29 @@ function shortTitleOf(header, record) {
82
82
  const value = header?.shortTitle === undefined ? undefined : record[header.shortTitle];
83
83
  return typeof value === "string" && value !== "" ? value : undefined;
84
84
  }
85
+ function renderPageHeaderElement(model, pieces, PageHeader, titleText) {
86
+ const { screen, record, hasHeaderActions } = model;
87
+ const { pageHeaderCompact, recordTitle, statusBadge } = pieces;
88
+ const header = screen.header;
89
+ const hasTitleBlock = titleText !== undefined;
90
+ return (_jsx(PageHeader, { ...(hasTitleBlock && { bodyTitle: true }), ...(hasTitleBlock && { recordTitle: shortTitleOf(header, record) ?? titleText }), ...(header?.narrowTitle !== undefined && {
91
+ narrowRecordTitle: model.effectiveTranslate(header.narrowTitle),
92
+ }), ...(header === undefined && recordTitle !== undefined && { title: recordTitle }), ...(!hasTitleBlock &&
93
+ !pageHeaderCompact &&
94
+ statusBadge !== undefined && {
95
+ status: statusBadge,
96
+ }), ...(model.pageHelp !== undefined && { help: model.pageHelp }), ...(hasHeaderActions && {
97
+ actions: renderHeaderActionsContent(model, { compact: pageHeaderCompact, PageHeader }),
98
+ }) }));
99
+ }
100
+ function renderPageHeaderBand(model, pieces, headerSlot, bandSubtitle) {
101
+ const { MetricBand } = model.primitives;
102
+ return (_jsxs(_Fragment, { children: [MetricBand === undefined && bandSubtitle, MetricBand === undefined && headerSlot, (model.hasMetrics || bandSubtitle !== undefined || headerSlot !== undefined) &&
103
+ (MetricBand !== undefined || model.hasMetrics) &&
104
+ renderBandWithNarrowMetrics(model, pieces.metricItems, bandSubtitle, MetricBand !== undefined ? headerSlot : undefined)] }));
105
+ }
85
106
  function renderPageHeaderBranch(model, pieces, headerSlot, PageHeader) {
86
- const { screen, record, primitives, hasHeaderActions, hasMetrics } = model;
87
- const { MetricBand } = primitives;
88
- const { pageHeaderCompact, recordTitle, statusBadge, metricItems } = pieces;
107
+ const { screen, record } = model;
89
108
  const header = screen.header;
90
109
  // Only an explicit `header` gets the body title block; recordTitleField alone keeps the shell
91
110
  // header title and breadcrumb.
@@ -93,32 +112,24 @@ function renderPageHeaderBranch(model, pieces, headerSlot, PageHeader) {
93
112
  // The title block owns chip and subtitle, so neither the shell header nor the band repeats them.
94
113
  const hasTitleBlock = titleText !== undefined;
95
114
  const bandSubtitle = hasTitleBlock ? undefined : pieces.bandSubtitle;
96
- return (_jsxs(_Fragment, { children: [_jsx(PageHeader, { ...(hasTitleBlock && { bodyTitle: true }), ...(hasTitleBlock && { recordTitle: shortTitleOf(header, record) ?? titleText }), ...(header?.narrowTitle !== undefined && {
97
- narrowRecordTitle: model.effectiveTranslate(header.narrowTitle),
98
- }), ...(header === undefined && recordTitle !== undefined && { title: recordTitle }), ...(!hasTitleBlock &&
99
- !pageHeaderCompact &&
100
- statusBadge !== undefined && {
101
- status: statusBadge,
102
- }), ...(hasHeaderActions && {
103
- actions: renderHeaderActionsContent(model, { compact: pageHeaderCompact, PageHeader }),
104
- }) }), titleText !== undefined &&
105
- renderRecordTitleBlock(model, titleText, statusBadge, pieces.headerSubtitleSlot, false), hasTitleBlock && renderMobileSummary(model), hasTitleBlock && renderDetailSummary(model), MetricBand === undefined && bandSubtitle, MetricBand === undefined && headerSlot, (hasMetrics || bandSubtitle !== undefined || headerSlot !== undefined) &&
106
- (MetricBand !== undefined || hasMetrics) &&
107
- renderBandWithNarrowMetrics(model, metricItems, bandSubtitle, MetricBand !== undefined ? headerSlot : undefined), !hasTitleBlock && renderMobileSummary(model), !hasTitleBlock && renderDetailSummary(model), pieces.actionErrorBanner] }));
115
+ return (_jsxs(_Fragment, { children: [renderPageHeaderElement(model, pieces, PageHeader, titleText), titleText !== undefined &&
116
+ renderRecordTitleBlock(model, titleText, pieces.statusBadge, pieces.headerSubtitleSlot, false), hasTitleBlock && renderMobileSummary(model), hasTitleBlock && renderDetailSummary(model), renderPageHeaderBand(model, pieces, headerSlot, bandSubtitle), !hasTitleBlock && renderMobileSummary(model), !hasTitleBlock && renderDetailSummary(model), pieces.actionErrorBanner] }));
108
117
  }
109
118
  function renderHeaderCardBranch(model, pieces, headerSlot) {
110
119
  const { primitives, hasHeaderActions, hasMetrics, hasHeaderCard } = model;
111
- const { Card } = primitives;
112
- const { recordTitle, headerTitleSlot, headerSubtitleSlot, headerActionsContent } = pieces;
120
+ const { Card, Grid } = primitives;
121
+ const { recordTitle, headerSubtitleSlot, headerActionsContent } = pieces;
122
+ const titleSlot = pieces.headerTitleSlot ?? recordTitle;
123
+ const actionsSlot = model.pageHelp !== undefined ? (_jsxs(Grid, { columns: "auto", children: [headerActionsContent, model.pageHelp] })) : (headerActionsContent);
113
124
  // Metrics must leave the head card to take part in the narrow reordering.
114
125
  const metricsOutsideCard = usesNarrowMetricsOrder(model) && hasMetrics;
115
126
  return (_jsxs(_Fragment, { children: [(hasHeaderCard || headerSlot !== undefined || recordTitle !== undefined) && (_jsxs(Card, { slots: {
116
- ...(headerTitleSlot !== undefined && { title: headerTitleSlot }),
117
- ...(headerTitleSlot === undefined &&
118
- recordTitle !== undefined && { title: recordTitle }),
127
+ ...(titleSlot !== undefined && { title: titleSlot }),
119
128
  ...(headerSubtitleSlot !== undefined && { subtitle: headerSubtitleSlot }),
120
129
  ...(headerSlot !== undefined && { headerContent: headerSlot }),
121
- ...(hasHeaderActions && { headerActions: headerActionsContent }),
130
+ ...((hasHeaderActions || model.pageHelp !== undefined) && {
131
+ headerActions: actionsSlot,
132
+ }),
122
133
  }, children: [hasMetrics && !metricsOutsideCard && renderMetricsBlock(model, pieces.metricItems), pieces.actionErrorBanner] })), renderMobileSummary(model), renderDetailSummary(model), metricsOutsideCard &&
123
134
  wrapNarrowOrder(model, NARROW_METRICS_ORDER, renderMetricsBlock(model, pieces.metricItems))] }));
124
135
  }
@@ -19,6 +19,7 @@ export type DetailHeaderModel = {
19
19
  readonly host: ReturnHost | undefined;
20
20
  readonly headerActionsList: readonly RenderEditAction[];
21
21
  readonly setActionError: Dispatch<SetStateAction<ErrorNotice | null>>;
22
+ readonly pageHelp?: ReactNode;
22
23
  };
23
24
  export type PageHeaderActionsOptions = {
24
25
  readonly compact: boolean;
@@ -1,4 +1,5 @@
1
1
  import type { ProjectionDetailScreenDefinition } from "@cosmicdrift/kumiko-framework/ui-types";
2
+ import { type ReactNode } from "react";
2
3
  import type { RenderEditAction } from "../components/render-edit.tsx";
3
4
  import type { useProjectionDetailData } from "./use-projection-detail-data.ts";
4
5
  type DetailLayoutInput = {
@@ -6,6 +7,7 @@ type DetailLayoutInput = {
6
7
  readonly headerActions: readonly RenderEditAction[] | undefined;
7
8
  readonly hasTabs: boolean;
8
9
  readonly detailScreen: ReturnType<typeof useProjectionDetailData>["detailScreen"];
10
+ readonly pageHelp: ReactNode | undefined;
9
11
  };
10
12
  export declare function useProjectionDetailLayout(input: DetailLayoutInput): {
11
13
  hasMetrics: boolean;
@@ -2,14 +2,14 @@ import { useMemo } from "react";
2
2
  import { screenFillsHeight } from "../screen-fills-height.js";
3
3
  const HEADER_CARD_DEFAULT_WIDTH = "4xl";
4
4
  export function useProjectionDetailLayout(input) {
5
- const { screen, headerActions, hasTabs, detailScreen } = input;
5
+ const { screen, headerActions, hasTabs, detailScreen, pageHelp } = input;
6
6
  const hasHeader = screen.header !== undefined;
7
7
  const hasMetrics = screen.metrics !== undefined && screen.metrics.length > 0;
8
8
  // ?? [] rather than threading `headerActions !== undefined` through every
9
9
  // use below — an empty array is a safe no-op for .map/.length.
10
10
  const headerActionsList = headerActions ?? [];
11
11
  const hasHeaderActions = headerActionsList.length > 0;
12
- const hasHeaderCard = hasHeader || hasMetrics || hasHeaderActions;
12
+ const hasHeaderCard = hasHeader || hasMetrics || hasHeaderActions || pageHelp !== undefined;
13
13
  // A header card (metric band, status, actions) needs more room than the
14
14
  // 640px form column; screens with only a record title keep the narrow one.
15
15
  const widensScreenFormColumn = hasHeaderCard &&
@@ -0,0 +1,7 @@
1
+ import type { ReactNode } from "react";
2
+ export declare function DocumentFieldEditor({ id, value, readOnly, onChange, }: {
3
+ readonly id: string;
4
+ readonly value: string;
5
+ readonly readOnly: boolean;
6
+ readonly onChange: (value: unknown) => void;
7
+ }): ReactNode;
@@ -0,0 +1,9 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useContentEditor } from "../app/content-editors.js";
3
+ import { documentHtmlToText } from "./document-text.js";
4
+ export function DocumentFieldEditor({ id, value, readOnly, onChange, }) {
5
+ const Editor = useContentEditor("document");
6
+ return (_jsx(Editor, { id: id, value: value, readOnly: readOnly, variables: [], formatting: "text",
7
+ // An emptied tiptap document is "<p></p>"; required and empty checks need "".
8
+ onChange: (html) => onChange(documentHtmlToText(html) === "" ? "" : html) }));
9
+ }
@@ -0,0 +1,3 @@
1
+ export declare function documentHtmlToText(html: string): string;
2
+ /** Blank line starts a paragraph, a single newline becomes a hard break. */
3
+ export declare function textToDocumentHtml(text: string): string;
@@ -0,0 +1,32 @@
1
+ const ENTITIES = {
2
+ "&amp;": "&",
3
+ "&lt;": "<",
4
+ "&gt;": ">",
5
+ "&quot;": '"',
6
+ "&#39;": "'",
7
+ "&nbsp;": " ",
8
+ };
9
+ // Regex instead of DOMParser: the renderer also runs on React Native, which has no DOM.
10
+ export function documentHtmlToText(html) {
11
+ return html
12
+ .replace(/<br\s*\/?>/gi, "\n")
13
+ .replace(/<\/(p|div|li|h[1-6]|blockquote)>/gi, "\n\n")
14
+ .replace(/<[^>]*>/g, "")
15
+ .replace(/&(?:amp|lt|gt|quot|#39|nbsp);/g, (entity) => ENTITIES[entity] ?? entity)
16
+ .replace(/\n{3,}/g, "\n\n")
17
+ .trim();
18
+ }
19
+ function escapeHtml(text) {
20
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
21
+ }
22
+ /** Blank line starts a paragraph, a single newline becomes a hard break. */
23
+ export function textToDocumentHtml(text) {
24
+ return text
25
+ .replace(/\r\n?/g, "\n")
26
+ .split(/\n{2,}/)
27
+ .map((paragraph) => paragraph.trim())
28
+ .filter((paragraph) => paragraph !== "")
29
+ .map((paragraph) => escapeHtml(paragraph).replace(/\n/g, "<br>"))
30
+ .map((paragraphHtml) => `<p>${paragraphHtml}</p>`)
31
+ .join("");
32
+ }
@@ -0,0 +1,43 @@
1
+ import type { EntityDefinition, PageHelpSpec } from "@cosmicdrift/kumiko-framework/ui-types";
2
+ import { type ReactNode } from "react";
3
+ import type { FeatureSchema } from "../app/feature-schema.ts";
4
+ import { type Translate } from "../headless/index.ts";
5
+ type HelpEntity = Pick<EntityDefinition, "fields">;
6
+ export type ResolvedPageHelpSection = {
7
+ readonly kind: "status";
8
+ readonly field: string;
9
+ readonly entityName: string;
10
+ readonly entity: HelpEntity;
11
+ readonly featureName: string;
12
+ /** i18n key of the card heading. */
13
+ readonly titleKey: string;
14
+ } | {
15
+ readonly kind: "text";
16
+ readonly title: string;
17
+ readonly text: string;
18
+ };
19
+ export type PageHelpButtonProps = {
20
+ readonly sections: readonly ResolvedPageHelpSection[];
21
+ readonly translate: Translate;
22
+ };
23
+ export declare function PageHelpButton({ sections, translate }: PageHelpButtonProps): ReactNode;
24
+ /** A `pageHelp` plus the entity its status sections fall back to (empty where the screen has none). */
25
+ export type PageHelpSource = {
26
+ readonly spec: PageHelpSpec | undefined;
27
+ readonly defaultEntity: string;
28
+ readonly scopeTitle?: string;
29
+ };
30
+ export type PageHelpContext = {
31
+ readonly featureName: string;
32
+ /** Short id of the screen the help belongs to; its title heads the screen's own status sections. */
33
+ readonly screenId: string;
34
+ /** Entities of the screen's own feature, used when `appFeatures` does not know the target. */
35
+ readonly ownEntities: Readonly<Record<string, HelpEntity>>;
36
+ readonly translate: Translate;
37
+ readonly appFeatures: readonly FeatureSchema[];
38
+ };
39
+ /** The help button for the sections of all `sources`, in order; undefined when nothing resolves.
40
+ * A status entity is `section.entity` (bare or `<feature>:<entity>`), else the source's default entity;
41
+ * labels and help sentences come from the feature owning it. */
42
+ export declare function pageHelpButtonOf(sources: readonly PageHelpSource[], context: PageHelpContext): ReactNode;
43
+ export {};
@@ -0,0 +1,84 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { parseRefTarget } from "@cosmicdrift/kumiko-framework/ui-types";
3
+ import { useState } from "react";
4
+ import { fieldOptionHelpKey, fieldOptionLabelKey } from "../headless/index.js";
5
+ import { usePrimitives } from "../primitives.js";
6
+ import { statusToneForOption } from "../status-tone.js";
7
+ // A tint of the primary token (light and dark follow the theme) so the help stands out from the neutral
8
+ // "Bearbeiten"; below sm only the icon shows, in the same square as the header's "…" button.
9
+ const TRIGGER_CLASS = "h-10 shrink-0 border-primary/30 bg-primary/10 text-primary hover:bg-primary/15 hover:text-primary";
10
+ const SECTION_STACK_CLASS = "flex flex-col gap-4 px-6 py-4";
11
+ function StatusLegend({ section, translate, }) {
12
+ const { Text, StatusBadge, Grid } = usePrimitives();
13
+ const { featureName, entityName, field: fieldName, entity } = section;
14
+ const field = entity.fields[fieldName];
15
+ if (field === undefined || field.type !== "select")
16
+ return null;
17
+ const rows = field.options.flatMap((value) => {
18
+ const label = translate(fieldOptionLabelKey(featureName, entityName, fieldName, value));
19
+ const tone = statusToneForOption(value, field.optionTones) ?? "muted";
20
+ return [
21
+ StatusBadge !== undefined ? (_jsx(StatusBadge, { value: label, tone: tone, testId: `page-help-badge-${value}` }, `badge-${value}`)) : (_jsx(Text, { testId: `page-help-badge-${value}`, children: label }, `badge-${value}`)),
22
+ _jsx(Text, { testId: `page-help-text-${value}`, children: translate(fieldOptionHelpKey(featureName, entityName, fieldName, value)) }, `text-${value}`),
23
+ ];
24
+ });
25
+ return (_jsx(Grid, { columns: 2, legend: true, ruled: true, testId: "page-help-options", children: rows }));
26
+ }
27
+ function PageHelpBody({ sections, translate }) {
28
+ const { Section, Text, FillContainer } = usePrimitives();
29
+ // Two tabs may share entity and field, two text sections a title: a repeat gets a counter.
30
+ const seen = new Map();
31
+ const uniqueKey = (base) => {
32
+ const count = (seen.get(base) ?? 0) + 1;
33
+ seen.set(base, count);
34
+ return `${base}#${count}`;
35
+ };
36
+ const cards = sections.map((section, index) => (_jsx(Section, { title: translate(section.kind === "status" ? section.titleKey : section.title), testId: `page-help-section-${index}`, ...(section.kind === "status" && {
37
+ subtitle: translate("kumiko.pageHelp.statusIntro"),
38
+ }), children: section.kind === "status" ? (_jsx(StatusLegend, { section: section, translate: translate })) : (_jsx(Text, { children: translate(section.text) })) }, uniqueKey(section.kind === "status"
39
+ ? `${section.featureName}:${section.entityName}:${section.field}`
40
+ : section.title))));
41
+ return FillContainer !== undefined ? (_jsx(FillContainer, { className: SECTION_STACK_CLASS, children: cards })) : (cards);
42
+ }
43
+ export function PageHelpButton({ sections, translate }) {
44
+ const { Button, Dialog, Drawer } = usePrimitives();
45
+ const [open, setOpen] = useState(false);
46
+ const title = translate("kumiko.pageHelp.button");
47
+ const body = _jsx(PageHelpBody, { sections: sections, translate: translate });
48
+ return (_jsxs(_Fragment, { children: [_jsx(Button, { variant: "secondary", icon: "help-circle", title: title, className: TRIGGER_CLASS, collapseLabel: true, onClick: () => setOpen(true), testId: "page-help-button", children: translate("kumiko.pageHelp.buttonLabel") }), Drawer !== undefined ? (_jsx(Drawer, { open: open, onOpenChange: setOpen, title: title, testId: "page-help-drawer", children: body })) : (_jsx(Dialog, { open: open, onOpenChange: setOpen, title: title, confirmLabel: translate("kumiko.dialog.close"), hideCancel: true, initialFocus: "confirm", onConfirm: () => undefined, testId: "page-help-drawer", children: body }))] }));
49
+ }
50
+ function resolveStatusSection(rawEntity, section, scopeTitle, context) {
51
+ const target = parseRefTarget(rawEntity, context.featureName);
52
+ const ownsTarget = target.featureName === context.featureName;
53
+ const entity = context.appFeatures.find((f) => f.featureName === target.featureName)?.entities[target.entityName] ?? (ownsTarget ? context.ownEntities[target.entityName] : undefined);
54
+ if (entity === undefined)
55
+ return undefined;
56
+ return {
57
+ kind: "status",
58
+ field: section.field,
59
+ entityName: target.entityName,
60
+ entity,
61
+ featureName: target.featureName,
62
+ titleKey: section.title ?? scopeTitle ?? `screen:${context.screenId}.title`,
63
+ };
64
+ }
65
+ /** The help button for the sections of all `sources`, in order; undefined when nothing resolves.
66
+ * A status entity is `section.entity` (bare or `<feature>:<entity>`), else the source's default entity;
67
+ * labels and help sentences come from the feature owning it. */
68
+ export function pageHelpButtonOf(sources, context) {
69
+ const sections = [];
70
+ for (const { spec, defaultEntity, scopeTitle } of sources) {
71
+ for (const section of spec?.sections ?? []) {
72
+ if (section.kind === "text") {
73
+ sections.push(section);
74
+ continue;
75
+ }
76
+ const resolved = resolveStatusSection(section.entity ?? defaultEntity, section, scopeTitle, context);
77
+ if (resolved !== undefined)
78
+ sections.push(resolved);
79
+ }
80
+ }
81
+ if (sections.length === 0)
82
+ return undefined;
83
+ return _jsx(PageHelpButton, { sections: sections, translate: context.translate });
84
+ }
@@ -37,12 +37,11 @@ function spanLongValue(field, columns) {
37
37
  }
38
38
  return { ...field, span: columns };
39
39
  }
40
- function createFieldCellRenderer(model, section, columns, facts) {
40
+ function createFieldCellRenderer(model, section, columns, flows, facts) {
41
41
  const { props, state, form } = model.engine;
42
42
  const { snapshot } = form;
43
43
  const { GridCell } = state.primitives;
44
44
  const { isSettingsList, isCreate } = model.footer;
45
- const usesFieldFlow = model.titles.usesFieldFlow && !facts;
46
45
  const { disabled, fieldAccent } = props;
47
46
  const showsChangedMarker = !isCreate || props.markChangedFields;
48
47
  const clearErrorsAndValidate = (fieldName) => {
@@ -52,7 +51,7 @@ function createFieldCellRenderer(model, section, columns, facts) {
52
51
  };
53
52
  return (rawField) => {
54
53
  const field = facts ? spanLongValue(rawField, columns) : rawField;
55
- return (_jsx(GridCellForField, { field: disabled ? { ...field, readOnly: true } : field, columns: columns, ...(!isSettingsList && usesFieldFlow && { flow: true }), ...(isSettingsList && {
54
+ return (_jsx(GridCellForField, { field: disabled ? { ...field, readOnly: true } : field, columns: columns, ...(!isSettingsList && flows && { flow: true }), ...(isSettingsList && {
56
55
  layout: "row",
57
56
  accent: fieldAccent?.(field.field) === true,
58
57
  }), issues: snapshot.errors[field.field], onChange: (v) => {
@@ -64,6 +63,11 @@ function createFieldCellRenderer(model, section, columns, facts) {
64
63
  section.title !== undefined && { sectionTitle: section.title }), ...(showsChangedMarker && field.field in snapshot.changes && { changed: true }) }, field.field));
65
64
  };
66
65
  }
66
+ // The flow layout sizes each field by its type and ignores `columns`; a section opts out with
67
+ // `flow: false` to get equal grid cells instead.
68
+ function usesFlowLayout(model, section, facts) {
69
+ return model.titles.usesFieldFlow && !facts && section.flow !== false;
70
+ }
67
71
  // Read-only text values with a declared column count form a label/value grid; the flow layout
68
72
  // would ignore `columns` and give every value the full width. Without a declared count the
69
73
  // stacked layout stays, so existing records do not reflow.
@@ -80,10 +84,10 @@ export function renderFieldGrid(model, section, fields, columns, gridKey, column
80
84
  const { rowAfterField } = model.engine.props;
81
85
  const dirty = Object.keys(model.engine.form.snapshot.changes).length > 0;
82
86
  const { isSettingsList } = model.footer;
83
- const { usesFieldFlow } = model.titles;
84
87
  const facts = isReadOnlyFactsGrid(model, fields, columns, columnsDeclared);
85
- const renderCell = createFieldCellRenderer(model, section, columns, facts);
86
- return (_jsx(Grid, { columns: columns, ...(facts && { facts: true }), ...(isSettingsList ? { list: true } : usesFieldFlow && !facts && { flow: true }), children: fields.map((field) => {
88
+ const flows = usesFlowLayout(model, section, facts);
89
+ const renderCell = createFieldCellRenderer(model, section, columns, flows, facts);
90
+ return (_jsx(Grid, { columns: columns, ...(facts && { facts: true }), ...(isSettingsList ? { list: true } : flows && { flow: true }), children: fields.map((field) => {
87
91
  const extraRow = rowAfterField?.(field.field, { dirty });
88
92
  if (extraRow === undefined)
89
93
  return renderCell(field);
@@ -136,10 +136,16 @@ function withSectionPresentation(model, section, sectionIndex, node) {
136
136
  ? "sm:hidden"
137
137
  : undefined;
138
138
  const titleClass = section.titleOnNarrow === false ? "max-sm:[&_[data-section-title]]:hidden" : undefined;
139
- if (section.after === undefined && narrowClass === undefined && titleClass === undefined) {
139
+ const sectionTail = section.kind === "fields" && section.id !== undefined
140
+ ? props.afterSection?.(section.id, form.snapshot.values)
141
+ : undefined;
142
+ if (section.after === undefined &&
143
+ sectionTail === undefined &&
144
+ narrowClass === undefined &&
145
+ titleClass === undefined) {
140
146
  return node;
141
147
  }
142
- return (_jsxs(FillContainer, { className: [narrowClass, titleClass, "gap-3"].filter((c) => c !== undefined).join(" "), children: [node, section.after !== undefined && (_jsx(EditSlotMount, { slot: section.after, slotName: "afterSection", screenId: props.screen.id, entityName: sections.vm.entityName, entityId: resolveExtensionEntityId(props.entityId, sections.vm.id), values: form.snapshot.values, ...(props.activeTabId !== undefined && { activeTabId: props.activeTabId }) }))] }, `section-presentation-${sectionIndex}`));
148
+ return (_jsxs(FillContainer, { className: [narrowClass, titleClass, "gap-3"].filter((c) => c !== undefined).join(" "), children: [node, sectionTail, section.after !== undefined && (_jsx(EditSlotMount, { slot: section.after, slotName: "afterSection", screenId: props.screen.id, entityName: sections.vm.entityName, entityId: resolveExtensionEntityId(props.entityId, sections.vm.id), values: form.snapshot.values, ...(props.activeTabId !== undefined && { activeTabId: props.activeTabId }) }))] }, `section-presentation-${sectionIndex}`));
143
149
  }
144
150
  export function renderEditSections(model) {
145
151
  const rendered = model.engine.sections.filteredSections.map((section, sectionIndex) => ({
@@ -225,6 +225,8 @@ export type RenderEditProps<TValues extends FormValues, TCtx = unknown> = {
225
225
  readonly leadContent?: ReactNode;
226
226
  /** Rendered after the sections, above the form actions, with the live form values. */
227
227
  readonly belowSections?: (values: Readonly<Record<string, unknown>>) => ReactNode;
228
+ /** Rendered at the end of the fields section with this id, with the live form values. */
229
+ readonly afterSection?: (sectionId: string, values: Readonly<Record<string, unknown>>) => ReactNode;
228
230
  /** Blocks submit (button and Enter) while fields stay editable — unlike
229
231
  * `disabled`, which locks the whole form. For a gate the host owns, e.g.
230
232
  * an acknowledgement checkbox in `leadContent`. */