diff --git a/.changeset/35688-in-cell-pickers.md b/.changeset/35688-in-cell-pickers.md new file mode 100644 index 00000000000..427ed612f89 --- /dev/null +++ b/.changeset/35688-in-cell-pickers.md @@ -0,0 +1,27 @@ +--- +'@object-ui/fields': patch +'@object-ui/plugin-grid': patch +'@object-ui/components': patch +'@object-ui/i18n': patch +--- + +feat(fields): in a list grid's cell editor, select, multi-select, tags, date, time and colour open ready to pick + +Clause-②: yes (widening) +Metadata-protocol: none + +The widget contract `FieldWidgetComponentProps` gains two optional host keys, `inCell` (draw the face for a grid cell's editor) and `onCommit` (the user has finished: write the last `onChange` value and close). `FieldEditWidget` forwards both, and `ObjectGrid`'s cell editor passes them. A host that passes neither renders every widget exactly as before. + +In the cell editor of every grid `ObjectGrid` draws: + +- **Single select and status** show their option list at once, with a search box that filters as you type. The arrow keys move through the list, Enter or a click picks, and the pick is saved; the selection stays on the cell. With nothing picked, Enter commits as before and Escape cancels. +- **Multi-select** (and a select declared `multiple`) is the same list with check marks: each pick toggles, and the edit is saved when you move on. +- **Tags** list this record's tags with check marks; unchecking removes one, and text that matches no tag is added from the list's leading "Add" row (Enter). +- **Date and date-time** open their calendar at once while the typed value stays visible and editable in the text box. The calendar offers Today, Tomorrow, Next week (seven days from today) and Clear. On a date, picking a day or a quick pick saves and closes; on a date-time, a day keeps the calendar open for the time, as in forms. +- **Time** opens the browser's time picker when the editor opens. +- **Colour** shows the hex box first (Enter saves, Escape leaves) and a row of swatches plus the browser's colour picker; a swatch saves and closes. +- A value picked this way hands the keyboard focus back to the selected cell, and in a grid that edits on a single click, the click that picked it no longer opens the editor again. + +`@object-ui/i18n` adds the strings these faces show in every locale: `fields.datePicker.nextWeek`, `fields.datePicker.clearPick`, `fields.options.search`, `fields.options.noMatches`, `fields.tags.add`, `fields.color.swatches`, `fields.color.custom`. + +Forms, dialogs and the record page keep their current controls. diff --git a/content/docs/frontend/plugins/plugin-grid.mdx b/content/docs/frontend/plugins/plugin-grid.mdx index 26a95d8bc1d..946eaefe6f0 100644 --- a/content/docs/frontend/plugins/plugin-grid.mdx +++ b/content/docs/frontend/plugins/plugin-grid.mdx @@ -374,6 +374,15 @@ through the host's data source (`dataSource.update`) with no callback to wire. window the layer opens upward, near the right edge it shifts left, and a cell half hidden behind a frozen column or the header is scrolled into view first. Scrolling the cell out of sight commits the edit. +- **Pickers open ready to pick** (objectstack#35688): a single select or + status shows its option list at once, with a search box that filters as you + type; the arrow keys and Enter (or a click) pick, and the pick is saved. A + multi-select is the same list with check marks, and tags list the field's + tags with an "Add" row for new text; both save when you move on. A date or + date-time opens its calendar while the value stays typeable in its box, with + Today, Tomorrow, Next week (seven days from today) and Clear; on a date, a + day or a quick pick saves. A time opens the browser's time picker, and a + colour offers swatches beside its hex box (a swatch saves, Escape leaves). To own persistence in a React host, supply `onCellChange` as a **component prop** — it is not a schema key. diff --git a/ui/examples/schema-catalog/test/form-field-channel-census-12130.test.tsx b/ui/examples/schema-catalog/test/form-field-channel-census-12130.test.tsx index cd3d582cf10..44a81261d00 100644 --- a/ui/examples/schema-catalog/test/form-field-channel-census-12130.test.tsx +++ b/ui/examples/schema-catalog/test/form-field-channel-census-12130.test.tsx @@ -309,6 +309,24 @@ const LEDGER: Readonly> = { readers: ['props@fields/src/widgets/AvatarField.tsx', 'props@fields/src/widgets/FileField.tsx', 'props@fields/src/widgets/ImageField.tsx'], why: 'RUNTIME SLOT — a host-supplied function; JSON has no function value (the objectui#6124 shape).', }, + // objectstack#35688 — the list grid's cell editor (`ObjectGrid` through + // `FieldEditWidget`) sets these two; a form never does. + inCell: { + readers: [ + 'props@fields/src/widgets/ColorField.tsx', 'props@fields/src/widgets/MultiSelectField.tsx', + 'props@fields/src/widgets/TagsField.tsx', 'props@fields/src/widgets/TimeField.tsx', + ], + why: 'RUNTIME SLOT (objectstack#35688) — host plumbing: the grid cell editor asks for the in-cell face; where a ' + + 'widget is drawn is the host\'s fact, not something a form document authors.', + }, + onCommit: { + readers: [ + 'props@fields/src/widgets/ColorField.tsx', 'props@fields/src/widgets/MultiSelectField.tsx', + 'props@fields/src/widgets/TagsField.tsx', 'props@fields/src/widgets/TimeField.tsx', + ], + why: 'RUNTIME SLOT (objectstack#35688) — a host-supplied function (the grid cell editor\'s commit); JSON has no ' + + 'function value (the objectui#6124 shape).', + }, // ── runtime-only, by an existing ruling ───────────────────────────────── field: { readers: [ diff --git a/ui/packages/components/src/renderers/complex/data-table.tsx b/ui/packages/components/src/renderers/complex/data-table.tsx index cfc79a5366f..606a3e37bd1 100644 --- a/ui/packages/components/src/renderers/complex/data-table.tsx +++ b/ui/packages/components/src/renderers/complex/data-table.tsx @@ -4981,6 +4981,16 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { if (wasSelected && togglesCell(row, col)) toggleCell(rowIndex, colIndex); return; } + // objectstack#35688 — a click inside the open editor (an + // option of the in-cell list, still in the DOM when its click + // lands) is the editor's own. When that pick has just + // committed, `startEdit`'s same-cell guard has already been + // cleared, so the click would open the editor again; this + // render still says the cell is editing, so stop here. + if (isEditing) { + e.stopPropagation(); + return; + } if (isEditable && singleClickEdit && !hasTextSelectionIn(e.currentTarget)) { e.stopPropagation(); startEdit(row, col.accessorKey); @@ -5131,7 +5141,12 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { pendingRow: rowHasChanges ? pendingRows.of(row, rowKey) : row, value: editValue, stage: stageEdit, - commit: (v?: any) => saveEdit(true, v), + // objectstack#35688 — a pick that commits hands the + // focus back to the selected cell, as Enter does. + commit: (v?: any) => { + focusSelectionRef.current = selectFirst; + saveEdit(true, v); + }, cancel: cancelEdit, }); if (node != null) { diff --git a/ui/packages/fields/README.md b/ui/packages/fields/README.md index 06847e0fa8f..bfeaf8ef475 100644 --- a/ui/packages/fields/README.md +++ b/ui/packages/fields/README.md @@ -123,6 +123,20 @@ The app-shell `ActionParamDialog` uses these to render declared action params through the exact same widgets as the object form — with a drift test pinning param support ⊇ form support. +### The grid cell editor's face (`inCell`, `onCommit`) + +`FieldEditWidget` forwards two optional host keys of `FieldWidgetComponentProps` +to the widget it draws. `inCell` asks for the face a list grid's cell editor +needs: a single select or multi-select field draws a searchable list of its +options that is open from the start, a tags field the same list of this +record's tags (plus an "Add" row for new text), a date opens its calendar (with today, tomorrow, next +week and clear picks) while its text stays typeable, a time opens the browser +picker, and a colour offers swatches. `onCommit` is the host's "write the last +`onChange` value and close", which the date picker calls after a day or a quick +pick and the in-cell colour face after a swatch. +A host that passes neither gets the form faces unchanged; `ObjectGrid` passes +both. + ### Resolving declared action params An action param is declared either inline (`name` + `type`) or field-backed diff --git a/ui/packages/fields/src/__tests__/inCellFaces-35688.test.tsx b/ui/packages/fields/src/__tests__/inCellFaces-35688.test.tsx new file mode 100644 index 00000000000..9c545605f6f --- /dev/null +++ b/ui/packages/fields/src/__tests__/inCellFaces-35688.test.tsx @@ -0,0 +1,282 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35688 (slice S2) — the faces the option, tags, date, time and + * colour widgets draw in the list grid's cell editor (`inCell`), and the + * `onCommit` call that ends an edit on a pick. Without `inCell` each widget + * keeps its form face. + */ + +import React from 'react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'; +import { SelectField } from '../widgets/SelectField'; +import { MultiSelectField } from '../widgets/MultiSelectField'; +import { TagsField } from '../widgets/TagsField'; +import { ColorField } from '../widgets/ColorField'; +import { TimeField } from '../widgets/TimeField'; +import { DatePickerField, DateTimePickerField } from '../widgets/date-picker/DatePickerField'; +import { FieldEditWidget } from '../FieldEditWidget'; + +afterEach(() => cleanup()); + +type Field = React.ComponentProps['field']; + +const SELECT = { + name: 'stage', + type: 'select', + options: [ + { value: 'new', label: 'New' }, + { value: 'qualified', label: 'Qualified' }, + { value: 'won', label: 'Closed won' }, + { value: 'lost', label: 'Closed lost' }, + ], +} as unknown as Field; + +/** The grid's editor wrapper, reduced to the one fact these tests need: did Enter reach it? */ +function GridEditor({ onGridKey, children }: { onGridKey: (key: string) => void; children: React.ReactNode }) { + return
onGridKey(e.key)}>{children}
; +} + +const optionRows = () => screen.getAllByRole('option'); + +describe('in-cell single select (objectstack#35688)', () => { + it('shows the searchable list at once, no trigger to press', () => { + render( {}} inCell />); + expect(screen.queryByTestId('select-trigger-stage')).toBeNull(); + const box = screen.getByRole('combobox'); + expect(box.tagName).toBe('INPUT'); + expect(box.getAttribute('aria-expanded')).toBe('true'); + expect(optionRows().map((o) => o.textContent)).toEqual(['New', 'Qualified', 'Closed won', 'Closed lost']); + // The current value is checked and active. + const current = screen.getByTestId('in-cell-option-qualified'); + expect(current.getAttribute('aria-selected')).toBe('true'); + expect(box.getAttribute('aria-activedescendant')).toBe(current.id); + }); + + it('typing filters; Enter picks the first match and does not reach the grid', () => { + const onChange = vi.fn(); + const onGridKey = vi.fn(); + render( + + + , + ); + const box = screen.getByRole('combobox'); + fireEvent.change(box, { target: { value: 'closed' } }); + expect(optionRows().map((o) => o.textContent)).toEqual(['Closed won', 'Closed lost']); + fireEvent.keyDown(box, { key: 'ArrowDown' }); + fireEvent.keyDown(box, { key: 'Enter' }); + expect(onChange).toHaveBeenCalledWith('lost'); + expect(onGridKey).not.toHaveBeenCalledWith('ArrowDown'); + expect(onGridKey).not.toHaveBeenCalledWith('Enter'); + }); + + it('a click picks; no match says so; Escape goes on to the grid', () => { + const onChange = vi.fn(); + const onGridKey = vi.fn(); + render( + + + , + ); + fireEvent.click(screen.getByTestId('in-cell-option-won')); + expect(onChange).toHaveBeenCalledWith('won'); + const box = screen.getByRole('combobox'); + fireEvent.change(box, { target: { value: 'zzz' } }); + expect(screen.queryAllByRole('option')).toHaveLength(0); + expect(screen.getByText('No matching options')).toBeTruthy(); + fireEvent.keyDown(box, { key: 'Escape' }); + expect(onGridKey).toHaveBeenCalledWith('Escape'); + }); + + it('clearing the search puts the active row back on the current value, not on its filtered index', () => { + const onChange = vi.fn(); + render(); + const box = screen.getByRole('combobox'); + const current = screen.getByTestId('in-cell-option-lost'); + expect(box.getAttribute('aria-activedescendant')).toBe(current.id); + // "lost" is row 1 of the filtered list and row 3 of the full one. + fireEvent.change(box, { target: { value: 'closed' } }); + fireEvent.change(box, { target: { value: '' } }); + expect(box.getAttribute('aria-activedescendant')).toBe(screen.getByTestId('in-cell-option-lost').id); + fireEvent.keyDown(box, { key: 'Enter' }); + expect(onChange).toHaveBeenCalledWith('lost'); + }); + + it('with nothing active, Enter goes on to the grid (it commits and moves)', () => { + const onChange = vi.fn(); + const onGridKey = vi.fn(); + render( + + + , + ); + fireEvent.keyDown(screen.getByRole('combobox'), { key: 'Enter' }); + expect(onChange).not.toHaveBeenCalled(); + expect(onGridKey).toHaveBeenCalledWith('Enter'); + }); + + it('CONTROL: without inCell the form face (the Radix trigger) is unchanged', () => { + render( {}} />); + expect(screen.getByTestId('select-trigger-stage')).toBeTruthy(); + expect(screen.queryByRole('listbox')).toBeNull(); + }); +}); + +describe('in-cell multi-select and tags (objectstack#35688)', () => { + it('multi-select: a searchable check list; a pick toggles and stages', () => { + const onChange = vi.fn(); + render(); + expect(screen.getByRole('listbox').getAttribute('aria-multiselectable')).toBe('true'); + fireEvent.click(screen.getByTestId('in-cell-option-won')); + expect(onChange).toHaveBeenLastCalledWith(['new', 'won']); + fireEvent.click(screen.getByTestId('in-cell-option-new')); + expect(onChange).toHaveBeenLastCalledWith([]); + }); + + it('a select declared multiple takes the same face', () => { + render( {}} inCell />); + expect(screen.getByRole('listbox').getAttribute('aria-multiselectable')).toBe('true'); + }); + + it('tags: typed text leads with an Add row, and Enter adds it', () => { + const onChange = vi.fn(); + const onGridKey = vi.fn(); + render( + + + , + ); + const box = screen.getByRole('combobox'); + fireEvent.change(box, { target: { value: 'vip' } }); + const rows = optionRows(); + expect(rows[0].getAttribute('data-testid')).toBe('in-cell-option-add'); + expect(rows[0].textContent).toBe('Add "vip"'); + expect(rows[1].textContent).toBe('vip-customer'); + fireEvent.keyDown(box, { key: 'Enter' }); + expect(onChange).toHaveBeenLastCalledWith(['urgent', 'vip-customer', 'vip']); + expect(onGridKey).not.toHaveBeenCalledWith('Enter'); + }); + + it('tags: unchecking removes a tag and keeps its row on offer', () => { + const onChange = vi.fn(); + const { rerender } = render( + , + ); + fireEvent.click(screen.getByTestId('in-cell-option-a')); + expect(onChange).toHaveBeenLastCalledWith(['b']); + rerender(); + const a = screen.getByTestId('in-cell-option-a'); + expect(a.getAttribute('aria-selected')).toBe('false'); + fireEvent.click(a); + expect(onChange).toHaveBeenLastCalledWith(['b', 'a']); + }); +}); + +describe('in-cell date (objectstack#35688)', () => { + const FIELD = { name: 'close_date', type: 'date' } as unknown as Field; + const localDay = (offset: number) => { + const d = new Date(); + d.setHours(0, 0, 0, 0); + d.setDate(d.getDate() + offset); + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; + }; + + it('the calendar shows at once, the value stays in the text box, and the box keeps the focus', () => { + const { container } = render( {}} inCell />); + const input = container.querySelector('[data-slot="date-picker"] input') as HTMLInputElement; + expect(input.value).toBe('10/16/2026'); + expect(screen.getByRole('grid')).toBeTruthy(); + input.focus(); + expect(document.activeElement).toBe(input); + for (const label of ['Today', 'Tomorrow', 'Next week', 'Clear']) expect(screen.getByRole('button', { name: label })).toBeTruthy(); + }); + + it('「下周」 is seven days from today, and the pick ends the edit', () => { + const onChange = vi.fn(); + const onCommit = vi.fn(); + render(); + fireEvent.click(screen.getByTestId('date-picker-next-week')); + expect(onChange).toHaveBeenCalledWith(localDay(7)); + expect(onCommit).toHaveBeenCalledTimes(1); + expect(onChange.mock.invocationCallOrder[0]).toBeLessThan(onCommit.mock.invocationCallOrder[0]); + }); + + it('a day in the calendar and the clear pick end the edit too', () => { + const onChange = vi.fn(); + const onCommit = vi.fn(); + render(); + fireEvent.click(within(screen.getByRole('grid')).getByText('20')); + expect(onChange).toHaveBeenLastCalledWith('2026-10-20'); + expect(onCommit).toHaveBeenCalledTimes(1); + cleanup(); + render(); + fireEvent.click(screen.getByTestId('date-picker-clear-pick')); + expect(onChange).toHaveBeenLastCalledWith(''); + expect(onCommit).toHaveBeenCalledTimes(2); + }); + + it('datetime: a day pick stays open for the time and does not end the edit', () => { + const onCommit = vi.fn(); + render( + {}} inCell onCommit={onCommit} />, + ); + fireEvent.click(screen.getByRole('button', { name: 'Tomorrow' })); + expect(onCommit).not.toHaveBeenCalled(); + expect(screen.getByTestId('date-picker-time')).toBeTruthy(); + }); + + it('CONTROL: the form face opens closed and offers only today and tomorrow', () => { + render( {}} />); + expect(screen.queryByRole('grid')).toBeNull(); + fireEvent.click(screen.getByTestId('date-picker-trigger')); + expect(screen.queryByTestId('date-picker-next-week')).toBeNull(); + expect(screen.queryByTestId('date-picker-clear-pick')).toBeNull(); + }); +}); + +describe('in-cell time and colour (objectstack#35688)', () => { + it('time: the browser picker shows on the first focus only', () => { + const showPicker = vi.fn(); + const { container } = render( {}} inCell />); + const input = container.querySelector('input[type="time"]') as HTMLInputElement & { showPicker?: () => void }; + input.showPicker = showPicker; + fireEvent.focus(input); + fireEvent.blur(input); + fireEvent.focus(input); + expect(showPicker).toHaveBeenCalledTimes(1); + expect(input.value).toBe('09:30'); + }); + + it('colour: the hex box comes first; a swatch picks and ends the edit', () => { + const onChange = vi.fn(); + const onCommit = vi.fn(); + const { container } = render( + , + ); + const first = container.querySelector('input,button') as HTMLInputElement; + expect(first.type).toBe('text'); + expect(first.value).toBe('#3b82f6'); + expect(screen.getByTestId('color-swatch-3b82f6').getAttribute('aria-pressed')).toBe('true'); + fireEvent.click(screen.getByTestId('color-swatch-ef4444')); + expect(onChange).toHaveBeenCalledWith('#ef4444'); + expect(onCommit).toHaveBeenCalledTimes(1); + }); +}); + +describe('FieldEditWidget hands the cell face on (objectstack#35688)', () => { + it('forwards inCell and onCommit to the widget', () => { + const onCommit = vi.fn(); + const element = FieldEditWidget({ field: { name: 'c', type: 'color' } as unknown as Field, value: '', onChange: () => {}, inCell: true, onCommit }); + const forwarded = element!.props as Record; + expect(forwarded.inCell).toBe(true); + expect(forwarded.onCommit).toBe(onCommit); + }); +}); diff --git a/ui/packages/fields/src/widgets/ColorField.tsx b/ui/packages/fields/src/widgets/ColorField.tsx index 64d93259cc2..fb9505bd96c 100644 --- a/ui/packages/fields/src/widgets/ColorField.tsx +++ b/ui/packages/fields/src/widgets/ColorField.tsx @@ -1,5 +1,6 @@ import React from 'react'; -import { Input, EmptyValue } from '@object-ui/components'; +import { Input, EmptyValue, cn } from '@object-ui/components'; +import { useFieldTranslation } from './useFieldTranslation.js'; import { FieldWidgetComponentProps } from './types.js'; import { toDomProps } from './toDomProps.js'; @@ -7,8 +8,19 @@ import { toDomProps } from './toDomProps.js'; * Color field widget - provides a color picker input * Supports hex color values (e.g., #ff0000) */ -export function ColorField({ value, onChange, field, readonly, error, ...props }: FieldWidgetComponentProps) { +/** + * The swatches the grid's cell editor offers (objectstack#35688): the 500 + * shade of each Tailwind hue, then black, grey and white. + */ +const IN_CELL_SWATCHES = [ + '#ef4444', '#f97316', '#f59e0b', '#eab308', '#84cc16', '#22c55e', + '#10b981', '#14b8a6', '#06b6d4', '#0ea5e9', '#3b82f6', '#6366f1', + '#8b5cf6', '#a855f7', '#d946ef', '#ec4899', '#000000', '#6b7280', '#ffffff', +] as const; + +export function ColorField({ value, onChange, field, readonly, error, inCell, onCommit, ...props }: FieldWidgetComponentProps) { const colorField = field as any; + const { t } = useFieldTranslation(); if (readonly) { return ( @@ -22,6 +34,55 @@ export function ColorField({ value, onChange, field, readonly, error, ...props } ); } + if (inCell && !props.disabled) { + // The grid's cell editor: the hex box takes the caret (Enter commits, Esc + // leaves), a swatch picks and commits, and the browser's picker is one + // more swatch for any other colour. + const current = (value || '').toLowerCase(); + return ( +
+ onChange(e.target.value)} + placeholder={colorField?.placeholder || '#000000'} + pattern="^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$" + aria-invalid={!!error} + /> +
+ {IN_CELL_SWATCHES.map((hex) => ( +
+
+ ); + } + return (
void; + onAdd?: (text: string) => void; + placeholder?: string; + testId?: string; + /** The host's DOM pass-through (id, aria-describedby, …), onto the search box. */ + inputProps?: React.InputHTMLAttributes; +}) { + const { t } = useFieldTranslation(); + const listId = React.useId(); + const [query, setQuery] = React.useState(''); + const needle = query.trim().toLocaleLowerCase(); + const shown = needle ? options.filter((o) => o.label.toLocaleLowerCase().includes(needle)) : options; + const addText = onAdd && query.trim() !== '' && !options.some((o) => o.label === query.trim()) ? query.trim() : null; + // The "Add" row leads, so Enter after typing a new tag adds it rather than + // toggling a longer tag that contains the text. + const lead = addText !== null ? 1 : 0; + const rowCount = lead + shown.length; + + // The active row starts on the current value (a single select) and on the + // first row once the user types; -1 is "none". It is an index into the FULL + // list, which is the list shown again when the search box is cleared (an + // index into the filtered list would land on another option then). + const initialActive = multiple ? -1 : options.findIndex((o) => selected.includes(o.value)); + const [active, setActive] = React.useState(initialActive); + const listRef = React.useRef(null); + + React.useEffect(() => { + if (active < 0) return; + const row = listRef.current?.querySelector(`[data-row-index="${active}"]`); + row?.scrollIntoView?.({ block: 'nearest' }); + }, [active]); + + const pickRow = (index: number) => { + if (index < lead && addText !== null) { + onAdd?.(addText); + setQuery(''); + setActive(-1); + } else if (index - lead < shown.length) onPick(shown[index - lead].value); + }; + + const onKeyDown = (e: React.KeyboardEvent) => { + if (isImeKey(e)) return; + if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { + e.preventDefault(); + // The arrows move inside the list, never the grid's selection. + e.stopPropagation(); + if (rowCount === 0) return; + const step = e.key === 'ArrowDown' ? 1 : -1; + setActive((i) => (i < 0 ? (step > 0 ? 0 : rowCount - 1) : (i + step + rowCount) % rowCount)); + } else if (e.key === 'Enter' && !e.shiftKey && active >= 0 && active < rowCount) { + e.preventDefault(); + e.stopPropagation(); + pickRow(active); + } + }; + + const activeId = active >= 0 && active < rowCount ? `${listId}-${active}` : undefined; + + return ( +
+ { + setQuery(e.target.value); + setActive(e.target.value.trim() ? 0 : initialActive); + }} + onKeyDown={onKeyDown} + className={cn( + 'h-8 w-full rounded-sm border border-input bg-background px-2 text-[13px] outline-none', + 'focus-visible:ring-1 focus-visible:ring-ring', + )} + /> +
    + {addText !== null ? ( +
  • e.preventDefault()} + onClick={() => pickRow(0)} + onPointerMove={() => setActive(0)} + className={cn( + 'flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1 text-[13px]', + active === 0 && 'bg-accent text-accent-foreground', + )} + > +
  • + ) : null} + {shown.map((o, at) => { + const i = at + lead; + const isSelected = selected.includes(o.value); + return ( +
  • e.preventDefault()} + onClick={() => { + setActive(i); + pickRow(i); + }} + onPointerMove={() => setActive(i)} + className={cn( + 'flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1 text-[13px]', + i === active && 'bg-accent text-accent-foreground', + )} + > +
  • + ); + })} + {rowCount === 0 ? ( +
  • + {t('fields.options.noMatches')} +
  • + ) : null} +
+
+ ); +} diff --git a/ui/packages/fields/src/widgets/MultiSelectField.tsx b/ui/packages/fields/src/widgets/MultiSelectField.tsx index 40ccbaf232c..14c75cf4ba2 100644 --- a/ui/packages/fields/src/widgets/MultiSelectField.tsx +++ b/ui/packages/fields/src/widgets/MultiSelectField.tsx @@ -6,6 +6,7 @@ import { toDomProps } from './toDomProps.js'; import { toHostGroupProps } from './toHostGroupProps.js'; import { OptionsEmptyState } from './OptionsEmptyState.js'; import { useCascadingOptions } from './useCascadingOptions.js'; +import { InCellOptionList } from './InCellOptionList.js'; interface Option extends OptionLike { color?: string } @@ -34,6 +35,8 @@ export function MultiSelectField({ emptyHint, dataSource: _dataSource, error, + inCell, + onCommit: _onCommit, ...props }: FieldWidgetComponentProps) { const config = field as any; @@ -141,6 +144,22 @@ export function MultiSelectField({ onChange(next); }; + // The grid's cell editor (objectstack#35688): a searchable check list; each + // pick toggles and stages, and the grid commits when the user moves on. + if (inCell && !props.disabled) { + const domProps = toDomProps(props); + return ( + ({ value: String(o.value), label: optionDisplayLabel(o) }))} + selected={selected} + multiple + onPick={toggle} + testId={fieldName ? `multiselect-in-cell-${fieldName}` : undefined} + inputProps={{ id: domProps.id, 'aria-describedby': domProps['aria-describedby'], 'aria-invalid': !!error }} + /> + ); + } + // DOM pass-through (objectui#3318): the container carries the form // renderer's id / aria-describedby, but NOT its `aria-invalid` — a plain // wrapper div is not where assistive tech reads the invalid state. That diff --git a/ui/packages/fields/src/widgets/SelectField.tsx b/ui/packages/fields/src/widgets/SelectField.tsx index cc05a8475e5..f08afe60b8b 100644 --- a/ui/packages/fields/src/widgets/SelectField.tsx +++ b/ui/packages/fields/src/widgets/SelectField.tsx @@ -18,6 +18,7 @@ import { MultiSelectField } from './MultiSelectField.js'; import { OptionsEmptyState } from './OptionsEmptyState.js'; import { toHostControlProps } from './toHostGroupProps.js'; import { useCascadingOptions } from './useCascadingOptions.js'; +import { InCellOptionList } from './InCellOptionList.js'; /** * SelectField - dropdown selection widget. @@ -87,6 +88,8 @@ function SingleSelectField({ dependsOn: dependsOnProp, emptyHint, dataSource: _dataSource, + inCell, + onCommit: _onCommit, ...props }: FieldWidgetComponentProps) { const config = field as SelectFieldMetadata; @@ -185,6 +188,22 @@ function SingleSelectField({ // the trigger as well would give the state a second, OR-merged author. const { name: domName, disabled: _domDisabled, ...triggerDomProps } = toDomProps(props); + // The grid's cell editor (objectstack#35688): the list is open from the + // start and filters as the user types; a pick goes to `onChange`, which the + // grid commits. + if (inCell && !props.disabled) { + return ( + ({ value: String(o.value), label: optionDisplayLabel(o) }))} + selected={value == null || (value as unknown) === '' ? [] : [String(value)]} + multiple={false} + onPick={(v) => onChange(v)} + testId={fieldName ? `select-in-cell-${fieldName}` : undefined} + inputProps={{ id: triggerDomProps.id, 'aria-describedby': triggerDomProps['aria-describedby'], 'aria-invalid': !!error }} + /> + ); + } + // `null` is how an empty value arrives — the cascade clear above emits it // (objectui#10291), and so does a record whose column is empty. Radix shows // the placeholder only for `''` / `undefined`, so a raw `null` paints a blank diff --git a/ui/packages/fields/src/widgets/TagsField.tsx b/ui/packages/fields/src/widgets/TagsField.tsx index 85b37c3e4bc..671ef8b41e6 100644 --- a/ui/packages/fields/src/widgets/TagsField.tsx +++ b/ui/packages/fields/src/widgets/TagsField.tsx @@ -4,17 +4,25 @@ import { FieldWidgetComponentProps } from './types.js'; import { toDomProps } from './toDomProps.js'; import { useFieldTranslation } from './useFieldTranslation.js'; import { isImeKey } from './imeKey.js'; +import { InCellOptionList } from './InCellOptionList.js'; /** * TagsField - free-form list of string tags. Type a value and press Enter (or * comma) to add it; click a tag's × to remove it. The stored value is a * string[]. Used for the `tags` field type. */ -export function TagsField({ value, onChange, field, readonly, className, error, ...props }: FieldWidgetComponentProps) { +export function TagsField({ value, onChange, field, readonly, className, error, inCell, onCommit: _onCommit, ...props }: FieldWidgetComponentProps) { const tags: string[] = Array.isArray(value) ? value : value == null ? [] : [value as unknown as string]; const [draft, setDraft] = React.useState(''); // Unconditional hook call (rules-of-hooks): before the readonly early return. const { t } = useFieldTranslation(); + // The in-cell list's rows (see the `inCell` branch): every tag the field has + // held since the editor opened, so an unchecked tag stays on offer. + // Adjusted while rendering, as React's "storing information from previous + // renders" does, rather than in an effect. + const [offered, setOffered] = React.useState(tags); + const unseen = tags.filter((v) => !offered.includes(v)); + if (unseen.length > 0) setOffered([...offered, ...unseen]); if (readonly) { if (tags.length === 0) return ; @@ -36,6 +44,24 @@ export function TagsField({ value, onChange, field, readonly, className, error, const domProps = toDomProps(props); + // The grid's cell editor (objectstack#35688): the field's tags as a + // searchable check list; unchecking removes a tag, and text that matches + // none is added from the list's "Add" row. Every change stages; the grid + // commits when the user moves on. + if (inCell && !props.disabled) { + return ( + ({ value: v, label: v }))} + selected={tags} + multiple + onPick={(v) => (tags.includes(v) ? removeTag(v) : onChange([...tags, v]))} + onAdd={addTag} + placeholder={field?.placeholder || t('fields.tags.placeholder')} + inputProps={{ id: domProps.id, 'aria-describedby': domProps['aria-describedby'], 'aria-invalid': !!error }} + /> + ); + } + /** * Commit the typed draft as a tag on blur — and then hand the event on to the * host (objectui#6802). diff --git a/ui/packages/fields/src/widgets/TimeField.tsx b/ui/packages/fields/src/widgets/TimeField.tsx index 923415f8025..1ec9bb06a14 100644 --- a/ui/packages/fields/src/widgets/TimeField.tsx +++ b/ui/packages/fields/src/widgets/TimeField.tsx @@ -8,7 +8,10 @@ import { openNativePicker } from './openNativePicker.js'; * TimeField - Time picker input widget * Uses native time input for hour and minute selection */ -export function TimeField({ value, onChange, field, readonly, error, ...props }: FieldWidgetComponentProps) { +export function TimeField({ value, onChange, field, readonly, error, inCell, onCommit: _onCommit, ...props }: FieldWidgetComponentProps) { + // The grid's cell editor shows the browser's time picker as soon as the + // control takes focus, once per editor (objectstack#35688). + const pickerShownRef = React.useRef(false); if (readonly) { return {value || }; } @@ -48,6 +51,13 @@ export function TimeField({ value, onChange, field, readonly, error, ...props }: openNativePicker(e.currentTarget); domProps.onClick?.(e); }} + onFocus={(e) => { + if (inCell && !pickerShownRef.current) { + pickerShownRef.current = true; + openNativePicker(e.currentTarget); + } + domProps.onFocus?.(e); + }} disabled={readonly || domProps.disabled} aria-invalid={!!error} /> diff --git a/ui/packages/fields/src/widgets/date-picker/DatePickerField.tsx b/ui/packages/fields/src/widgets/date-picker/DatePickerField.tsx index ac51fcdf5bf..e6233665d49 100644 --- a/ui/packages/fields/src/widgets/date-picker/DatePickerField.tsx +++ b/ui/packages/fields/src/widgets/date-picker/DatePickerField.tsx @@ -118,13 +118,17 @@ function TemporalPicker({ error, onInvalidInputChange, withTime, + inCell, + onCommit, ...props }: FieldWidgetComponentProps & { withTime: boolean }) { const locale = useDisplayLocale(); const { t } = useFieldTranslation(); const noticeId = React.useId(); - const [open, setOpen] = React.useState(false); + // The grid's cell editor opens with its calendar showing (objectstack#35688). + const [open, setOpen] = React.useState(!!inCell && !readonly); const hourRef = React.useRef(null); + const rootRef = React.useRef(null); // The value in the native control's shape: `YYYY-MM-DD`, or the local wall // clock `YYYY-MM-DDTHH:mm`. `''` for an empty value and for a stored day that @@ -203,6 +207,8 @@ function TemporalPicker({ if (!withTime) { write(toLocalDay(day)); setOpen(false); + // In a grid cell the pick is the whole edit: the grid commits it. + onCommit?.(); return; } const time = nativeValue.slice(11, 16) || '00:00'; @@ -220,6 +226,13 @@ function TemporalPicker({ write(`${day}T${nextHour}:${nextMinute}`); }; + /** The in-cell face's clear pick: empties the value and ends the edit. */ + const clearAndCommit = () => { + write(''); + setOpen(false); + onCommit?.(); + }; + const shortcut = (offsetDays: number) => { const day = new Date(); day.setHours(0, 0, 0, 0); @@ -239,7 +252,7 @@ function TemporalPicker({ : domProps['aria-describedby']; return ( -
+
- + e.preventDefault() : undefined} + onInteractOutside={inCell + ? (e) => { + if (rootRef.current?.contains(e.target as Node)) e.preventDefault(); + } + : undefined} + > {/* Opens on the value's month, and on today's with no value. */} {/* Below `sm` each day and month arrow is a 44 px cell: seven fit a 375 px screen. */} {withTime ? ( @@ -362,6 +386,17 @@ function TemporalPicker({ + {inCell ? ( + <> + {/* Seven days from today (ruling of record 7057128455). */} + + + + ) : null}
diff --git a/ui/packages/fields/src/widgets/toHostProps.ts b/ui/packages/fields/src/widgets/toHostProps.ts index 84bc03f3124..a2daa3aa8ff 100644 --- a/ui/packages/fields/src/widgets/toHostProps.ts +++ b/ui/packages/fields/src/widgets/toHostProps.ts @@ -124,6 +124,9 @@ const HOST_PLUMBING_KEYS = [ 'onAutofill', 'openingValue', 'onCreateNew', + // objectstack#35688 — the grid cell editor's face and its commit. + 'inCell', + 'onCommit', ] as const; type HostPlumbingKey = (typeof HOST_PLUMBING_KEYS)[number]; diff --git a/ui/packages/fields/src/widgets/types.ts b/ui/packages/fields/src/widgets/types.ts index e242d202375..c10d47e31d9 100644 --- a/ui/packages/fields/src/widgets/types.ts +++ b/ui/packages/fields/src/widgets/types.ts @@ -241,6 +241,32 @@ export type FieldWidgetComponentProps = { * editor and the line-item grid set it) instead of the full form layout. */ compact?: boolean; + /** + * Draw the face for the list grid's cell editor, the layer over one cell + * (objectstack#35688): the control opens at once, sized to the cell's row. + * A single select shows its searchable option list and picks on a click or + * Enter; a multi-select or tags field a searchable check list; a date opens + * its calendar with the today / tomorrow / next week / clear picks; a colour + * its swatches. Without it every widget draws its form face, unchanged. + * + * **Producer**: `ObjectGrid`'s `renderCellEditor`, through `FieldEditWidget`. + * **Consumer**: the option, tags, date, time and colour widgets. + */ + inCell?: boolean; + /** + * The user has finished: the host writes the value last handed to + * `onChange` and closes the editor. A widget calls it after the gesture + * that ends a choice, and never instead of `onChange`. + * + * **Producer**: `ObjectGrid`'s `renderCellEditor` (the grid's commit). + * **Consumer**: the `date` picker calls it on a calendar day or a quick + * pick (Today, Tomorrow; the `inCell` face adds Next week and Clear), + * whether or not `inCell` is set; the `datetime` picker only on the in-cell + * Clear; the colour widget on a swatch of its `inCell` face. A host + * that passes nothing keeps the editor open until it commits on its own + * terms (Enter, a click elsewhere). + */ + onCommit?: () => void; /** * Receive the FULL selected record rather than just its id, so a host can * auto-fill sibling fields from it (a line-item grid copying a product's diff --git a/ui/packages/fields/src/widgets/useFieldTranslation.ts b/ui/packages/fields/src/widgets/useFieldTranslation.ts index 373784d9ffe..237a63e572e 100644 --- a/ui/packages/fields/src/widgets/useFieldTranslation.ts +++ b/ui/packages/fields/src/widgets/useFieldTranslation.ts @@ -73,6 +73,9 @@ const FIELD_DEFAULTS: Record = { // renderer so both cannot drift apart in a locale. 'fields.options.empty': 'No options available', 'fields.options.selectFirst': 'Select {{fields}} first', + // objectstack#35688 — the grid cell editor's option list. + 'fields.options.search': 'Search…', + 'fields.options.noMatches': 'No matching options', // objectui#12145 — three widgets' accessible names: the crop dialog's // preview canvas, the percent slider, and the record picker's grid. The // grid borrows the command palette's `Records` key rather than adding a @@ -247,6 +250,9 @@ const FIELD_DEFAULTS: Record = { // values as the `en` pack. 'fields.datePicker.today': 'Today', 'fields.datePicker.tomorrow': 'Tomorrow', + // objectstack#35688 — the grid cell editor's two extra date picks. + 'fields.datePicker.nextWeek': 'Next week', + 'fields.datePicker.clearPick': 'Clear', 'fields.datePicker.clear': 'Clear date', 'fields.datePicker.openCalendar': 'Open calendar', 'fields.datePicker.invalid': @@ -254,6 +260,10 @@ const FIELD_DEFAULTS: Record = { // objectui#3342 — the tags widget's input hint. Used only when the field // author declared no `placeholder` of their own (author declaration wins). 'fields.tags.placeholder': 'Type and press Enter to add…', + // objectstack#35688 — the grid cell editor's tag list and colour swatches. + 'fields.tags.add': 'Add "{{value}}"', + 'fields.color.swatches': 'Colors', + 'fields.color.custom': 'Custom color', // objectui#4028 — `AddressField`'s five sub-labels. The parts of an address // are NOT fields on the object (`billing_address` is one column), so no // translation bundle could ever key them and an app had no workaround short diff --git a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts index 5609f491290..c65cf7663e9 100644 --- a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts +++ b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts @@ -449,7 +449,10 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // `approvalsInbox.slaCalendarNotFound`, the inbox naming the calendar an // escalation deadline cannot be counted on („{{calendar}}“) — one // interpolated span, runtime data. - expect(okSpans, 'correctly paired spans').toBe(119); + // 120 once objectstack-ai/objectstack#35688 added `fields.tags.add`, the + // grid cell editor's row adding the typed tag („{{value}}“) — one + // interpolated span, user input. + expect(okSpans, 'correctly paired spans').toBe(120); }); it('keeps the count identity that replaces the card’s count(„) === count(“)', () => { @@ -564,8 +567,10 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // after objectstack-ai/objectstack#34740 retired // `empty.objectNotFoundDescription`, one matched pair fewer. 119 / 119 / 0 // after objectstack-ai/objectstack#35357 added - // `approvalsInbox.slaCalendarNotFound`, one more matched pair. - expect({ open, close, rdq }).toEqual({ open: 119, close: 119, rdq: 0 }); + // `approvalsInbox.slaCalendarNotFound`, one more matched pair. 120 / 120 / 0 + // after objectstack-ai/objectstack#35688 added `fields.tags.add`, one more + // matched pair. + expect({ open, close, rdq }).toEqual({ open: 120, close: 120, rdq: 0 }); // The durable shape: every „ closed by a “, every surplus “ an English // opener answered by a ”. Survived translating the two English values. expect(close).toBe(open + rdq); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 70af4a16288..074312089e0 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -346,6 +346,8 @@ const ar = { options: { empty: "لا توجد خيارات متاحة", selectFirst: "اختر {{fields}} أولاً", + search: "بحث…", + noMatches: "لا توجد خيارات مطابقة", }, objectRef: { loading: "جارٍ تحميل الكائنات…", @@ -430,6 +432,8 @@ const ar = { datePicker: { today: "اليوم", tomorrow: "غدًا", + nextWeek: "الأسبوع القادم", + clearPick: "مسح", clear: "مسح التاريخ", openCalendar: "فتح التقويم", time: "الوقت", @@ -444,6 +448,11 @@ const ar = { }, tags: { placeholder: "اكتب واضغط Enter للإضافة…", + add: "إضافة «{{value}}»", + }, + color: { + swatches: "الألوان", + custom: "لون مخصص", }, // objectui#4028 — `AddressField`'s five sub-labels. address: { diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 7e99247e5ca..635889ef9a3 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -328,6 +328,8 @@ const de = { options: { empty: "Keine Optionen verfügbar", selectFirst: "Zuerst {{fields}} auswählen", + search: "Suchen…", + noMatches: "Keine passenden Optionen", }, objectRef: { loading: "Objekte werden geladen…", @@ -412,6 +414,8 @@ const de = { datePicker: { today: "Heute", tomorrow: "Morgen", + nextWeek: "Nächste Woche", + clearPick: "Leeren", clear: "Datum löschen", openCalendar: "Kalender öffnen", time: "Uhrzeit", @@ -426,6 +430,11 @@ const de = { }, tags: { placeholder: "Tippen und mit der Eingabetaste hinzufügen…", + add: "„{{value}}“ hinzufügen", + }, + color: { + swatches: "Farben", + custom: "Eigene Farbe", }, // objectui#4028 — `AddressField`'s five sub-labels. address: { diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 13266e90f2a..f1f9b85adbb 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -499,6 +499,8 @@ const en = { options: { empty: 'No options available', selectFirst: 'Select {{fields}} first', + search: 'Search…', + noMatches: 'No matching options', }, objectRef: { loading: 'Loading objects…', @@ -643,6 +645,8 @@ const en = { datePicker: { today: 'Today', tomorrow: 'Tomorrow', + nextWeek: 'Next week', + clearPick: 'Clear', clear: 'Clear date', openCalendar: 'Open calendar', time: 'Time', @@ -659,6 +663,11 @@ const en = { // is empty. The author-declared `field.placeholder` always wins over this. tags: { placeholder: 'Type and press Enter to add…', + add: 'Add "{{value}}"', + }, + color: { + swatches: 'Colors', + custom: 'Custom color', }, // objectui#4028 — `AddressField`'s five sub-labels, previously English // string literals with no key at all: on a Chinese console every address diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index f06b1b1529d..53cb01a2a4f 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -336,6 +336,8 @@ const es = { options: { empty: "No hay opciones disponibles", selectFirst: "Seleccione primero {{fields}}", + search: "Buscar…", + noMatches: "No hay opciones coincidentes", }, objectRef: { loading: "Cargando objetos…", @@ -420,6 +422,8 @@ const es = { datePicker: { today: "Hoy", tomorrow: "Mañana", + nextWeek: "Próxima semana", + clearPick: "Borrar", clear: "Borrar fecha", openCalendar: "Abrir calendario", time: "Hora", @@ -434,6 +438,11 @@ const es = { }, tags: { placeholder: "Escriba y pulse Intro para añadir…", + add: "Añadir «{{value}}»", + }, + color: { + swatches: "Colores", + custom: "Color personalizado", }, // objectui#4028 — `AddressField`'s five sub-labels. address: { diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 749a7bfda0e..999bc6a3826 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -331,6 +331,8 @@ const fr = { options: { empty: "Aucune option disponible", selectFirst: "Sélectionnez d’abord {{fields}}", + search: "Rechercher…", + noMatches: "Aucune option correspondante", }, objectRef: { loading: "Chargement des objets…", @@ -415,6 +417,8 @@ const fr = { datePicker: { today: "Aujourd’hui", tomorrow: "Demain", + nextWeek: "Semaine prochaine", + clearPick: "Effacer", clear: "Effacer la date", openCalendar: "Ouvrir le calendrier", time: "Heure", @@ -429,6 +433,11 @@ const fr = { }, tags: { placeholder: "Saisissez puis appuyez sur Entrée pour ajouter…", + add: "Ajouter « {{value}} »", + }, + color: { + swatches: "Couleurs", + custom: "Couleur personnalisée", }, // objectui#4028 — `AddressField`'s five sub-labels. address: { diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 9ff01af1738..342d82cd761 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -328,6 +328,8 @@ const ja = { options: { empty: "選択できる項目がありません", selectFirst: "まず {{fields}} を選択してください", + search: "検索…", + noMatches: "一致する項目がありません", }, objectRef: { loading: "オブジェクトを読み込み中…", @@ -412,6 +414,8 @@ const ja = { datePicker: { today: "今日", tomorrow: "明日", + nextWeek: "来週", + clearPick: "クリア", clear: "日付をクリア", openCalendar: "カレンダーを開く", time: "時刻", @@ -426,6 +430,11 @@ const ja = { }, tags: { placeholder: "入力してEnterキーで追加…", + add: "「{{value}}」を追加", + }, + color: { + swatches: "色", + custom: "カスタムカラー", }, // objectui#4028 — `AddressField`'s five sub-labels. address: { diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 7136511d607..3c8814d4470 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -328,6 +328,8 @@ const ko = { options: { empty: "선택할 수 있는 옵션이 없습니다", selectFirst: "먼저 {{fields}}을(를) 선택하세요", + search: "검색…", + noMatches: "일치하는 옵션이 없습니다", }, objectRef: { loading: "객체를 불러오는 중…", @@ -412,6 +414,8 @@ const ko = { datePicker: { today: "오늘", tomorrow: "내일", + nextWeek: "다음 주", + clearPick: "지우기", clear: "날짜 지우기", openCalendar: "달력 열기", time: "시간", @@ -426,6 +430,11 @@ const ko = { }, tags: { placeholder: "입력 후 Enter 키로 추가…", + add: "“{{value}}” 추가", + }, + color: { + swatches: "색상", + custom: "사용자 지정 색상", }, // objectui#4028 — `AddressField`'s five sub-labels. address: { diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 0d1c9c34747..10373294265 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -331,6 +331,8 @@ const pt = { options: { empty: "Nenhuma opção disponível", selectFirst: "Selecione primeiro {{fields}}", + search: "Pesquisar…", + noMatches: "Nenhuma opção correspondente", }, objectRef: { loading: "Carregando objetos…", @@ -415,6 +417,8 @@ const pt = { datePicker: { today: "Hoje", tomorrow: "Amanhã", + nextWeek: "Próxima semana", + clearPick: "Limpar", clear: "Limpar data", openCalendar: "Abrir calendário", time: "Horário", @@ -429,6 +433,11 @@ const pt = { }, tags: { placeholder: "Digite e pressione Enter para adicionar…", + add: "Adicionar “{{value}}”", + }, + color: { + swatches: "Cores", + custom: "Cor personalizada", }, // objectui#4028 — `AddressField`'s five sub-labels. address: { diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index ef52983f948..c49baaec9de 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -337,6 +337,8 @@ const ru = { options: { empty: "Нет доступных вариантов", selectFirst: "Сначала выберите {{fields}}", + search: "Поиск…", + noMatches: "Нет подходящих вариантов", }, objectRef: { loading: "Загрузка объектов…", @@ -421,6 +423,8 @@ const ru = { datePicker: { today: "Сегодня", tomorrow: "Завтра", + nextWeek: "Через неделю", + clearPick: "Очистить", clear: "Очистить дату", openCalendar: "Открыть календарь", time: "Время", @@ -435,6 +439,11 @@ const ru = { }, tags: { placeholder: "Введите и нажмите Enter, чтобы добавить…", + add: "Добавить «{{value}}»", + }, + color: { + swatches: "Цвета", + custom: "Свой цвет", }, // objectui#4028 — `AddressField`'s five sub-labels. address: { diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 7288c069e0d..f97845114f7 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -338,6 +338,8 @@ const zh = { options: { empty: '暂无可选项', selectFirst: '请先选择{{fields}}', + search: '搜索…', + noMatches: '没有匹配的选项', }, objectRef: { loading: '正在加载对象…', @@ -422,6 +424,8 @@ const zh = { datePicker: { today: '今天', tomorrow: '明天', + nextWeek: '下周', + clearPick: '清空', clear: '清除日期', openCalendar: '打开日历', time: '时间', @@ -436,6 +440,11 @@ const zh = { }, tags: { placeholder: '输入后回车添加…', + add: '添加“{{value}}”', + }, + color: { + swatches: '颜色', + custom: '自定义颜色', }, // objectui#4028 — `AddressField`'s five sub-labels. These were English // string literals with no key, and this pack is the one the issue was diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 33893d18585..d70169cc26e 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -338,6 +338,8 @@ const zhHant = { options: { empty: '暫無可選項', selectFirst: '請先選擇{{fields}}', + search: '搜尋…', + noMatches: '沒有匹配的選項', }, objectRef: { loading: '正在載入物件…', @@ -422,6 +424,8 @@ const zhHant = { datePicker: { today: '今天', tomorrow: '明天', + nextWeek: '下週', + clearPick: '清空', clear: '清除日期', openCalendar: '開啟日曆', time: '時間', @@ -436,6 +440,11 @@ const zhHant = { }, tags: { placeholder: '輸入後回車新增…', + add: '新增“{{value}}”', + }, + color: { + swatches: '顏色', + custom: '自定義顏色', }, // objectui#4028 — `AddressField`'s five sub-labels. These were English // string literals with no key, and this pack is the one the issue was diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 7bd85d57cfa..641bb18da86 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -781,6 +781,8 @@ function cellEditorWidthClass(type: string): string { case 'tags': case 'checkboxes': return 'w-full min-w-64'; + case 'select': + case 'status': case 'date': case 'datetime': case 'phone': @@ -3410,7 +3412,10 @@ export const ObjectGrid: React.FC = ({ ? (ctx: { column: any; row: any; pendingRow: any; value: any; stage: (v: any) => void; commit: (v?: any) => void }) => { const fieldDef = (objectSchema as any)?.fields?.[ctx.column?.accessorKey]; if (!fieldDef || !hasFieldEditWidget(fieldDef.type)) return null; - const discrete = DISCRETE_EDIT_TYPES.has(fieldDef.type); + // objectstack#35688 — a `select` declared `multiple` draws the multi-select + // check list (`SelectField` hands it to `MultiSelectField`): each check + // stages, and the edit is saved when the user moves on. + const discrete = DISCRETE_EDIT_TYPES.has(fieldDef.type) && !fieldDef.multiple; let field: any = { name: ctx.column.accessorKey, ...fieldDef }; // State-machine-aware: a field bound to a `state_machine` validation // only offers transitions valid from the current value, so the editor @@ -3460,6 +3465,10 @@ export const ObjectGrid: React.FC = ({ // saved-row scoping rather than to `{}` — gated forever — and it // is the spelling objectui#7188's ruling chose. dependentValues={ctx.pendingRow ?? ctx.row} + // objectstack#35688 — the cell editor's face: pickers open at once, + // and a calendar day or a swatch ends the edit. + inCell + onCommit={() => ctx.commit()} />
); diff --git a/ui/packages/plugin-grid/src/__tests__/inCellSelectMultipleRouting-35688.test.tsx b/ui/packages/plugin-grid/src/__tests__/inCellSelectMultipleRouting-35688.test.tsx new file mode 100644 index 00000000000..8a5d6f22f59 --- /dev/null +++ b/ui/packages/plugin-grid/src/__tests__/inCellSelectMultipleRouting-35688.test.tsx @@ -0,0 +1,167 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35688 (S2), measured through the real `ObjectGrid` → `data-table` + * path with the real `@object-ui/fields` editors: a `select` declared + * `multiple` draws the check list in the cell editor, and each check only + * stages. The edit is saved when the user moves on, as for `multiselect`. + * A single `select` still saves on the pick (CONTROL). + */ +import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; +import { render, screen, waitFor, fireEvent, cleanup } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; + +import { ObjectGrid } from '../ObjectGrid'; +import { __clearRecordCrudVerdictCache } from '../hooks/useRecordCrudVerdicts'; +import { installExplainDouble } from './explainDouble'; +import { registerAllFields } from '@object-ui/fields'; +import { ActionProvider, SchemaRendererProvider } from '@object-ui/react'; + +registerAllFields(); + +beforeAll(() => { + if (!Element.prototype.scrollIntoView) { + Element.prototype.scrollIntoView = vi.fn() as any; + } + if (!(Element.prototype as any).hasPointerCapture) { + (Element.prototype as any).hasPointerCapture = () => false; + } + if (!(Element.prototype as any).setPointerCapture) { + (Element.prototype as any).setPointerCapture = () => {}; + } + if (!(Element.prototype as any).releasePointerCapture) { + (Element.prototype as any).releasePointerCapture = () => {}; + } +}); + +beforeEach(() => { + __clearRecordCrudVerdictCache(); + installExplainDouble(); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +const OBJECT = 'task_35688_s2'; +const COLORS = [ + { label: 'Red', value: 'red' }, + { label: 'Green', value: 'green' }, + { label: 'Blue', value: 'blue' }, +]; + +function makeDataSource() { + const store: Record = { + r1: { id: 'r1', title: 'Design system', priority: 'high', colors: ['blue'] }, + }; + return { + find: vi.fn(async () => { + const data = Object.values(store).map((r) => ({ ...r })); + return { data, total: data.length, hasMore: false, pageSize: 50 }; + }), + findOne: vi.fn(async (_o: string, id: string) => ({ ...store[id] })), + update: vi.fn(async (_o: string, id: string, changes: Record) => { + store[id] = { ...store[id], ...changes }; + return { ...store[id] }; + }), + getObjectSchema: async (name: string) => ({ + name, + fields: { + id: { type: 'text' }, + title: { type: 'text', label: 'Title' }, + priority: { + type: 'select', + label: 'Priority', + options: [ + { label: 'Low', value: 'low' }, + { label: 'High', value: 'high' }, + ], + }, + colors: { type: 'select', multiple: true, label: 'Colors', options: COLORS }, + }, + }), + } as any; +} + +function renderGrid() { + const ds = makeDataSource(); + const schema: any = { + type: 'object-grid', + objectName: OBJECT, + editable: true, + singleClickEdit: true, + columns: [ + { field: 'title', label: 'Title', type: 'text' }, + { field: 'priority', label: 'Priority', type: 'select' }, + { field: 'colors', label: 'Colors', type: 'select' }, + ], + pagination: { pageSize: 50 }, + }; + const utils = render( + + +
+ + +
+
+
, + ); + return { ...utils, ds }; +} + +/** The body cell under the header named `label`. */ +function cellUnder(container: HTMLElement, label: string): HTMLElement { + const headers = Array.from(container.querySelectorAll('thead th')); + const at = headers.findIndex((th) => th.textContent?.trim().startsWith(label)); + expect(at).toBeGreaterThanOrEqual(0); + return container.querySelectorAll('tbody tr')[0].querySelectorAll('td')[at] as HTMLElement; +} + +// The grid batches edits (no `cellSelection`, so no per-cell autosave): what a +// pick wrote shows as the row's pending change, and nothing reaches `update`. +describe('ObjectGrid cell editor: a select declared multiple (objectstack#35688 S2)', () => { + it('each check stages and the editor stays open; moving on closes it with every check', async () => { + const { container } = renderGrid(); + await waitFor(() => expect(screen.getByText('Design system')).toBeInTheDocument()); + + fireEvent.click(cellUnder(container, 'Colors')); + await waitFor(() => expect(screen.getByTestId('in-cell-option-red')).toBeInTheDocument()); + + fireEvent.click(screen.getByTestId('in-cell-option-red')); + // Still open after the first check, with the check on. + expect(screen.getByTestId('in-cell-option-green')).toBeInTheDocument(); + expect(screen.getByTestId('in-cell-option-red')).toHaveAttribute('aria-selected', 'true'); + fireEvent.click(screen.getByTestId('in-cell-option-green')); + expect(screen.getByTestId('in-cell-option-green')).toHaveAttribute('aria-selected', 'true'); + + fireEvent.pointerDown(screen.getByTestId('outside')); + await waitFor(() => expect(screen.queryByTestId('in-cell-option-red')).toBeNull()); + // This grid batches its edits: the row carries the three colours, pending. + await waitFor(() => expect(screen.getByText(/1 row modified/)).toBeInTheDocument()); + const cell = cellUnder(container, 'Colors'); + for (const label of ['Blue', 'Red', 'Green']) expect(cell.textContent).toContain(label); + expect(screen.queryByTestId('in-cell-option-red')).toBeNull(); + }); + + it('CONTROL: a single select saves on the pick and closes', async () => { + const { container } = renderGrid(); + await waitFor(() => expect(screen.getByText('Design system')).toBeInTheDocument()); + + fireEvent.click(cellUnder(container, 'Priority')); + await waitFor(() => expect(screen.getByTestId('in-cell-option-low')).toBeInTheDocument()); + fireEvent.click(screen.getByTestId('in-cell-option-low')); + + // The pick closes the editor, and the click that made it does not open it again. + await waitFor(() => expect(screen.queryByTestId('in-cell-option-low')).toBeNull()); + await waitFor(() => expect(screen.getByText(/1 row modified/)).toBeInTheDocument()); + expect(cellUnder(container, 'Priority').textContent).toContain('Low'); + }); +});