Skip to content

Commit b222d52

Browse files
committed
fix(fields,plugin-grid): a select declared multiple stages each check in the grid; the list's start row survives a cleared search
- ObjectGrid routes a select declared multiple as a staging editor, as multiselect: each check stages and the edit is saved when the user moves on. - data-table: a click inside the open editor no longer starts the edit again in a single-click-edit grid (a pick that had just committed reopened it). - InCellOptionList: the starting active row is an index into the full list, so clearing the search box lands on the current value again. - ColorField: swatch colour through a custom property and a static utility. - Docs: onCommit's consumers stated exactly; tags list this record's tags. Claude-Session: https://claude.ai/code/session_01L6bhgX2KGAUnpHKYJjea4U Co-authored-by: Claude <noreply@anthropic.com>
1 parent f1d3e1b commit b222d52

9 files changed

Lines changed: 215 additions & 13 deletions

File tree

‎.changeset/35688-in-cell-pickers.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,11 @@ In the cell editor of every grid `ObjectGrid` draws:
1616

1717
- **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.
1818
- **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.
19-
- **Tags** list the field's tags with check marks; unchecking removes one, and text that matches no tag is added from the list's leading "Add" row (Enter).
19+
- **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).
2020
- **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.
2121
- **Time** opens the browser's time picker when the editor opens.
2222
- **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.
23-
- A value picked this way hands the keyboard focus back to the selected cell.
23+
- 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.
2424

2525
`@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`.
2626

‎ui/packages/components/src/renderers/complex/data-table.tsx‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4981,6 +4981,16 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
49814981
if (wasSelected && togglesCell(row, col)) toggleCell(rowIndex, colIndex);
49824982
return;
49834983
}
4984+
// objectstack#35688 — a click inside the open editor (an
4985+
// option of the in-cell list, still in the DOM when its click
4986+
// lands) is the editor's own. When that pick has just
4987+
// committed, `startEdit`'s same-cell guard has already been
4988+
// cleared, so the click would open the editor again; this
4989+
// render still says the cell is editing, so stop here.
4990+
if (isEditing) {
4991+
e.stopPropagation();
4992+
return;
4993+
}
49844994
if (isEditable && singleClickEdit && !hasTextSelectionIn(e.currentTarget)) {
49854995
e.stopPropagation();
49864996
startEdit(row, col.accessorKey);

‎ui/packages/fields/README.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -127,11 +127,13 @@ param support ⊇ form support.
127127

128128
`FieldEditWidget` forwards two optional host keys of `FieldWidgetComponentProps`
129129
to the widget it draws. `inCell` asks for the face a list grid's cell editor
130-
needs: a single select, multi-select or tags field draws a searchable list that
131-
is open from the start, a date opens its calendar (with today, tomorrow, next
130+
needs: a single select or multi-select field draws a searchable list of its
131+
options that is open from the start, a tags field the same list of this
132+
record's tags (plus an "Add" row for new text), a date opens its calendar (with today, tomorrow, next
132133
week and clear picks) while its text stays typeable, a time opens the browser
133134
picker, and a colour offers swatches. `onCommit` is the host's "write the last
134-
`onChange` value and close", which the date and colour faces call after a pick.
135+
`onChange` value and close", which the date picker calls after a day or a quick
136+
pick and the in-cell colour face after a swatch.
135137
A host that passes neither gets the form faces unchanged; `ObjectGrid` passes
136138
both.
137139

‎ui/packages/fields/src/__tests__/inCellFaces-35688.test.tsx‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,20 @@ describe('in-cell single select (objectstack#35688)', () => {
9696
expect(onGridKey).toHaveBeenCalledWith('Escape');
9797
});
9898

99+
it('clearing the search puts the active row back on the current value, not on its filtered index', () => {
100+
const onChange = vi.fn();
101+
render(<SelectField field={SELECT} value="lost" onChange={onChange} inCell />);
102+
const box = screen.getByRole('combobox');
103+
const current = screen.getByTestId('in-cell-option-lost');
104+
expect(box.getAttribute('aria-activedescendant')).toBe(current.id);
105+
// "lost" is row 1 of the filtered list and row 3 of the full one.
106+
fireEvent.change(box, { target: { value: 'closed' } });
107+
fireEvent.change(box, { target: { value: '' } });
108+
expect(box.getAttribute('aria-activedescendant')).toBe(screen.getByTestId('in-cell-option-lost').id);
109+
fireEvent.keyDown(box, { key: 'Enter' });
110+
expect(onChange).toHaveBeenCalledWith('lost');
111+
});
112+
99113
it('with nothing active, Enter goes on to the grid (it commits and moves)', () => {
100114
const onChange = vi.fn();
101115
const onGridKey = vi.fn();

‎ui/packages/fields/src/widgets/ColorField.tsx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,10 +63,12 @@ export function ColorField({ value, onChange, field, readonly, error, inCell, on
6363
onCommit?.();
6464
}}
6565
className={cn(
66-
'h-4 w-4 rounded-sm border border-input',
66+
'h-4 w-4 rounded-sm border border-input bg-(--swatch)',
6767
current === hex && 'ring-2 ring-ring ring-offset-1 ring-offset-background',
6868
)}
69-
style={{ backgroundColor: hex }}
69+
// The swatch's colour is the value it writes, carried as a custom
70+
// property read by a static utility (ui/AGENTS.md, Styling).
71+
style={{ '--swatch': hex } as React.CSSProperties}
7072
/>
7173
))}
7274
<input

‎ui/packages/fields/src/widgets/InCellOptionList.tsx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,10 @@ export function InCellOptionList({
5959
const rowCount = lead + shown.length;
6060

6161
// The active row starts on the current value (a single select) and on the
62-
// first row once the user types; -1 is "none".
63-
const initialActive = multiple ? -1 : shown.findIndex((o) => selected.includes(o.value));
62+
// first row once the user types; -1 is "none". It is an index into the FULL
63+
// list, which is the list shown again when the search box is cleared (an
64+
// index into the filtered list would land on another option then).
65+
const initialActive = multiple ? -1 : options.findIndex((o) => selected.includes(o.value));
6466
const [active, setActive] = React.useState(initialActive);
6567
const listRef = React.useRef<HTMLUListElement | null>(null);
6668

‎ui/packages/fields/src/widgets/types.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -256,11 +256,13 @@ export type FieldWidgetComponentProps<T = any> = {
256256
/**
257257
* The user has finished: the host writes the value last handed to
258258
* `onChange` and closes the editor. A widget calls it after the gesture
259-
* that ends a choice (a day or a quick pick in the calendar, a swatch), and
260-
* never instead of `onChange`.
259+
* that ends a choice, and never instead of `onChange`.
261260
*
262261
* **Producer**: `ObjectGrid`'s `renderCellEditor` (the grid's commit).
263-
* **Consumer**: the `inCell` faces of the date and colour widgets. A host
262+
* **Consumer**: the `date` picker calls it on a calendar day or a quick
263+
* pick (Today, Tomorrow; the `inCell` face adds Next week and Clear),
264+
* whether or not `inCell` is set; the `datetime` picker only on the in-cell
265+
* Clear; the colour widget on a swatch of its `inCell` face. A host
264266
* that passes nothing keeps the editor open until it commits on its own
265267
* terms (Enter, a click elsewhere).
266268
*/

‎ui/packages/plugin-grid/src/ObjectGrid.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3412,7 +3412,10 @@ export const ObjectGrid: React.FC<ObjectGridComponentProps> = ({
34123412
? (ctx: { column: any; row: any; pendingRow: any; value: any; stage: (v: any) => void; commit: (v?: any) => void }) => {
34133413
const fieldDef = (objectSchema as any)?.fields?.[ctx.column?.accessorKey];
34143414
if (!fieldDef || !hasFieldEditWidget(fieldDef.type)) return null;
3415-
const discrete = DISCRETE_EDIT_TYPES.has(fieldDef.type);
3415+
// objectstack#35688 — a `select` declared `multiple` draws the multi-select
3416+
// check list (`SelectField` hands it to `MultiSelectField`): each check
3417+
// stages, and the edit is saved when the user moves on.
3418+
const discrete = DISCRETE_EDIT_TYPES.has(fieldDef.type) && !fieldDef.multiple;
34163419
let field: any = { name: ctx.column.accessorKey, ...fieldDef };
34173420
// State-machine-aware: a field bound to a `state_machine` validation
34183421
// only offers transitions valid from the current value, so the editor
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* objectstack#35688 (S2), measured through the real `ObjectGrid` → `data-table`
11+
* path with the real `@object-ui/fields` editors: a `select` declared
12+
* `multiple` draws the check list in the cell editor, and each check only
13+
* stages. The edit is saved when the user moves on, as for `multiselect`.
14+
* A single `select` still saves on the pick (CONTROL).
15+
*/
16+
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest';
17+
import { render, screen, waitFor, fireEvent, cleanup } from '@testing-library/react';
18+
import '@testing-library/jest-dom';
19+
import React from 'react';
20+
21+
import { ObjectGrid } from '../ObjectGrid';
22+
import { __clearRecordCrudVerdictCache } from '../hooks/useRecordCrudVerdicts';
23+
import { installExplainDouble } from './explainDouble';
24+
import { registerAllFields } from '@object-ui/fields';
25+
import { ActionProvider, SchemaRendererProvider } from '@object-ui/react';
26+
27+
registerAllFields();
28+
29+
beforeAll(() => {
30+
if (!Element.prototype.scrollIntoView) {
31+
Element.prototype.scrollIntoView = vi.fn() as any;
32+
}
33+
if (!(Element.prototype as any).hasPointerCapture) {
34+
(Element.prototype as any).hasPointerCapture = () => false;
35+
}
36+
if (!(Element.prototype as any).setPointerCapture) {
37+
(Element.prototype as any).setPointerCapture = () => {};
38+
}
39+
if (!(Element.prototype as any).releasePointerCapture) {
40+
(Element.prototype as any).releasePointerCapture = () => {};
41+
}
42+
});
43+
44+
beforeEach(() => {
45+
__clearRecordCrudVerdictCache();
46+
installExplainDouble();
47+
});
48+
afterEach(() => {
49+
cleanup();
50+
vi.unstubAllGlobals();
51+
});
52+
53+
const OBJECT = 'task_35688_s2';
54+
const COLORS = [
55+
{ label: 'Red', value: 'red' },
56+
{ label: 'Green', value: 'green' },
57+
{ label: 'Blue', value: 'blue' },
58+
];
59+
60+
function makeDataSource() {
61+
const store: Record<string, any> = {
62+
r1: { id: 'r1', title: 'Design system', priority: 'high', colors: ['blue'] },
63+
};
64+
return {
65+
find: vi.fn(async () => {
66+
const data = Object.values(store).map((r) => ({ ...r }));
67+
return { data, total: data.length, hasMore: false, pageSize: 50 };
68+
}),
69+
findOne: vi.fn(async (_o: string, id: string) => ({ ...store[id] })),
70+
update: vi.fn(async (_o: string, id: string, changes: Record<string, any>) => {
71+
store[id] = { ...store[id], ...changes };
72+
return { ...store[id] };
73+
}),
74+
getObjectSchema: async (name: string) => ({
75+
name,
76+
fields: {
77+
id: { type: 'text' },
78+
title: { type: 'text', label: 'Title' },
79+
priority: {
80+
type: 'select',
81+
label: 'Priority',
82+
options: [
83+
{ label: 'Low', value: 'low' },
84+
{ label: 'High', value: 'high' },
85+
],
86+
},
87+
colors: { type: 'select', multiple: true, label: 'Colors', options: COLORS },
88+
},
89+
}),
90+
} as any;
91+
}
92+
93+
function renderGrid() {
94+
const ds = makeDataSource();
95+
const schema: any = {
96+
type: 'object-grid',
97+
objectName: OBJECT,
98+
editable: true,
99+
singleClickEdit: true,
100+
columns: [
101+
{ field: 'title', label: 'Title', type: 'text' },
102+
{ field: 'priority', label: 'Priority', type: 'select' },
103+
{ field: 'colors', label: 'Colors', type: 'select' },
104+
],
105+
pagination: { pageSize: 50 },
106+
};
107+
const utils = render(
108+
<ActionProvider>
109+
<SchemaRendererProvider dataSource={ds}>
110+
<div>
111+
<button data-testid="outside">outside</button>
112+
<ObjectGrid schema={schema} dataSource={ds} />
113+
</div>
114+
</SchemaRendererProvider>
115+
</ActionProvider>,
116+
);
117+
return { ...utils, ds };
118+
}
119+
120+
/** The body cell under the header named `label`. */
121+
function cellUnder(container: HTMLElement, label: string): HTMLElement {
122+
const headers = Array.from(container.querySelectorAll('thead th'));
123+
const at = headers.findIndex((th) => th.textContent?.trim().startsWith(label));
124+
expect(at).toBeGreaterThanOrEqual(0);
125+
return container.querySelectorAll('tbody tr')[0].querySelectorAll('td')[at] as HTMLElement;
126+
}
127+
128+
// The grid batches edits (no `cellSelection`, so no per-cell autosave): what a
129+
// pick wrote shows as the row's pending change, and nothing reaches `update`.
130+
describe('ObjectGrid cell editor: a select declared multiple (objectstack#35688 S2)', () => {
131+
it('each check stages and the editor stays open; moving on closes it with every check', async () => {
132+
const { container } = renderGrid();
133+
await waitFor(() => expect(screen.getByText('Design system')).toBeInTheDocument());
134+
135+
fireEvent.click(cellUnder(container, 'Colors'));
136+
await waitFor(() => expect(screen.getByTestId('in-cell-option-red')).toBeInTheDocument());
137+
138+
fireEvent.click(screen.getByTestId('in-cell-option-red'));
139+
// Still open after the first check, with the check on.
140+
expect(screen.getByTestId('in-cell-option-green')).toBeInTheDocument();
141+
expect(screen.getByTestId('in-cell-option-red')).toHaveAttribute('aria-selected', 'true');
142+
fireEvent.click(screen.getByTestId('in-cell-option-green'));
143+
expect(screen.getByTestId('in-cell-option-green')).toHaveAttribute('aria-selected', 'true');
144+
145+
fireEvent.pointerDown(screen.getByTestId('outside'));
146+
await waitFor(() => expect(screen.queryByTestId('in-cell-option-red')).toBeNull());
147+
// This grid batches its edits: the row carries the three colours, pending.
148+
await waitFor(() => expect(screen.getByText(/1 row modified/)).toBeInTheDocument());
149+
const cell = cellUnder(container, 'Colors');
150+
for (const label of ['Blue', 'Red', 'Green']) expect(cell.textContent).toContain(label);
151+
expect(screen.queryByTestId('in-cell-option-red')).toBeNull();
152+
});
153+
154+
it('CONTROL: a single select saves on the pick and closes', async () => {
155+
const { container } = renderGrid();
156+
await waitFor(() => expect(screen.getByText('Design system')).toBeInTheDocument());
157+
158+
fireEvent.click(cellUnder(container, 'Priority'));
159+
await waitFor(() => expect(screen.getByTestId('in-cell-option-low')).toBeInTheDocument());
160+
fireEvent.click(screen.getByTestId('in-cell-option-low'));
161+
162+
// The pick closes the editor, and the click that made it does not open it again.
163+
await waitFor(() => expect(screen.queryByTestId('in-cell-option-low')).toBeNull());
164+
await waitFor(() => expect(screen.getByText(/1 row modified/)).toBeInTheDocument());
165+
expect(cellUnder(container, 'Priority').textContent).toContain('Low');
166+
});
167+
});

0 commit comments

Comments
 (0)