Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions changelog.d/ts-ui-catalog-v0.md
Original file line number Diff line number Diff line change
@@ -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 `Ui<Name>Props` 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
`<Entity><Grid>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 `<Entity>.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.<field>` in `@metaobjectsdev/react` was
`Record<string, any>`. 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.<field>` 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 `<CurrencyInput>`.** 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 `<CurrencyInput>` (integer
minor units, with the field's `@currency` and its `view.currency` `@locale`) through
react-hook-form's `<Controller>`, with or without a `componentMap`. With a map it sits inside
the map's `Field`, as `<ImageUpload>` 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.
- **`<CurrencyInput>` 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`.
78 changes: 58 additions & 20 deletions client/web/packages/react/src/currency-input.tsx
Original file line number Diff line number Diff line change
@@ -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". */
Expand All @@ -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<HTMLInputElement>) {
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<HTMLInputElement>) {
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<HTMLInputElement>) {
if (!edited.current) {
setText(display(props.value));
return;
}
commit();
}

function handleKeyDown(e: KeyboardEvent<HTMLInputElement>) {
if (e.key === "Enter" && edited.current) commit();
}

function handleChange(e: ChangeEvent<HTMLInputElement>) {
edited.current = true;
setText(e.target.value);
}

Expand All @@ -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}
Expand Down
7 changes: 7 additions & 0 deletions client/web/packages/react/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
// Public API surface for @metaobjectsdev/react.
export {
useEntityForm,
numberValueAs,
type EntityFieldMeta,
type EntityMeta,
type BoundInputProps,
type InputAccessor,
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,
Expand Down
Loading
Loading