diff --git a/changelog.d/ts-ui-catalog-v0.md b/changelog.d/ts-ui-catalog-v0.md new file mode 100644 index 0000000000..3b70fd6023 --- /dev/null +++ b/changelog.d/ts-ui-catalog-v0.md @@ -0,0 +1,59 @@ +- **TypeScript client tier: UI catalog v0, component maps and a record-admin screen.** The + catalog types (`UI_CATALOG_COMPONENTS`, `UiCatalogProps` and one `UiProps` per name in + `@metaobjectsdev/runtime-web`) describe what the form and grid generators already emit: form, + field shell, five controls, nested and repeatable groups, button and data grid, plus `Page` + and `Panel` for a screen. `formFile()` and `tanstackGrid()` take a `componentMap` option. When + it is set, the form renders through the app's map, and the columns module exports an + `DataGrid` component. Without it, their output is unchanged, with three + exceptions below: assigned primary keys, int, long, double, float and currency members of a + nested value object, and top-level currency fields. + `@metaobjectsdev/react` ships `defaultComponents` and `UiComponentMap`, and + `@metaobjectsdev/tanstack` ships `defaultDataGrid`. The new ejectable `recordAdmin()` generator + (`meta eject record-admin`) writes `.admin.tsx`, a list, create and edit screen + derived from the generated form, grid and hooks. With no map configured, it renders through + the default components. TypeScript only, and no metamodel vocabulary. See + `docs/features/ui-catalog.md`. Generated-output change — regenerate to pick it up; three-way + merge preserves hand edits. The changes that ride along: + + - **Generated forms render an assigned primary key.** A key the caller assigns (an + `identity.primary` with no `@generation`, on a field with no `@default`) is required by the + InsertSchema, but the form hid it, so a create form for such an entity could never pass + validation. `formFile()` now renders that key as an editable field on create and disables it + on edit (when `defaultValues` is set). Generated and defaulted keys stay hidden. This + changes the form output for those entities with or without a `componentMap`. + - **`BoundInputProps` is a typed shape.** `form.input.` in `@metaobjectsdev/react` was + `Record`. It now declares `name`, `onChange`, `onBlur`, `ref` and `aria-label`, + plus optional `type`, `step`, `inputMode` and `placeholder`, so a catalog `TextInput` accepts + the spread. Spreading `form.input.` is unaffected. Code that builds a + `BoundInputProps` value by hand, such as a test stub, must now supply the required members. + - **`useEntityForm` submits number inputs as numbers.** A field whose constant has + `htmlType: "number"` (`field.int`, `field.long`, `field.double`, `field.float`, + including an assigned key) used to submit the input's string, which the + generated `z.number()` schema refused. It now registers with `setValueAs`: a typed value + becomes a number, and a blank one becomes `undefined` on create and `null` on edit. A + `field.decimal` is a text input and keeps its string. The new `numberValueAs` export does + the same for an int, long, double, float or currency member of a nested value object, which + the generated form registers directly. There a blank member is `undefined` on edit too, + because the value object is written whole and its schema takes no null member. + - **Generated forms render a currency field as ``.** A top-level + `field.currency` was a plain input that submitted a string, which the `z.number().int()` + schema refused. `formFile()` now binds `@metaobjectsdev/react`'s `` (integer + minor units, with the field's `@currency` and its `view.currency` `@locale`) through + react-hook-form's ``, with or without a `componentMap`. With a map it sits inside + the map's `Field`, as `` does, because catalog v0 has no currency control. A + blank amount stays blank: it is omitted on create and sent as `null` on edit. A required + amount is natively `required`; with a `@default` it is required only on edit, so the + default can fill a blank on create. An array of amounts keeps the plain control other array fields get. + - **`` accepts no amount, commits on Enter and edits in the locale's notation.** + `value` is now `number | null | undefined`, and `null` or `undefined` renders an empty box. + The new optional `onClear` is called when the user empties a box that held an amount; + without it the old behavior (`onChange(0)`) stays. Focusing and leaving the box without + editing it emits nothing. Enter commits the typed amount, so a form submitted with Enter + saves what is on screen. Focus writes the amount with the decimal separator the locale uses + for money, which `parseCurrency` reads, so a `de-DE` amount edits as `12,50` and a `fr-CH` + one as `12.50` (its plain numbers use a comma), and neither is misread on blur. The new + `currencyDecimalSeparator(currency, locale)` in `@metaobjectsdev/runtime-web` returns it. + Existing callers that pass a number compile unchanged. + - **A boolean with no view renders through the map's `Checkbox`.** With a `componentMap`, a + `field.boolean` that declares no `view.checkbox`, top-level or in a nested value object, is + asked of `Checkbox`, not `TextInput`. diff --git a/client/web/packages/react/src/currency-input.tsx b/client/web/packages/react/src/currency-input.tsx index c537f867d8..ae9c9a497d 100644 --- a/client/web/packages/react/src/currency-input.tsx +++ b/client/web/packages/react/src/currency-input.tsx @@ -1,12 +1,17 @@ import { useState, useEffect, useRef } from "react"; -import type { ReactElement, FocusEvent, ChangeEvent } from "react"; -import { formatCurrency, parseCurrency, minorUnitsFor } from "@metaobjectsdev/runtime-web"; +import type { ReactElement, FocusEvent, ChangeEvent, KeyboardEvent } from "react"; +import { formatCurrency, parseCurrency, minorUnitsFor, currencyDecimalSeparator } from "@metaobjectsdev/runtime-web"; export interface CurrencyInputProps { - /** Value in integer minor units (cents for USD). */ - value: number; - /** Called with new value in integer minor units after blur. */ + /** Value in integer minor units (cents for USD). `null` or `undefined` is no amount: an empty box. */ + value: number | null | undefined; + /** Called with new value in integer minor units after blur, or on Enter. */ onChange: (cents: number) => void; + /** + * Called when the user empties a box that held an amount. Without it, an empty optional + * box emits `onChange(0)`. + */ + onClear?: () => void; /** ISO 4217 currency code. Defaults to "USD". */ currency?: string; /** BCP 47 locale code. Defaults to "en-US". */ @@ -20,67 +25,99 @@ export interface CurrencyInputProps { /** * Bidirectional currency input. Displays formatted dollars; captures - * dollars from the user; emits cents to onChange on blur. + * dollars from the user; emits cents to onChange on blur or Enter. * - * - Focus strips symbol + grouping for easier editing - * - Blur re-formats + emits cents - * - Empty input + !required → emits 0 + * - No amount (`null`/`undefined`) renders an empty box + * - Focus strips symbol + grouping for easier editing, in the locale's notation + * - Blur or Enter re-formats + emits cents, only when the user edited the box + * - Empty input that held an amount + !required → onClear, else emits 0 * - Empty input + required → reverts to last valid; no onChange - * - Unparseable input on blur → reverts to last valid format; no onChange + * - Unparseable input → reverts to last valid format; no onChange * - Float drift avoided: parseCurrency uses decimal-string arithmetic */ export function CurrencyInput(props: CurrencyInputProps): ReactElement { const currency = props.currency ?? "USD"; const locale = props.locale ?? "en-US"; + const display = (cents: number | null | undefined): string => + cents === null || cents === undefined ? "" : formatCurrency(cents, currency, locale); - const [text, setText] = useState(() => formatCurrency(props.value, currency, locale)); + const [text, setText] = useState(() => display(props.value)); const [isInvalid, setIsInvalid] = useState(false); const lastValidValue = useRef(props.value); + const edited = useRef(false); // Re-format when external value changes (controlled component sync) useEffect(() => { if (props.value !== lastValidValue.current) { - setText(formatCurrency(props.value, currency, locale)); + setText(display(props.value)); lastValidValue.current = props.value; } }, [props.value, currency, locale]); function handleFocus(_e: FocusEvent) { setIsInvalid(false); - // Strip symbol + grouping so user can edit the raw number + edited.current = false; + if (props.value === null || props.value === undefined) { + setText(""); + return; + } + // Strip symbol + grouping so user can edit the raw number, with the separator parseCurrency reads const minorUnits = minorUnitsFor(currency, locale); const factor = Math.pow(10, minorUnits); - const dollars = (props.value / factor).toFixed(minorUnits); - setText(dollars); + setText((props.value / factor).toFixed(minorUnits).replace(".", currencyDecimalSeparator(currency, locale))); } - function handleBlur(_e: FocusEvent) { + function commit() { + edited.current = false; const trimmed = text.trim(); if (trimmed === "") { + if (props.value === null || props.value === undefined) { + setText(""); + return; + } if (props.required) { setIsInvalid(true); - setText(formatCurrency(props.value, currency, locale)); + setText(display(props.value)); return; } setIsInvalid(false); + if (props.onClear !== undefined) { + props.onClear(); + lastValidValue.current = undefined; + setText(""); + return; + } props.onChange(0); lastValidValue.current = 0; - setText(formatCurrency(0, currency, locale)); + setText(display(0)); return; } const parsed = parseCurrency(trimmed, currency, locale); if (parsed === null) { // Unparseable — revert to last valid - setText(formatCurrency(lastValidValue.current, currency, locale)); + setText(display(lastValidValue.current)); return; } setIsInvalid(false); props.onChange(parsed); lastValidValue.current = parsed; - setText(formatCurrency(parsed, currency, locale)); + setText(display(parsed)); + } + + function handleBlur(_e: FocusEvent) { + if (!edited.current) { + setText(display(props.value)); + return; + } + commit(); + } + + function handleKeyDown(e: KeyboardEvent) { + if (e.key === "Enter" && edited.current) commit(); } function handleChange(e: ChangeEvent) { + edited.current = true; setText(e.target.value); } @@ -92,6 +129,7 @@ export function CurrencyInput(props: CurrencyInputProps): ReactElement { onChange={handleChange} onFocus={handleFocus} onBlur={handleBlur} + onKeyDown={handleKeyDown} className={props.className} placeholder={props.placeholder} required={props.required} diff --git a/client/web/packages/react/src/index.ts b/client/web/packages/react/src/index.ts index 96a819004f..e14a9e08fe 100644 --- a/client/web/packages/react/src/index.ts +++ b/client/web/packages/react/src/index.ts @@ -1,6 +1,7 @@ // Public API surface for @metaobjectsdev/react. export { useEntityForm, + numberValueAs, type EntityFieldMeta, type EntityMeta, type BoundInputProps, @@ -8,6 +9,12 @@ export { type UseEntityFormOptions, type UseEntityFormReturn, } from "./use-entity-form.js"; +export { + defaultComponents, + type UiComponentMap, + type ReactUiCatalogProps, + type UiControlRef, +} from "./ui-components.js"; export { CurrencyInput, type CurrencyInputProps } from "./currency-input.js"; export { ImageUploadAdapterProvider, diff --git a/client/web/packages/react/src/ui-components.tsx b/client/web/packages/react/src/ui-components.tsx new file mode 100644 index 0000000000..cf6a2fa787 --- /dev/null +++ b/client/web/packages/react/src/ui-components.tsx @@ -0,0 +1,206 @@ +// The UI catalog (v0) instantiated for React, and the default component map. +// +// `UiComponentMap` is what an application's component map module exports as `components` +// and what the generators' `componentMap` option points at: one React component per +// catalog name. `defaultComponents` is that map rendered as the plain markup the form +// generator writes when no map is configured (the same `metaobjects-*` classes, so +// `@metaobjectsdev/react/form.css` styles both). It carries no look of its own. +// +// An app keeps the defaults it likes and replaces the rest: +// +// import { defaultComponents } from "@metaobjectsdev/react"; +// import { defaultDataGrid } from "@metaobjectsdev/tanstack"; +// export const components = { ...defaultComponents, DataGrid: defaultDataGrid, TextInput: MyInput }; +// +// Bound controls receive the form library's `ref` and must attach it to their native +// element. These defaults use `forwardRef`, which works on React 18 and 19; a React 19 +// component may take `ref` as an ordinary prop instead. + +import { forwardRef, type ComponentType, type ReactElement, type ReactNode, type Ref, type SyntheticEvent } from "react"; +import type { + UiOption, + UiCatalogName, + UiCatalogProps, + UiFormProps, + UiFormActionsProps, + UiFieldProps, + UiFormSectionProps, + UiFieldArrayProps, + UiTextInputProps, + UiTextAreaProps, + UiSelectProps, + UiCheckboxProps, + UiRadioGroupProps, + UiButtonProps, + UiPageProps, + UiPanelProps, +} from "@metaobjectsdev/runtime-web"; + +/** The ref a bound control receives. `never` because the element type is the control's own choice. */ +export type UiControlRef = Ref; + +/** The catalog's props for React: children are `ReactNode`, handlers take a synthetic event. */ +export type ReactUiCatalogProps = UiCatalogProps; + +/** One React component per catalog name: what a component map module exports as `components`. */ +export type UiComponentMap = { readonly [K in UiCatalogName]: ComponentType }; + +type Native

= Omit; + +function Form(props: UiFormProps): ReactElement { + return ( +

+ {props.children} +
+ ); +} + +function FormActions(props: UiFormActionsProps): ReactElement { + return
{props.children}
; +} + +function Field(props: UiFieldProps): ReactElement { + return ( +
+ + {props.children} + {props.error !== undefined && ( + {props.error} + )} +
+ ); +} + +function FormSection(props: UiFormSectionProps): ReactElement { + return ( +
+ {props.legend} + {props.children} + {props.onRemove !== undefined && ( + + )} +
+ ); +} + +function FieldArray(props: UiFieldArrayProps): ReactElement { + return ( +
+ {props.label} + {props.children} + +
+ ); +} + +const TextInput = forwardRef>>( + function TextInput(props, ref) { + return ; + }, +); + +const TextArea = forwardRef>>( + function TextArea(props, ref) { + return