From d84aa949a026da2ef5e11572345df25be7a7b291 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 02:33:18 +0000 Subject: [PATCH 1/4] feat(list): "Add group field" groups by the view's first single select, and asks when there is none The Group editors used to add the first column, usually the record's name, so every record became its own group. Now the first single select or radio in the reader's column order is added at once (a shown column before a hidden one); with none, the field dropdown opens and nothing is grouped until a pick. The dropdown lists the fields that suit grouping first. GroupingEditor gains the optional pickAddField prop; ViewSettingsField carries the declared type. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgXeD1yUYqBJm8uzRrP --- .changeset/36204-group-add-default-field.md | 19 ++ .../areas/records-forms.json | 10 +- .../ObjectView.listUrlState-11860.test.tsx | 17 +- ...grouping-editor-add-default-36204.test.tsx | 123 +++++++++ .../components/src/custom/grouping-editor.tsx | 79 ++++-- ui/packages/plugin-list/src/ListView.tsx | 26 +- .../ListView.fieldListRead-11984.test.tsx | 17 +- .../ListView.groupAddDefault-36204.test.tsx | 236 ++++++++++++++++++ .../src/__tests__/ListView.harness.test.tsx | 25 +- .../ListView.onGroupingChange-11860.test.tsx | 23 +- .../src/components/ViewSettingsPopover.tsx | 68 ++++- 11 files changed, 596 insertions(+), 47 deletions(-) create mode 100644 .changeset/36204-group-add-default-field.md create mode 100644 ui/packages/components/src/__tests__/grouping-editor-add-default-36204.test.tsx create mode 100644 ui/packages/plugin-list/src/__tests__/ListView.groupAddDefault-36204.test.tsx diff --git a/.changeset/36204-group-add-default-field.md b/.changeset/36204-group-add-default-field.md new file mode 100644 index 00000000000..44329cac5b2 --- /dev/null +++ b/.changeset/36204-group-add-default-field.md @@ -0,0 +1,19 @@ +--- +'@object-ui/components': patch +'@object-ui/plugin-list': patch +--- + +feat(list): "Add group field" groups by the view's first single select, and asks when there is none + +Clause-②: yes (widening) — `@object-ui/components`'s `GroupingEditor` gains the optional prop `pickAddField`; `@object-ui/plugin-list`'s `ViewSettingsField` gains the optional members `type` and `multiple`, `groupFieldOptions` an optional second argument (the column order), and the module exports `pickGroupAddField`; nothing removed or renamed +Metadata-protocol: none + +On a list, 「添加分组字段」 / "Add group field" used to group at once by the list's first column, usually the record's name, so every record became a group of its own. Now, in the toolbar's Group panel and in the view settings menu's Group level alike: + +- It groups at once by the first single select or radio field (a status is one) in the reader's column order, a shown column before a hidden one. A select that holds many values is not picked. +- A view with no such field is not grouped yet: the field dropdown opens, and the list is grouped once a field is picked there. Closing the dropdown without a pick changes nothing. +- The field dropdown lists the fields that suit grouping first (single select, radio, person, linked record, tick, date, each single-valued), then the rest, such as a name or a number, which can still be picked. Each part keeps the column order. +- A second level follows the same rule among the fields no level uses yet. +- The grouping is still a part of the list's draft: **Discard** and **Save** appear, and nothing is written. + +`@object-ui/components`: `GroupingEditor`'s `pickAddField(remaining)` chooses the field "Add group field" adds from the fields no level uses, in `fieldOptions` order; `undefined` opens a row with an open field dropdown and writes the level only on a pick. Without the prop the first remaining field is added at once, as before. diff --git a/docs/qa/platform-checklist/areas/records-forms.json b/docs/qa/platform-checklist/areas/records-forms.json index 8bb59598f1f..c62597c30f8 100644 --- a/docs/qa/platform-checklist/areas/records-forms.json +++ b/docs/qa/platform-checklist/areas/records-forms.json @@ -3604,7 +3604,7 @@ "title": "Grid personalization persists across reload: column resize/reorder/pin, row-height, group-by (with API-true totals), row-color", "since": "v16", "status": "active", - "revision": 9, + "revision": 10, "priority": "P2", "surface": "browser", "personas": [ @@ -3631,7 +3631,7 @@ "open showcase_task grid; screenshot", "resize a column (reorder two columns only on a grid that sets reorderableColumns; there is no runtime pin control — acceptance[0]), and set a row height on the Row height level of the list's options menu (the toolbar's options trigger, then 行高 / Row height: three choices, 紧凑 / 标准 / 宽松 — Compact / Standard / Spacious, ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx; a gallery's Row height level picks its card size the same way) — three modes, stored as rowHeight compact / medium / tall (the spec's five row heights compact/short/medium/tall/extra_tall narrow onto these three: objectui core normalize-list-view.ts DENSITY_MODE_TO_ROW_HEIGHT / ROW_HEIGHT_TO_DENSITY_MODE)", "reload; confirm the column widths and row-height restored — they persist in the signed-in user's own list preference, sys_user_preference ui.list.showcase_task (perView..columnState.widths / rowHeight, objectui#12418). A column ORDER is not: since objectstack#35955 it is the list's unsaved draft, so a reload reopens on the view's own order unless it was saved into a view, with localStorage grid-columns-showcase_task[-] as the component's cache; the old per-view override through dataSource.updateViewConfig is retired (objectui#12504). Also reload in a FRESH browser context as the same user: the layout follows the user", - "group-by status ('Add group field' pre-selects the first field, Title, and groups at once, so switch it to Status). A runtime grouping lives in the list's URL (uf__group, ui/packages/app-shell/src/views/objectViewListUrlState.ts), not in sys_user_preference: reloading that URL keeps it, a reload of the bare list URL reopens on the view's own grouping by design, and steps[6] reads it that way (QA run #33861). Confirm per-group headers appear and each group shows its record count — summarizeField (estimate_hours) is declared on the KANBAN config of task.view.ts, not on the grid, so grid groups carry counts; clear grouping and confirm the headers are removed cleanly", + "group-by status ('Add group field' groups at once by the grid's first single select in column order, Status here, objectstack#36204; the field dropdown lists the fields that suit grouping first, and on a grid with no single select it opens with nothing grouped until a field is picked). A runtime grouping lives in the list's URL (uf__group, ui/packages/app-shell/src/views/objectViewListUrlState.ts), not in sys_user_preference: reloading that URL keeps it, a reload of the bare list URL reopens on the view's own grouping by design, and steps[6] reads it that way (QA run #33861). Confirm per-group headers appear and each group shows its record count — summarizeField (estimate_hours) is declared on the KANBAN config of task.view.ts, not on the grid, so grid groups carry counts; clear grouping and confirm the headers are removed cleanly", "cross-check each group's count against a direct per-group server count (GET /api/v1/data/showcase_task filtered to that status, read its total)", "read the row-color rule the stock Grid view declares — rowColor on priority with the colors map low slate / medium blue / high amber / urgent red (examples/app-showcase/src/ui/views/task.view.ts); there is no runtime row-color authoring control — and confirm rows paint by it (useRowColor, the -100 tint of each name)", "reload once more; confirm every personalization this item stores survives (column widths, row height); capture a screenshot per variant" @@ -3737,6 +3737,12 @@ "date": "2026-11-21", "change": "steps[2], steps[6] and acceptance[0] (clause, verify) re-pointed to the list draft (objectstack#35955): a column order is the list's unsaved draft, kept only by Save into a view, so it no longer comes back after a reload; the widths and the row height still persist in the user's ui.list. row. Not loosened: widths and row height must still survive a reload and follow the user to a fresh browser", "ref": "#35955" + }, + { + "revision": 10, + "date": "2026-11-22", + "change": "steps[3] re-pointed (objectstack#36204): 'Add group field' no longer pre-selects the first column; it groups at once by the first single select or radio in the reader's column order (Status on this grid), lists the fields that suit grouping first, and on a grid with none opens the field dropdown without grouping. No clause changed.", + "ref": "#36204" } ] }, diff --git a/ui/packages/app-shell/src/views/ObjectView.listUrlState-11860.test.tsx b/ui/packages/app-shell/src/views/ObjectView.listUrlState-11860.test.tsx index 376ec4ca484..58228bb14d5 100644 --- a/ui/packages/app-shell/src/views/ObjectView.listUrlState-11860.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.listUrlState-11860.test.tsx @@ -760,6 +760,19 @@ async function openGroupPanel() { await settle(); } +/** + * "Add group field", then the field. This harness's data source answers no + * `getObjectSchema`, so the list knows no field's type and the button opens + * the field dropdown instead of adding a level (objectstack#36204): the level + * is written once a field is picked there. + */ +async function addGroupLevel(name: string) { + fireEvent.click(screen.getByTestId('grouping-add')); + const listbox = await screen.findByRole('listbox'); + // No definition either for the labels: the options are the field names. + fireEvent.click(within(listbox).getByRole('option', { name })); +} + /** The Group level's own Clear, inside the Display menu. */ function clearGrouping() { const panel = screen.getByTestId('view-settings-content'); @@ -789,7 +802,7 @@ describe('the toolbar grouping is in the URL too (objectui#11860)', () => { const host = await mountHost(['/elsewhere', `${VIEW}/all`]); expect(groupedBy()).toBeUndefined(); await openGroupPanel(); - fireEvent.click(screen.getByTestId('grouping-add')); + await addGroupLevel('priority'); await settle(); const written = groupParamOf(host); expect(written?.fields).toHaveLength(1); @@ -810,7 +823,7 @@ describe('the toolbar grouping is in the URL too (objectui#11860)', () => { it('the grouping a user set on a link survives a reload of that link', async () => { const host = await mountHost([`${VIEW}/all`]); await openGroupPanel(); - fireEvent.click(screen.getByTestId('grouping-add')); + await addGroupLevel('priority'); await settle(); const url = `${host.pathname()}${host.search()}`; const field = groupParamOf(host).fields[0].field; diff --git a/ui/packages/components/src/__tests__/grouping-editor-add-default-36204.test.tsx b/ui/packages/components/src/__tests__/grouping-editor-add-default-36204.test.tsx new file mode 100644 index 00000000000..56138d8ac67 --- /dev/null +++ b/ui/packages/components/src/__tests__/grouping-editor-add-default-36204.test.tsx @@ -0,0 +1,123 @@ +/** + * 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. + */ + +/** + * "Add group field" asks its host which field to add (objectstack#36204). + * + * It used to add the first field no level used, at once: in a list the first + * column, a name as a rule, so the first click grouped the records one per + * group. `pickAddField` lets the host choose; when it has no field to offer + * the editor writes nothing and opens a row whose field dropdown is already + * open, and the level is written only once a field is picked there. + * + * DIRECTION: without the prop every pin but the CONTROL fails on the old + * editor (the button wrote the first field at once, and no pending row + * existed); the CONTROL is the old behaviour, kept for a host that passes + * no `pickAddField`. + */ +import { describe, it, expect, vi } from 'vitest'; +import React from 'react'; +import { render, screen, fireEvent, waitFor, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { GroupingEditor, type GroupingConfigValue } from '../custom/grouping-editor'; + +const FIELD_OPTIONS = [ + { value: 'name', label: 'Name' }, + { value: 'status', label: 'Status' }, + { value: 'owner', label: 'Owner' }, +]; + +function renderEditor( + value: GroupingConfigValue | undefined, + pickAddField?: (remaining: Array<{ value: string; label: string }>) => string | undefined, +) { + const onChange = vi.fn(); + const utils = render( + , + ); + return { ...utils, onChange }; +} + +const labels = (options: HTMLElement[]) => options.map((o) => o.textContent ?? ''); + +describe('"Add group field" adds the field the host picks', () => { + it('adds the picked field at once', () => { + const { onChange } = renderEditor(undefined, () => 'status'); + fireEvent.click(screen.getByTestId('grouping-add')); + expect(onChange).toHaveBeenCalledTimes(1); + expect(onChange.mock.calls[0][0]).toStrictEqual({ + fields: [{ field: 'status', order: 'asc', collapsed: false }], + }); + }); + + it('is asked with the fields no level uses, in `fieldOptions` order, and appends the level', () => { + const pick = vi.fn((remaining: Array<{ value: string }>) => remaining[remaining.length - 1].value); + const { onChange } = renderEditor({ fields: [{ field: 'status', order: 'desc', collapsed: true }] }, pick); + fireEvent.click(screen.getByTestId('grouping-add')); + expect(pick.mock.calls[0][0].map((o) => o.value)).toEqual(['name', 'owner']); + expect(onChange.mock.calls[0][0]).toStrictEqual({ + fields: [ + { field: 'status', order: 'desc', collapsed: true }, + { field: 'owner', order: 'asc', collapsed: false }, + ], + }); + }); + + it('CONTROL: without `pickAddField` the first unused field is added at once, as before', () => { + const { onChange } = renderEditor(undefined); + fireEvent.click(screen.getByTestId('grouping-add')); + expect(onChange.mock.calls[0][0]).toStrictEqual({ + fields: [{ field: 'name', order: 'asc', collapsed: false }], + }); + }); +}); + +describe('no field picked: the field dropdown opens and nothing is written until a pick', () => { + it('opens a row with its dropdown open, writes nothing, and hides the add button', async () => { + const { onChange } = renderEditor(undefined, () => undefined); + fireEvent.click(screen.getByTestId('grouping-add')); + expect(onChange).not.toHaveBeenCalled(); + expect(screen.getByTestId('grouping-field-pending')).toBeInTheDocument(); + expect(screen.queryByTestId('grouping-add')).toBeNull(); + // No level yet: the list is not grouped. + expect(screen.queryByTestId('grouping-field-0')).toBeNull(); + const listbox = await screen.findByRole('listbox'); + expect(labels(within(listbox).getAllByRole('option'))).toEqual(['Name', 'Status', 'Owner']); + }); + + it('a pick writes the level and the row becomes that level', async () => { + const { onChange, rerender } = renderEditor(undefined, () => undefined); + fireEvent.click(screen.getByTestId('grouping-add')); + const listbox = await screen.findByRole('listbox'); + fireEvent.click(within(listbox).getAllByRole('option').find((o) => o.textContent === 'Owner')!); + expect(onChange).toHaveBeenCalledTimes(1); + const written = onChange.mock.calls[0][0]; + expect(written).toStrictEqual({ fields: [{ field: 'owner', order: 'asc', collapsed: false }] }); + rerender( undefined} />); + await waitFor(() => expect(screen.queryByTestId('grouping-field-pending')).toBeNull()); + expect(screen.getByTestId('grouping-field-0')).toHaveTextContent('Owner'); + expect(screen.getByTestId('grouping-add')).toBeInTheDocument(); + }); + + it('offers only the fields no level uses', async () => { + renderEditor({ fields: [{ field: 'name', order: 'asc', collapsed: false }] }, () => undefined); + fireEvent.click(screen.getByTestId('grouping-add')); + const listbox = await screen.findByRole('listbox'); + expect(labels(within(listbox).getAllByRole('option'))).toEqual(['Status', 'Owner']); + }); + + it('closing the dropdown without a pick drops the row and writes nothing', async () => { + const { onChange } = renderEditor(undefined, () => undefined); + fireEvent.click(screen.getByTestId('grouping-add')); + const listbox = await screen.findByRole('listbox'); + fireEvent.keyDown(listbox, { key: 'Escape' }); + await waitFor(() => expect(screen.queryByTestId('grouping-field-pending')).toBeNull()); + expect(onChange).not.toHaveBeenCalled(); + expect(screen.getByTestId('grouping-add')).toBeInTheDocument(); + }); +}); diff --git a/ui/packages/components/src/custom/grouping-editor.tsx b/ui/packages/components/src/custom/grouping-editor.tsx index 8b7efbd0a2e..1cf70721543 100644 --- a/ui/packages/components/src/custom/grouping-editor.tsx +++ b/ui/packages/components/src/custom/grouping-editor.tsx @@ -30,6 +30,15 @@ export interface GroupingEditorProps { onChange: (next: GroupingConfigValue | undefined) => void; /** Available fields to group by. */ fieldOptions: Array<{ value: string; label: string }>; + /** + * The field "Add group field" adds, chosen from the fields no level uses + * yet (`remaining`, in `fieldOptions` order). Returning `undefined` adds no + * level: a row with an open field dropdown appears instead, and the level is + * written only once a field is picked there; closing the dropdown without a + * pick drops the row and writes nothing (objectstack#36204). Absent, the + * first remaining field is added at once. + */ + pickAddField?: (remaining: Array<{ value: string; label: string }>) => string | undefined; /** Maximum nesting depth. Airtable defaults to 3. */ maxLevels?: number; className?: string; @@ -70,6 +79,7 @@ export function GroupingEditor({ value, onChange, fieldOptions, + pickAddField, maxLevels = 3, className, labels, @@ -77,6 +87,11 @@ export function GroupingEditor({ const L = { ...DEFAULT_LABELS, ...(labels || {}) }; const current = value?.fields ?? []; const usedFields = new Set(current.map((g) => g.field)); + // objectstack#36204 — "Add group field" found no field to add by itself + // (`pickAddField` answered `undefined`): a row asking for one is open, and + // nothing is written until a field is picked in it. + const [askingField, setAskingField] = React.useState(false); + const remaining = fieldOptions.filter((f) => !usedFields.has(f.value)); const writeFields = (next: GroupingFieldEntry[]) => { onChange(next.length ? { fields: next } : undefined); @@ -173,27 +188,53 @@ export function GroupingEditor({ ); })} - {current.length < maxLevels && (() => { - const remaining = fieldOptions.filter((f) => !usedFields.has(f.value)); - if (remaining.length === 0) return null; - return ( - + )} ); } diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 3bbffca603b..32b039cb51e 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -19,6 +19,7 @@ import { ViewSettingsPopover, ViewSettingsContent, groupFieldOptions, + pickGroupAddField, type ViewSettingsField, PHONE_TOUCH_TARGET, useBelowSm, @@ -6529,8 +6530,16 @@ export const ListView = React.forwardRef(({ const label = objectDef?.fields?.[name]?.label; return typeof label === 'string' && label ? label : undefined; }; - const groupability = (name: string): Pick => - isVirtualSearchField(objectDef?.fields?.[name] as SearchFieldMeta | undefined) ? { groupable: false } : {}; + // objectstack#36204 — and the declared type, which the Group editors rank + // and pick by (`groupFieldOptions`, `pickGroupAddField`). + const groupability = (name: string): Pick => { + const def = objectDef?.fields?.[name] as (SearchFieldMeta & { type?: unknown; multiple?: unknown }) | undefined; + return { + ...(isVirtualSearchField(def) ? { groupable: false } : {}), + ...(typeof def?.type === 'string' ? { type: def.type } : {}), + ...(def?.multiple === true ? { multiple: true } : {}), + }; + }; return (Array.isArray(schema.columns) ? (schema.columns as any[]) : []).flatMap((f: any) => { if (typeof f === 'string') { if (!canReadField(perms, schema.objectName, f)) return []; @@ -6547,6 +6556,14 @@ export const ListView = React.forwardRef(({ }); }, [schema.columns, tFieldLabel, perms, schema.objectName, objectDef]); + // The order the reader's grid columns are drawn in (the column state the + // header drag keeps), handed to the View settings menu's Fields level and, + // objectstack#36204, to both Group editors, which list and pick fields in + // the column order. Another visualization has no column order of its own. + const gridColumnOrder = currentView === 'grid' + ? (schema.columnState as { order?: string[]; widths?: Record } | undefined)?.order + : undefined; + // objectui#11984 — what the two hide-fields lists (the toolbar popover and // the View settings section) are handed of `hiddenFields`. An entry naming a // field the caller may not read is WITHHELD from them: not listed, not @@ -7257,7 +7274,7 @@ export const ListView = React.forwardRef(({ viewName={typeof schema.label === 'string' && schema.label && (onRenameView || onPersonalizationChange) ? { label: schema.label, onRename: onRenameView } : undefined} - fieldOrder={currentView === 'grid' ? (schema.columnState as { order?: string[]; widths?: Record } | undefined)?.order : undefined} + fieldOrder={gridColumnOrder} onFieldOrderChange={currentView === 'grid' && onColumnStateChange ? (order) => onColumnStateChange({ ...(schema.columnState as { order?: string[]; widths?: Record } | undefined), order }) : undefined} @@ -7628,7 +7645,8 @@ export const ListView = React.forwardRef(({
{ await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2)); await waitFor(async () => expect(await hideFields()).toEqual(FIELD_LABELS)); expect(chips()).toEqual(['Status', 'Secret Status']); - // The level's own field is offered in its own dropdown, so all five are. + // The level's own field is offered in its own dropdown, so all five are: + // the select fields first, as the Group editors rank them (objectstack#36204). const group = await inPopover(toolbarButton(/^group/i), (c) => comboboxOptions(within(c).getByTestId('grouping-field-0'))); - expect(group).toEqual(FIELD_LABELS); + expect(group).toEqual(['Status', 'Secret Status', 'Title', 'Priority', 'Secret Note']); }); }); @@ -520,20 +521,22 @@ describe('a stored configuration on an unreadable field is kept as stored (objec const content = await openPopover(toolbarButton(/^group/i)); const level = within(content).getByTestId('grouping-field-0'); expect(level).toHaveTextContent('secret_note'); - expect(await comboboxOptions(level)).toEqual(['secret_note', 'Title', 'Status', 'Priority']); + // The select field first, as the Group editors rank them (objectstack#36204). + expect(await comboboxOptions(level)).toEqual(['secret_note', 'Status', 'Title', 'Priority']); expect(onGroupingChange).not.toHaveBeenCalled(); - // "Add group field" seeds a readable field, and the new level does not offer it. + // "Add group field" seeds a readable field (the first readable select, + // objectstack#36204), and the new level does not offer the unreadable one. fireEvent.click(within(content).getByTestId('grouping-add')); expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [ { field: 'secret_note', order: 'asc', collapsed: false }, - { field: 'title', order: 'asc', collapsed: false }, + { field: 'status', order: 'asc', collapsed: false }, ], }); - expect(await comboboxOptions(within(content).getByTestId('grouping-field-1'))).toEqual(['Title', 'Status', 'Priority']); + expect(await comboboxOptions(within(content).getByTestId('grouping-field-1'))).toEqual(['Status', 'Title', 'Priority']); // Its own level can be removed. fireEvent.click(within(content).getByTestId('grouping-remove-0')); - expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [{ field: 'title', order: 'asc', collapsed: false }] }); + expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [{ field: 'status', order: 'asc', collapsed: false }] }); }); it('a hidden-field entry on it is not listed, counted or cleared, and every write keeps it', async () => { diff --git a/ui/packages/plugin-list/src/__tests__/ListView.groupAddDefault-36204.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.groupAddDefault-36204.test.tsx new file mode 100644 index 00000000000..e01be94d8ff --- /dev/null +++ b/ui/packages/plugin-list/src/__tests__/ListView.groupAddDefault-36204.test.tsx @@ -0,0 +1,236 @@ +/** + * 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. + */ + +/** + * "Add group field" groups by the view's first single select, not its first + * column (objectstack#36204). + * + * It used to add the first field the editor listed, the list's first column, + * a name as a rule: twelve customers became twelve groups of one. Now, in + * both Group editors (the wide toolbar's panel and the View settings menu's + * Group level): + * 1. the first single select or radio in the reader's column order is added + * at once, a shown column before a hidden one; + * 2. with none, nothing is grouped yet: the field dropdown opens, and the + * level is written once a field is picked; + * 3. the dropdown lists the fields that suit grouping first (select, radio, + * person, linked record, tick, date; single-valued), then the rest, each + * part in column order; + * 4. the change still goes only to `onGroupingChange` (the host's draft, + * objectstack#35955): the data source is asked to write nothing. + * + * DIRECTION: on main every pin but the CONTROLs fails: the button added + * `name`, and the dropdown listed the columns in their own order. + */ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { act, cleanup, render, screen, fireEvent, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; +import type { ListViewSchema } from '@object-ui/types'; +import { SchemaRendererProvider } from '@object-ui/react'; +import { ListView } from '../ListView'; +import { groupFieldOptions, pickGroupAddField, type ViewSettingsField } from '../components/ViewSettingsPopover'; + +const OBJECT = 'customer_36204'; + +const FIELDS: Record> = { + name: { type: 'text', label: 'Customer name' }, + owner: { type: 'user', label: 'Owner', reference: 'sys_user' }, + industry: { type: 'select', label: 'Industry', options: [{ value: 'it', label: 'IT' }] }, + stage: { type: 'radio', label: 'Stage', options: [{ value: 'new', label: 'New' }] }, + tags: { type: 'select', multiple: true, label: 'Tags', options: [{ value: 'a', label: 'A' }] }, + notes: { type: 'textarea', label: 'Notes' }, + signed: { type: 'date', label: 'Signed on' }, +}; + +function mount(schemaExtra: Record) { + const dataSource = { + find: vi.fn().mockResolvedValue({ data: [{ id: '1', name: 'Acme', industry: 'it' }], total: 1 }), + queryGroupHeaders: vi.fn().mockResolvedValue([]), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + getObjectSchema: vi.fn().mockResolvedValue({ name: OBJECT, fields: FIELDS }), + }; + const onGroupingChange = vi.fn(); + const schema = { + type: 'list-view', + objectName: OBJECT, + viewType: 'grid', + compactToolbar: false, + ...schemaExtra, + } as unknown as ListViewSchema; + render( + + + , + ); + return { dataSource, onGroupingChange }; +} + +async function definitionRead(dataSource: { getObjectSchema: ReturnType }) { + await vi.waitFor(() => expect(dataSource.getObjectSchema).toHaveBeenCalled()); + await act(async () => {}); +} + +async function openToolbarGroup(): Promise { + fireEvent.click(screen.getByRole('button', { name: /^group/i })); + return screen.findByTestId('group-field-list'); +} + +async function openDisplayGroup(): Promise { + fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + const content = await screen.findByTestId('view-settings-content'); + fireEvent.click(within(content).getByTestId('options-row-group')); + await within(content).findByTestId('grouping-add'); + return content; +} + +async function listboxLabels(): Promise { + const listbox = await screen.findByRole('listbox'); + return within(listbox).getAllByRole('option').map((o) => o.textContent ?? ''); +} + +const level = (field: string) => ({ field, order: 'asc', collapsed: false }); + +afterEach(() => cleanup()); + +describe('"Add group field" adds the first single select (objectstack#36204)', () => { + const columns = ['name', 'owner', 'industry', 'notes']; + + it('the toolbar Group panel groups by Industry, not by the first column', async () => { + const { dataSource, onGroupingChange } = mount({ columns }); + await definitionRead(dataSource); + const panel = await openToolbarGroup(); + fireEvent.click(within(panel).getByTestId('grouping-add')); + expect(onGroupingChange).toHaveBeenCalledTimes(1); + expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('industry')] }); + // A draft for the host: the data source is asked to write nothing. + expect(dataSource.create).not.toHaveBeenCalled(); + expect(dataSource.update).not.toHaveBeenCalled(); + expect(dataSource.delete).not.toHaveBeenCalled(); + }); + + it('the View settings Group level does the same', async () => { + const { dataSource, onGroupingChange } = mount({ columns, compactToolbar: true }); + await definitionRead(dataSource); + const content = await openDisplayGroup(); + fireEvent.click(within(content).getByTestId('grouping-add')); + expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('industry')] }); + }); + + it('the dropdown lists Owner and Industry ahead of Customer name, in both editors', async () => { + const { dataSource } = mount({ columns, grouping: { fields: [level('industry')] } }); + await definitionRead(dataSource); + const panel = await openToolbarGroup(); + fireEvent.keyDown(within(panel).getByTestId('grouping-field-0'), { key: 'ArrowDown' }); + expect(await listboxLabels()).toEqual(['Owner', 'Industry', 'Customer name', 'Notes']); + cleanup(); + + const second = mount({ columns, compactToolbar: true, grouping: { fields: [level('industry')] } }); + await definitionRead(second.dataSource); + const content = await openDisplayGroup(); + fireEvent.keyDown(within(content).getByTestId('grouping-field-0'), { key: 'ArrowDown' }); + expect(await listboxLabels()).toEqual(['Owner', 'Industry', 'Customer name', 'Notes']); + }); + + it('follows the reader\'s column order: the select drawn first wins', async () => { + const { dataSource, onGroupingChange } = mount({ + columns: ['name', 'industry', 'stage'], + columnState: { order: ['stage', 'name', 'industry'] }, + }); + await definitionRead(dataSource); + const panel = await openToolbarGroup(); + fireEvent.click(within(panel).getByTestId('grouping-add')); + expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('stage')] }); + }); + + it('a shown select is picked before a hidden one; a hidden one when none is shown', async () => { + const first = mount({ columns: ['name', 'industry', 'stage'], hiddenFields: ['industry'] }); + await definitionRead(first.dataSource); + fireEvent.click(within(await openToolbarGroup()).getByTestId('grouping-add')); + expect(first.onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('stage')] }); + cleanup(); + + const second = mount({ columns: ['name', 'industry'], hiddenFields: ['industry'] }); + await definitionRead(second.dataSource); + fireEvent.click(within(await openToolbarGroup()).getByTestId('grouping-add')); + expect(second.onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('industry')] }); + }); + + it('the second level follows the same rule: the next unused select', async () => { + const { dataSource, onGroupingChange } = mount({ + columns: ['name', 'industry', 'stage'], + grouping: { fields: [level('industry')] }, + }); + await definitionRead(dataSource); + fireEvent.click(within(await openToolbarGroup()).getByTestId('grouping-add')); + expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('industry'), level('stage')] }); + }); +}); + +describe('a view with no single select: the dropdown opens and nothing is grouped yet', () => { + // `tags` is a select holding many values: not a default. + const columns = ['name', 'owner', 'tags', 'signed']; + + it('the toolbar Group panel: no write until a pick, then the picked field', async () => { + const { dataSource, onGroupingChange } = mount({ columns }); + await definitionRead(dataSource); + const panel = await openToolbarGroup(); + fireEvent.click(within(panel).getByTestId('grouping-add')); + expect(onGroupingChange).not.toHaveBeenCalled(); + expect(within(panel).queryByTestId('grouping-field-0')).toBeNull(); + expect(await listboxLabels()).toEqual(['Owner', 'Signed on', 'Customer name', 'Tags']); + fireEvent.click(within(screen.getByRole('listbox')).getByRole('option', { name: 'Owner' })); + expect(onGroupingChange).toHaveBeenCalledTimes(1); + expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('owner')] }); + }); + + it('the View settings Group level does the same', async () => { + const { dataSource, onGroupingChange } = mount({ columns, compactToolbar: true }); + await definitionRead(dataSource); + const content = await openDisplayGroup(); + fireEvent.click(within(content).getByTestId('grouping-add')); + expect(onGroupingChange).not.toHaveBeenCalled(); + expect(await listboxLabels()).toEqual(['Owner', 'Signed on', 'Customer name', 'Tags']); + }); +}); + +describe('the ranking and the pick, as functions', () => { + const fields: ViewSettingsField[] = [ + { name: 'name', label: 'Name', type: 'text' }, + { name: 'tags', label: 'Tags', type: 'select', multiple: true }, + { name: 'flag', label: 'Flag', type: 'boolean' }, + { name: 'calc', label: 'Calc', type: 'formula', groupable: false }, + { name: 'when', label: 'When', type: 'datetime' }, + { name: 'parent', label: 'Parent', type: 'lookup' }, + { name: 'status', label: 'Status', type: 'select' }, + { name: 'untyped', label: 'Untyped' }, + ]; + + it('suits-grouping types first, the rest after, each in column order; formulas left out', () => { + expect(groupFieldOptions(fields).map((o) => o.value)) + .toEqual(['flag', 'when', 'parent', 'status', 'name', 'tags', 'untyped']); + }); + + it('the column order a reader set comes first', () => { + expect(groupFieldOptions(fields, ['status', 'name']).map((o) => o.value)) + .toEqual(['status', 'flag', 'when', 'parent', 'name', 'tags', 'untyped']); + }); + + it('picks the first single-valued select or radio among the remaining, in the order given', () => { + const pick = pickGroupAddField(fields); + expect(pick(groupFieldOptions(fields))).toBe('status'); + expect(pick(groupFieldOptions(fields).filter((o) => o.value !== 'status'))).toBeUndefined(); + }); + + it('CONTROL: a field with no declared type is never picked, only listed', () => { + expect(pickGroupAddField([{ name: 'untyped' }])([{ value: 'untyped' }])).toBeUndefined(); + }); +}); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx index 44cb31c0fe2..a4319cb8e42 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx @@ -3509,12 +3509,23 @@ describe('ListView.groupPickerUnstored-32631', () => { }); describe('the Group editors do not offer a formula field (objectstack#32631)', () => { - it('the toolbar Group panel: "Add group field" seeds the first stored field, and the level lists stored fields only', async () => { + // objectstack#36204 — no field here is a select, so "Add group field" + // groups by nothing yet: it opens the field dropdown, and that list is + // the one these pins read. + async function addAndRead(scope: { getByTestId: (id: string) => HTMLElement }): Promise { + fireEvent.click(scope.getByTestId('grouping-add')); + const listbox = await screen.findByRole('listbox'); + return within(listbox).getAllByRole('option').map((o) => o.textContent ?? ''); + } + + it('the toolbar Group panel: "Add group field" lists stored fields only, and the pick is the level', async () => { const { onGroupingChange } = mount(); await screen.findByTestId('grid-stub'); fireEvent.click(screen.getByRole('button', { name: /group/i })); await screen.findByTestId('group-field-list'); - fireEvent.click(screen.getByTestId('grouping-add')); + expect(await addAndRead(screen)).toEqual(['Subject', 'Status']); + expect(onGroupingChange).not.toHaveBeenCalled(); + fireEvent.click(within(screen.getByRole('listbox')).getByRole('option', { name: 'Subject' })); expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [{ field: 'subject', order: 'asc', collapsed: false }] }); expect(await openOptions(screen.getByTestId('grouping-field-0'))).toEqual(['Subject', 'Status']); }); @@ -3525,9 +3536,9 @@ describe('ListView.groupPickerUnstored-32631', () => { fireEvent.click(screen.getByTestId('toolbar-display-trigger')); const content = await screen.findByTestId('view-settings-content'); fireEvent.click(within(content).getByTestId('options-row-group')); - fireEvent.click(await within(content).findByTestId('grouping-add')); - expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [{ field: 'subject', order: 'asc', collapsed: false }] }); - expect(await openOptions(within(content).getByTestId('grouping-field-0'))).toEqual(['Subject', 'Status']); + await within(content).findByTestId('grouping-add'); + expect(await addAndRead(within(content))).toEqual(['Subject', 'Status']); + expect(onGroupingChange).not.toHaveBeenCalled(); }); it('CONTROL — the same field stored (`text`) is offered first, in both editors', async () => { @@ -3535,9 +3546,9 @@ describe('ListView.groupPickerUnstored-32631', () => { await screen.findByTestId('grid-stub'); fireEvent.click(screen.getByRole('button', { name: /group/i })); await screen.findByTestId('group-field-list'); - fireEvent.click(screen.getByTestId('grouping-add')); + expect(await addAndRead(screen)).toEqual(['Title', 'Subject', 'Status']); + fireEvent.click(within(screen.getByRole('listbox')).getByRole('option', { name: 'Title' })); expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [TITLE] }); - expect(await openOptions(screen.getByTestId('grouping-field-0'))).toEqual(['Title', 'Subject', 'Status']); }); }); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.onGroupingChange-11860.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.onGroupingChange-11860.test.tsx index ff8a0e731b2..a654e968539 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.onGroupingChange-11860.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.onGroupingChange-11860.test.tsx @@ -37,6 +37,16 @@ import { ListView } from '../ListView'; /** A partial stub: only the members the list's mount path calls. */ const dataSource = { find: vi.fn().mockResolvedValue([]), + // objectstack#36204 — the declared types "Add group field" picks by: it + // adds the first single select (`status`) at once. + getObjectSchema: vi.fn().mockResolvedValue({ + name: 'contacts', + fields: { + name: { type: 'text', label: 'Name' }, + email: { type: 'email', label: 'Email' }, + status: { type: 'select', label: 'Status', options: [{ value: 'open', label: 'Open' }] }, + }, + }), findOne: vi.fn(), create: vi.fn(), update: vi.fn(), @@ -56,10 +66,16 @@ function schemaWith(extra: Partial = {}): ListViewSchema { } as ListViewSchema; } +/** Wait until the object's declaration is read: the Group editors pick by its types. */ +async function definitionRead() { + await vi.waitFor(() => expect(dataSource.getObjectSchema).toHaveBeenCalled()); + await act(async () => {}); +} + function mount(schema: ListViewSchema, onGroupingChange: (g: GroupingConfig | undefined) => void) { const view = (s: ListViewSchema) => ( - + ); const result = render(view(schema)); @@ -85,12 +101,13 @@ describe('ListView reports a user grouping change to its host (objectui#11860)', mount(schemaWith(), onGroupingChange); fireEvent.click(screen.getByRole('button', { name: /group/i })); await vi.waitFor(() => expect(screen.getByTestId('group-field-list')).toBeInTheDocument()); + await definitionRead(); fireEvent.click(screen.getByTestId('grouping-add')); expect(onGroupingChange).toHaveBeenCalledTimes(1); const added = onGroupingChange.mock.calls[0][0] as GroupingConfig; expectSpecShape(added); - expect(added.fields).toHaveLength(1); + expect(added.fields).toEqual([{ field: 'status', order: 'asc', collapsed: false }]); fireEvent.click(screen.getByTestId('grouping-order-0')); expect(onGroupingChange).toHaveBeenCalledTimes(2); @@ -125,9 +142,11 @@ describe('ListView reports a user grouping change to its host (objectui#11860)', const content = screen.getByTestId('view-settings-content'); // Grouping is a level of the Display menu. fireEvent.click(within(content).getByTestId('options-row-group')); + await definitionRead(); fireEvent.click(await within(content).findByTestId('grouping-add')); expect(onGroupingChange).toHaveBeenCalledTimes(1); expectSpecShape(onGroupingChange.mock.calls[0][0]); + expect(onGroupingChange.mock.calls[0][0].fields[0].field).toBe('status'); const clear = Array.from(content.querySelectorAll('button')).find((b) => b.textContent === 'Clear'); expect(clear).toBeDefined(); diff --git a/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx b/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx index daf077642da..f290732553f 100644 --- a/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx +++ b/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx @@ -98,6 +98,35 @@ export interface ViewSettingsField { * Absent means groupable. */ groupable?: boolean; + /** + * The field's type in the object's declaration, and whether it holds many + * values (`multiple: true`). The Group editors rank and pick by them + * (objectstack#36204); absent ⇒ ranked with the fields that suit grouping + * least, and never added by "Add group field" on its own. + */ + type?: string; + multiple?: boolean; +} + +/** + * objectstack#36204 — the types whose values many records share, so grouping + * by one gives a few groups worth reading: single select and radio (a status + * is one), a person, a linked record, a tick, a date. A field holding many + * values (`multiple: true`) is not among them. The Group editors list these + * fields first; the rest (a name, a free text, a number: nearly one value per + * record) follow, still offered. + */ +const GROUP_FRIENDLY_TYPES = new Set([ + 'select', 'radio', + 'user', 'lookup', 'master_detail', 'tree', + 'boolean', 'toggle', + 'date', 'datetime', +]); +/** The single-choice types "Add group field" groups by on its own. */ +const GROUP_DEFAULT_TYPES = new Set(['select', 'radio']); + +function suitsGrouping(f: ViewSettingsField): boolean { + return !!f.type && GROUP_FRIENDLY_TYPES.has(f.type) && f.multiple !== true; } /** @@ -106,13 +135,43 @@ export interface ViewSettingsField { * wide toolbar's, read it, so the two forms offer the same fields. A level that * already names a withheld field still shows: `GroupingEditor` mounts a value * its options do not carry, so the level can be removed. + * + * objectstack#36204 — in the reader's column order (`order`, as + * `orderFields` reads it), the fields that suit grouping first + * (`GROUP_FRIENDLY_TYPES`), then the rest, each part in that order. */ -export function groupFieldOptions(fields: readonly ViewSettingsField[]): Array<{ value: string; label: string }> { - return fields - .filter((f) => f.groupable !== false) +export function groupFieldOptions( + fields: readonly ViewSettingsField[], + order?: readonly string[], +): Array<{ value: string; label: string }> { + const offered = orderFields(fields, order).filter((f) => f.groupable !== false); + return [...offered.filter(suitsGrouping), ...offered.filter((f) => !suitsGrouping(f))] .map((f) => ({ value: f.name, label: f.label || f.name })); } +/** + * objectstack#36204 — the field "Add group field" adds, as `GroupingEditor`'s + * `pickAddField`: of the fields no level uses yet, the first single select or + * radio (`GROUP_DEFAULT_TYPES`, single-valued) in the order the editor lists + * them, a shown column before a hidden one. None ⇒ `undefined`: the editor + * opens its field dropdown and groups by nothing until a field is picked, + * where it used to group by the first column, a name as a rule, one group per + * record. + */ +export function pickGroupAddField( + fields: readonly ViewSettingsField[], + hidden?: ReadonlySet, +): (remaining: ReadonlyArray<{ value: string }>) => string | undefined { + const byName = new Map(fields.map((f) => [f.name, f])); + return (remaining) => { + const candidates = remaining.filter((option) => { + const f = byName.get(option.value); + return !!f && !!f.type && GROUP_DEFAULT_TYPES.has(f.type) && f.multiple !== true; + }); + return (candidates.find((option) => !hidden?.has(option.value)) ?? candidates[0])?.value; + }; +} + export type ViewSettingsDensityMode = 'compact' | 'comfortable' | 'spacious'; export interface ViewSettingsDensity { @@ -703,7 +762,8 @@ export function ViewSettingsContent(props: ViewSettingsPopoverProps & { closeMen
Date: Sun, 22 Nov 2026 03:26:21 +0000 Subject: [PATCH 2/4] fix(list): add-group asks for a field and offers only groupable ones "Add group field" adds no level by itself: the field dropdown opens and the list is grouped once a field is picked there; closing it without a pick writes nothing. The dropdown offers only single select or radio, tick, person and linked-record fields, single-valued. With none, the button is disabled and says why; until the object's field types are read it is disabled without a reason, and with no definition at all every column is offered as before. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgXeD1yUYqBJm8uzRrP --- .changeset/36204-group-add-default-field.md | 15 +- .../areas/records-forms.json | 4 +- ...grouping-editor-add-default-36204.test.tsx | 150 +++++++----- .../components/src/custom/grouping-editor.tsx | 71 ++++-- ui/packages/i18n/src/locales/ar.ts | 1 + ui/packages/i18n/src/locales/de.ts | 1 + ui/packages/i18n/src/locales/en.ts | 1 + ui/packages/i18n/src/locales/es.ts | 1 + ui/packages/i18n/src/locales/fr.ts | 1 + ui/packages/i18n/src/locales/ja.ts | 1 + ui/packages/i18n/src/locales/ko.ts | 1 + ui/packages/i18n/src/locales/pt-BR.ts | 1 + ui/packages/i18n/src/locales/ru.ts | 1 + ui/packages/i18n/src/locales/zh-Hans.ts | 1 + ui/packages/i18n/src/locales/zh-Hant.ts | 1 + ui/packages/plugin-list/src/ListView.tsx | 57 ++++- .../ListView.fieldListRead-11984.test.tsx | 24 +- .../ListView.groupAddDefault-36204.test.tsx | 230 +++++++++--------- .../src/__tests__/ListView.harness.test.tsx | 21 +- .../ListView.onGroupingChange-11860.test.tsx | 18 +- .../src/components/ViewSettingsPopover.tsx | 80 +++--- 21 files changed, 414 insertions(+), 267 deletions(-) diff --git a/.changeset/36204-group-add-default-field.md b/.changeset/36204-group-add-default-field.md index 44329cac5b2..e005421e138 100644 --- a/.changeset/36204-group-add-default-field.md +++ b/.changeset/36204-group-add-default-field.md @@ -1,19 +1,22 @@ --- '@object-ui/components': patch '@object-ui/plugin-list': patch +'@object-ui/i18n': patch --- -feat(list): "Add group field" groups by the view's first single select, and asks when there is none +feat(list): "Add group field" asks which field, and offers only fields that can group -Clause-②: yes (widening) — `@object-ui/components`'s `GroupingEditor` gains the optional prop `pickAddField`; `@object-ui/plugin-list`'s `ViewSettingsField` gains the optional members `type` and `multiple`, `groupFieldOptions` an optional second argument (the column order), and the module exports `pickGroupAddField`; nothing removed or renamed +Clause-②: yes (widening) — `@object-ui/components`'s `GroupingEditor` gains the optional props `askFieldOnAdd`, `fieldOptionsLoading` and `fieldLabel`, and its `labels` the optional `noFields`; `@object-ui/i18n` gains the key `list.noGroupableFields` in every locale; nothing removed or renamed Metadata-protocol: none On a list, 「添加分组字段」 / "Add group field" used to group at once by the list's first column, usually the record's name, so every record became a group of its own. Now, in the toolbar's Group panel and in the view settings menu's Group level alike: -- It groups at once by the first single select or radio field (a status is one) in the reader's column order, a shown column before a hidden one. A select that holds many values is not picked. -- A view with no such field is not grouped yet: the field dropdown opens, and the list is grouped once a field is picked there. Closing the dropdown without a pick changes nothing. -- The field dropdown lists the fields that suit grouping first (single select, radio, person, linked record, tick, date, each single-valued), then the rest, such as a name or a number, which can still be picked. Each part keeps the column order. +- It adds no field by itself and does not group. The field dropdown opens, and the list is grouped once a field is picked there. Closing the dropdown without a pick leaves the list as it was. +- The dropdown lists only the fields that can group: single select or radio (a status is one), tick (boolean or toggle), person, and linked record (lookup, master-detail, tree), each single-valued. Text, number, date and multi-select fields are not offered. The list's columns come first in the reader's column order, then the object's other groupable fields the reader may read. +- With no field that can group, the button is drawn disabled and says why: 「没有可以用来分组的字段」 / "No field here can group the list". +- Until the object's field types are read, the button is disabled without a reason. When no definition can be read at all, every column is offered, as before. +- A view already grouped by another kind of field keeps showing that grouping, and its level can still be changed or removed. - A second level follows the same rule among the fields no level uses yet. - The grouping is still a part of the list's draft: **Discard** and **Save** appear, and nothing is written. -`@object-ui/components`: `GroupingEditor`'s `pickAddField(remaining)` chooses the field "Add group field" adds from the fields no level uses, in `fieldOptions` order; `undefined` opens a row with an open field dropdown and writes the level only on a pick. Without the prop the first remaining field is added at once, as before. +`@object-ui/components`: with `askFieldOnAdd`, `GroupingEditor`'s "Add group field" opens a row whose field dropdown is already open and writes the level only on a pick. With no `fieldOptions` it draws the button disabled, explained by `labels.noFields`, or without a reason while `fieldOptionsLoading`. `fieldLabel(field)` labels a level whose field `fieldOptions` does not carry. Without these props the editor behaves as before. diff --git a/docs/qa/platform-checklist/areas/records-forms.json b/docs/qa/platform-checklist/areas/records-forms.json index f373bb6d3c7..4ab14c5ac31 100644 --- a/docs/qa/platform-checklist/areas/records-forms.json +++ b/docs/qa/platform-checklist/areas/records-forms.json @@ -3637,7 +3637,7 @@ "open showcase_task grid; screenshot", "resize a column (reorder two columns only on a grid that sets reorderableColumns; there is no runtime pin control — acceptance[0]), and set a row height on the Row height level of the list's options menu (the toolbar's options trigger, then 行高 / Row height: three choices, 紧凑 / 标准 / 宽松 — Compact / Standard / Spacious, ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx; a gallery's Row height level picks its card size the same way) — three modes, stored as rowHeight compact / medium / tall (the spec's five row heights compact/short/medium/tall/extra_tall narrow onto these three: objectui core normalize-list-view.ts DENSITY_MODE_TO_ROW_HEIGHT / ROW_HEIGHT_TO_DENSITY_MODE)", "reload; confirm the column widths and row-height restored — they are kept in this browser for the signed-in user, localStorage list-layout::showcase_task (perView..widths / rowHeight, objectstack#35955; before it the user's sys_user_preference ui.list.showcase_task row, objectui#12418). A column ORDER is not: since objectstack#35955 it is the list's unsaved draft, so a reload reopens on the view's own order unless it was saved into a view, with localStorage grid-columns-showcase_task[-] as the component's cache; the old per-view override through dataSource.updateViewConfig is retired (objectui#12504). Also open the list in a FRESH browser context as the same user: the layout does NOT follow the user there — it opens on the view's own widths and row height, by design (objectstack#35955)", - "group-by status ('Add group field' groups at once by the grid's first single select in column order, Status here, objectstack#36204; the field dropdown lists the fields that suit grouping first, and on a grid with no single select it opens with nothing grouped until a field is picked). A runtime grouping lives in the list's URL (uf__group, ui/packages/app-shell/src/views/objectViewListUrlState.ts), not in sys_user_preference: reloading that URL keeps it, a reload of the bare list URL reopens on the view's own grouping by design, and steps[6] reads it that way (QA run #33861). Confirm per-group headers appear and each group shows its record count — summarizeField (estimate_hours) is declared on the KANBAN config of task.view.ts, not on the grid, so grid groups carry counts; clear grouping and confirm the headers are removed cleanly", + "group-by status ('Add group field' adds no field and does not group: the field dropdown opens listing only the fields that can group, single select or radio, tick, person and linked record, so no Title, number or date, objectstack#36204; pick Status there. Closing it without a pick leaves the grid ungrouped, and a grid with no such field draws the button disabled with its reason). A runtime grouping lives in the list's URL (uf__group, ui/packages/app-shell/src/views/objectViewListUrlState.ts), not in sys_user_preference: reloading that URL keeps it, a reload of the bare list URL reopens on the view's own grouping by design, and steps[6] reads it that way (QA run #33861). Confirm per-group headers appear and each group shows its record count — summarizeField (estimate_hours) is declared on the KANBAN config of task.view.ts, not on the grid, so grid groups carry counts; clear grouping and confirm the headers are removed cleanly", "cross-check each group's count against a direct per-group server count (GET /api/v1/data/showcase_task filtered to that status, read its total)", "read the row-color rule the stock Grid view declares — rowColor on priority with the colors map low slate / medium blue / high amber / urgent red (examples/app-showcase/src/ui/views/task.view.ts); there is no runtime row-color authoring control — and confirm rows paint by it (useRowColor, the -100 tint of each name)", "reload once more; confirm every personalization this item stores survives (column widths, row height); capture a screenshot per variant" @@ -3753,7 +3753,7 @@ { "revision": 11, "date": "2026-11-22", - "change": "steps[3] re-pointed (objectstack#36204): 'Add group field' no longer pre-selects the first column; it groups at once by the first single select or radio in the reader's column order (Status on this grid), lists the fields that suit grouping first, and on a grid with none opens the field dropdown without grouping. No clause changed.", + "change": "steps[3] re-pointed (objectstack#36204): 'Add group field' no longer pre-selects the first column; it opens the field dropdown without grouping, the dropdown lists only fields that can group (single select or radio, tick, person, linked record), the grouping happens on the pick of Status, and with no such field the button is disabled with its reason. No clause changed.", "ref": "#36204" } ] diff --git a/ui/packages/components/src/__tests__/grouping-editor-add-default-36204.test.tsx b/ui/packages/components/src/__tests__/grouping-editor-add-default-36204.test.tsx index 56138d8ac67..46cd9d649bc 100644 --- a/ui/packages/components/src/__tests__/grouping-editor-add-default-36204.test.tsx +++ b/ui/packages/components/src/__tests__/grouping-editor-add-default-36204.test.tsx @@ -7,79 +7,45 @@ */ /** - * "Add group field" asks its host which field to add (objectstack#36204). + * "Add group field" adds no field by itself (objectstack#36204). * * It used to add the first field no level used, at once: in a list the first * column, a name as a rule, so the first click grouped the records one per - * group. `pickAddField` lets the host choose; when it has no field to offer - * the editor writes nothing and opens a row whose field dropdown is already - * open, and the level is written only once a field is picked there. + * group. With `askFieldOnAdd` the click writes nothing and opens a row whose + * field dropdown is already open; the level is written only once a field is + * picked there, and closing the dropdown without a pick writes nothing. + * With no field to offer the button stays, disabled, and `labels.noFields` + * says why; while `fieldOptionsLoading` it is disabled without a reason. * - * DIRECTION: without the prop every pin but the CONTROL fails on the old - * editor (the button wrote the first field at once, and no pending row - * existed); the CONTROL is the old behaviour, kept for a host that passes - * no `pickAddField`. + * DIRECTION: every pin but the CONTROLs fails on the old editor (the button + * wrote the first field at once, no pending row existed, and with no option + * the button was simply not drawn). The CONTROLs are the old behaviour, kept + * for a host that passes none of the new props. */ import { describe, it, expect, vi } from 'vitest'; import React from 'react'; import { render, screen, fireEvent, waitFor, within } from '@testing-library/react'; import '@testing-library/jest-dom'; -import { GroupingEditor, type GroupingConfigValue } from '../custom/grouping-editor'; +import { GroupingEditor, type GroupingConfigValue, type GroupingEditorProps } from '../custom/grouping-editor'; const FIELD_OPTIONS = [ - { value: 'name', label: 'Name' }, { value: 'status', label: 'Status' }, { value: 'owner', label: 'Owner' }, + { value: 'vip', label: 'VIP' }, ]; -function renderEditor( - value: GroupingConfigValue | undefined, - pickAddField?: (remaining: Array<{ value: string; label: string }>) => string | undefined, -) { +function renderEditor(value: GroupingConfigValue | undefined, extra: Partial = {}) { const onChange = vi.fn(); - const utils = render( - , - ); - return { ...utils, onChange }; + const props: GroupingEditorProps = { value, onChange, fieldOptions: FIELD_OPTIONS, askFieldOnAdd: true, ...extra }; + const utils = render(); + return { ...utils, onChange, props }; } const labels = (options: HTMLElement[]) => options.map((o) => o.textContent ?? ''); -describe('"Add group field" adds the field the host picks', () => { - it('adds the picked field at once', () => { - const { onChange } = renderEditor(undefined, () => 'status'); - fireEvent.click(screen.getByTestId('grouping-add')); - expect(onChange).toHaveBeenCalledTimes(1); - expect(onChange.mock.calls[0][0]).toStrictEqual({ - fields: [{ field: 'status', order: 'asc', collapsed: false }], - }); - }); - - it('is asked with the fields no level uses, in `fieldOptions` order, and appends the level', () => { - const pick = vi.fn((remaining: Array<{ value: string }>) => remaining[remaining.length - 1].value); - const { onChange } = renderEditor({ fields: [{ field: 'status', order: 'desc', collapsed: true }] }, pick); - fireEvent.click(screen.getByTestId('grouping-add')); - expect(pick.mock.calls[0][0].map((o) => o.value)).toEqual(['name', 'owner']); - expect(onChange.mock.calls[0][0]).toStrictEqual({ - fields: [ - { field: 'status', order: 'desc', collapsed: true }, - { field: 'owner', order: 'asc', collapsed: false }, - ], - }); - }); - - it('CONTROL: without `pickAddField` the first unused field is added at once, as before', () => { - const { onChange } = renderEditor(undefined); - fireEvent.click(screen.getByTestId('grouping-add')); - expect(onChange.mock.calls[0][0]).toStrictEqual({ - fields: [{ field: 'name', order: 'asc', collapsed: false }], - }); - }); -}); - -describe('no field picked: the field dropdown opens and nothing is written until a pick', () => { +describe('"Add group field" opens the field dropdown and writes nothing until a pick', () => { it('opens a row with its dropdown open, writes nothing, and hides the add button', async () => { - const { onChange } = renderEditor(undefined, () => undefined); + const { onChange } = renderEditor(undefined); fireEvent.click(screen.getByTestId('grouping-add')); expect(onChange).not.toHaveBeenCalled(); expect(screen.getByTestId('grouping-field-pending')).toBeInTheDocument(); @@ -87,32 +53,39 @@ describe('no field picked: the field dropdown opens and nothing is written until // No level yet: the list is not grouped. expect(screen.queryByTestId('grouping-field-0')).toBeNull(); const listbox = await screen.findByRole('listbox'); - expect(labels(within(listbox).getAllByRole('option'))).toEqual(['Name', 'Status', 'Owner']); + expect(labels(within(listbox).getAllByRole('option'))).toEqual(['Status', 'Owner', 'VIP']); }); it('a pick writes the level and the row becomes that level', async () => { - const { onChange, rerender } = renderEditor(undefined, () => undefined); + const { onChange, rerender, props } = renderEditor(undefined); fireEvent.click(screen.getByTestId('grouping-add')); const listbox = await screen.findByRole('listbox'); fireEvent.click(within(listbox).getAllByRole('option').find((o) => o.textContent === 'Owner')!); expect(onChange).toHaveBeenCalledTimes(1); const written = onChange.mock.calls[0][0]; expect(written).toStrictEqual({ fields: [{ field: 'owner', order: 'asc', collapsed: false }] }); - rerender( undefined} />); + rerender(); await waitFor(() => expect(screen.queryByTestId('grouping-field-pending')).toBeNull()); expect(screen.getByTestId('grouping-field-0')).toHaveTextContent('Owner'); expect(screen.getByTestId('grouping-add')).toBeInTheDocument(); }); - it('offers only the fields no level uses', async () => { - renderEditor({ fields: [{ field: 'name', order: 'asc', collapsed: false }] }, () => undefined); + it('a second level offers only the fields no level uses and appends', async () => { + const { onChange } = renderEditor({ fields: [{ field: 'status', order: 'desc', collapsed: true }] }); fireEvent.click(screen.getByTestId('grouping-add')); const listbox = await screen.findByRole('listbox'); - expect(labels(within(listbox).getAllByRole('option'))).toEqual(['Status', 'Owner']); + expect(labels(within(listbox).getAllByRole('option'))).toEqual(['Owner', 'VIP']); + fireEvent.click(within(listbox).getAllByRole('option').find((o) => o.textContent === 'VIP')!); + expect(onChange.mock.calls[0][0]).toStrictEqual({ + fields: [ + { field: 'status', order: 'desc', collapsed: true }, + { field: 'vip', order: 'asc', collapsed: false }, + ], + }); }); it('closing the dropdown without a pick drops the row and writes nothing', async () => { - const { onChange } = renderEditor(undefined, () => undefined); + const { onChange } = renderEditor(undefined); fireEvent.click(screen.getByTestId('grouping-add')); const listbox = await screen.findByRole('listbox'); fireEvent.keyDown(listbox, { key: 'Escape' }); @@ -120,4 +93,63 @@ describe('no field picked: the field dropdown opens and nothing is written until expect(onChange).not.toHaveBeenCalled(); expect(screen.getByTestId('grouping-add')).toBeInTheDocument(); }); + + it('CONTROL: without `askFieldOnAdd` the first unused field is added at once, as before', () => { + const { onChange } = renderEditor(undefined, { askFieldOnAdd: undefined }); + fireEvent.click(screen.getByTestId('grouping-add')); + expect(onChange.mock.calls[0][0]).toStrictEqual({ + fields: [{ field: 'status', order: 'asc', collapsed: false }], + }); + }); +}); + +describe('no field to offer: the button stays, disabled, and says why', () => { + it('with `labels.noFields` the button is disabled and described by the reason', () => { + const { onChange } = renderEditor(undefined, { fieldOptions: [], labels: { noFields: 'Nothing can group this' } }); + const button = screen.getByTestId('grouping-add'); + expect(button).toBeDisabled(); + const reason = screen.getByTestId('grouping-no-fields'); + expect(reason).toHaveTextContent('Nothing can group this'); + expect(button).toHaveAttribute('aria-describedby', reason.id); + fireEvent.click(button); + expect(onChange).not.toHaveBeenCalled(); + expect(screen.queryByTestId('grouping-field-pending')).toBeNull(); + }); + + it('while the options load the button is disabled without a reason', () => { + renderEditor(undefined, { fieldOptions: [], fieldOptionsLoading: true, labels: { noFields: 'Nothing can group this' } }); + const button = screen.getByTestId('grouping-add'); + expect(button).toBeDisabled(); + expect(button).not.toHaveAttribute('aria-describedby'); + expect(screen.queryByTestId('grouping-no-fields')).toBeNull(); + }); + + it('once the options arrive the button is enabled', async () => { + const { rerender, props } = renderEditor(undefined, { fieldOptions: [], fieldOptionsLoading: true }); + expect(screen.getByTestId('grouping-add')).toBeDisabled(); + rerender(); + expect(screen.getByTestId('grouping-add')).toBeEnabled(); + fireEvent.click(screen.getByTestId('grouping-add')); + expect(await screen.findByRole('listbox')).toBeInTheDocument(); + }); + + it('CONTROL: with no option and no `noFields`, no add button is drawn, as before', () => { + renderEditor(undefined, { fieldOptions: [], askFieldOnAdd: undefined }); + expect(screen.queryByTestId('grouping-add')).toBeNull(); + expect(screen.queryByTestId('grouping-no-fields')).toBeNull(); + }); +}); + +describe('a level grouped by a field the host does not offer', () => { + it('shows the label `fieldLabel` gives', () => { + renderEditor({ fields: [{ field: 'customer_name', order: 'asc', collapsed: false }] }, { + fieldLabel: (f) => (f === 'customer_name' ? 'Customer name' : undefined), + }); + expect(screen.getByTestId('grouping-field-0')).toHaveTextContent('Customer name'); + }); + + it('CONTROL: without `fieldLabel` it shows the field name', () => { + renderEditor({ fields: [{ field: 'customer_name', order: 'asc', collapsed: false }] }); + expect(screen.getByTestId('grouping-field-0')).toHaveTextContent('customer_name'); + }); }); diff --git a/ui/packages/components/src/custom/grouping-editor.tsx b/ui/packages/components/src/custom/grouping-editor.tsx index 1cf70721543..bb520b71805 100644 --- a/ui/packages/components/src/custom/grouping-editor.tsx +++ b/ui/packages/components/src/custom/grouping-editor.tsx @@ -31,14 +31,25 @@ export interface GroupingEditorProps { /** Available fields to group by. */ fieldOptions: Array<{ value: string; label: string }>; /** - * The field "Add group field" adds, chosen from the fields no level uses - * yet (`remaining`, in `fieldOptions` order). Returning `undefined` adds no - * level: a row with an open field dropdown appears instead, and the level is - * written only once a field is picked there; closing the dropdown without a - * pick drops the row and writes nothing (objectstack#36204). Absent, the - * first remaining field is added at once. + * objectstack#36204 — "Add group field" adds no field by itself: it opens a + * row whose field dropdown is already open, listing the fields no level + * uses yet, and the level is written only once a field is picked there. + * Closing the dropdown without a pick drops the row and writes nothing. + * Absent, the first unused field is added at once, as before. */ - pickAddField?: (remaining: Array<{ value: string; label: string }>) => string | undefined; + askFieldOnAdd?: boolean; + /** + * The field options are still being worked out (the host has not read the + * fields' types yet). With no option to offer, "Add group field" is drawn + * disabled, without the `noFields` reason, until they arrive. + */ + fieldOptionsLoading?: boolean; + /** + * The label of a field a level holds that `fieldOptions` does not carry (a + * view grouped by a field the host does not offer). Absent, or answering + * `undefined`, the level shows the field's name. + */ + fieldLabel?: (field: string) => string | undefined; /** Maximum nesting depth. Airtable defaults to 3. */ maxLevels?: number; className?: string; @@ -49,6 +60,12 @@ export interface GroupingEditorProps { removeTitle?: string; ascendingTitle?: string; descendingTitle?: string; + /** + * objectstack#36204 — with no field to offer, "Add group field" is drawn + * disabled and this says why. Absent, the editor draws no add button + * then, as before. + */ + noFields?: string; }; } @@ -79,7 +96,9 @@ export function GroupingEditor({ value, onChange, fieldOptions, - pickAddField, + askFieldOnAdd, + fieldOptionsLoading, + fieldLabel, maxLevels = 3, className, labels, @@ -87,10 +106,11 @@ export function GroupingEditor({ const L = { ...DEFAULT_LABELS, ...(labels || {}) }; const current = value?.fields ?? []; const usedFields = new Set(current.map((g) => g.field)); - // objectstack#36204 — "Add group field" found no field to add by itself - // (`pickAddField` answered `undefined`): a row asking for one is open, and - // nothing is written until a field is picked in it. + // objectstack#36204 — "Add group field" was pressed with `askFieldOnAdd`: + // a row asking for a field is open, and nothing is written until a field is + // picked in it. const [askingField, setAskingField] = React.useState(false); + const noFieldsId = React.useId(); const remaining = fieldOptions.filter((f) => !usedFields.has(f.value)); const writeFields = (next: GroupingFieldEntry[]) => { @@ -131,7 +151,7 @@ export function GroupingEditor({ {isOutsideOptions && ( - {g.field} + {fieldLabel?.(g.field) || g.field} )} {fieldOptions @@ -223,18 +243,39 @@ export function GroupingEditor({ data-testid="grouping-add" className="flex h-7 items-center gap-1 self-start rounded-md border border-dashed border-input bg-background px-2 text-xs text-muted-foreground hover:bg-muted hover:text-foreground max-sm:h-11" onClick={() => { - const field = pickAddField ? pickAddField(remaining) : remaining[0].value; - if (field === undefined) { + if (askFieldOnAdd) { setAskingField(true); return; } - writeFields([...current, { field, order: 'asc', collapsed: false }]); + writeFields([...current, { field: remaining[0].value, order: 'asc', collapsed: false }]); }} > {L.addGroup} )} + {/* objectstack#36204 — nothing to offer: the button stays, disabled, and + says why (`labels.noFields`), or waits for the options to load. */} + {current.length < maxLevels && fieldOptions.length === 0 && (fieldOptionsLoading || labels?.noFields) && ( +
+ + {!fieldOptionsLoading && ( +

+ {labels?.noFields} +

+ )} +
+ )}
); } diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 120b21bae5d..ac4367b3cba 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1114,6 +1114,7 @@ const ar = { layout: "التخطيط", resetToViewDefault: "إعادة التعيين إلى الإعدادات الافتراضية للعرض", addGroup: "إضافة حقل مجموعة", + noGroupableFields: "لا يوجد حقل يمكن التجميع حسبه", collapsedByDefault: "مطوي افتراضياً", removeGroup: "إزالة", groupingUnstoredNotice: "لا يمكن تجميع هذه القائمة حسب {{fields}}: تُحسب القيمة عند العرض ولا تُخزَّن. تُعرض القائمة دون هذا التجميع.", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 887d18748cc..eda07a8bf3f 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -993,6 +993,7 @@ const de = { layout: "Layout", resetToViewDefault: "Auf Standard der Ansicht zurücksetzen", addGroup: "Gruppenfeld hinzufügen", + noGroupableFields: "Kein Feld eignet sich zum Gruppieren", collapsedByDefault: "Standardmäßig eingeklappt", removeGroup: "Entfernen", groupingUnstoredNotice: "Diese Liste kann nicht nach {{fields}} gruppiert werden: Der Wert wird bei der Anzeige berechnet und nicht gespeichert. Die Liste wird ohne diese Gruppierung angezeigt.", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 3cfe8d26b90..07e37257295 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1288,6 +1288,7 @@ const en = { layout: 'Layout', resetToViewDefault: 'Reset to view default', addGroup: 'Add group field', + noGroupableFields: 'No field here can group the list', collapsedByDefault: 'Collapsed by default', removeGroup: 'Remove', groupingUnstoredNotice: 'This list cannot be grouped by {{fields}}: its value is calculated when shown, not stored. The list is shown without that grouping.', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index fb637668030..b854c1b56fc 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1026,6 +1026,7 @@ const es = { layout: "Diseño", resetToViewDefault: "Restablecer los valores predeterminados de la vista", addGroup: "Agregar campo de grupo", + noGroupableFields: "Ningún campo sirve para agrupar", collapsedByDefault: "Contraído por defecto", removeGroup: "Eliminar", groupingUnstoredNotice: "Esta lista no se puede agrupar por {{fields}}: su valor se calcula al mostrarse y no se almacena. La lista se muestra sin esa agrupación.", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index dc29c1abdc3..6914fbc77c3 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1021,6 +1021,7 @@ const fr = { layout: "Disposition", resetToViewDefault: "Rétablir les valeurs par défaut de la vue", addGroup: "Ajouter un champ de groupe", + noGroupableFields: "Aucun champ ne permet de grouper", collapsedByDefault: "Réduit par défaut", removeGroup: "Supprimer", groupingUnstoredNotice: "Cette liste ne peut pas être regroupée par {{fields}} : sa valeur est calculée à l’affichage et n’est pas stockée. La liste est affichée sans ce regroupement.", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index e2958736230..b69e8881d55 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -993,6 +993,7 @@ const ja = { layout: "レイアウト", resetToViewDefault: "ビューの既定に戻す", addGroup: "グループフィールドを追加", + noGroupableFields: "グループ化に使えるフィールドがありません", collapsedByDefault: "デフォルトで折りたたむ", removeGroup: "削除", groupingUnstoredNotice: "{{fields}} ではこの一覧をグループ化できません。値は表示時に計算され、保存されていません。このグループ化を除いて一覧を表示しています。", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index e59c88644e2..69d3b03386f 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -993,6 +993,7 @@ const ko = { layout: "레이아웃", resetToViewDefault: "보기 기본값으로 재설정", addGroup: "그룹 필드 추가", + noGroupableFields: "그룹화에 사용할 수 있는 필드가 없습니다", collapsedByDefault: "기본적으로 접힘", removeGroup: "제거", groupingUnstoredNotice: "{{fields}} 기준으로 이 목록을 그룹화할 수 없습니다. 값이 표시될 때 계산되며 저장되지 않습니다. 해당 그룹화 없이 목록을 표시합니다.", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index ec8cec204fd..235d2f76c72 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1021,6 +1021,7 @@ const pt = { layout: "Layout", resetToViewDefault: "Restaurar o padrão da exibição", addGroup: "Adicionar campo de grupo", + noGroupableFields: "Nenhum campo pode agrupar a lista", collapsedByDefault: "Recolhido por padrão", removeGroup: "Remover", groupingUnstoredNotice: "Esta lista não pode ser agrupada por {{fields}}: o valor é calculado ao ser exibido e não é armazenado. A lista é exibida sem esse agrupamento.", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index ca8a827371c..823399be5e4 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1055,6 +1055,7 @@ const ru = { layout: "Макет", resetToViewDefault: "Сбросить к настройкам представления", addGroup: "Добавить поле группировки", + noGroupableFields: "Нет полей для группировки", collapsedByDefault: "Свёрнуто по умолчанию", removeGroup: "Удалить", groupingUnstoredNotice: "Этот список нельзя сгруппировать по полю {{fields}}: его значение вычисляется при отображении и не хранится. Список показан без этой группировки.", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 561f324b67c..f1abf7115c7 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1020,6 +1020,7 @@ const zh = { layout: '布局', resetToViewDefault: '恢复视图默认设置', addGroup: '添加分组字段', + noGroupableFields: '没有可以用来分组的字段', collapsedByDefault: '默认折叠', removeGroup: '删除', groupingUnstoredNotice: '无法按 {{fields}} 分组:它的值在显示时计算,并未存储。列表已暂不按它分组显示。', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 87ef15640b0..6ae50a14d6a 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1020,6 +1020,7 @@ const zhHant = { layout: '佈局', resetToViewDefault: '恢復檢視預設設定', addGroup: '新增分組欄位', + noGroupableFields: '沒有可以用來分組的欄位', collapsedByDefault: '預設摺疊', removeGroup: '刪除', groupingUnstoredNotice: '無法按 {{fields}} 分組:它的值在顯示時計算,並未儲存。列表已暫不按它分組顯示。', diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 32b039cb51e..eb00d3e935f 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -19,7 +19,7 @@ import { ViewSettingsPopover, ViewSettingsContent, groupFieldOptions, - pickGroupAddField, + isGroupableField, type ViewSettingsField, PHONE_TOUCH_TARGET, useBelowSm, @@ -6530,8 +6530,8 @@ export const ListView = React.forwardRef(({ const label = objectDef?.fields?.[name]?.label; return typeof label === 'string' && label ? label : undefined; }; - // objectstack#36204 — and the declared type, which the Group editors rank - // and pick by (`groupFieldOptions`, `pickGroupAddField`). + // objectstack#36204 — and the declared type, which the Group editors + // offer a field by (`groupFieldOptions`). const groupability = (name: string): Pick => { const def = objectDef?.fields?.[name] as (SearchFieldMeta & { type?: unknown; multiple?: unknown }) | undefined; return { @@ -6564,6 +6564,48 @@ export const ListView = React.forwardRef(({ ? (schema.columnState as { order?: string[]; widths?: Record } | undefined)?.order : undefined; + // objectstack#36204 — what both Group editors offer: the fields of a type a + // list can be grouped by (`isGroupableField`: single select, radio, tick, + // person, linked record; one value each), the view's columns first in the + // reader's column order, then the object's other business fields of those + // types that the caller may read and the definition does not hide, in the + // definition's order. Until the definition's read answers nothing is + // offered and "Add group field" waits, disabled (`groupOptionsLoading`), so + // it never says "nothing to group by" before the types are known. A host + // with no definition to read (no `getObjectSchema`, or the read failed) + // knows no type: every column is offered then, as before. Plain per-render + // values, not memos (AGENTS.md #10). + const groupOptionsLoading = !objectDefLoaded; + const definedFields = objectDef?.fields as + | Record + | undefined; + const groupOptions: Array<{ value: string; label: string }> = groupOptionsLoading + ? [] + : !definedFields + ? groupFieldOptions(allFields, gridColumnOrder, false) + : [ + ...groupFieldOptions(allFields, gridColumnOrder), + ...Object.entries(definedFields).flatMap(([name, def]) => { + if (!def || allFields.some((f) => f.name === name)) return []; + if (def.hidden === true || def.system === true) return []; + if (!canReadField(perms, schema.objectName, name)) return []; + if (isVirtualSearchField(def as SearchFieldMeta)) return []; + if (!isGroupableField({ type: typeof def.type === 'string' ? def.type : undefined, multiple: def.multiple === true })) return []; + const label = typeof def.label === 'string' && def.label ? def.label : name; + return [{ value: name, label: tFieldLabel(name, label) }]; + }), + ]; + // The label a level shows for a field the editor does not offer (a view + // grouped by a text or number field keeps showing it, under its label). + const groupFieldLabel = (field: string): string | undefined => { + const column = allFields.find((f) => f.name === field); + if (column?.label) return column.label; + // A field the caller may not read keeps showing its name (objectui#11984). + if (!canReadField(perms, schema.objectName, field)) return undefined; + const label = definedFields?.[field]?.label; + return typeof label === 'string' && label ? tFieldLabel(field, label) : undefined; + }; + // objectui#11984 — what the two hide-fields lists (the toolbar popover and // the View settings section) are handed of `hiddenFields`. An entry naming a // field the caller may not read is WITHHELD from them: not listed, not @@ -7251,6 +7293,8 @@ export const ListView = React.forwardRef(({ showGroup={toolbarFlags.showGroup} groupingConfig={chosenGroupingConfig} setGroupingConfig={changeGrouping} + groupOptions={groupOptions} + groupOptionsLoading={groupOptionsLoading} showColor={toolbarFlags.showColor} rowColorConfig={offeredRowColorConfig} setRowColorConfig={setRowColorConfig} @@ -7645,13 +7689,16 @@ export const ListView = React.forwardRef(({
diff --git a/ui/packages/plugin-list/src/__tests__/ListView.fieldListRead-11984.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.fieldListRead-11984.test.tsx index b06ffd09e2a..a96264b0b99 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.fieldListRead-11984.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.fieldListRead-11984.test.tsx @@ -356,7 +356,9 @@ describe('every field list ListView and its toolbar offer asks the field read (o const sweep = await sweepToolbar(); expect(fieldListsOf(sweep)).toEqual(FIELD_LIST_TRIGGERS[layout]); for (const name of FIELD_LIST_TRIGGERS[layout]) { - expect(sweep.offered.get(name), name).toContain('Secret Note'); + // The Group editor offers only fields that can group (objectstack#36204): + // the textarea `secret_note` is not one, the select `secret_status` is. + expect(sweep.offered.get(name), name).toContain(name === 'Group' ? 'Secret Status' : 'Secret Note'); } expect(sweep.toolbarText).toContain('Secret Status'); }); @@ -500,10 +502,10 @@ describe('each field list, one pin per position (objectui#11984)', () => { await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2)); await waitFor(async () => expect(await hideFields()).toEqual(FIELD_LABELS)); expect(chips()).toEqual(['Status', 'Secret Status']); - // The level's own field is offered in its own dropdown, so all five are: - // the select fields first, as the Group editors rank them (objectstack#36204). + // The Group editor offers the select fields only (objectstack#36204), so + // both selects are, the unreadable one included. const group = await inPopover(toolbarButton(/^group/i), (c) => comboboxOptions(within(c).getByTestId('grouping-field-0'))); - expect(group).toEqual(['Status', 'Secret Status', 'Title', 'Priority', 'Secret Note']); + expect(group).toEqual(['Status', 'Secret Status']); }); }); @@ -521,19 +523,23 @@ describe('a stored configuration on an unreadable field is kept as stored (objec const content = await openPopover(toolbarButton(/^group/i)); const level = within(content).getByTestId('grouping-field-0'); expect(level).toHaveTextContent('secret_note'); - // The select field first, as the Group editors rank them (objectstack#36204). - expect(await comboboxOptions(level)).toEqual(['secret_note', 'Status', 'Title', 'Priority']); + // The Group editor offers the readable select alone (objectstack#36204). + expect(await comboboxOptions(level)).toEqual(['secret_note', 'Status']); expect(onGroupingChange).not.toHaveBeenCalled(); - // "Add group field" seeds a readable field (the first readable select, - // objectstack#36204), and the new level does not offer the unreadable one. + // "Add group field" opens the field dropdown (objectstack#36204), which + // does not offer the unreadable field; the pick is the new level. fireEvent.click(within(content).getByTestId('grouping-add')); + expect(onGroupingChange).not.toHaveBeenCalled(); + const offered = await screen.findByRole('listbox'); + expect(within(offered).getAllByRole('option').map(text)).toEqual(['Status']); + fireEvent.click(within(offered).getByRole('option', { name: 'Status' })); expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [ { field: 'secret_note', order: 'asc', collapsed: false }, { field: 'status', order: 'asc', collapsed: false }, ], }); - expect(await comboboxOptions(within(content).getByTestId('grouping-field-1'))).toEqual(['Status', 'Title', 'Priority']); + expect(await comboboxOptions(within(content).getByTestId('grouping-field-1'))).toEqual(['Status']); // Its own level can be removed. fireEvent.click(within(content).getByTestId('grouping-remove-0')); expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [{ field: 'status', order: 'asc', collapsed: false }] }); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.groupAddDefault-36204.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.groupAddDefault-36204.test.tsx index e01be94d8ff..f712ecc2904 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.groupAddDefault-36204.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.groupAddDefault-36204.test.tsx @@ -7,25 +7,29 @@ */ /** - * "Add group field" groups by the view's first single select, not its first - * column (objectstack#36204). + * "Add group field" asks for the field, and offers select-like fields only + * (objectstack#36204, the card as the maintainer rewrote it). * * It used to add the first field the editor listed, the list's first column, * a name as a rule: twelve customers became twelve groups of one. Now, in * both Group editors (the wide toolbar's panel and the View settings menu's * Group level): - * 1. the first single select or radio in the reader's column order is added - * at once, a shown column before a hidden one; - * 2. with none, nothing is grouped yet: the field dropdown opens, and the - * level is written once a field is picked; - * 3. the dropdown lists the fields that suit grouping first (select, radio, - * person, linked record, tick, date; single-valued), then the rest, each - * part in column order; - * 4. the change still goes only to `onGroupingChange` (the host's draft, + * 1. no field is added by the click: the field dropdown opens, the list is + * not grouped, and the level is written once a field is picked; closing + * the dropdown without a pick writes nothing; + * 2. the dropdown offers single select, radio, tick, person and linked + * record fields holding one value each: the view's columns first, then + * the object's other business fields of those types. Text, numbers, + * dates and many-valued fields are not offered; + * 3. with none to offer, the button is disabled and says why; while the + * definition is still being read it is disabled without a reason; + * 4. a view grouped by a field of another type keeps showing it, under its + * label, and can still be changed or removed; + * 5. the change still goes only to `onGroupingChange` (the host's draft, * objectstack#35955): the data source is asked to write nothing. * - * DIRECTION: on main every pin but the CONTROLs fails: the button added - * `name`, and the dropdown listed the columns in their own order. + * DIRECTION: on main every pin but the CONTROL fails: the button added + * `name` at once, every column was offered, and nothing was ever disabled. */ import { describe, it, expect, vi, afterEach } from 'vitest'; import { act, cleanup, render, screen, fireEvent, within } from '@testing-library/react'; @@ -34,7 +38,7 @@ import React from 'react'; import type { ListViewSchema } from '@object-ui/types'; import { SchemaRendererProvider } from '@object-ui/react'; import { ListView } from '../ListView'; -import { groupFieldOptions, pickGroupAddField, type ViewSettingsField } from '../components/ViewSettingsPopover'; +import { groupFieldOptions, isGroupableField, type ViewSettingsField } from '../components/ViewSettingsPopover'; const OBJECT = 'customer_36204'; @@ -46,9 +50,14 @@ const FIELDS: Record> = { tags: { type: 'select', multiple: true, label: 'Tags', options: [{ value: 'a', label: 'A' }] }, notes: { type: 'textarea', label: 'Notes' }, signed: { type: 'date', label: 'Signed on' }, + revenue: { type: 'currency', label: 'Revenue' }, + vip: { type: 'boolean', label: 'VIP' }, + parent: { type: 'lookup', label: 'Parent account', reference: OBJECT }, + internal_code: { type: 'select', label: 'Internal code', hidden: true, options: [{ value: 'x', label: 'X' }] }, + created_by: { type: 'lookup', label: 'Created by', reference: 'sys_user', system: true }, }; -function mount(schemaExtra: Record) { +function mount(schemaExtra: Record, definition: Promise | null = Promise.resolve({ name: OBJECT, fields: FIELDS })) { const dataSource = { find: vi.fn().mockResolvedValue({ data: [{ id: '1', name: 'Acme', industry: 'it' }], total: 1 }), queryGroupHeaders: vi.fn().mockResolvedValue([]), @@ -56,7 +65,7 @@ function mount(schemaExtra: Record) { create: vi.fn(), update: vi.fn(), delete: vi.fn(), - getObjectSchema: vi.fn().mockResolvedValue({ name: OBJECT, fields: FIELDS }), + ...(definition ? { getObjectSchema: vi.fn(() => definition) } : {}), }; const onGroupingChange = vi.fn(); const schema = { @@ -74,8 +83,8 @@ function mount(schemaExtra: Record) { return { dataSource, onGroupingChange }; } -async function definitionRead(dataSource: { getObjectSchema: ReturnType }) { - await vi.waitFor(() => expect(dataSource.getObjectSchema).toHaveBeenCalled()); +async function definitionRead(dataSource: { getObjectSchema?: ReturnType }) { + if (dataSource.getObjectSchema) await vi.waitFor(() => expect(dataSource.getObjectSchema).toHaveBeenCalled()); await act(async () => {}); } @@ -92,6 +101,11 @@ async function openDisplayGroup(): Promise { return content; } +const OPENERS = [ + ['the toolbar Group panel', false, openToolbarGroup], + ['the View settings Group level', true, openDisplayGroup], +] as const; + async function listboxLabels(): Promise { const listbox = await screen.findByRole('listbox'); return within(listbox).getAllByRole('option').map((o) => o.textContent ?? ''); @@ -101,108 +115,106 @@ const level = (field: string) => ({ field, order: 'asc', collapsed: false }); afterEach(() => cleanup()); -describe('"Add group field" adds the first single select (objectstack#36204)', () => { - const columns = ['name', 'owner', 'industry', 'notes']; - - it('the toolbar Group panel groups by Industry, not by the first column', async () => { - const { dataSource, onGroupingChange } = mount({ columns }); - await definitionRead(dataSource); - const panel = await openToolbarGroup(); - fireEvent.click(within(panel).getByTestId('grouping-add')); - expect(onGroupingChange).toHaveBeenCalledTimes(1); - expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('industry')] }); - // A draft for the host: the data source is asked to write nothing. - expect(dataSource.create).not.toHaveBeenCalled(); - expect(dataSource.update).not.toHaveBeenCalled(); - expect(dataSource.delete).not.toHaveBeenCalled(); - }); +afterEach(() => cleanup()); - it('the View settings Group level does the same', async () => { - const { dataSource, onGroupingChange } = mount({ columns, compactToolbar: true }); - await definitionRead(dataSource); - const content = await openDisplayGroup(); - fireEvent.click(within(content).getByTestId('grouping-add')); - expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('industry')] }); - }); +describe('"Add group field" opens the field dropdown and groups only on a pick (objectstack#36204)', () => { + const columns = ['name', 'industry', 'owner', 'notes', 'signed', 'revenue', 'tags']; + + for (const [where, compactToolbar, open] of OPENERS) { + it(`${where}: the click writes nothing and opens the dropdown; a pick is the level`, async () => { + const { dataSource, onGroupingChange } = mount({ columns, compactToolbar }); + await definitionRead(dataSource); + const panel = await open(); + fireEvent.click(within(panel).getByTestId('grouping-add')); + expect(onGroupingChange).not.toHaveBeenCalled(); + expect(within(panel).queryByTestId('grouping-field-0')).toBeNull(); + expect(within(panel).getByTestId('grouping-field-pending')).toBeInTheDocument(); + // The view's select-like columns, then the object's other ones; no + // name, text, date, number or many-valued select. + expect(await listboxLabels()).toEqual(['Industry', 'Owner', 'Stage', 'VIP', 'Parent account']); + fireEvent.click(within(screen.getByRole('listbox')).getByRole('option', { name: 'Industry' })); + expect(onGroupingChange).toHaveBeenCalledTimes(1); + expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('industry')] }); + // A draft for the host: the data source is asked to write nothing. + expect(dataSource.create).not.toHaveBeenCalled(); + expect(dataSource.update).not.toHaveBeenCalled(); + expect(dataSource.delete).not.toHaveBeenCalled(); + }); - it('the dropdown lists Owner and Industry ahead of Customer name, in both editors', async () => { - const { dataSource } = mount({ columns, grouping: { fields: [level('industry')] } }); - await definitionRead(dataSource); - const panel = await openToolbarGroup(); - fireEvent.keyDown(within(panel).getByTestId('grouping-field-0'), { key: 'ArrowDown' }); - expect(await listboxLabels()).toEqual(['Owner', 'Industry', 'Customer name', 'Notes']); - cleanup(); - - const second = mount({ columns, compactToolbar: true, grouping: { fields: [level('industry')] } }); - await definitionRead(second.dataSource); - const content = await openDisplayGroup(); - fireEvent.keyDown(within(content).getByTestId('grouping-field-0'), { key: 'ArrowDown' }); - expect(await listboxLabels()).toEqual(['Owner', 'Industry', 'Customer name', 'Notes']); - }); + it(`${where}: closing the dropdown without a pick writes nothing`, async () => { + const { dataSource, onGroupingChange } = mount({ columns, compactToolbar }); + await definitionRead(dataSource); + const panel = await open(); + fireEvent.click(within(panel).getByTestId('grouping-add')); + fireEvent.keyDown(await screen.findByRole('listbox'), { key: 'Escape' }); + await vi.waitFor(() => expect(within(panel).queryByTestId('grouping-field-pending')).toBeNull()); + expect(onGroupingChange).not.toHaveBeenCalled(); + expect(within(panel).getByTestId('grouping-add')).toBeEnabled(); + }); - it('follows the reader\'s column order: the select drawn first wins', async () => { - const { dataSource, onGroupingChange } = mount({ - columns: ['name', 'industry', 'stage'], - columnState: { order: ['stage', 'name', 'industry'] }, + it(`${where}: no groupable field — the button is disabled and says why`, async () => { + const { dataSource } = mount({ columns: ['name', 'notes', 'signed', 'revenue', 'tags'], compactToolbar }, Promise.resolve({ + name: OBJECT, + fields: { name: FIELDS.name, notes: FIELDS.notes, signed: FIELDS.signed, revenue: FIELDS.revenue, tags: FIELDS.tags }, + })); + await definitionRead(dataSource); + const panel = await open(); + expect(within(panel).getByTestId('grouping-add')).toBeDisabled(); + expect(within(panel).getByTestId('grouping-no-fields')).toHaveTextContent('No field here can group the list'); + expect(within(panel).getByTestId('grouping-add')).toHaveAttribute('aria-describedby', within(panel).getByTestId('grouping-no-fields').id); }); + } + + it('the second level offers the same fields, less the one in use', async () => { + const { dataSource, onGroupingChange } = mount({ columns, grouping: { fields: [level('industry')] } }); await definitionRead(dataSource); const panel = await openToolbarGroup(); fireEvent.click(within(panel).getByTestId('grouping-add')); - expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('stage')] }); + expect(onGroupingChange).not.toHaveBeenCalled(); + expect(await listboxLabels()).toEqual(['Owner', 'Stage', 'VIP', 'Parent account']); + fireEvent.click(within(screen.getByRole('listbox')).getByRole('option', { name: 'Owner' })); + expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('industry'), level('owner')] }); }); - it('a shown select is picked before a hidden one; a hidden one when none is shown', async () => { - const first = mount({ columns: ['name', 'industry', 'stage'], hiddenFields: ['industry'] }); - await definitionRead(first.dataSource); - fireEvent.click(within(await openToolbarGroup()).getByTestId('grouping-add')); - expect(first.onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('stage')] }); - cleanup(); - - const second = mount({ columns: ['name', 'industry'], hiddenFields: ['industry'] }); - await definitionRead(second.dataSource); + it('the columns come in the reader\'s column order', async () => { + const { dataSource } = mount({ columns: ['name', 'industry', 'owner'], columnState: { order: ['owner', 'name', 'industry'] } }); + await definitionRead(dataSource); fireEvent.click(within(await openToolbarGroup()).getByTestId('grouping-add')); - expect(second.onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('industry')] }); + expect((await listboxLabels()).slice(0, 2)).toEqual(['Owner', 'Industry']); }); - it('the second level follows the same rule: the next unused select', async () => { - const { dataSource, onGroupingChange } = mount({ - columns: ['name', 'industry', 'stage'], - grouping: { fields: [level('industry')] }, - }); + it('a view grouped by a field of another type keeps it, under its label, and can change it', async () => { + const { dataSource, onGroupingChange } = mount({ columns, grouping: { fields: [level('name')] } }); await definitionRead(dataSource); - fireEvent.click(within(await openToolbarGroup()).getByTestId('grouping-add')); - expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('industry'), level('stage')] }); + const panel = await openToolbarGroup(); + const trigger = within(panel).getByTestId('grouping-field-0'); + expect(trigger).toHaveTextContent('Customer name'); + fireEvent.keyDown(trigger, { key: 'ArrowDown' }); + expect(await listboxLabels()).toEqual(['Customer name', 'Industry', 'Owner', 'Stage', 'VIP', 'Parent account']); + fireEvent.click(within(screen.getByRole('listbox')).getByRole('option', { name: 'Industry' })); + expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('industry')] }); }); -}); -describe('a view with no single select: the dropdown opens and nothing is grouped yet', () => { - // `tags` is a select holding many values: not a default. - const columns = ['name', 'owner', 'tags', 'signed']; - - it('the toolbar Group panel: no write until a pick, then the picked field', async () => { - const { dataSource, onGroupingChange } = mount({ columns }); - await definitionRead(dataSource); + it('while the definition is being read the button waits, disabled, without a reason', async () => { + let answer: (value: unknown) => void = () => {}; + const { dataSource } = mount({ columns }, new Promise((resolve) => { answer = resolve; })); + await vi.waitFor(() => expect(dataSource.getObjectSchema).toHaveBeenCalled()); const panel = await openToolbarGroup(); - fireEvent.click(within(panel).getByTestId('grouping-add')); - expect(onGroupingChange).not.toHaveBeenCalled(); - expect(within(panel).queryByTestId('grouping-field-0')).toBeNull(); - expect(await listboxLabels()).toEqual(['Owner', 'Signed on', 'Customer name', 'Tags']); - fireEvent.click(within(screen.getByRole('listbox')).getByRole('option', { name: 'Owner' })); - expect(onGroupingChange).toHaveBeenCalledTimes(1); - expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('owner')] }); + expect(within(panel).getByTestId('grouping-add')).toBeDisabled(); + expect(within(panel).queryByTestId('grouping-no-fields')).toBeNull(); + await act(async () => { answer({ name: OBJECT, fields: FIELDS }); }); + expect(within(panel).getByTestId('grouping-add')).toBeEnabled(); }); - it('the View settings Group level does the same', async () => { - const { dataSource, onGroupingChange } = mount({ columns, compactToolbar: true }); + it('CONTROL: a host with no definition to read offers every column, as before', async () => { + const { dataSource } = mount({ columns: ['name', 'industry', 'notes'] }, null); await definitionRead(dataSource); - const content = await openDisplayGroup(); - fireEvent.click(within(content).getByTestId('grouping-add')); - expect(onGroupingChange).not.toHaveBeenCalled(); - expect(await listboxLabels()).toEqual(['Owner', 'Signed on', 'Customer name', 'Tags']); + fireEvent.click(within(await openToolbarGroup()).getByTestId('grouping-add')); + expect(await listboxLabels()).toEqual(['name', 'industry', 'notes']); }); }); -describe('the ranking and the pick, as functions', () => { +describe('the offer, as functions', () => { const fields: ViewSettingsField[] = [ { name: 'name', label: 'Name', type: 'text' }, { name: 'tags', label: 'Tags', type: 'select', multiple: true }, @@ -210,27 +222,23 @@ describe('the ranking and the pick, as functions', () => { { name: 'calc', label: 'Calc', type: 'formula', groupable: false }, { name: 'when', label: 'When', type: 'datetime' }, { name: 'parent', label: 'Parent', type: 'lookup' }, + { name: 'people', label: 'People', type: 'user', multiple: true }, { name: 'status', label: 'Status', type: 'select' }, { name: 'untyped', label: 'Untyped' }, ]; - it('suits-grouping types first, the rest after, each in column order; formulas left out', () => { - expect(groupFieldOptions(fields).map((o) => o.value)) - .toEqual(['flag', 'when', 'parent', 'status', 'name', 'tags', 'untyped']); - }); - - it('the column order a reader set comes first', () => { - expect(groupFieldOptions(fields, ['status', 'name']).map((o) => o.value)) - .toEqual(['status', 'flag', 'when', 'parent', 'name', 'tags', 'untyped']); + it('only single-valued select, radio, tick, person and linked-record fields', () => { + expect(groupFieldOptions(fields).map((o) => o.value)).toEqual(['flag', 'parent', 'status']); + expect(['select', 'radio', 'boolean', 'toggle', 'user', 'lookup', 'master_detail', 'tree'].every((type) => isGroupableField({ type }))).toBe(true); + expect(['text', 'number', 'currency', 'date', 'datetime', 'multiselect', 'checkboxes', 'formula'].some((type) => isGroupableField({ type }))).toBe(false); }); - it('picks the first single-valued select or radio among the remaining, in the order given', () => { - const pick = pickGroupAddField(fields); - expect(pick(groupFieldOptions(fields))).toBe('status'); - expect(pick(groupFieldOptions(fields).filter((o) => o.value !== 'status'))).toBeUndefined(); + it('in the column order a reader set', () => { + expect(groupFieldOptions(fields, ['status', 'flag']).map((o) => o.value)).toEqual(['status', 'flag', 'parent']); }); - it('CONTROL: a field with no declared type is never picked, only listed', () => { - expect(pickGroupAddField([{ name: 'untyped' }])([{ value: 'untyped' }])).toBeUndefined(); + it('CONTROL: with no type known every field but the refused formula is offered, as before', () => { + expect(groupFieldOptions(fields, undefined, false).map((o) => o.value)) + .toEqual(['name', 'tags', 'flag', 'when', 'parent', 'people', 'status', 'untyped']); }); }); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx index a4319cb8e42..78ebcefd5d3 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx @@ -3439,12 +3439,15 @@ describe('ListView.groupPickerUnstored-32631', () => { const TITLE = { field: 'display_title', order: 'asc' as const, collapsed: false }; const STATUS = { field: 'status', order: 'asc' as const, collapsed: false }; - const objectDef = (titleType: 'formula' | 'text') => ({ + // objectstack#36204 — the Group editors offer select-like fields only, so + // the stored fields here are selects: the formula is what these pins are + // about, and a select formula (`returnType`) is still a formula. + const objectDef = (titleType: 'formula' | 'text' | 'select') => ({ name: OBJECT, fields: { display_title: { type: titleType, label: 'Title', ...(titleType === 'formula' ? { expression: 'subject' } : {}) }, - subject: { type: 'text', label: 'Subject' }, - status: { type: 'text', label: 'Status' }, + subject: { type: 'select', label: 'Subject' }, + status: { type: 'select', label: 'Status' }, }, }); @@ -3452,7 +3455,7 @@ describe('ListView.groupPickerUnstored-32631', () => { let previousGrid: ReturnType; function mount(opts: { - titleType?: 'formula' | 'text'; + titleType?: 'formula' | 'text' | 'select'; compactToolbar?: boolean; grouping?: { fields: Array }; viewGrouping?: { fields: Array } | undefined; @@ -3509,9 +3512,8 @@ describe('ListView.groupPickerUnstored-32631', () => { }); describe('the Group editors do not offer a formula field (objectstack#32631)', () => { - // objectstack#36204 — no field here is a select, so "Add group field" - // groups by nothing yet: it opens the field dropdown, and that list is - // the one these pins read. + // objectstack#36204 — "Add group field" groups by nothing yet: it opens + // the field dropdown, and that list is the one these pins read. async function addAndRead(scope: { getByTestId: (id: string) => HTMLElement }): Promise { fireEvent.click(scope.getByTestId('grouping-add')); const listbox = await screen.findByRole('listbox'); @@ -3541,14 +3543,15 @@ describe('ListView.groupPickerUnstored-32631', () => { expect(onGroupingChange).not.toHaveBeenCalled(); }); - it('CONTROL — the same field stored (`text`) is offered first, in both editors', async () => { - const { onGroupingChange } = mount({ titleType: 'text' }); + it('CONTROL — the same field stored (a `select`) is offered first', async () => { + const { onGroupingChange } = mount({ titleType: 'select' }); await screen.findByTestId('grid-stub'); fireEvent.click(screen.getByRole('button', { name: /group/i })); await screen.findByTestId('group-field-list'); expect(await addAndRead(screen)).toEqual(['Title', 'Subject', 'Status']); fireEvent.click(within(screen.getByRole('listbox')).getByRole('option', { name: 'Title' })); expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [TITLE] }); + expect(await openOptions(screen.getByTestId('grouping-field-0'))).toEqual(['Title', 'Subject', 'Status']); }); }); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.onGroupingChange-11860.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.onGroupingChange-11860.test.tsx index a654e968539..19cb29b679b 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.onGroupingChange-11860.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.onGroupingChange-11860.test.tsx @@ -37,8 +37,8 @@ import { ListView } from '../ListView'; /** A partial stub: only the members the list's mount path calls. */ const dataSource = { find: vi.fn().mockResolvedValue([]), - // objectstack#36204 — the declared types "Add group field" picks by: it - // adds the first single select (`status`) at once. + // objectstack#36204 — the declared types the Group editors offer by: + // `status`, the one select, is the field offered. getObjectSchema: vi.fn().mockResolvedValue({ name: 'contacts', fields: { @@ -66,12 +66,19 @@ function schemaWith(extra: Partial = {}): ListViewSchema { } as ListViewSchema; } -/** Wait until the object's declaration is read: the Group editors pick by its types. */ +/** Wait until the object's declaration is read: the Group editors offer by its types. */ async function definitionRead() { await vi.waitFor(() => expect(dataSource.getObjectSchema).toHaveBeenCalled()); await act(async () => {}); } +/** "Add group field" opens the field dropdown (objectstack#36204); pick `label` in it. */ +async function pickNewLevel(label: string) { + fireEvent.click(screen.getByTestId('grouping-add')); + const listbox = await screen.findByRole('listbox'); + fireEvent.click(within(listbox).getByRole('option', { name: label })); +} + function mount(schema: ListViewSchema, onGroupingChange: (g: GroupingConfig | undefined) => void) { const view = (s: ListViewSchema) => ( @@ -103,7 +110,7 @@ describe('ListView reports a user grouping change to its host (objectui#11860)', await vi.waitFor(() => expect(screen.getByTestId('group-field-list')).toBeInTheDocument()); await definitionRead(); - fireEvent.click(screen.getByTestId('grouping-add')); + await pickNewLevel('Status'); expect(onGroupingChange).toHaveBeenCalledTimes(1); const added = onGroupingChange.mock.calls[0][0] as GroupingConfig; expectSpecShape(added); @@ -143,7 +150,8 @@ describe('ListView reports a user grouping change to its host (objectui#11860)', // Grouping is a level of the Display menu. fireEvent.click(within(content).getByTestId('options-row-group')); await definitionRead(); - fireEvent.click(await within(content).findByTestId('grouping-add')); + await within(content).findByTestId('grouping-add'); + await pickNewLevel('Status'); expect(onGroupingChange).toHaveBeenCalledTimes(1); expectSpecShape(onGroupingChange.mock.calls[0][0]); expect(onGroupingChange.mock.calls[0][0].fields[0].field).toBe('status'); diff --git a/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx b/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx index f290732553f..251eb61b9c6 100644 --- a/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx +++ b/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx @@ -100,33 +100,29 @@ export interface ViewSettingsField { groupable?: boolean; /** * The field's type in the object's declaration, and whether it holds many - * values (`multiple: true`). The Group editors rank and pick by them - * (objectstack#36204); absent ⇒ ranked with the fields that suit grouping - * least, and never added by "Add group field" on its own. + * values (`multiple: true`). The Group editors offer a field by them + * (objectstack#36204); absent ⇒ not offered there while types are known. */ type?: string; multiple?: boolean; } /** - * objectstack#36204 — the types whose values many records share, so grouping - * by one gives a few groups worth reading: single select and radio (a status - * is one), a person, a linked record, a tick, a date. A field holding many - * values (`multiple: true`) is not among them. The Group editors list these - * fields first; the rest (a name, a free text, a number: nearly one value per - * record) follow, still offered. + * objectstack#36204 — the types a list can be grouped by, as the maintainer + * set them: single select and radio (a status is a `select`), a tick + * (`boolean`, `toggle`), a person (`user`) and a linked record (`lookup`, + * `master_detail`, `tree`), each holding one value. Text, numbers, dates and + * many-valued fields are not offered. */ -const GROUP_FRIENDLY_TYPES = new Set([ +const GROUPABLE_TYPES = new Set([ 'select', 'radio', - 'user', 'lookup', 'master_detail', 'tree', 'boolean', 'toggle', - 'date', 'datetime', + 'user', 'lookup', 'master_detail', 'tree', ]); -/** The single-choice types "Add group field" groups by on its own. */ -const GROUP_DEFAULT_TYPES = new Set(['select', 'radio']); -function suitsGrouping(f: ViewSettingsField): boolean { - return !!f.type && GROUP_FRIENDLY_TYPES.has(f.type) && f.multiple !== true; +/** Whether the Group editors offer a field of this declaration (`GROUPABLE_TYPES`, one value). */ +export function isGroupableField(f: Pick): boolean { + return !!f.type && GROUPABLE_TYPES.has(f.type) && f.multiple !== true; } /** @@ -136,42 +132,22 @@ function suitsGrouping(f: ViewSettingsField): boolean { * already names a withheld field still shows: `GroupingEditor` mounts a value * its options do not carry, so the level can be removed. * - * objectstack#36204 — in the reader's column order (`order`, as - * `orderFields` reads it), the fields that suit grouping first - * (`GROUP_FRIENDLY_TYPES`), then the rest, each part in that order. + * objectstack#36204 — and, while the fields' types are known (`typesKnown`, + * the default), only those of a groupable type (`isGroupableField`), in the + * reader's column order (`order`, as `orderFields` reads it). With no type + * known at all (the host has no object definition) every field is offered, + * as before: nothing tells them apart. */ export function groupFieldOptions( fields: readonly ViewSettingsField[], order?: readonly string[], + typesKnown = true, ): Array<{ value: string; label: string }> { - const offered = orderFields(fields, order).filter((f) => f.groupable !== false); - return [...offered.filter(suitsGrouping), ...offered.filter((f) => !suitsGrouping(f))] + return orderFields(fields, order) + .filter((f) => f.groupable !== false && (!typesKnown || isGroupableField(f))) .map((f) => ({ value: f.name, label: f.label || f.name })); } -/** - * objectstack#36204 — the field "Add group field" adds, as `GroupingEditor`'s - * `pickAddField`: of the fields no level uses yet, the first single select or - * radio (`GROUP_DEFAULT_TYPES`, single-valued) in the order the editor lists - * them, a shown column before a hidden one. None ⇒ `undefined`: the editor - * opens its field dropdown and groups by nothing until a field is picked, - * where it used to group by the first column, a name as a rule, one group per - * record. - */ -export function pickGroupAddField( - fields: readonly ViewSettingsField[], - hidden?: ReadonlySet, -): (remaining: ReadonlyArray<{ value: string }>) => string | undefined { - const byName = new Map(fields.map((f) => [f.name, f])); - return (remaining) => { - const candidates = remaining.filter((option) => { - const f = byName.get(option.value); - return !!f && !!f.type && GROUP_DEFAULT_TYPES.has(f.type) && f.multiple !== true; - }); - return (candidates.find((option) => !hidden?.has(option.value)) ?? candidates[0])?.value; - }; -} - export type ViewSettingsDensityMode = 'compact' | 'comfortable' | 'spacious'; export interface ViewSettingsDensity { @@ -236,6 +212,13 @@ export interface ViewSettingsPopoverProps { showGroup?: boolean; groupingConfig?: any; setGroupingConfig?: (next: any) => void; + /** + * objectstack#36204 — the fields the Group level offers, as the host works + * them out for both Group editors, and whether it is still reading their + * types. Absent ⇒ `groupFieldOptions(allFields, fieldOrder)`. + */ + groupOptions?: Array<{ value: string; label: string }>; + groupOptionsLoading?: boolean; showColor?: boolean; rowColorConfig?: { field: string; colors?: Record } | undefined; @@ -568,6 +551,8 @@ export function ViewSettingsContent(props: ViewSettingsPopoverProps & { closeMen showGroup, groupingConfig, setGroupingConfig, + groupOptions, + groupOptionsLoading, showColor, rowColorConfig, setRowColorConfig, @@ -762,13 +747,16 @@ export function ViewSettingsContent(props: ViewSettingsPopoverProps & { closeMen
setGroupingConfig(next as any)} /> From 953c8cbf95bde0828c0fc321327f9a11b233a2c3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 03:48:40 +0000 Subject: [PATCH 3/4] fix(list): add-group offers the record owner, not provenance The group dropdown's extra fields now follow the Filter panel's tiers: business fields, then system fields such as the owner. Created by and updated by are offered only when the view shows them as a column, so an object without a person or choice field of its own still says it has nothing to group by. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgXeD1yUYqBJm8uzRrP --- .changeset/36204-group-add-default-field.md | 2 +- ui/packages/plugin-list/src/ListView.tsx | 31 +++++++++++++------ .../ListView.groupAddDefault-36204.test.tsx | 26 +++++++++++----- 3 files changed, 40 insertions(+), 19 deletions(-) diff --git a/.changeset/36204-group-add-default-field.md b/.changeset/36204-group-add-default-field.md index e005421e138..84206c7ac8e 100644 --- a/.changeset/36204-group-add-default-field.md +++ b/.changeset/36204-group-add-default-field.md @@ -12,7 +12,7 @@ Metadata-protocol: none On a list, 「添加分组字段」 / "Add group field" used to group at once by the list's first column, usually the record's name, so every record became a group of its own. Now, in the toolbar's Group panel and in the view settings menu's Group level alike: - It adds no field by itself and does not group. The field dropdown opens, and the list is grouped once a field is picked there. Closing the dropdown without a pick leaves the list as it was. -- The dropdown lists only the fields that can group: single select or radio (a status is one), tick (boolean or toggle), person, and linked record (lookup, master-detail, tree), each single-valued. Text, number, date and multi-select fields are not offered. The list's columns come first in the reader's column order, then the object's other groupable fields the reader may read. +- The dropdown lists only the fields that can group: single select or radio (a status is one), tick (boolean or toggle), person, and linked record (lookup, master-detail, tree), each single-valued. Text, number, date and multi-select fields are not offered. The list's columns come first in the reader's column order, then the object's other groupable fields the reader may read, business fields before system ones such as the record owner. Created by and updated by are offered only when the view shows them as a column. - With no field that can group, the button is drawn disabled and says why: 「没有可以用来分组的字段」 / "No field here can group the list". - Until the object's field types are read, the button is disabled without a reason. When no definition can be read at all, every column is offered, as before. - A view already grouped by another kind of field keeps showing that grouping, and its level can still be changed or removed. diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index eb00d3e935f..34b71870e8e 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -60,7 +60,7 @@ import { SchemaRenderer, useNavigationOverlay, classifyLoadError, answeredLoadFa import type { LoadErrorKind, AnsweredLoadFailure } from '@object-ui/react'; import { useDensityMode, resolveInlineAriaProps } from '@object-ui/react'; import type { DataTableSchema, DependsOnInput, ListViewSchema, ObjectMapConfig } from '@object-ui/types'; -import { detectStatusField, isSystemManagedField } from '@object-ui/types'; +import { AUDIT_FIELD_NAMES, detectStatusField, isSystemManagedField } from '@object-ui/types'; import { usePullToRefresh } from '@object-ui/mobile'; import { type ListViewVisualization, resolveConditionalFormatting, buildExpandFields, buildExportFileName, resolveAffordance, isObjectExportOffered, type SchemaLike, partitionRowsByPredicate, normalizeListViewSchema, isListViewVisualization, rowHeightToDensityMode, mergeFilterNodes, toFilterNodeSafely, FilterOperatorError, columnIdentity, collectPredicateFieldRefs, collectGroupingFieldRefs, listViewPredicates, PLATFORM_RECORD_COLUMNS, EXPANDABLE_FIELD_TYPES, UNMATERIALIZED_FIELD_TYPES, readObjectSortability, isPlatformSortableField, leadWithNameField, filterPlatformSortableSort, applyNonGridRowCeiling, type NonGridCeilingResult, resolveNameField, declaredNameField, resolveDependsOnFields, GANTT_CONFIG_SPELLING, kanbanDeclaredLanes, csvBlob, readWithheldFieldNames, refersToWithheldField, withHeaderSortPick } from '@object-ui/core'; import { useObjectLabel, useSafeFieldLabel, createSafeTranslation, useDisplayLocale, pickLocalized, recordCurrencyField, recordCurrencyReadField } from '@object-ui/i18n'; @@ -6567,8 +6567,10 @@ export const ListView = React.forwardRef(({ // objectstack#36204 — what both Group editors offer: the fields of a type a // list can be grouped by (`isGroupableField`: single select, radio, tick, // person, linked record; one value each), the view's columns first in the - // reader's column order, then the object's other business fields of those - // types that the caller may read and the definition does not hide, in the + // reader's column order, then the object's other fields of those types + // that the caller may read and the definition does not hide: business + // fields, then system ones such as the owner (not the created-by and + // updated-by provenance), as the Filter panel orders them, each in the // definition's order. Until the definition's read answers nothing is // offered and "Add group field" waits, disabled (`groupOptionsLoading`), so // it never says "nothing to group by" before the types are known. A host @@ -6583,18 +6585,27 @@ export const ListView = React.forwardRef(({ ? [] : !definedFields ? groupFieldOptions(allFields, gridColumnOrder, false) - : [ - ...groupFieldOptions(allFields, gridColumnOrder), - ...Object.entries(definedFields).flatMap(([name, def]) => { + : (() => { + const extra = Object.entries(definedFields).flatMap(([name, def]) => { if (!def || allFields.some((f) => f.name === name)) return []; - if (def.hidden === true || def.system === true) return []; + // Record provenance (created by, updated by) is offered only as a + // column the view shows: on every object, it would otherwise + // leave no object without a field to group by. + if (def.hidden === true || AUDIT_FIELD_NAMES.has(name)) return []; if (!canReadField(perms, schema.objectName, name)) return []; if (isVirtualSearchField(def as SearchFieldMeta)) return []; if (!isGroupableField({ type: typeof def.type === 'string' ? def.type : undefined, multiple: def.multiple === true })) return []; const label = typeof def.label === 'string' && def.label ? def.label : name; - return [{ value: name, label: tFieldLabel(name, label) }]; - }), - ]; + return [{ value: name, label: tFieldLabel(name, label), system: isSystemManagedField(name, def as { system?: boolean }) }]; + }); + // The Filter panel's tiers: business fields, then the system ones + // (the owner, created by …), each in the definition's order. + return [ + ...groupFieldOptions(allFields, gridColumnOrder), + ...extra.filter((f) => !f.system).map(({ value, label }) => ({ value, label })), + ...extra.filter((f) => f.system).map(({ value, label }) => ({ value, label })), + ]; + })(); // The label a level shows for a field the editor does not offer (a view // grouped by a text or number field keeps showing it, under its label). const groupFieldLabel = (field: string): string | undefined => { diff --git a/ui/packages/plugin-list/src/__tests__/ListView.groupAddDefault-36204.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.groupAddDefault-36204.test.tsx index f712ecc2904..4dff4f09f33 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.groupAddDefault-36204.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.groupAddDefault-36204.test.tsx @@ -19,7 +19,9 @@ * the dropdown without a pick writes nothing; * 2. the dropdown offers single select, radio, tick, person and linked * record fields holding one value each: the view's columns first, then - * the object's other business fields of those types. Text, numbers, + * the object's other business fields of those types, then its system + * ones such as the owner (created by and updated by only as a column). + * Text, numbers, * dates and many-valued fields are not offered; * 3. with none to offer, the button is disabled and says why; while the * definition is still being read it is disabled without a reason; @@ -54,6 +56,7 @@ const FIELDS: Record> = { vip: { type: 'boolean', label: 'VIP' }, parent: { type: 'lookup', label: 'Parent account', reference: OBJECT }, internal_code: { type: 'select', label: 'Internal code', hidden: true, options: [{ value: 'x', label: 'X' }] }, + owner_id: { type: 'lookup', label: 'Record owner', reference: 'sys_user', system: true }, created_by: { type: 'lookup', label: 'Created by', reference: 'sys_user', system: true }, }; @@ -115,8 +118,6 @@ const level = (field: string) => ({ field, order: 'asc', collapsed: false }); afterEach(() => cleanup()); -afterEach(() => cleanup()); - describe('"Add group field" opens the field dropdown and groups only on a pick (objectstack#36204)', () => { const columns = ['name', 'industry', 'owner', 'notes', 'signed', 'revenue', 'tags']; @@ -129,9 +130,11 @@ describe('"Add group field" opens the field dropdown and groups only on a pick ( expect(onGroupingChange).not.toHaveBeenCalled(); expect(within(panel).queryByTestId('grouping-field-0')).toBeNull(); expect(within(panel).getByTestId('grouping-field-pending')).toBeInTheDocument(); - // The view's select-like columns, then the object's other ones; no - // name, text, date, number or many-valued select. - expect(await listboxLabels()).toEqual(['Industry', 'Owner', 'Stage', 'VIP', 'Parent account']); + // The view's select-like columns, then the object's other business + // ones, then its system ones (the record owner), as the Filter panel + // orders them; no name, text, date, number, many-valued select, hidden + // field, or created-by provenance the view does not show. + expect(await listboxLabels()).toEqual(['Industry', 'Owner', 'Stage', 'VIP', 'Parent account', 'Record owner']); fireEvent.click(within(screen.getByRole('listbox')).getByRole('option', { name: 'Industry' })); expect(onGroupingChange).toHaveBeenCalledTimes(1); expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('industry')] }); @@ -171,7 +174,7 @@ describe('"Add group field" opens the field dropdown and groups only on a pick ( const panel = await openToolbarGroup(); fireEvent.click(within(panel).getByTestId('grouping-add')); expect(onGroupingChange).not.toHaveBeenCalled(); - expect(await listboxLabels()).toEqual(['Owner', 'Stage', 'VIP', 'Parent account']); + expect(await listboxLabels()).toEqual(['Owner', 'Stage', 'VIP', 'Parent account', 'Record owner']); fireEvent.click(within(screen.getByRole('listbox')).getByRole('option', { name: 'Owner' })); expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('industry'), level('owner')] }); }); @@ -183,6 +186,13 @@ describe('"Add group field" opens the field dropdown and groups only on a pick ( expect((await listboxLabels()).slice(0, 2)).toEqual(['Owner', 'Industry']); }); + it('created-by provenance is offered when the view shows it as a column', async () => { + const { dataSource } = mount({ columns: ['name', 'created_by'] }); + await definitionRead(dataSource); + fireEvent.click(within(await openToolbarGroup()).getByTestId('grouping-add')); + expect((await listboxLabels())[0]).toBe('Created by'); + }); + it('a view grouped by a field of another type keeps it, under its label, and can change it', async () => { const { dataSource, onGroupingChange } = mount({ columns, grouping: { fields: [level('name')] } }); await definitionRead(dataSource); @@ -190,7 +200,7 @@ describe('"Add group field" opens the field dropdown and groups only on a pick ( const trigger = within(panel).getByTestId('grouping-field-0'); expect(trigger).toHaveTextContent('Customer name'); fireEvent.keyDown(trigger, { key: 'ArrowDown' }); - expect(await listboxLabels()).toEqual(['Customer name', 'Industry', 'Owner', 'Stage', 'VIP', 'Parent account']); + expect(await listboxLabels()).toEqual(['Customer name', 'Industry', 'Owner', 'Stage', 'VIP', 'Parent account', 'Record owner']); fireEvent.click(within(screen.getByRole('listbox')).getByRole('option', { name: 'Industry' })); expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('industry')] }); }); From 89c829005b44d4ea22376b84608956a974345970 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 04:23:52 +0000 Subject: [PATCH 4/4] fix(list): View settings labels a group field picked outside the columns The View settings menu labelled grouping levels from the columns only, so a field the Group level now offers beyond them (the record owner, an object field the view does not show) read as its machine name on the menu's Group row and on its level. The host hands the popover the same label function the toolbar editor uses. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgXeD1yUYqBJm8uzRrP --- .changeset/36204-group-add-default-field.md | 2 +- ui/packages/plugin-list/src/ListView.tsx | 1 + .../ListView.groupAddDefault-36204.test.tsx | 16 ++++++++++++++++ .../src/components/ViewSettingsPopover.tsx | 13 +++++++++++-- 4 files changed, 29 insertions(+), 3 deletions(-) diff --git a/.changeset/36204-group-add-default-field.md b/.changeset/36204-group-add-default-field.md index 84206c7ac8e..a92b394d24e 100644 --- a/.changeset/36204-group-add-default-field.md +++ b/.changeset/36204-group-add-default-field.md @@ -4,7 +4,7 @@ '@object-ui/i18n': patch --- -feat(list): "Add group field" asks which field, and offers only fields that can group +fix(list): "Add group field" asks which field, and offers only fields that can group Clause-②: yes (widening) — `@object-ui/components`'s `GroupingEditor` gains the optional props `askFieldOnAdd`, `fieldOptionsLoading` and `fieldLabel`, and its `labels` the optional `noFields`; `@object-ui/i18n` gains the key `list.noGroupableFields` in every locale; nothing removed or renamed Metadata-protocol: none diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 34b71870e8e..8f27117d26f 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -7306,6 +7306,7 @@ export const ListView = React.forwardRef(({ setGroupingConfig={changeGrouping} groupOptions={groupOptions} groupOptionsLoading={groupOptionsLoading} + groupFieldLabel={groupFieldLabel} showColor={toolbarFlags.showColor} rowColorConfig={offeredRowColorConfig} setRowColorConfig={setRowColorConfig} diff --git a/ui/packages/plugin-list/src/__tests__/ListView.groupAddDefault-36204.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.groupAddDefault-36204.test.tsx index 4dff4f09f33..3c4d7dc6614 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.groupAddDefault-36204.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.groupAddDefault-36204.test.tsx @@ -205,6 +205,22 @@ describe('"Add group field" opens the field dropdown and groups only on a pick ( expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('industry')] }); }); + it('View settings labels a field picked outside the columns, on its level and on the menu\'s Group row', async () => { + // `columns` holds neither Parent account nor Record owner: both are the + // object's own fields, offered after the columns. + const { dataSource, onGroupingChange } = mount({ columns, compactToolbar: true }); + await definitionRead(dataSource); + const content = await openDisplayGroup(); + fireEvent.click(within(content).getByTestId('grouping-add')); + fireEvent.click(within(screen.getByRole('listbox')).getByRole('option', { name: 'Record owner' })); + expect(onGroupingChange).toHaveBeenLastCalledWith({ fields: [level('owner_id')] }); + expect(await within(content).findByTestId('grouping-field-0')).toHaveTextContent('Record owner'); + fireEvent.click(within(content).getByTestId('options-back')); + const row = await within(content).findByTestId('options-row-group'); + expect(row).toHaveTextContent('Record owner'); + expect(row).not.toHaveTextContent('owner_id'); + }); + it('while the definition is being read the button waits, disabled, without a reason', async () => { let answer: (value: unknown) => void = () => {}; const { dataSource } = mount({ columns }, new Promise((resolve) => { answer = resolve; })); diff --git a/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx b/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx index 251eb61b9c6..1fa63db96c7 100644 --- a/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx +++ b/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx @@ -219,6 +219,13 @@ export interface ViewSettingsPopoverProps { */ groupOptions?: Array<{ value: string; label: string }>; groupOptionsLoading?: boolean; + /** + * objectstack#36204 — the label of a field a grouping level holds, as the + * host knows it: `groupOptions` reach past the columns, so a level can hold + * a field `allFields` does not carry. Absent, or answering `undefined`, + * the column's label, else the field's name. + */ + groupFieldLabel?: (field: string) => string | undefined; showColor?: boolean; rowColorConfig?: { field: string; colors?: Record } | undefined; @@ -553,6 +560,7 @@ export function ViewSettingsContent(props: ViewSettingsPopoverProps & { closeMen setGroupingConfig, groupOptions, groupOptionsLoading, + groupFieldLabel, showColor, rowColorConfig, setRowColorConfig, @@ -582,6 +590,7 @@ export function ViewSettingsContent(props: ViewSettingsPopoverProps & { closeMen const hasFooter = !!onSave || !!onReset || hasExport; const fieldLabel = (name: string) => allFields.find((f) => f.name === name)?.label || name; + const groupLevelLabel = (name: string) => groupFieldLabel?.(name) || fieldLabel(name); const none = t('list.none', { defaultValue: 'None' }); const groupFields: string[] = Array.isArray(groupingConfig?.fields) ? groupingConfig.fields.map((f: { field?: string }) => f?.field).filter((f: unknown): f is string => typeof f === 'string' && !!f) @@ -654,7 +663,7 @@ export function ViewSettingsContent(props: ViewSettingsPopoverProps & { closeMen {showGroup && setGroupingConfig && ( 0 ? groupFields.map(fieldLabel).join(' › ') : none} + value={groupFields.length > 0 ? groupFields.map(groupLevelLabel).join(' › ') : none} onOpen={() => setPage('group')} testId="options-row-group" /> @@ -750,7 +759,7 @@ export function ViewSettingsContent(props: ViewSettingsPopoverProps & { closeMen fieldOptions={groupOptions ?? groupFieldOptions(allFields, fieldOrder)} askFieldOnAdd fieldOptionsLoading={groupOptionsLoading} - fieldLabel={fieldLabel} + fieldLabel={groupLevelLabel} maxLevels={3} labels={{ addGroup: t('list.addGroup', 'Add group field'),