diff --git a/.changeset/36043-line-item-cell-editors.md b/.changeset/36043-line-item-cell-editors.md new file mode 100644 index 00000000000..84896d5d04d --- /dev/null +++ b/.changeset/36043-line-item-cell-editors.md @@ -0,0 +1,26 @@ +--- +'@objectstack/spec': minor +'@object-ui/fields': minor +'@object-ui/plugin-form': minor +'@objectstack/metadata-core': patch +'@object-ui/types': patch +--- + +feat: the form's line-item table edits people, multi-select, tags, check and rating cells the way the main list does + +Clause-②: yes (widening) +Metadata-protocol: semantic + +`InlineGridColumnSchema.type` (a relationship field's `inlineColumns`, a form view's `subforms[].columns`, and the page blocks that carry the same column) accepts five more cell types, each spelled as its namesake field type: `user` (people), `multiselect`, `tags`, `boolean` (check) and `rating`. The column also takes an optional `max`, the star count of a `rating` cell (default 5). + +In the line-item table: + +- A `user` cell opens the main list's person picker under the cell: a searchable list with recent people and Clear; a pick writes and closes. `multiple` holds several people. +- A `multiselect` cell holds several of its options and a `tags` cell holds free-form tags. Each opens its searchable list under the cell; a click outside or Tab writes what was picked, Esc writes nothing. A list emptied in the cell writes `null`, as a cleared multi-value field stores, so a line whose only value was removed is still a blank line. A `tags` cell takes no `options`. +- A `boolean` cell is a checkbox: a click or Space toggles it and writes `true` / `false`. +- A `rating` cell draws its stars; a click on a star, or a digit key on the cell, sets it, and 0 clears it. +- Read-only and list-mode cells show people by name, a rating as its stars, a multi-select's option labels, and a check cell as the session's yes/no word. + +Visible change on existing forms: a column the table derives from a child field (no `type` written) now follows that field. A `boolean` / `toggle` field becomes a checkbox instead of the yes/no select, and it writes `true` / `false` instead of the strings `'true'` / `'false'` (the server reads both the same). A `rating` field becomes stars instead of a number box. `user`, `multiselect`, `checkboxes` and `tags` fields get their own cells instead of a plain text box that took a typed user id or a single option. A column that writes its `type` is unchanged, a `type: 'select'` column over a boolean field included. Which derived columns are visible by default is unchanged. + +The field-level security scrubber classifies the column's new `max` key as kept (a number, never a field name). diff --git a/content/docs/data-modeling/field-types.mdx b/content/docs/data-modeling/field-types.mdx index 37be5b2fac7..9e4b344f59a 100644 --- a/content/docs/data-modeling/field-types.mdx +++ b/content/docs/data-modeling/field-types.mdx @@ -599,16 +599,22 @@ the parent's form edits the children as rows of a table: - **Columns.** Without `inlineColumns` the columns are derived from the child object. An explicit column (`InlineGridColumn`) names the child field in `name` and may set `label`, - `width` (pixels), `required` and `type`. A column's `type` is one of nine cell controls: - `text`, `number`, `currency`, `date`, `datetime`, `time`, `select`, `lookup` and `file`. - Declaring `type` opts the column out of derivation, so supply what the control needs - (`options` for a select, `reference` and `displayField` for a lookup). + `width` (pixels), `required` and `type`. A column's `type` is one of fourteen cell controls: + `text`, `number`, `currency`, `date`, `datetime`, `time`, `select`, `lookup`, `file`, `user`, + `multiselect`, `tags`, `boolean` and `rating`. Declaring `type` opts the column out of + derivation, so supply what the control needs (`options` for a select or multi-select, + `reference` and `displayField` for a lookup, `max` for a rating). - **File cells.** A `file` column is an upload control in the cell, with removable chips and thumbnails for images; `accept` and `multiple` restrict it. Derived columns map `file`, `image` and `avatar` child fields to `file` cells, an image field accepting `image/*`. Shown as text, a file cell reads the file's name, or a count when it holds several. -- **Booleans.** A derived `boolean` or `toggle` child field becomes a `select` cell storing - `'true'` / `'false'`, labelled in the session language. +- **Booleans.** A derived `boolean` or `toggle` child field becomes a checkbox cell storing + `true` / `false`; read-only, it shows the session language's yes / no word. A column authored + as `type: 'select'` over a boolean field keeps the select. +- **People, multi-select, tags and rating.** A derived `user` field becomes the person picker + (several people when the field is `multiple`), `multiselect` and `checkboxes` fields a list + holding several options, `tags` a free-form tag list, and `rating` a row of stars (`max` + from the field, default 5). Each edits as the same cell does in the list view. - **Currency.** A `currency` cell shows the resolved currency's symbol, and decimals of that currency's CLDR fraction digits; `prefix` replaces the symbol only. - **Order.** When the columns are derived and the child object has a field named `position`, `sort_order`, `sequence`, diff --git a/content/docs/references/data/field.mdx b/content/docs/references/data/field.mdx index 94b8fa424e1..3a585e95257 100644 --- a/content/docs/references/data/field.mdx +++ b/content/docs/references/data/field.mdx @@ -83,7 +83,7 @@ const result = CurrencyConfigSchema.parse(data); | **deleteBehavior** | `Enum<'set_null' \| 'cascade' \| 'restrict'>` | optional (default: `"set_null"`) | What happens if referenced record is deleted | | **inlineEdit** | `boolean \| Enum<'grid' \| 'form'>` | optional | How the parent's form edits these child records inline (atomic master-detail) when a field group of the parent names this child (fieldGroups[].relatedList); a child no group names is not inlined, whatever this says. true or absent = auto-pick grid/form by child shape; 'grid' = editable line-item grid; 'form' = list + per-row full form. | | **inlineTitle** | `string` | optional | Title for the inline master-detail grid | -| **inlineColumns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| 'lookup' \| 'file'>; width?: number; … }[]` | optional | Explicit columns for the inline grid (derived from the child object when omitted). Each entry is a strict, name-keyed column (`{ name, label?, type?, … }` — objectui GridColumn); identity-only entries (`{ name }`) hydrate everything else from the child object's fields. Unknown keys and the retired `field` spelling are refused at parse. | +| **inlineColumns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| …>; width?: number; … }[]` | optional | Explicit columns for the inline grid (derived from the child object when omitted). Each entry is a strict, name-keyed column (`{ name, label?, type?, … }` — objectui GridColumn); identity-only entries (`{ name }`) hydrate everything else from the child object's fields. Unknown keys and the retired `field` spelling are refused at parse. | | **inlineAmountField** | `string` | optional | Numeric child field summed for the inline grid total | | **relatedList** | `boolean \| 'primary'` | optional | Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). true = an auxiliary panel on the record page; absent = an auxiliary panel, except that a master_detail field becomes a body table when a field group of the parent names it (fieldGroups[].relatedList); false = hidden: the child object is not shown on the parent record page; 'primary' = a body table: part of the record's main content, shown as a full-width table in the record's detail body. Write true on a master_detail field to keep it an auxiliary panel even from a field group. 'primary' places a list and does not order it: the parent object's relatedLists orders the full-width tables and the auxiliary panels. The page layout is defined by ADR-0085. A derived related list (relatedList: 'primary') inherits its row order from the child object's DEFAULT list view sort — the isDefault view, or the first declared list item when none is marked default; wire spelling is sort=`` / sort=-``, never $orderby. A child object with no list-view sort emits no ordering parameter, and rows fall back to record-id order. | | **relatedListTitle** | `string` | optional | Title for the detail-page related list | @@ -220,16 +220,17 @@ const result = CurrencyConfigSchema.parse(data); | :--- | :--- | :--- | :--- | | **name** | `string` | ✅ | Child field this column shows — the key the grid reads and writes on each row object (objectui GridColumn.name). The retired `field` spelling is refused. | | **label** | `string` | optional | Column header; defaults to the child field's label via hydration. | -| **type** | `Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| 'lookup' \| 'file'>` | optional | Cell control, derived from the child field's type when omitted. Declaring it opts the column out of schema hydration — supply the extras (options / reference / …) yourself. | +| **type** | `Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| …>` | optional | Cell control, derived from the child field's type when omitted: `user` is a person picker, `multiselect` a list holding several of the column's options, `tags` a list of free-form tags, `boolean` a checkbox and `rating` a row of stars. Declaring it opts the column out of schema hydration — supply the extras (options / reference / …) yourself. | | **width** | `number` | optional | Fixed column width in px; omitted columns use type-based role sizing (text flexes, numeric/date/select stay fixed). | | **required** | `boolean` | optional | Cell is flagged inline-invalid while empty. Computed columns are never required. | -| **options** | `{ label: string; value: string }[]` | optional | Select-cell options for `type: 'select'`; derived from the child field's options when the column declares no `type`. | +| **options** | `{ label: string; value: string }[]` | optional | Options of a `select` or `multiselect` cell, and the words a `boolean` cell reads as (values `true` / `false`); derived from the child field's options when the column declares no `type`. A `tags` cell reads none: it holds free-form tags. | | **prefix** | `string` | optional | Symbol shown in a `currency` cell in place of the resolved currency's own symbol. No default: when omitted, the cell shows the symbol of the currency it resolves. It replaces the symbol only — the amount's decimal places stay the currency's. | | **step** | `number` | optional | Input step for numeric cells. | | **reference** | `string` | optional | Referenced object for `type: 'lookup'` cells; derived from the child lookup field when the column declares no `type`. | | **displayField** | `string` | optional | Label field shown for a picked lookup record. | | **idField** | `string` | optional | Id field stored for a picked lookup record. | -| **multiple** | `boolean` | optional | Multi-value column: multi-record lookup, or multi-file upload cell. | +| **multiple** | `boolean` | optional | Multi-value column: multi-record lookup, several people in a `user` cell, or multi-file upload cell. | +| **max** | `integer` | optional | Star count of a `rating` cell (default 5); derived from the child field's `max` when the column declares no `type`. | | **accept** | `string[]` | optional | Accepted MIME types / extensions for a `file` cell's picker (e.g. ['image/*', '.pdf']); omit to accept anything. | | **defaultHidden** | `boolean` | optional | Collapsed into the grid's column chooser by default (not dropped); required columns are never default-hidden. | | **computed** | `boolean` | optional | Read-only computed column, recomputed live from sibling cells via `expr` and written back into the row. | @@ -417,16 +418,17 @@ Allowed Values: `phone`, `id_card`, `bank_account`, `email`, `name` | :--- | :--- | :--- | :--- | | **name** | `string` | ✅ | Child field this column shows — the key the grid reads and writes on each row object (objectui GridColumn.name). The retired `field` spelling is refused. | | **label** | `string` | optional | Column header; defaults to the child field's label via hydration. | -| **type** | `Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| 'lookup' \| 'file'>` | optional | Cell control, derived from the child field's type when omitted. Declaring it opts the column out of schema hydration — supply the extras (options / reference / …) yourself. | +| **type** | `Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| 'lookup' \| 'file' \| 'user' \| 'multiselect' \| 'tags' \| 'boolean' \| 'rating'>` | optional | Cell control, derived from the child field's type when omitted: `user` is a person picker, `multiselect` a list holding several of the column's options, `tags` a list of free-form tags, `boolean` a checkbox and `rating` a row of stars. Declaring it opts the column out of schema hydration — supply the extras (options / reference / …) yourself. | | **width** | `number` | optional | Fixed column width in px; omitted columns use type-based role sizing (text flexes, numeric/date/select stay fixed). | | **required** | `boolean` | optional | Cell is flagged inline-invalid while empty. Computed columns are never required. | -| **options** | `{ label: string; value: string }[]` | optional | Select-cell options for `type: 'select'`; derived from the child field's options when the column declares no `type`. | +| **options** | `{ label: string; value: string }[]` | optional | Options of a `select` or `multiselect` cell, and the words a `boolean` cell reads as (values `true` / `false`); derived from the child field's options when the column declares no `type`. A `tags` cell reads none: it holds free-form tags. | | **prefix** | `string` | optional | Symbol shown in a `currency` cell in place of the resolved currency's own symbol. No default: when omitted, the cell shows the symbol of the currency it resolves. It replaces the symbol only — the amount's decimal places stay the currency's. | | **step** | `number` | optional | Input step for numeric cells. | | **reference** | `string` | optional | Referenced object for `type: 'lookup'` cells; derived from the child lookup field when the column declares no `type`. | | **displayField** | `string` | optional | Label field shown for a picked lookup record. | | **idField** | `string` | optional | Id field stored for a picked lookup record. | -| **multiple** | `boolean` | optional | Multi-value column: multi-record lookup, or multi-file upload cell. | +| **multiple** | `boolean` | optional | Multi-value column: multi-record lookup, several people in a `user` cell, or multi-file upload cell. | +| **max** | `integer` | optional | Star count of a `rating` cell (default 5); derived from the child field's `max` when the column declares no `type`. | | **accept** | `string[]` | optional | Accepted MIME types / extensions for a `file` cell's picker (e.g. ['image/*', '.pdf']); omit to accept anything. | | **defaultHidden** | `boolean` | optional | Collapsed into the grid's column chooser by default (not dropped); required columns are never default-hidden. | | **computed** | `boolean` | optional | Read-only computed column, recomputed live from sibling cells via `expr` and written back into the row. | diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 0f8f3a27aa2..110d3593031 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -263,7 +263,7 @@ const result = ApiMethod.parse(data); | **deleteBehavior** | `Enum<'set_null' \| 'cascade' \| 'restrict'>` | optional (default: `"set_null"`) | What happens if referenced record is deleted | | **inlineEdit** | `boolean \| Enum<'grid' \| 'form'>` | optional | How the parent's form edits these child records inline (atomic master-detail) when a field group of the parent names this child (fieldGroups[].relatedList); a child no group names is not inlined, whatever this says. true or absent = auto-pick grid/form by child shape; 'grid' = editable line-item grid; 'form' = list + per-row full form. | | **inlineTitle** | `string` | optional | Title for the inline master-detail grid | -| **inlineColumns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| 'lookup' \| 'file'>; width?: number; … }[]` | optional | Explicit columns for the inline grid (derived from the child object when omitted). Each entry is a strict, name-keyed column (`{ name, label?, type?, … }` — objectui GridColumn); identity-only entries (`{ name }`) hydrate everything else from the child object's fields. Unknown keys and the retired `field` spelling are refused at parse. | +| **inlineColumns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| …>; width?: number; … }[]` | optional | Explicit columns for the inline grid (derived from the child object when omitted). Each entry is a strict, name-keyed column (`{ name, label?, type?, … }` — objectui GridColumn); identity-only entries (`{ name }`) hydrate everything else from the child object's fields. Unknown keys and the retired `field` spelling are refused at parse. | | **inlineAmountField** | `string` | optional | Numeric child field summed for the inline grid total | | **relatedList** | `boolean \| 'primary'` | optional | Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). true = an auxiliary panel on the record page; absent = an auxiliary panel, except that a master_detail field becomes a body table when a field group of the parent names it (fieldGroups[].relatedList); false = hidden: the child object is not shown on the parent record page; 'primary' = a body table: part of the record's main content, shown as a full-width table in the record's detail body. Write true on a master_detail field to keep it an auxiliary panel even from a field group. 'primary' places a list and does not order it: the parent object's relatedLists orders the full-width tables and the auxiliary panels. The page layout is defined by ADR-0085. A derived related list (relatedList: 'primary') inherits its row order from the child object's DEFAULT list view sort — the isDefault view, or the first declared list item when none is marked default; wire spelling is sort=`` / sort=-``, never $orderby. A child object with no list-view sort emits no ordering parameter, and rows fall back to record-id order. | | **relatedListTitle** | `string` | optional | Title for the detail-page related list | @@ -658,7 +658,7 @@ const result = ApiMethod.parse(data); | **deleteBehavior** | `Enum<'set_null' \| 'cascade' \| 'restrict'>` | optional (default: `"set_null"`) | What happens if referenced record is deleted | | **inlineEdit** | `boolean \| Enum<'grid' \| 'form'>` | optional | How the parent's form edits these child records inline (atomic master-detail) when a field group of the parent names this child (fieldGroups[].relatedList); a child no group names is not inlined, whatever this says. true or absent = auto-pick grid/form by child shape; 'grid' = editable line-item grid; 'form' = list + per-row full form. | | **inlineTitle** | `string` | optional | Title for the inline master-detail grid | -| **inlineColumns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| 'lookup' \| 'file'>; width?: number; … }[]` | optional | Explicit columns for the inline grid (derived from the child object when omitted). Each entry is a strict, name-keyed column (`{ name, label?, type?, … }` — objectui GridColumn); identity-only entries (`{ name }`) hydrate everything else from the child object's fields. Unknown keys and the retired `field` spelling are refused at parse. | +| **inlineColumns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| …>; width?: number; … }[]` | optional | Explicit columns for the inline grid (derived from the child object when omitted). Each entry is a strict, name-keyed column (`{ name, label?, type?, … }` — objectui GridColumn); identity-only entries (`{ name }`) hydrate everything else from the child object's fields. Unknown keys and the retired `field` spelling are refused at parse. | | **inlineAmountField** | `string` | optional | Numeric child field summed for the inline grid total | | **relatedList** | `boolean \| 'primary'` | optional | Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). true = an auxiliary panel on the record page; absent = an auxiliary panel, except that a master_detail field becomes a body table when a field group of the parent names it (fieldGroups[].relatedList); false = hidden: the child object is not shown on the parent record page; 'primary' = a body table: part of the record's main content, shown as a full-width table in the record's detail body. Write true on a master_detail field to keep it an auxiliary panel even from a field group. 'primary' places a list and does not order it: the parent object's relatedLists orders the full-width tables and the auxiliary panels. The page layout is defined by ADR-0085. A derived related list (relatedList: 'primary') inherits its row order from the child object's DEFAULT list view sort — the isDefault view, or the first declared list item when none is marked default; wire spelling is sort=`` / sort=-``, never $orderby. A child object with no list-view sort emits no ordering parameter, and rows fall back to record-id order. | | **relatedListTitle** | `string` | optional | Title for the detail-page related list | diff --git a/content/docs/references/system/migration.mdx b/content/docs/references/system/migration.mdx index 1acff62cf59..5f2e76c3b35 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -86,7 +86,7 @@ Add a new field to an existing object | **deleteBehavior** | `Enum<'set_null' \| 'cascade' \| 'restrict'>` | optional (default: `"set_null"`) | What happens if referenced record is deleted | | **inlineEdit** | `boolean \| Enum<'grid' \| 'form'>` | optional | How the parent's form edits these child records inline (atomic master-detail) when a field group of the parent names this child (fieldGroups[].relatedList); a child no group names is not inlined, whatever this says. true or absent = auto-pick grid/form by child shape; 'grid' = editable line-item grid; 'form' = list + per-row full form. | | **inlineTitle** | `string` | optional | Title for the inline master-detail grid | -| **inlineColumns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| 'lookup' \| 'file'>; width?: number; … }[]` | optional | Explicit columns for the inline grid (derived from the child object when omitted). Each entry is a strict, name-keyed column (`{ name, label?, type?, … }` — objectui GridColumn); identity-only entries (`{ name }`) hydrate everything else from the child object's fields. Unknown keys and the retired `field` spelling are refused at parse. | +| **inlineColumns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| …>; width?: number; … }[]` | optional | Explicit columns for the inline grid (derived from the child object when omitted). Each entry is a strict, name-keyed column (`{ name, label?, type?, … }` — objectui GridColumn); identity-only entries (`{ name }`) hydrate everything else from the child object's fields. Unknown keys and the retired `field` spelling are refused at parse. | | **inlineAmountField** | `string` | optional | Numeric child field summed for the inline grid total | | **relatedList** | `boolean \| 'primary'` | optional | Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). true = an auxiliary panel on the record page; absent = an auxiliary panel, except that a master_detail field becomes a body table when a field group of the parent names it (fieldGroups[].relatedList); false = hidden: the child object is not shown on the parent record page; 'primary' = a body table: part of the record's main content, shown as a full-width table in the record's detail body. Write true on a master_detail field to keep it an auxiliary panel even from a field group. 'primary' places a list and does not order it: the parent object's relatedLists orders the full-width tables and the auxiliary panels. The page layout is defined by ADR-0085. A derived related list (relatedList: 'primary') inherits its row order from the child object's DEFAULT list view sort — the isDefault view, or the first declared list item when none is marked default; wire spelling is sort=`` / sort=-``, never $orderby. A child object with no list-view sort emits no ordering parameter, and rows fall back to record-id order. | | **relatedListTitle** | `string` | optional | Title for the detail-page related list | @@ -526,7 +526,7 @@ Add a new field to an existing object | **deleteBehavior** | `Enum<'set_null' \| 'cascade' \| 'restrict'>` | optional (default: `"set_null"`) | What happens if referenced record is deleted | | **inlineEdit** | `boolean \| Enum<'grid' \| 'form'>` | optional | How the parent's form edits these child records inline (atomic master-detail) when a field group of the parent names this child (fieldGroups[].relatedList); a child no group names is not inlined, whatever this says. true or absent = auto-pick grid/form by child shape; 'grid' = editable line-item grid; 'form' = list + per-row full form. | | **inlineTitle** | `string` | optional | Title for the inline master-detail grid | -| **inlineColumns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| 'lookup' \| 'file'>; width?: number; … }[]` | optional | Explicit columns for the inline grid (derived from the child object when omitted). Each entry is a strict, name-keyed column (`{ name, label?, type?, … }` — objectui GridColumn); identity-only entries (`{ name }`) hydrate everything else from the child object's fields. Unknown keys and the retired `field` spelling are refused at parse. | +| **inlineColumns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| …>; width?: number; … }[]` | optional | Explicit columns for the inline grid (derived from the child object when omitted). Each entry is a strict, name-keyed column (`{ name, label?, type?, … }` — objectui GridColumn); identity-only entries (`{ name }`) hydrate everything else from the child object's fields. Unknown keys and the retired `field` spelling are refused at parse. | | **inlineAmountField** | `string` | optional | Numeric child field summed for the inline grid total | | **relatedList** | `boolean \| 'primary'` | optional | Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). true = an auxiliary panel on the record page; absent = an auxiliary panel, except that a master_detail field becomes a body table when a field group of the parent names it (fieldGroups[].relatedList); false = hidden: the child object is not shown on the parent record page; 'primary' = a body table: part of the record's main content, shown as a full-width table in the record's detail body. Write true on a master_detail field to keep it an auxiliary panel even from a field group. 'primary' places a list and does not order it: the parent object's relatedLists orders the full-width tables and the auxiliary panels. The page layout is defined by ADR-0085. A derived related list (relatedList: 'primary') inherits its row order from the child object's DEFAULT list view sort — the isDefault view, or the first declared list item when none is marked default; wire spelling is sort=`` / sort=-``, never $orderby. A child object with no list-view sort emits no ordering parameter, and rows fall back to record-id order. | | **relatedListTitle** | `string` | optional | Title for the detail-page related list | diff --git a/content/docs/references/ui/component.mdx b/content/docs/references/ui/component.mdx index 0b3c9f9b600..38e00d792e8 100644 --- a/content/docs/references/ui/component.mdx +++ b/content/docs/references/ui/component.mdx @@ -629,7 +629,7 @@ Sort field and direction pair | **pattern** | `string` | optional | Regular expression the value must match, as a string — the native control's `pattern`, enforced by the browser at submit | | **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | The value type a formula field displays (number / text / boolean / date / currency / percent) | | **summaryOperations** | `{ object: string; field?: string; function: Enum<'count' \| 'sum' \| 'min' \| 'max' \| 'avg'>; relationshipField?: string; … }` | optional | The roll-up a summary field displays — the object field's own `{ object, field, function, … }` | -| **columns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| 'lookup' \| 'file'>; width?: number; … }[]` | optional | The columns of a `grid` field — the strict, name-keyed inline grid column a relationship field's `inlineColumns` takes | +| **columns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| …>; width?: number; … }[]` | optional | The columns of a `grid` field — the strict, name-keyed inline grid column a relationship field's `inlineColumns` takes | | **minRows** | `number` | optional | A `grid` field's minimum row count: its Remove action is disabled at this many rows (no minimum when unset). Read only by the `grid` widget | | **maxRows** | `number` | optional | A `grid` field's maximum row count: its Add and Duplicate actions are disabled, and no blank entry row is drawn, at this many rows (no maximum when unset). Read only by the `grid` widget | | **allowAdd** | `boolean` | optional | Whether a `grid` field offers Add, and each row's Duplicate (a duplicate is an add): on unless `false`. A read-only or disabled grid offers neither. Read only by the `grid` widget | @@ -1233,7 +1233,7 @@ Sort field and direction pair | :--- | :--- | :--- | :--- | | **childObject** | `string` | ✅ | Child object whose records are entered inline | | **relationshipField** | `string` | optional | FK on the child pointing back to the parent (auto-detected from the child's master_detail/lookup field when omitted) | -| **columns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| 'lookup' \| 'file'>; width?: number; … }[]` | optional | Editable grid columns (derived from the child object when omitted). Each entry is the strict, name-keyed inline grid column a relationship field's `inlineColumns` takes (`{ name, label?, type?, … }` — objectui GridColumn); identity-only entries (`{ name }`) hydrate everything else from the child object's fields. Unknown keys and the retired `field` spelling are refused at parse. | +| **columns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| …>; width?: number; … }[]` | optional | Editable grid columns (derived from the child object when omitted). Each entry is the strict, name-keyed inline grid column a relationship field's `inlineColumns` takes (`{ name, label?, type?, … }` — objectui GridColumn); identity-only entries (`{ name }`) hydrate everything else from the child object's fields. Unknown keys and the retired `field` spelling are refused at parse. | | **formFields** | `string[]` | optional | Child field names for the per-row expand form. When omitted they are derived from the child object's fields — except on an entry that names both `relationshipField` and at least one column, which is kept as authored: nothing is derived, and the per-row form is offered only when `inlineMode` is 'form', where it draws the child object's full field list | | **inlineMode** | `Enum<'grid' \| 'form'>` | optional | Inline-edit form factor: 'grid' = editable cells; 'form' = read-only list + per-row full form. When omitted it is resolved from the relationship field's `inlineEdit`, else from the child object's shape — except on an entry that names both `relationshipField` and at least one column, which is kept as authored: nothing is resolved, the collection renders as a grid, and the per-row form is offered only when `formFields` lists more fields than `columns` | | **amountField** | `string` | optional | Numeric child column summed for the running total and the `totalField` rollup. When omitted it is picked from the grid's number and currency columns: a computed one, else one named `amount`, `total`, `subtotal`, `line_total`, `line_amount` or `net_amount`, else the last currency column, else the last numeric one — except on an entry that names `relationshipField` and at least one column and gives every column a `type`. The renderer keeps that entry exactly as authored, so nothing is picked. With no `amountField` authored or picked, the sums read a child column named `amount`, and the grid shows a running total only when `totalField` is set | @@ -1888,7 +1888,7 @@ Type: `string` | :--- | :--- | :--- | :--- | | **childObject** | `string` | optional | Child object whose records this grid lists, edits and saves. Optional because the component-level `dataSource` binding can supply the object instead; with neither, the panel shows a configuration hint and fetches nothing | | **relationshipField** | `string` | ✅ | FK on the child object pointing back to the parent record — the rows are queried as `{ [relationshipField]: parentId }`. Required: this panel does not auto-detect it | -| **columns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| 'lookup' \| 'file'>; width?: number; … }[]` | ✅ | Editable grid columns. Each entry is the strict, name-keyed inline grid column a relationship field's `inlineColumns` takes (`{ name, label?, type?, options?, … }` — objectui GridColumn); unknown keys and the retired `field` spelling are refused. As on the master-detail carriers, identity-only entries (`{ name }`) hydrate everything else from the child object's fields, `label`, `type` and `options` included, so an identity-only column is headed by the child field's label and translates with it. Declaring `type` opts a column out of hydration — supply its `label`, `options` and other extras yourself. Required, with at least one column: nothing derives them, and an empty list draws a grid with no cells | +| **columns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| …>; width?: number; … }[]` | ✅ | Editable grid columns. Each entry is the strict, name-keyed inline grid column a relationship field's `inlineColumns` takes (`{ name, label?, type?, options?, … }` — objectui GridColumn); unknown keys and the retired `field` spelling are refused. As on the master-detail carriers, identity-only entries (`{ name }`) hydrate everything else from the child object's fields, `label`, `type` and `options` included, so an identity-only column is headed by the child field's label and translates with it. Declaring `type` opts a column out of hydration — supply its `label`, `options` and other extras yourself. Required, with at least one column: nothing derives them, and an empty list draws a grid with no cells | | **parentObject** | `string` | optional | Parent object the `totalField` rollup is written to (default: the object of the record on the page) | | **parentId** | `string` | optional | Parent record id the rows belong to (default: the record on the page). Wins over `recordId` | | **recordId** | `string` | optional | Alternate spelling of `parentId` the renderer also reads; `parentId` wins when both are set | @@ -1908,16 +1908,17 @@ Type: `string` | :--- | :--- | :--- | :--- | | **name** | `string` | ✅ | Child field this column shows — the key the grid reads and writes on each row object (objectui GridColumn.name). The retired `field` spelling is refused. | | **label** | `string` | optional | Column header; defaults to the child field's label via hydration. | -| **type** | `Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| 'lookup' \| 'file'>` | optional | Cell control, derived from the child field's type when omitted. Declaring it opts the column out of schema hydration — supply the extras (options / reference / …) yourself. | +| **type** | `Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| …>` | optional | Cell control, derived from the child field's type when omitted: `user` is a person picker, `multiselect` a list holding several of the column's options, `tags` a list of free-form tags, `boolean` a checkbox and `rating` a row of stars. Declaring it opts the column out of schema hydration — supply the extras (options / reference / …) yourself. | | **width** | `number` | optional | Fixed column width in px; omitted columns use type-based role sizing (text flexes, numeric/date/select stay fixed). | | **required** | `boolean` | optional | Cell is flagged inline-invalid while empty. Computed columns are never required. | -| **options** | `{ label: string; value: string }[]` | optional | Select-cell options for `type: 'select'`; derived from the child field's options when the column declares no `type`. | +| **options** | `{ label: string; value: string }[]` | optional | Options of a `select` or `multiselect` cell, and the words a `boolean` cell reads as (values `true` / `false`); derived from the child field's options when the column declares no `type`. A `tags` cell reads none: it holds free-form tags. | | **prefix** | `string` | optional | Symbol shown in a `currency` cell in place of the resolved currency's own symbol. No default: when omitted, the cell shows the symbol of the currency it resolves. It replaces the symbol only — the amount's decimal places stay the currency's. | | **step** | `number` | optional | Input step for numeric cells. | | **reference** | `string` | optional | Referenced object for `type: 'lookup'` cells; derived from the child lookup field when the column declares no `type`. | | **displayField** | `string` | optional | Label field shown for a picked lookup record. | | **idField** | `string` | optional | Id field stored for a picked lookup record. | -| **multiple** | `boolean` | optional | Multi-value column: multi-record lookup, or multi-file upload cell. | +| **multiple** | `boolean` | optional | Multi-value column: multi-record lookup, several people in a `user` cell, or multi-file upload cell. | +| **max** | `integer` | optional | Star count of a `rating` cell (default 5); derived from the child field's `max` when the column declares no `type`. | | **accept** | `string[]` | optional | Accepted MIME types / extensions for a `file` cell's picker (e.g. ['image/*', '.pdf']); omit to accept anything. | | **defaultHidden** | `boolean` | optional | Collapsed into the grid's column chooser by default (not dropped); required columns are never default-hidden. | | **computed** | `boolean` | optional | Read-only computed column, recomputed live from sibling cells via `expr` and written back into the row. | diff --git a/content/docs/references/ui/view.mdx b/content/docs/references/ui/view.mdx index 7c132674c7d..47f954eaa91 100644 --- a/content/docs/references/ui/view.mdx +++ b/content/docs/references/ui/view.mdx @@ -474,7 +474,7 @@ Form-view select option — the object-field option shape minus the per-option ` | :--- | :--- | :--- | :--- | | **childObject** | `string` | ✅ | Child object whose records are entered inline | | **relationshipField** | `string` | optional | FK on the child pointing back to the parent (auto-detected when omitted) | -| **columns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| 'lookup' \| 'file'>; width?: number; … }[]` | optional | Editable grid columns (derived from the child object when omitted). Each entry is the strict, name-keyed inline grid column a relationship field's `inlineColumns` takes (`{ name, label?, type?, … }` — objectui GridColumn); identity-only entries (`{ name }`) hydrate everything else from the child object's fields. Unknown keys and the retired `field` spelling are refused at parse. | +| **columns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| …>; width?: number; … }[]` | optional | Editable grid columns (derived from the child object when omitted). Each entry is the strict, name-keyed inline grid column a relationship field's `inlineColumns` takes (`{ name, label?, type?, … }` — objectui GridColumn); identity-only entries (`{ name }`) hydrate everything else from the child object's fields. Unknown keys and the retired `field` spelling are refused at parse. | | **amountField** | `string` | optional | Numeric child column summed for the running total | | **totalField** | `string` | optional | Parent field to receive the rolled-up sum | | **title** | `string` | optional | Section title | diff --git a/packages/metadata-core/src/object-schema-fls-references.ts b/packages/metadata-core/src/object-schema-fls-references.ts index a56596b643e..b23994b143d 100644 --- a/packages/metadata-core/src/object-schema-fls-references.ts +++ b/packages/metadata-core/src/object-schema-fls-references.ts @@ -549,6 +549,8 @@ export const INLINE_COLUMN_POSITIONS: Readonly> = { name: keep, label: keep, type: keep, options: keep, prefix: keep, step: keep, reference: keep, displayField: keep, idField: keep, multiple: keep, accept: keep, defaultHidden: keep, computed: keep, scale: keep, autofill: keep, width: keep, required: keep, + // A `rating` cell's star count (#36043): a number, never a field name. + max: keep, // Judged by `inlineColumn` before the table runs: a denied one drops the column. expr: keep, readonlyWhen: expression, diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index 87e905cc603..50fa7eb3c07 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -519,6 +519,7 @@ "data/InlineGridColumn:expr", "data/InlineGridColumn:idField", "data/InlineGridColumn:label", + "data/InlineGridColumn:max", "data/InlineGridColumn:multiple", "data/InlineGridColumn:name", "data/InlineGridColumn:options", diff --git a/packages/spec/liveness/field.json b/packages/spec/liveness/field.json index d58ee426229..1c4b65c4370 100644 --- a/packages/spec/liveness/field.json +++ b/packages/spec/liveness/field.json @@ -465,7 +465,7 @@ "verifiedAt": "2026-08-17", "evidenceScope": "in-repo", "evidence": "ui/packages/app-shell/src/providers/MetadataProvider.tsx (attachInlineSubforms passes d.inlineColumns as the subform's columns) → plugin-form/MasterDetailForm.tsx (hydrateColumns) → fields/GridField.tsx (the name-keyed GridColumn renderer, objectui#3951)", - "note": "LIVE via objectui renderer. #9227 closed the element shape (strict, name-keyed InlineGridColumnSchema): the child keys below are exactly the GridColumn keys the widget has a live read for, measured against objectui main 2026-08-17. NOTE the .objectui-sha pin (665661ab) predates objectui#3951 — the PINNED console still reads the retired field spelling; the drilled evidence below cites objectui main, which is the contract this schema mirrors. Renderer read points moved out of spec source (#23434). Column-type hydration (packages/spec/src/stack.zod.ts HYDRATED_INLINE_COLUMN_TYPE; packages/spec/src/inline-grid-column-carriers.test.ts): objectui @db11afd4967c packages/plugin-form/src/deriveMasterDetail.ts#hydrateColumns leaves a column that declares a `type` alone and otherwise sets `type: fieldTypeToColumnType(childField.type)`; objectui @db11afd4967c packages/plugin-form/src/deriveMasterDetail.ts#fieldTypeToColumnType maps each of the column schema's nine types' namesake field type to that same column type, and its only `currency` arm is the `currency` field type. Line-position field (packages/spec/src/data/inline-grid-sort-fields.ts INLINE_GRID_SORT_FIELDS): objectui @89cad75d5570 packages/plugin-form/src/deriveMasterDetail.ts#SORT_FIELD_NAMES, the same six names in the same order. Per-row expand form (packages/spec/src/data/inline-grid-columns.ts deriveInlineRowFormFields and its test): objectui @31971ff1e28f packages/plugin-form/src/deriveMasterDetail.ts#deriveFormFields is the derivation rule, and the first two test fixtures are its own cases in objectui @31971ff1e28f packages/plugin-form/src/deriveMasterDetail.test.ts (describe \"deriveFormFields (per-row expand form)\"); the offer condition (isInlineRowFormOffered) is the one objectui @31971ff1e28f packages/plugin-form/src/MasterDetailForm.tsx#MasterDetailLines applies — `inlineMode === 'form'`, or more `formFields` than `columns`.", + "note": "LIVE via objectui renderer. #9227 closed the element shape (strict, name-keyed InlineGridColumnSchema): the child keys below are exactly the GridColumn keys the widget has a live read for, measured against objectui main 2026-08-17. NOTE the .objectui-sha pin (665661ab) predates objectui#3951 — the PINNED console still reads the retired field spelling; the drilled evidence below cites objectui main, which is the contract this schema mirrors. Renderer read points moved out of spec source (#23434). Column-type hydration (packages/spec/src/stack.zod.ts HYDRATED_INLINE_COLUMN_TYPE; packages/spec/src/inline-grid-column-carriers.test.ts): objectui @db11afd4967c packages/plugin-form/src/deriveMasterDetail.ts#hydrateColumns leaves a column that declares a `type` alone and otherwise sets `type: fieldTypeToColumnType(childField.type)`; objectui @db11afd4967c packages/plugin-form/src/deriveMasterDetail.ts#fieldTypeToColumnType maps each of the column schema's types' namesake field type to that same column type, and its only `currency` arm is the `currency` field type; since objectstack#36043 the in-repo ui/packages/plugin-form/src/deriveMasterDetail.ts#fieldTypeToColumnType does the same for all fourteen, `user`, `multiselect`, `tags`, `boolean` and `rating` included. Line-position field (packages/spec/src/data/inline-grid-sort-fields.ts INLINE_GRID_SORT_FIELDS): objectui @89cad75d5570 packages/plugin-form/src/deriveMasterDetail.ts#SORT_FIELD_NAMES, the same six names in the same order. Per-row expand form (packages/spec/src/data/inline-grid-columns.ts deriveInlineRowFormFields and its test): objectui @31971ff1e28f packages/plugin-form/src/deriveMasterDetail.ts#deriveFormFields is the derivation rule, and the first two test fixtures are its own cases in objectui @31971ff1e28f packages/plugin-form/src/deriveMasterDetail.test.ts (describe \"deriveFormFields (per-row expand form)\"); the offer condition (isInlineRowFormOffered) is the one objectui @31971ff1e28f packages/plugin-form/src/MasterDetailForm.tsx#MasterDetailLines applies — `inlineMode === 'form'`, or more `formFields` than `columns`.", "children": { "name": { "status": "live", @@ -477,7 +477,7 @@ }, "type": { "status": "live", - "note": "objectui GridField.tsx — selects the cell control (text/number/currency/date/datetime/time/select/lookup/file) and drives type-based min widths (minWidthFor/widthStyle); hydrateColumns derives it from the child field type when absent." + "note": "objectui GridField.tsx — selects the cell control (text/number/currency/date/datetime/time/select/lookup/file/user/multiselect/tags/boolean/rating) and drives type-based min widths (minWidthFor/widthStyle); hydrateColumns derives it from the child field type when absent." }, "width": { "status": "live", @@ -489,7 +489,7 @@ }, "options": { "status": "live", - "note": "objectui GridField.tsx select cells — SelectItem per {label,value}; display formatting resolves the stored value to its label." + "note": "ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx — a select cell's choices, a multiselect cell's choices (several held) and a boolean cell's two words (values `true` / `false`); display formatting resolves the stored value to its label. A tags cell reads none (objectstack#36043)." }, "prefix": { "status": "live", @@ -513,7 +513,11 @@ }, "multiple": { "status": "live", - "note": "objectui GridField.tsx — multi-record lookup cells and multi-file upload cells." + "note": "objectui GridField.tsx — multi-record lookup cells, multi-person user cells and multi-file upload cells." + }, + "max": { + "status": "live", + "note": "objectui grid-field/GridFieldWidget.tsx — the star count of a rating cell (RatingField's `max`, default 5); hydrateColumns copies the child rating field's `max` when the column declares no type." }, "accept": { "status": "live", diff --git a/packages/spec/liveness/state-counts/field.md b/packages/spec/liveness/state-counts/field.md index 65f799c5dca..d548a6de241 100644 --- a/packages/spec/liveness/state-counts/field.md +++ b/packages/spec/liveness/state-counts/field.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `field` | 108 | 0 | 0 | 1 | 6 | 115 | +| `field` | 109 | 0 | 0 | 1 | 6 | 116 | diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index 18a10a187e0..5f8d354a95e 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -1364,7 +1364,10 @@ export const InlineGridColumnSchema = lazySchema(() => strictObject({ }, { name: z.string().min(1).describe('Child field this column shows — the key the grid reads and writes on each row object (objectui GridColumn.name). The retired `field` spelling is refused.').meta({ title: 'Name' }), label: z.string().optional().describe("Column header; defaults to the child field's label via hydration.").meta({ title: 'Label' }), - type: z.enum(['text', 'number', 'currency', 'date', 'datetime', 'time', 'select', 'lookup', 'file']).optional().describe("Cell control, derived from the child field's type when omitted. Declaring it opts the column out of schema hydration — supply the extras (options / reference / …) yourself.").meta({ title: 'Type' }), + // #36043 — `user` (people), `multiselect`, `tags`, `boolean` (check) and + // `rating` joined the nine. Each member is spelled as its namesake field + // type, which the renderer's derivation maps to that same column type. + type: z.enum(['text', 'number', 'currency', 'date', 'datetime', 'time', 'select', 'lookup', 'file', 'user', 'multiselect', 'tags', 'boolean', 'rating']).optional().describe("Cell control, derived from the child field's type when omitted: `user` is a person picker, `multiselect` a list holding several of the column's options, `tags` a list of free-form tags, `boolean` a checkbox and `rating` a row of stars. Declaring it opts the column out of schema hydration — supply the extras (options / reference / …) yourself.").meta({ title: 'Type' }), width: z.number().positive().optional().describe('Fixed column width in px; omitted columns use type-based role sizing (text flexes, numeric/date/select stay fixed).').meta({ title: 'Width' }), required: z.boolean().optional().describe('Cell is flagged inline-invalid while empty. Computed columns are never required.').meta({ title: 'Required' }), options: z.array(strictObject({ @@ -1374,7 +1377,7 @@ export const InlineGridColumnSchema = lazySchema(() => strictObject({ }, { label: z.string().describe('Option label shown in the select cell.'), value: z.string().min(1).describe("Stored option value; must match the child select field's option values."), - })).optional().describe("Select-cell options for `type: 'select'`; derived from the child field's options when the column declares no `type`.").meta({ title: 'Options' }), + })).optional().describe("Options of a `select` or `multiselect` cell, and the words a `boolean` cell reads as (values `true` / `false`); derived from the child field's options when the column declares no `type`. A `tags` cell reads none: it holds free-form tags.").meta({ title: 'Options' }), // #20045 — no default symbol: the grid shows the resolved currency's own // symbol when this is omitted (objectui GridField `currencyAdornment`, // objectui#10355), so the former 「(default '¥')」 described a fallback the @@ -1384,7 +1387,8 @@ export const InlineGridColumnSchema = lazySchema(() => strictObject({ reference: z.string().optional().describe("Referenced object for `type: 'lookup'` cells; derived from the child lookup field when the column declares no `type`.").meta({ title: 'Reference' }), displayField: z.string().optional().describe('Label field shown for a picked lookup record.').meta({ title: 'Display Field' }), idField: z.string().optional().describe('Id field stored for a picked lookup record.').meta({ title: 'ID Field' }), - multiple: z.boolean().optional().describe('Multi-value column: multi-record lookup, or multi-file upload cell.').meta({ title: 'Multiple' }), + multiple: z.boolean().optional().describe('Multi-value column: multi-record lookup, several people in a `user` cell, or multi-file upload cell.').meta({ title: 'Multiple' }), + max: z.number().int().positive().optional().describe("Star count of a `rating` cell (default 5); derived from the child field's `max` when the column declares no `type`.").meta({ title: 'Max' }), accept: z.array(z.string()).optional().describe("Accepted MIME types / extensions for a `file` cell's picker (e.g. ['image/*', '.pdf']); omit to accept anything.").meta({ title: 'Accept' }), defaultHidden: z.boolean().optional().describe("Collapsed into the grid's column chooser by default (not dropped); required columns are never default-hidden.").meta({ title: 'Default Hidden' }), computed: z.boolean().optional().describe('Read-only computed column, recomputed live from sibling cells via `expr` and written back into the row.').meta({ title: 'Computed' }), diff --git a/packages/spec/src/data/inline-grid-columns.ts b/packages/spec/src/data/inline-grid-columns.ts index 8fa0ca9f1ba..af3d86ba6fa 100644 --- a/packages/spec/src/data/inline-grid-columns.ts +++ b/packages/spec/src/data/inline-grid-columns.ts @@ -141,9 +141,10 @@ function cellTypeOf(type: unknown): string { switch (type) { case 'number': case 'percent': - case 'rating': case 'slider': return 'number'; + case 'rating': + return 'rating'; case 'currency': return 'currency'; case 'date': @@ -155,12 +156,20 @@ function cellTypeOf(type: unknown): string { case 'select': case 'picklist': case 'radio': + return 'select'; case 'boolean': case 'toggle': - return 'select'; + return 'boolean'; + case 'multiselect': + case 'checkboxes': + return 'multiselect'; + case 'tags': + return 'tags'; case 'lookup': case 'master_detail': return 'lookup'; + case 'user': + return 'user'; case 'file': case 'image': case 'avatar': @@ -170,16 +179,26 @@ function cellTypeOf(type: unknown): string { } } -/** Lower is kept first when filling the visible budget; a cell type absent here sorts last (5). */ +/** + * Lower is kept first when filling the visible budget; a cell type absent here + * sorts last (5). The five cell types #36043 added keep the priority their + * field types had before it (a check cell was a select, a rating a number, the + * other three plain text), so which derived columns are visible is unchanged. + */ const CELL_FILL_PRIORITY: Readonly> = { select: 0, + boolean: 0, currency: 1, number: 1, + rating: 1, lookup: 2, date: 3, datetime: 3, time: 3, text: 4, + user: 4, + multiselect: 4, + tags: 4, }; /** A field's own key, read the way the renderer reads `def?.key` off an untyped bag. */ diff --git a/packages/spec/src/inline-grid-column-carriers.test.ts b/packages/spec/src/inline-grid-column-carriers.test.ts index 6d23071154e..0b59eeae0a6 100644 --- a/packages/spec/src/inline-grid-column-carriers.test.ts +++ b/packages/spec/src/inline-grid-column-carriers.test.ts @@ -295,7 +295,7 @@ function typeConditionalRules(): { rules: TypeConditionalRule[]; unprobed: strin * A stack whose child object carries a field `probe` of `fieldType`, and an * identity-only `inlineColumns` entry over it. The field type is the column * type's own name: the renderer's column-type derivation maps each of the - * column schema's nine types' namesake field type to that same column type + * column schema's fourteen types' namesake field type to that same column type * (recorded in `packages/spec/liveness/field.json`, row `inlineColumns`). */ const stackWithProbeField = (fieldType: string, column: Record) => { diff --git a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts index ccb92382bf2..bffdfe72c93 100644 --- a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts +++ b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts @@ -299,14 +299,14 @@ const LEDGER: ReadonlyArray = [ // // The `object.fields` subset precedent at the top of this ledger, on the // field form: a curated repeater over four of `InlineGridColumnSchema`'s - // twenty keys. Unlike `object.fields` there is no fuller editor to defer to, + // twenty-one keys. Unlike `object.fields` there is no fuller editor to defer to, // so the long tail is authored in source, and the reason says why that is // the right place for each group of keys left out. { kind: 'subset', type: 'field', path: 'inlineColumns', - why: "a curated inline-grid column (ruling record 5861442317): `name` plus the three keys that apply to a column of any type (`label`, `width`, `defaultHidden`). An entry naming only a field is the shape the key's own describe recommends, because objectui's `hydrateColumns` completes it from the child field, so the rest is authored in source: `type`, since declaring it opts the column out of that hydration; the keys that apply to one cell type only (`options`, `reference`, `displayField`, `idField`, `autofill`, `multiple`, `accept`, `prefix`, `step`, `scale`, `computed`, `expr`), since a column takes its type from the child field at render and a sub-row here cannot be gated on it, so each would be offered on every column; and `required` / `readonlyWhen` / `requiredWhen`, which hydration copies from the child field, where the rule the server enforces lives", + why: "a curated inline-grid column (ruling record 5861442317): `name` plus the three keys that apply to a column of any type (`label`, `width`, `defaultHidden`). An entry naming only a field is the shape the key's own describe recommends, because objectui's `hydrateColumns` completes it from the child field, so the rest is authored in source: `type`, since declaring it opts the column out of that hydration; the keys that apply to one cell type only (`options`, `reference`, `displayField`, `idField`, `autofill`, `multiple`, `accept`, `max`, `prefix`, `step`, `scale`, `computed`, `expr`), since a column takes its type from the child field at render and a sub-row here cannot be gated on it, so each would be offered on every column; and `required` / `readonlyWhen` / `requiredWhen`, which hydration copies from the child field, where the rule the server enforces lives", }, // ── The root coordinate (#19333): top-level keys no form may offer ── // diff --git a/packages/spec/src/ui/component.zod.ts b/packages/spec/src/ui/component.zod.ts index 5ce3d62ec48..164e594741c 100644 --- a/packages/spec/src/ui/component.zod.ts +++ b/packages/spec/src/ui/component.zod.ts @@ -2582,7 +2582,7 @@ const RECORD_LINE_ITEMS_HISTORY = * field's `inlineColumns`, a form view's `subforms[].columns` and an * `object-master-detail-form` detail entry's `columns` take, not a copy: the * panel hands its columns to the same objectui grid (`GridField`, whose - * `GridColumn` declares exactly that schema's twenty keys and IS the spec's + * `GridColumn` declares exactly that schema's twenty-one keys and IS the spec's * type by reference). The column also means here what it means on those * carriers (#24140, route B), because the column schema's own `label` describe * — "defaults to the child field's label via hydration" — governs every diff --git a/ui/packages/fields/src/widgets/GridField.test.tsx b/ui/packages/fields/src/widgets/GridField.test.tsx index 219ea575c92..3a101598d76 100644 --- a/ui/packages/fields/src/widgets/GridField.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.test.tsx @@ -1,5 +1,5 @@ import { describe, it, expect, vi } from 'vitest'; -import { render, screen, fireEvent, waitFor } from '@testing-library/react'; +import { render, screen, fireEvent, waitFor, within } from '@testing-library/react'; import React from 'react'; import { UploadProvider } from './UploadProvider'; import { Dialog, DialogContent, DialogTitle } from '@object-ui/components'; @@ -1348,6 +1348,196 @@ describe('cell faces that open under the cell (objectstack#36023)', () => { }); }); +describe('the cells that edit as in the main list: people, multi-select, tags, check, rating (objectstack#36043)', () => { + const COLORS = [ + { label: 'Red', value: 'red' }, + { label: 'Green', value: 'green' }, + { label: 'Blue', value: 'blue' }, + ]; + const cols = { + columns: [ + { name: 'description', label: 'Description', type: 'text' as const }, + { name: 'colors', label: 'Colors', type: 'multiselect' as const, options: COLORS }, + { name: 'labels', label: 'Labels', type: 'tags' as const }, + { name: 'done', label: 'Done', type: 'boolean' as const }, + { name: 'score', label: 'Score', type: 'rating' as const }, + { name: 'owner', label: 'Owner', type: 'user' as const }, + ], + } as any; + + function Stateful({ initial, onChange, field = cols }: { initial: any[]; onChange?: (v: any[]) => void; field?: any }) { + const [rows, setRows] = React.useState(initial); + return ( + { + setRows(v); + onChange?.(v); + }} + field={field} + /> + ); + } + + describe('a multi-select cell', () => { + // A click outside writes too (the popover's own dismiss); this harness's + // pointer events do not reach that dismiss, so the pin leaves through Tab. + it('reads its option labels; the list opens under the cell, holds several picks, and leaving it writes them', async () => { + const onChange = vi.fn(); + render(); + const cell = screen.getByRole('button', { name: 'Colors' }); + expect(cell.textContent).toBe('Red'); + fireEvent.click(cell); + const panel = await screen.findByTestId('line-items-multiselect-panel'); + fireEvent.click(within(panel).getByRole('option', { name: /Green/ })); + fireEvent.click(within(panel).getByRole('option', { name: /Blue/ })); + // Still open, and nothing written while the list is open. + expect(screen.getByTestId('line-items-multiselect-panel')).toBeTruthy(); + expect(onChange).not.toHaveBeenCalled(); + fireEvent.keyDown(panel.querySelector('input')!, { key: 'Tab' }); + await waitFor(() => expect(screen.queryByTestId('line-items-multiselect-panel')).toBeNull()); + expect(onChange.mock.calls.at(-1)![0][0].colors).toEqual(['red', 'green', 'blue']); + expect(screen.getByRole('button', { name: 'Colors' }).textContent).toBe('Red, Green, Blue'); + }); + + it('Esc closes the list and writes nothing', async () => { + const onChange = vi.fn(); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Colors' })); + const panel = await screen.findByTestId('line-items-multiselect-panel'); + fireEvent.click(within(panel).getByRole('option', { name: /Green/ })); + fireEvent.keyDown(panel.querySelector('input')!, { key: 'Escape' }); + await waitFor(() => expect(screen.queryByTestId('line-items-multiselect-panel')).toBeNull()); + expect(onChange).not.toHaveBeenCalled(); + expect(screen.getByRole('button', { name: 'Colors' }).textContent).toBe('Red'); + }); + + // A cleared multi-value field stores `null`, and the save path counts only + // `null` / `''` as blank: a `[]` would send a line the user emptied. + it('emptied, it writes null rather than an empty list', async () => { + const onChange = vi.fn(); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Colors' })); + const panel = await screen.findByTestId('line-items-multiselect-panel'); + fireEvent.click(within(panel).getByRole('option', { name: /Red/ })); + fireEvent.keyDown(panel.querySelector('input')!, { key: 'Tab' }); + await waitFor(() => expect(screen.queryByTestId('line-items-multiselect-panel')).toBeNull()); + expect(onChange.mock.calls.at(-1)![0][0].colors).toBeNull(); + }); + + it('a required multi-select holding no option reads invalid', () => { + const field = { columns: [{ name: 'colors', label: 'Colors', type: 'multiselect', options: COLORS, required: true }] }; + render( {}} field={field as any} />); + expect(screen.getByTestId('line-items-invalid-0-colors')).toBeTruthy(); + }); + }); + + describe('a tags cell', () => { + it('reads its tags; a new tag is added from the list, and Tab writes and moves on', async () => { + const onChange = vi.fn(); + render(); + const cell = screen.getByRole('button', { name: 'Labels' }); + expect(cell.textContent).toBe('urgent'); + fireEvent.click(cell); + const panel = await screen.findByTestId('line-items-tags-panel'); + const search = panel.querySelector('input') as HTMLInputElement; + fireEvent.change(search, { target: { value: 'export' } }); + fireEvent.keyDown(search, { key: 'Enter' }); + fireEvent.keyDown(search, { key: 'Tab' }); + await waitFor(() => expect(screen.queryByTestId('line-items-tags-panel')).toBeNull()); + expect(onChange.mock.calls.at(-1)![0][0].labels).toEqual(['urgent', 'export']); + expect(document.activeElement).toBe(screen.getByRole('checkbox', { name: 'Done' })); + }); + + it('emptied, it writes null rather than an empty list', async () => { + const onChange = vi.fn(); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Labels' })); + const panel = await screen.findByTestId('line-items-tags-panel'); + fireEvent.click(within(panel).getByRole('option', { name: /urgent/ })); + fireEvent.keyDown(panel.querySelector('input')!, { key: 'Tab' }); + await waitFor(() => expect(screen.queryByTestId('line-items-tags-panel')).toBeNull()); + expect(onChange.mock.calls.at(-1)![0][0].labels).toBeNull(); + // It reads as an empty cell, as an emptied multi-select does. + expect(screen.getByRole('button', { name: 'Labels' }).textContent).toBe('—'); + }); + }); + + describe('a check cell', () => { + it('is a checkbox over the stored value; a click writes a boolean', () => { + const onChange = vi.fn(); + render(); + const [first, second] = screen.getAllByRole('checkbox', { name: 'Done' }); + expect(first.getAttribute('aria-checked')).toBe('true'); + expect(second.getAttribute('aria-checked')).toBe('false'); + fireEvent.click(second); + expect(onChange.mock.calls.at(-1)![0][1].done).toBe(true); + fireEvent.click(first); + expect(onChange.mock.calls.at(-1)![0][0].done).toBe(false); + }); + + it('read-only, it reads as its option word', () => { + const field = { + columns: [{ name: 'done', label: 'Done', type: 'boolean', options: [{ label: 'WORD-ON', value: 'true' }, { label: 'WORD-OFF', value: 'false' }] }], + }; + render( {}} readonly field={field as any} />); + const table = screen.getByTestId('line-items-readonly'); + expect(table.textContent).toContain('WORD-ON'); + expect(table.textContent).toContain('WORD-OFF'); + expect(screen.queryByRole('checkbox')).toBeNull(); + }); + }); + + describe('a rating cell', () => { + const filled = (cell: Element) => + Array.from(cell.querySelectorAll('button svg')).filter((svg) => (svg.getAttribute('class') ?? '').includes('fill-yellow-400')).length; + const ratingCell = () => document.querySelector('[data-grid-cell="0:score"] [data-cell]') as HTMLElement; + + it('draws five stars by default with the value filled; a click on a star sets it', () => { + const onChange = vi.fn(); + render(); + const cell = ratingCell(); + expect(cell.querySelectorAll('button')).toHaveLength(5); + expect(filled(cell)).toBe(3); + fireEvent.click(cell.querySelectorAll('button')[3]); + expect(onChange.mock.calls.at(-1)![0][0].score).toBe(4); + }); + + it('a digit key on the cell sets that many stars; 0 clears', () => { + const onChange = vi.fn(); + render(); + fireEvent.keyDown(ratingCell(), { key: '2' }); + expect(onChange.mock.calls.at(-1)![0][0].score).toBe(2); + fireEvent.keyDown(ratingCell(), { key: '0' }); + expect(onChange.mock.calls.at(-1)![0][0].score).toBeNull(); + // A digit above the column's stars sets nothing. + onChange.mockClear(); + fireEvent.keyDown(ratingCell(), { key: '7' }); + expect(onChange).not.toHaveBeenCalled(); + }); + + it("draws the column's `max` stars", () => { + const field = { columns: [{ name: 'score', label: 'Score', type: 'rating', max: 10 }] }; + render( {}} field={field as any} />); + expect(ratingCell().querySelectorAll('button')).toHaveLength(10); + expect(filled(ratingCell())).toBe(8); + }); + }); + + describe('a people cell', () => { + it("opens the main list's person picker under the cell; its Clear writes and closes at once", async () => { + const onChange = vi.fn(); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Owner' })); + const panel = await screen.findByTestId('line-items-user-panel'); + expect(within(panel).getByTestId('lookup-in-cell')).toBeTruthy(); + fireEvent.click(within(panel).getByTestId('lookup-in-cell-clear')); + await waitFor(() => expect(screen.queryByTestId('line-items-user-panel')).toBeNull()); + expect(onChange.mock.calls.at(-1)![0][0].owner).toBeNull(); + }); + }); +}); + /** * objectstack#36102 — `@object-ui/fields` exports a lazy face for the grid * (`./GridField.ts`); the body (`./grid-field/GridFieldWidget.tsx`) loads diff --git a/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx index baa9863a23c..b1d5fa0db4f 100644 --- a/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx +++ b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx @@ -26,7 +26,12 @@ import { useFieldTranslation } from '../useFieldTranslation.js'; import { toDomProps } from '../toDomProps.js'; import { PHONE_TOUCH_HEIGHT, PHONE_TOUCH_SQUARE } from '../touchTarget.js'; import { toHostGroupProps } from '../toHostGroupProps.js'; -import { GRID_CELL_CONTROL_CLASS, GridDateCell, GridSelectCell, GrowingCellInput } from '../gridCellPanels.js'; +import { GRID_CELL_CONTROL_CLASS, GridDateCell, GridPanelCell, GridSelectCell, GrowingCellInput } from '../gridCellPanels.js'; +import { MultiSelectField } from '../MultiSelectField.js'; +import { TagsField } from '../TagsField.js'; +import { UserField } from '../UserField.js'; +import { RatingField } from '../RatingField.js'; +import { useBooleanValueLabel } from '../booleanValueLabel.js'; import { isImeKey } from '../imeKey.js'; import { GRID_FIELD_RETIRED_KEYS, type GridFieldMetadata, type GridFieldRetiredKey } from '@object-ui/types'; // The grid's pure half: the column type, the computed-cell evaluator, the @@ -119,6 +124,18 @@ type Row = Record; const isNumeric = (t?: string) => t === 'number' || t === 'currency'; +/** A cell holding nothing: no value, an empty string, or an empty list (multi-select, tags, people). */ +const isEmptyCell = (value: unknown) => + value == null || value === '' || (Array.isArray(value) && value.length === 0); + +/** The star count of a `rating` column: its `max`, else `Field.rating`'s own 5 (objectstack#36043). */ +const ratingMax = (c: GridColumn) => c.max ?? 5; +/** A list cell emptied by the user writes `null`, not `[]` (objectstack#36043): + * the field contract stores a cleared multi-value field as `null`, and the + * save path's blank-line check (`isBlankRow`) reads only `null` / `''` as + * empty, so a `[]` would send a line the user emptied as a child record. */ +const emptyListAsNull = (next: V): V | null => (Array.isArray(next) && next.length === 0 ? null : next); + /** Comfortable minimum widths per column type so cells never get crushed; the * grid scrolls horizontally instead. Authors can still pin a `width`. */ const MIN_WIDTH_BY_TYPE: Record = { @@ -133,6 +150,12 @@ const MIN_WIDTH_BY_TYPE: Record = { datetime: 200, time: 116, file: 168, + // objectstack#36043 — the five cells that edit as in the main list. + user: 168, + multiselect: 168, + tags: 168, + boolean: 72, + rating: 120, }; const minWidthFor = (c: GridColumn): number => c.width ?? MIN_WIDTH_BY_TYPE[c.type ?? 'text'] ?? 132; @@ -282,17 +305,20 @@ function currencyText(c: GridColumn, n: number, currency: string | undefined, lo } /** - * The session-language words a file cell's text is made of (objectui#12924), - * read by the component from the packs and handed to {@link cellDisplayText}: - * the count a cell holding several files states (`detail.fileCount`, the count - * family `FileCellRenderer` states a file count with), and the name a file - * whose value carries none is shown by (`fields.file.fileFallback`, the name - * `FileField` and `FileCellRenderer` give it). Both used to be the English - * literals `N files` / `File` here, on every locale. + * The session-language words a cell's text is made of (objectui#12924), read + * by the component from the packs and handed to {@link cellDisplayText}: the + * count a cell holding several files states (`detail.fileCount`, the count + * family `FileCellRenderer` states a file count with), the name a file whose + * value carries none is shown by (`fields.file.fileFallback`, the name + * `FileField` and `FileCellRenderer` give it), and a check cell's word for its + * value. The first two used to be the English literals `N files` / `File` + * here, on every locale. */ -interface FileCellText { +interface CellText { count: (count: number) => string; nameless: string; + /** The session's word for a check cell's value (objectstack#36043). */ + booleanWord: (value: boolean) => string; } /** Read-only display text for a cell in list mode (select → option label, @@ -300,8 +326,9 @@ interface FileCellText { * name or a count of its files, empty → em dash). Lookups render separately. * `currency` is the column's resolved currency, read only by the currency * branch. The component binds `fileText` once, as its `displayText`. */ -function cellDisplayText(c: GridColumn, value: any, locale: string, fileText: FileCellText, currency?: string): string { - if (value === null || value === undefined || value === '') return '—'; +function cellDisplayText(c: GridColumn, value: any, locale: string, fileText: CellText, currency?: string): string { + // An emptied multi-value cell (a tags list) reads as empty too, like multi-select. + if (value === null || value === undefined || value === '' || (Array.isArray(value) && value.length === 0)) return '—'; if (isTemporal(c.type)) return temporalText(c.type, value, locale); if (c.type === 'file') { const files = Array.isArray(value) ? value : [value]; @@ -314,6 +341,17 @@ function cellDisplayText(c: GridColumn, value: any, locale: string, fileText: Fi const opt = c.options.find((o) => String(o.value) === String(value)); return opt ? opt.label : String(value); } + // A multi-select cell names each value by its option's label (objectstack#36043). + if (c.type === 'multiselect' && Array.isArray(value)) { + if (value.length === 0) return '—'; + return value.map((v) => c.options?.find((o) => String(o.value) === String(v))?.label ?? String(v)).join(', '); + } + // A check cell reads as its option's word (the session's, from the derive), + // else the session's word itself (objectstack#36043). + if (c.type === 'boolean') { + const on = value === true || BOOLEAN_READINGS.get(value) === true; + return c.options?.find((o) => o.value === String(on))?.label ?? fileText.booleanWord(on); + } if (isNumeric(c.type)) { const n = Number(value); // The numeric branch formats in the SAME declared locale the temporal @@ -634,12 +672,29 @@ function GridFieldBody({ // several files and the name of a nameless one. Bound into `displayText` // here, so every cell that draws its text through it — the list-mode cell, // the computed cell and the read-only table — takes the same words. - const fileText: FileCellText = { + const booleanWord = useBooleanValueLabel(); + const fileText: CellText = { count: (count) => t('detail.fileCount', { count, defaultValue: '{{count}} files' }), nameless: t('fields.file.fileFallback', { defaultValue: 'File' }), + booleanWord, }; const displayText = (c: GridColumn, value: any, locale: string, cellCurrency?: string) => cellDisplayText(c, value, locale, fileText, cellCurrency); + /** + * The read-only face of a cell that is not text (objectstack#36043): people + * by name, a rating as its stars; `null` for every other cell, which reads + * through `displayText`. Shared by the read-only table and list mode. + */ + const readOnlyFace = (c: GridColumn, value: any): React.ReactNode | null => { + if (isEmptyCell(value)) return null; + if (c.type === 'user') { + return {}} readonly field={{ type: 'user', multiple: c.multiple } as any} />; + } + if (c.type === 'rating') { + return {}} readonly field={{ type: 'rating', max: ratingMax(c) } as any} />; + } + return null; + }; const cellIdBase = React.useId(); // The tenant default currency (ADR-0053) — the resolver's last step, and in // practice the currency of every `currency` column (objectui#10355, see @@ -656,7 +711,7 @@ function GridFieldBody({ // the row's boolean cells read as booleans (`ruleRecordOf`). Every column, // shown or not, since a predicate may read any cell of the row. const booleanColumns = React.useMemo( - () => allColumns.filter(isBooleanSelectColumn).map((c) => c.name), + () => allColumns.filter((c) => c.type === 'boolean' || isBooleanSelectColumn(c)).map((c) => c.name), [allColumns], ); const cellRules = useCallback( @@ -1110,7 +1165,7 @@ function GridFieldBody({ // (objectui#3569), a select's stored value instead of // its option label, and an amount ungrouped and in no // locale (objectui#12915). - displayText(c, row[c.name], displayLocale, currencyOf(c)) + readOnlyFace(c, row[c.name]) ?? displayText(c, row[c.name], displayLocale, currencyOf(c)) )} ))} @@ -1212,6 +1267,8 @@ function GridFieldBody({ field={{ reference: c.reference, displayField: c.displayField, idField: c.idField } as any} /> ); } + const face = readOnlyFace(c, val); + if (face) return face; return ( {displayText(c, val, displayLocale, currencyOf(c))} @@ -1281,6 +1338,106 @@ function GridFieldBody({ /> ); } + // objectstack#36043 — multi-select, tags and people open the face the + // main list's cell editor draws, in a panel under the cell; the cell keeps + // drawing its value meanwhile. + if (c.type === 'multiselect' || c.type === 'tags') { + const held: string[] = Array.isArray(val) ? val.map(String) : isEmptyCell(val) ? [] : [String(val)]; + const Face = c.type === 'multiselect' ? MultiSelectField : TagsField; + return ( + + value={held} + onWrite={(next) => setCellValue(rowIdx, c.name, emptyListAsNull(next))} + display={ + + {displayText(c, held, displayLocale)} + + } + disabled={locked} + invalid={invalid} + label={c.label || c.name} + onNavKeyDown={(e) => onCellKeyDown(e, rowIdx, colIdx)} + data-cell={`${rowIdx}-${colIdx}`} + panelTestId={`line-items-${c.type}-panel`} + > + {({ draft, setDraft }) => ( + setDraft(next)} + field={{ name: c.name, type: c.type, options: c.options } as any} + /> + )} + + ); + } + if (c.type === 'user') { + const field = { name: c.name, type: 'user', label: c.label, multiple: c.multiple } as any; + return ( + + value={val ?? null} + onWrite={(next) => setCellValue(rowIdx, c.name, emptyListAsNull(next))} + display={readOnlyFace(c, val) ?? —} + disabled={locked} + invalid={invalid} + label={c.label || c.name} + onNavKeyDown={(e) => onCellKeyDown(e, rowIdx, colIdx)} + data-cell={`${rowIdx}-${colIdx}`} + panelTestId="line-items-user-panel" + > + {({ draft, setDraft, commit }) => ( + setDraft(next)} onCommit={commit} field={field} /> + )} + + ); + } + // A check cell is a checkbox: a click or Space toggles it (objectstack#36043). + if (c.type === 'boolean') { + return ( +
+ setCellValue(rowIdx, c.name, checked === true)} + onKeyDown={(e) => onCellKeyDown(e, rowIdx, colIdx)} + disabled={locked} + /> +
+ ); + } + // A rating is set in place: a click on a star, or a digit key on the + // cell (0 clears), as in the main list (objectstack#36023, #36043). + if (c.type === 'rating') { + const max = ratingMax(c); + return ( +
{ + if (!locked && /^[0-9]$/.test(e.key) && Number(e.key) <= max) { + e.preventDefault(); + setCellValue(rowIdx, c.name, e.key === '0' ? null : Number(e.key)); + return; + } + onCellKeyDown(e, rowIdx, colIdx); + }} + > + setCellValue(rowIdx, c.name, next)} + field={{ type: 'rating', max } as any} + disabled={locked} + error={invalid ? requiredCellText(c) : undefined} + /> +
+ ); + } // The editable currency cell shows the SAME symbol its display face does // (objectui#10355) — `currencyAdornment`, never a default `¥`. const adornment = c.type === 'currency' ? currencyAdornment(c, currencyOf(c), displayLocale) : ''; @@ -1490,7 +1647,7 @@ function GridFieldBody({ !isList && required && !c.computed && - (row[c.name] == null || row[c.name] === ''); + isEmptyCell(row[c.name]); return ( { + /** The value being edited: the cell's value until the face changes it. */ + draft: V; + /** Change the value being edited; nothing is written yet. */ + setDraft: (next: V) => void; + /** Write the value being edited and close the panel (a single pick ends the edit). */ + commit: () => void; +} + +export interface GridPanelCellProps { + /** The cell's written value. */ + value: V; + /** Write a value the panel ended with. Called only when it differs from `value`. */ + onWrite: (next: V) => void; + /** What the cell shows, open or closed. */ + display: React.ReactNode; + disabled?: boolean; + invalid?: boolean; + label: string; + /** The grid's own key handler: the arrows move between lines. */ + onNavKeyDown: (e: React.KeyboardEvent) => void; + 'data-cell': string; + /** The panel's test id. */ + panelTestId: string; + /** The face drawn in the panel: a widget's own `inCell` face. */ + children: (face: GridPanelFace) => React.ReactNode; +} + +/** + * A cell whose editor is a widget's own in-cell face (objectstack#36043), the + * face the main list's cell editor draws: a click, Enter, Space, F2 or + * Alt+ArrowDown opens it in a panel under the cell, which keeps drawing its + * value. The face edits a draft. A click outside the panel or Tab writes it + * and closes; Esc closes and writes nothing; a face that ends on one pick + * (a single person) calls `commit`. + */ +export function GridPanelCell({ + value, + onWrite, + display, + disabled, + invalid, + label, + onNavKeyDown, + 'data-cell': dataCell, + panelTestId, + children, +}: GridPanelCellProps) { + const [open, setOpen] = React.useState(false); + const [draft, setDraftState] = React.useState(value); + // Read by `commit`, which a face may call in the same handler that set the draft. + const draftRef = React.useRef(value); + const triggerRef = React.useRef(null); + + const setDraft = (next: V) => { + draftRef.current = next; + setDraftState(next); + }; + const openPanel = () => { + setDraft(value); + setOpen(true); + }; + const close = (write: boolean) => { + if (write && !sameValue(draftRef.current, value)) onWrite(draftRef.current); + setOpen(false); + }; + + return ( + { + // Opening goes through `openPanel`; any other close writes, as a click outside does. + if (!next) close(true); + }} + > + + + + { + // Esc takes back what the panel changed. + e.preventDefault(); + close(false); + triggerRef.current?.focus(); + }} + onKeyDown={(e) => { + if (e.key !== 'Tab') return; + // The panel lives outside the table, so Tab is moved on by hand. + e.preventDefault(); + close(true); + const trigger = triggerRef.current; + if (!trigger) return; + (neighbourTabbable(trigger, e.shiftKey) ?? trigger).focus(); + }} + > + {children({ + draft, + setDraft, + commit: () => { + close(true); + triggerRef.current?.focus(); + }, + })} + + + ); +} + +/** Two cell values are the same write: equal scalars, or arrays of equal members in order. */ +function sameValue(a: unknown, b: unknown): boolean { + if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((v, i) => Object.is(v, b[i])); + return Object.is(a, b) || ((a == null || a === '') && (b == null || b === '')); +} + export interface GridDateCellProps extends Omit, 'value' | 'onChange'> { /** `date` or `datetime`: which native control, and what a calendar day writes. */ kind: 'date' | 'datetime'; diff --git a/ui/packages/plugin-form/src/MasterDetailForm.lateCatalogue-12924.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.lateCatalogue-12924.test.tsx index 84fcbb2cd48..9ef71300952 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.lateCatalogue-12924.test.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.lateCatalogue-12924.test.tsx @@ -14,7 +14,13 @@ * its first paint renders through `fallbackLng: 'en'`, and it re-renders in the * user's language when the catalogue lands. `MasterDetailForm` derives a * `boolean` / `toggle` column's two options once, in its resolve effect, when - * the child schema arrives. A schema that arrives first is derived with the + * the child schema arrives. + * + * Since objectstack#36043 a derived boolean column edits as a checkbox, which + * draws no word, so the words are read where the grid still draws them: the + * at-a-glance rows of a detail in `inlineMode: 'form'` (the `Charges` detail + * below). The `Lines` detail is an editable grid and carries the unsaved edit + * and its checkboxes. A schema that arrives first is derived with the * `en` words, and the re-render the catalogue triggers must still re-label * those options, which this file pins. * @@ -84,14 +90,28 @@ const LINES = [ { id: 'l1', invoice: 'inv1', description: 'Freight', billable: true }, { id: 'l2', invoice: 'inv1', description: 'Packing', billable: false }, ]; +const CHARGE_CHILD = { + name: 'inv_charge', + fields: { + invoice: { type: 'master_detail', label: 'Invoice', reference: 'inv' }, + note: { type: 'text', label: 'Note' }, + chargeable: { type: 'boolean', label: 'Chargeable' }, + }, +}; +const CHARGES = [ + { id: 'c1', invoice: 'inv1', note: 'Courier', chargeable: true }, + { id: 'c2', invoice: 'inv1', note: 'Waived', chargeable: false }, +]; function dataSource() { return { getObjectSchema: vi.fn(async (o: string) => - o === 'inv_line' ? CHILD : { name: 'inv', fields: { ref: { type: 'text', label: 'Ref' } } }, + o === 'inv_line' ? CHILD : o === 'inv_charge' ? CHARGE_CHILD : { name: 'inv', fields: { ref: { type: 'text', label: 'Ref' } } }, ), findOne: vi.fn().mockResolvedValue({ id: 'inv1', ref: 'INV-1' }), - find: vi.fn(async (o: string) => ({ data: o === 'inv_line' ? LINES.map((l) => ({ ...l })) : [] })), + find: vi.fn(async (o: string) => ({ + data: o === 'inv_line' ? LINES.map((l) => ({ ...l })) : o === 'inv_charge' ? CHARGES.map((c) => ({ ...c })) : [], + })), create: vi.fn(), update: vi.fn(), delete: vi.fn(), @@ -99,8 +119,16 @@ function dataSource() { }; } -/** The two lines' `Billable` pickers' text, in row order. */ -const billable = () => screen.getAllByRole('combobox', { name: 'Billable' }).slice(0, 2).map((el) => el.textContent); +/** The two charges' `Chargeable` words, in row order: the at-a-glance rows of + * the `inlineMode: 'form'` detail, where the grid draws a boolean's word. */ +const chargeable = () => + Array.from(document.querySelectorAll('[data-grid-cell$=":chargeable"]')).slice(0, 2).map((el) => el.textContent); +/** The two lines' `Billable` checkboxes, in row order: the editable grid's + * check cells (objectstack#36043), which hold the value and draw no word. */ +const billableChecks = () => + Array.from(document.querySelectorAll('[data-grid-cell$=":billable"] [role="checkbox"]')).slice(0, 2).map((el) => + el.getAttribute('aria-checked'), + ); const descriptions = () => screen.getAllByLabelText('Description') as HTMLInputElement[]; describe('MasterDetailForm re-labels derived boolean options when the catalogue lands late (objectui#12924)', () => { @@ -120,7 +148,10 @@ describe('MasterDetailForm re-labels derived boolean options when the catalogue mode: 'edit', recordId: 'inv1', fields: ['ref'], - details: [{ childObject: 'inv_line', title: 'Lines', inlineMode: 'grid' }], + details: [ + { childObject: 'inv_line', title: 'Lines', inlineMode: 'grid' }, + { childObject: 'inv_charge', title: 'Charges', inlineMode: 'form' }, + ], } as never} dataSource={ds as never} /> @@ -130,14 +161,15 @@ describe('MasterDetailForm re-labels derived boolean options when the catalogue // Precondition: the catalogue is held, so the columns were derived with // the `en` fallback's words. If this read were already zh, the row would // not be measuring a late catalogue. - await waitFor(() => expect(billable()).toEqual(['Yes', 'No'])); + await waitFor(() => expect(chargeable()).toEqual(['Yes', 'No'])); + expect(billableChecks()).toEqual(['true', 'false']); expect(screen.getByTestId('md-form-submit').textContent).toBe('Save'); expect(gate.asked).toContain('zh-Hans'); // An unsaved edit on the first line, made before the catalogue lands. fireEvent.change(descriptions()[0], { target: { value: 'Freight, edited' } }); expect(descriptions()[0].value).toBe('Freight, edited'); - const lineReads = () => ds.find.mock.calls.filter(([o]) => o === 'inv_line').length; + const lineReads = () => ds.find.mock.calls.filter(([o]) => o === 'inv_line' || o === 'inv_charge').length; const readsBefore = lineReads(); const schemaReadsBefore = ds.getObjectSchema.mock.calls.length; @@ -146,11 +178,12 @@ describe('MasterDetailForm re-labels derived boolean options when the catalogue // The catalogue landed and the form re-rendered in zh: its Save button // reads the zh word. Without this, a red below could mean nothing landed. await waitFor(() => expect(screen.getByTestId('md-form-submit').textContent).toBe(ZH.common.save)); - await waitFor(() => expect(billable()).toEqual([YES, NO])); + await waitFor(() => expect(chargeable()).toEqual([YES, NO])); // The resolve effect did not run again: no second schema fetch, no line // re-read, and the edit is still on screen. expect(ds.getObjectSchema.mock.calls.length).toBe(schemaReadsBefore); expect(lineReads()).toBe(readsBefore); expect(descriptions()[0].value).toBe('Freight, edited'); + expect(billableChecks()).toEqual(['true', 'false']); }); }); diff --git a/ui/packages/plugin-form/src/deriveMasterDetail.booleanOptions-12924.test.tsx b/ui/packages/plugin-form/src/deriveMasterDetail.booleanOptions-12924.test.tsx index 296a07bfeef..81881612db8 100644 --- a/ui/packages/plugin-form/src/deriveMasterDetail.booleanOptions-12924.test.tsx +++ b/ui/packages/plugin-form/src/deriveMasterDetail.booleanOptions-12924.test.tsx @@ -13,7 +13,9 @@ * The derive functions turned such a child field into a select column whose * options were `{ label: 'Yes', value: 'true' }` and `{ label: 'No', value: * 'false' }`, English on every locale: the editable cell's picker and the - * list-mode cell showed it. The labels now come from `useBooleanValueLabel` + * list-mode cell showed it. Since objectstack#36043 the column is a check + * column (`type: 'boolean'`): the editable cell is a checkbox, and the two + * options are the words its read-only and list-mode cells read as. The labels now come from `useBooleanValueLabel` * (`@object-ui/fields`), the one rule that names a boolean value as a word * (`common.yes` / `common.no`, objectui#11689). The derive module is pure, so * its two producers hold the hook and hand it in, and every derive function @@ -24,11 +26,12 @@ * - the derive functions draw the labels with the function they are handed, * and keep the stored values; * - `record:line_items` (`LineItemsPanel`) hydrates an untyped column over a - * boolean child field into a picker that reads the zh words, draws the - * same words in its read-only table, and re-labels the picker when the + * boolean child field into a check cell over the stored value, draws the + * zh words in its read-only table, and re-labels that table when the * language is switched while it is on screen; - * - `MasterDetailForm` derives a boolean column that reads the zh words, in - * its editable grid and in its list-mode (per-row form) cells. + * - `MasterDetailForm` derives a boolean column that is a check cell in its + * editable grid and reads the zh words in its list-mode (per-row form) + * cells. * * Every oracle is read from the zh pack. */ @@ -73,13 +76,13 @@ describe('the derive functions draw a boolean column\'s labels with the `boolean const byName = Object.fromEntries( deriveColumns(CHILD, { relationshipField: 'invoice', booleanLabel: marked }).map((c) => [c.name, c]), ); - expect(byName.billable).toMatchObject({ type: 'select', options: MARKED_OPTIONS }); - expect(byName.rush).toMatchObject({ type: 'select', options: MARKED_OPTIONS }); + expect(byName.billable).toMatchObject({ type: 'boolean', options: MARKED_OPTIONS }); + expect(byName.rush).toMatchObject({ type: 'boolean', options: MARKED_OPTIONS }); }); it('hydrateColumns: an untyped column over a boolean field gets the same two options', () => { const [col] = hydrateColumns([{ name: 'billable' }], CHILD, { booleanLabel: marked }); - expect(col).toMatchObject({ type: 'select', label: 'Billable', options: MARKED_OPTIONS }); + expect(col).toMatchObject({ type: 'boolean', label: 'Billable', options: MARKED_OPTIONS }); }); it('deriveDetail: both of its column paths hand the function on', () => { @@ -119,11 +122,12 @@ function dataSource() { const inZh = (node: React.ReactNode) => render({node}); -/** The two lines' `Billable` pickers, in row order. */ -const billablePickers = () => screen.getAllByRole('combobox', { name: 'Billable' }).slice(0, 2); +/** The two lines' `Billable` check cells' states, in row order. */ +const billableChecks = () => + screen.getAllByRole('checkbox', { name: 'Billable' }).slice(0, 2).map((el) => el.getAttribute('aria-checked')); describe('the line-items carriers read a boolean column in the session language (objectui#12924)', () => { - it('record:line_items: an untyped column over a boolean field is a picker reading the zh words', async () => { + it('record:line_items: an untyped column over a boolean field is a check cell over the stored value (objectstack#36043)', async () => { inZh( , ); - // `waitFor`: the zh catalogue loads after the first render, and the grid - // is re-hydrated when the words change. - await waitFor(() => expect(billablePickers().map((el) => el.textContent)).toEqual([YES, NO])); + await waitFor(() => expect(billableChecks()).toEqual(['true', 'false'])); + expect(screen.queryByRole('combobox', { name: 'Billable' })).toBeNull(); expect(screen.queryByText('Yes')).toBeNull(); expect(screen.queryByText('No')).toBeNull(); }); @@ -165,9 +168,9 @@ describe('the line-items carriers read a boolean column in the session language ); }; - it('MasterDetailForm, editable grid: the derived picker reads the zh words', async () => { + it('MasterDetailForm, editable grid: the derived column is a check cell (objectstack#36043)', async () => { await masterDetail('grid'); - await waitFor(() => expect(billablePickers().map((el) => el.textContent)).toEqual([YES, NO])); + await waitFor(() => expect(billableChecks()).toEqual(['true', 'false'])); expect(screen.queryByText('Yes')).toBeNull(); }); @@ -198,7 +201,7 @@ describe('the line-items carriers read a boolean column in the session language expect(container.textContent).not.toMatch(/\b(Yes|No|true|false)\b/); }); - it('record:line_items: a language switched while the grid is on screen re-labels the picker', async () => { + it('record:line_items: a language switched while the read-only table is on screen re-labels its cells', async () => { // The grid memo is keyed on the two WORDS, so a switch re-hydrates the // columns; the function itself is a new one every render and cannot key it. function SwitchTo({ language }: { language: string }) { @@ -209,7 +212,7 @@ describe('the line-items carriers read a boolean column in the session language ); } - render( + const { container } = render( @@ -219,15 +222,18 @@ describe('the line-items carriers read a boolean column in the session language relationshipField: 'invoice', parentObject: 'inv', parentId: 'inv1', + readonly: true, columns: [{ name: 'description' }, { name: 'billable' }], } as never} /> , ); - await waitFor(() => expect(billablePickers().map((el) => el.textContent)).toEqual(['Yes', 'No'])); + const billableCells = () => + Array.from(container.querySelectorAll('tbody tr')).map((tr) => tr.querySelectorAll('td')[2]?.textContent); + await waitFor(() => expect(billableCells()).toEqual(['Yes', 'No'])); fireEvent.click(screen.getByRole('button', { name: 'switch' })); - await waitFor(() => expect(billablePickers().map((el) => el.textContent)).toEqual([YES, NO])); + await waitFor(() => expect(billableCells()).toEqual([YES, NO])); }); it('MasterDetailForm, list mode: each line\'s cell reads the zh words', async () => { diff --git a/ui/packages/plugin-form/src/deriveMasterDetail.inlineGridColumns-11345.test.ts b/ui/packages/plugin-form/src/deriveMasterDetail.inlineGridColumns-11345.test.ts index 38ae21489e2..222fc7e849e 100644 --- a/ui/packages/plugin-form/src/deriveMasterDetail.inlineGridColumns-11345.test.ts +++ b/ui/packages/plugin-form/src/deriveMasterDetail.inlineGridColumns-11345.test.ts @@ -14,7 +14,9 @@ * expected arrays below were produced by the implementation this card * replaced (the local `curateColumns` budget), and `deriveColumns` is a * public export of `@object-ui/plugin-form`: the swap must not move a single - * column, label, type or flag. The corpus covers the budget edge from both + * column, label, type or flag — save the one type objectstack#36043 moved + * on purpose (a derived `boolean` column is the check cell), marked where + * it sits. The corpus covers the budget edge from both * sides, `maxColumns` (explicit, `0`, negative), the relationship field, * `exclude`, the filters, more required columns than the budget, a computed * required column, and FALSY field definitions — the one input where the @@ -168,7 +170,9 @@ const CORPUS: Array<{ title: string; schema: ChildObjectSchemaLike | undefined; { name: 'delivered_on', label: 'delivered_on', type: 'datetime', required: false, defaultHidden: true }, { name: 'shipped_at', label: 'shipped_at', type: 'time', required: false, defaultHidden: true }, { name: 'tax_class', label: 'tax_class', type: 'select', required: false, options: [{ label: 'Standard', value: 'std' }, { label: 'Zero', value: '0' }] }, - { name: 'gift', label: 'gift', type: 'select', required: false, options: [{ label: 'Yes', value: 'true' }, { label: 'No', value: 'false' }] }, + // The one column objectstack#36043 moved on purpose: a derived boolean + // column is the check cell now, keeping the yes / no words as its options. + { name: 'gift', label: 'gift', type: 'boolean', required: false, options: [{ label: 'Yes', value: 'true' }, { label: 'No', value: 'false' }] }, { name: 'remark', label: 'remark', type: 'text', required: false, defaultHidden: true }, ], }, diff --git a/ui/packages/plugin-form/src/deriveMasterDetail.test.ts b/ui/packages/plugin-form/src/deriveMasterDetail.test.ts index 7a55672b664..a45eee97069 100644 --- a/ui/packages/plugin-form/src/deriveMasterDetail.test.ts +++ b/ui/packages/plugin-form/src/deriveMasterDetail.test.ts @@ -48,6 +48,23 @@ describe('fieldTypeToColumnType', () => { expect(fieldTypeToColumnType('time')).toBe('time'); }); + // objectstack#36043 — each of these used to fold into a number box, a + // yes/no select or a plain text box. + it('maps people, multi-select, tags, check and rating to their own cells', () => { + expect(fieldTypeToColumnType('user')).toBe('user'); + expect(fieldTypeToColumnType('multiselect')).toBe('multiselect'); + expect(fieldTypeToColumnType('checkboxes')).toBe('multiselect'); + expect(fieldTypeToColumnType('tags')).toBe('tags'); + expect(fieldTypeToColumnType('boolean')).toBe('boolean'); + expect(fieldTypeToColumnType('toggle')).toBe('boolean'); + expect(fieldTypeToColumnType('rating')).toBe('rating'); + // CONTROL: their neighbours keep their cells. + expect(fieldTypeToColumnType('select')).toBe('select'); + expect(fieldTypeToColumnType('radio')).toBe('select'); + expect(fieldTypeToColumnType('percent')).toBe('number'); + expect(fieldTypeToColumnType('lookup')).toBe('lookup'); + }); + it('maps the spec file-family media types to a file column', () => { expect(fieldTypeToColumnType('file')).toBe('file'); expect(fieldTypeToColumnType('image')).toBe('file'); @@ -538,12 +555,12 @@ describe('hydrateColumns types a formula / summary column by its declared value }); }); - it('returnType number → number (its scale carried); date → date; boolean → select with the boolean labels; text → text', () => { + it('returnType number → number (its scale carried); date → date; boolean → check with the boolean labels; text → text', () => { const byName = hydrate(['weight', 'ships_on', 'is_large', 'line_code']); expect(byName.weight).toMatchObject({ type: 'number', computed: true, scale: 1 }); expect(byName.ships_on.type).toBe('date'); expect(byName.is_large).toMatchObject({ - type: 'select', + type: 'boolean', options: [{ label: en.common.yes, value: 'true' }, { label: en.common.no, value: 'false' }], }); expect(byName.line_code.type).toBe('text'); @@ -566,3 +583,72 @@ describe('hydrateColumns types a formula / summary column by its declared value expect(cols[1].type).toBe('currency'); }); }); + +describe('people, multi-select, tags, check and rating columns take their extras from the child field (objectstack#36043)', () => { + const lineSchema = { + name: 'task_line', + fields: { + task: { type: 'master_detail', reference: 'task' }, + assignee: { type: 'user', label: 'Assignee' }, + watchers: { type: 'user', label: 'Watchers', multiple: true }, + colors: { type: 'multiselect', label: 'Colors', options: [{ label: 'Red', value: 'red' }, 'green'] }, + sizes: { type: 'checkboxes', label: 'Sizes', options: [{ label: 'S', value: 's' }] }, + labels: { type: 'tags', label: 'Labels' }, + topics: { type: 'tags', label: 'Topics', options: ['ops', 'sales'] }, + done: { type: 'boolean', label: 'Done' }, + score: { type: 'rating', label: 'Score' }, + stars: { type: 'rating', label: 'Stars', max: 10 }, + title: { type: 'text', label: 'Title' }, + }, + }; + const derived = () => Object.fromEntries(deriveColumns(lineSchema, { booleanLabel, relationshipField: 'task', maxColumns: 0 }).map((c) => [c.name, c])); + const hydrated = (names: string[]) => + Object.fromEntries(hydrateColumns(names.map((name) => ({ name })) as any, lineSchema, { booleanLabel }).map((c) => [c.name, c])); + + it('a people column carries `multiple` only from a multi-person field', () => { + for (const byName of [derived(), hydrated(['assignee', 'watchers'])]) { + expect(byName.assignee).toEqual({ name: 'assignee', label: 'Assignee', type: 'user', required: false }); + expect(byName.watchers).toMatchObject({ type: 'user', multiple: true }); + } + }); + + it('multi-select and checkboxes columns carry their options; a tags column carries none, even from a field that declares some', () => { + for (const byName of [derived(), hydrated(['colors', 'sizes', 'labels', 'topics'])]) { + expect(byName.colors).toMatchObject({ type: 'multiselect', options: [{ label: 'Red', value: 'red' }, { label: 'green', value: 'green' }] }); + expect(byName.sizes).toMatchObject({ type: 'multiselect', options: [{ label: 'S', value: 's' }] }); + expect(byName.labels).toEqual({ name: 'labels', label: 'Labels', type: 'tags', required: false }); + // The tags cell reads no option list (TagsField offers the tags it holds + // plus free text), so a carried list would be a promise nothing keeps. + expect(byName.topics).toEqual({ name: 'topics', label: 'Topics', type: 'tags', required: false }); + } + }); + + it('a check column carries the two words its cell reads as', () => { + for (const byName of [derived(), hydrated(['done'])]) { + expect(byName.done).toMatchObject({ + type: 'boolean', + options: [{ label: en.common.yes, value: 'true' }, { label: en.common.no, value: 'false' }], + }); + } + }); + + it("a rating column carries the field's `max`, and none when the field declares none (the cell draws 5)", () => { + for (const byName of [derived(), hydrated(['score', 'stars'])]) { + expect(byName.score).toEqual({ name: 'score', label: 'Score', type: 'rating', required: false }); + expect(byName.stars).toMatchObject({ type: 'rating', max: 10 }); + } + }); + + it('CONTROL: an authored column keeps its own type and extras, a select over a boolean field included', () => { + const cols = hydrateColumns( + [ + { name: 'done', type: 'select', options: [{ label: 'On', value: 'true' }] }, + { name: 'stars', type: 'rating', max: 3 }, + ] as any, + lineSchema, + { booleanLabel }, + ); + expect(cols[0]).toEqual({ name: 'done', type: 'select', options: [{ label: 'On', value: 'true' }] }); + expect(cols[1]).toEqual({ name: 'stars', type: 'rating', max: 3 }); + }); +}); diff --git a/ui/packages/plugin-form/src/deriveMasterDetail.ts b/ui/packages/plugin-form/src/deriveMasterDetail.ts index 06c9c5aa29a..38fc0fa7f47 100644 --- a/ui/packages/plugin-form/src/deriveMasterDetail.ts +++ b/ui/packages/plugin-form/src/deriveMasterDetail.ts @@ -54,9 +54,13 @@ export function fieldTypeToColumnType(type: string | undefined): GridColumn['typ switch (type) { case 'number': case 'percent': - case 'rating': case 'slider': return 'number'; + // objectstack#36043 — a rating, a check, a person and a list of options + // or tags each get the cell the main list edits them with, not a number + // box, a yes/no select or a plain text box. + case 'rating': + return 'rating'; case 'currency': return 'currency'; // Three distinct controls, NOT one (objectui#3569). Collapsing `datetime` @@ -74,12 +78,20 @@ export function fieldTypeToColumnType(type: string | undefined): GridColumn['typ case 'select': case 'picklist': case 'radio': + return 'select'; case 'boolean': case 'toggle': - return 'select'; + return 'boolean'; + case 'multiselect': + case 'checkboxes': + return 'multiselect'; + case 'tags': + return 'tags'; case 'lookup': case 'master_detail': return 'lookup'; + case 'user': + return 'user'; case 'file': case 'image': case 'avatar': @@ -112,8 +124,9 @@ export function fieldTypeToColumnType(type: string | undefined): GridColumn['typ * * The declared value type is then a field type like any other, so * {@link fieldTypeToColumnType} maps it with no second table: `number` → - * `number`, `currency` → `currency`, `date` → `date`, `boolean` → `select` - * (with the two option labels {@link optionsFor} draws for a boolean field), + * `number`, `currency` → `currency`, `date` → `date`, `boolean` → `boolean` + * (a check cell, carrying the two option labels {@link optionsFor} draws for a + * boolean field, objectstack#36043), * `text` → `text`. A currency column's code is resolved where every currency * column's is (`GridField`'s `columnCurrencies`, filled from the child field's * own `currencyConfig` by `parentCurrencyFieldsOf`, whatever the field's type). @@ -148,10 +161,10 @@ function applyFileColumnProps(col: GridColumn, d: any): void { } /** - * A select column's options, from its child field. A `boolean` / `toggle` - * field has no options of its own, so it gets two, whose STORED values are - * `'true'` / `'false'` and whose LABELS are the session's word for each value, - * drawn by `booleanLabel` (objectui#12924). + * A column's options, from its child field. A `boolean` / `toggle` field has + * no options of its own, so it gets two, keyed `'true'` / `'false'`, whose + * LABELS are the session's word for each value, drawn by `booleanLabel` + * (objectui#12924): the words its check cell is read as (objectstack#36043). * * The labels used to be the literals `Yes` / `No`, so the line-items grid's * select and its read-only cells read English on every locale. They now come @@ -179,6 +192,26 @@ function optionsFor(def: any, booleanLabel: BooleanValueLabel): GridColumn['opti ); } +/** + * The column types that carry the child field's options (objectstack#36043): + * the choices of a select or multi-select cell, and the two words a check cell + * is read as. A tags cell carries none: like the list view's tags cell, it + * offers the tags it holds plus free text, and reads no option list. + */ +function takesOptions(type: GridColumn['type']): boolean { + return type === 'select' || type === 'multiselect' || type === 'boolean'; +} + +/** + * The extras a `user` or `rating` cell reads from its child field + * (objectstack#36043): whether a person cell holds several people, and how + * many stars a rating cell draws. A key the column already carries is kept. + */ +function applyPickerColumnProps(col: GridColumn, d: any): void { + if (col.type === 'user' && col.multiple == null && d?.multiple === true) col.multiple = true; + if (col.type === 'rating' && col.max == null && Number.isInteger(d?.max) && d.max > 0) col.max = d.max; +} + /** * Find the field on the child object that points back to the parent — the * master_detail/lookup field whose `reference` is the parent object. Prefer @@ -252,7 +285,8 @@ function deriveColumn(name: string, d: any, booleanLabel: BooleanValueLabel): Gr required: !!d?.required, }; const options = optionsFor(d, booleanLabel); - if (col.type === 'select' && options) col.options = options; + if (takesOptions(col.type) && options) col.options = options; + applyPickerColumnProps(col, d); if (col.type === 'lookup') { col.reference = d?.reference; // The display pointer is read in `@objectstack/spec`'s spelling, @@ -363,7 +397,8 @@ function reportCurrencyColumnScale( * * `booleanLabel` is required for the same reason as on {@link deriveColumns}: * an untyped column over a `boolean` / `toggle` child field hydrates into a - * select whose two option labels it draws (objectui#12924). + * check cell whose two option labels it draws (objectui#12924; a check cell + * since objectstack#36043). */ export function hydrateColumns( columns: GridColumn[] | undefined, @@ -388,7 +423,8 @@ export function hydrateColumns( if (next.label == null) next.label = d?.label || col.name; if (next.required == null) next.required = !!d?.required; const options = optionsFor(d, opts.booleanLabel); - if (type === 'select' && options && !next.options) next.options = options; + if (takesOptions(type) && options && !next.options) next.options = options; + applyPickerColumnProps(next, d); if (type === 'lookup') { if (next.reference == null) next.reference = d?.reference; // The same read as `deriveColumns` above (objectui#11070 round 6). diff --git a/ui/packages/types/src/__tests__/strict-face-read-keys-11070.test.ts b/ui/packages/types/src/__tests__/strict-face-read-keys-11070.test.ts index 0f49f4fbbd9..0e9f60a3671 100644 --- a/ui/packages/types/src/__tests__/strict-face-read-keys-11070.test.ts +++ b/ui/packages/types/src/__tests__/strict-face-read-keys-11070.test.ts @@ -278,7 +278,9 @@ describe('objectui#11070 — a declared key is judged by its declared type on bo ['an adapter-shaped `dataSource`', { type: 'object-grid', properties: { objectName: 'task' }, dataSource: 'objectstack' }], // Round 7: the grid's columns are the spec's strict inline grid column. ['a grid column keyed by the retired `field` spelling', form({ type: 'grid', columns: [{ field: 'qty' }] })], - ['a grid column `type` outside the spec\'s nine cell controls (`boolean`)', form({ type: 'grid', columns: [{ name: 'done', type: 'boolean' }] })], + // `boolean` joined the cell types in objectstack#36043; `toggle` is a field + // type the column reads through `boolean`, never a column type of its own. + ['a grid column `type` outside the spec\'s fourteen cell controls (`toggle`)', form({ type: 'grid', columns: [{ name: 'done', type: 'toggle' }] })], ['a grid column `defaultValue` (the spec column declares none, and the grid reads none)', form({ type: 'grid', columns: [{ name: 'qty', defaultValue: 1 }] })], ['a `scale` on a column declaring `type: \'currency\'` (the spec refuses it there)', form({ type: 'grid', columns: [{ name: 'amount', type: 'currency', scale: 2 }] })], ['a bare-object `columns` (the spec types it as an array)', form({ type: 'grid', columns: { name: 'qty' } })], diff --git a/ui/packages/types/src/form.ts b/ui/packages/types/src/form.ts index 3601af11021..c88feb4cedd 100644 --- a/ui/packages/types/src/form.ts +++ b/ui/packages/types/src/form.ts @@ -2148,7 +2148,7 @@ export interface FormField { * `name`-keyed inline grid column (`{ name, label?, type?, width?, … }`). * The `grid` widget reads `columns` off its metadata carrier and each column * by exactly the spec's keys, so a column the spec refuses (the retired - * `field` spelling, a `title`, a `type` outside its nine cell controls) is + * `field` spelling, a `title`, a `type` outside its cell controls) is * refused here too rather than rendered as an empty or plain-text cell. The * spec spells the list `inlineColumns` on a `master_detail` field; a `grid` * field is objectui's own type, whose key is `columns` (objectui#11070).