diff --git a/.changeset/36204-group-add-default-field.md b/.changeset/36204-group-add-default-field.md new file mode 100644 index 00000000000..a92b394d24e --- /dev/null +++ b/.changeset/36204-group-add-default-field.md @@ -0,0 +1,22 @@ +--- +'@object-ui/components': patch +'@object-ui/plugin-list': patch +'@object-ui/i18n': patch +--- + +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 + +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, 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. +- 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`: 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 46b2d4dffba..4ab14c5ac31 100644 --- a/docs/qa/platform-checklist/areas/records-forms.json +++ b/docs/qa/platform-checklist/areas/records-forms.json @@ -3610,7 +3610,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": 10, + "revision": 11, "priority": "P2", "surface": "browser", "personas": [ @@ -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' 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' 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" @@ -3749,6 +3749,12 @@ "date": "2026-11-21", "change": "steps[2], acceptance[1] (verify), acceptance[4] (clause, verify, evidence) and source[2] re-pointed (objectstack#35955 PR3, Sales ruling D1 on #35955): column widths and row height are kept in this browser only, localStorage list-layout::, and the ui.list. row is retired. Changed on purpose: they no longer follow the user to a fresh browser. Not loosened: they still survive a reload in the same browser and never reach another account", "ref": "#35955" + }, + { + "revision": 11, + "date": "2026-11-22", + "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/app-shell/src/views/ObjectView.listUrlState-11860.test.tsx b/ui/packages/app-shell/src/views/ObjectView.listUrlState-11860.test.tsx index 2a028009959..8353b7fefdb 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 @@ -758,6 +758,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'); @@ -787,7 +800,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); @@ -808,7 +821,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..46cd9d649bc --- /dev/null +++ b/ui/packages/components/src/__tests__/grouping-editor-add-default-36204.test.tsx @@ -0,0 +1,155 @@ +/** + * 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" 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. 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: 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, type GroupingEditorProps } from '../custom/grouping-editor'; + +const FIELD_OPTIONS = [ + { value: 'status', label: 'Status' }, + { value: 'owner', label: 'Owner' }, + { value: 'vip', label: 'VIP' }, +]; + +function renderEditor(value: GroupingConfigValue | undefined, extra: Partial = {}) { + const onChange = vi.fn(); + 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" 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); + 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(['Status', 'Owner', 'VIP']); + }); + + it('a pick writes the level and the row becomes that level', async () => { + 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(); + await waitFor(() => expect(screen.queryByTestId('grouping-field-pending')).toBeNull()); + expect(screen.getByTestId('grouping-field-0')).toHaveTextContent('Owner'); + expect(screen.getByTestId('grouping-add')).toBeInTheDocument(); + }); + + 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(['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); + 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(); + }); + + 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 8b7efbd0a2e..bb520b71805 100644 --- a/ui/packages/components/src/custom/grouping-editor.tsx +++ b/ui/packages/components/src/custom/grouping-editor.tsx @@ -30,6 +30,26 @@ export interface GroupingEditorProps { onChange: (next: GroupingConfigValue | undefined) => void; /** Available fields to group by. */ fieldOptions: Array<{ value: string; label: string }>; + /** + * 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. + */ + 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; @@ -40,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; }; } @@ -70,6 +96,9 @@ export function GroupingEditor({ value, onChange, fieldOptions, + askFieldOnAdd, + fieldOptionsLoading, + fieldLabel, maxLevels = 3, className, labels, @@ -77,6 +106,12 @@ 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" 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[]) => { onChange(next.length ? { fields: next } : undefined); @@ -116,7 +151,7 @@ export function GroupingEditor({ {isOutsideOptions && ( - {g.field} + {fieldLabel?.(g.field) || g.field} )} {fieldOptions @@ -173,27 +208,74 @@ export function GroupingEditor({ ); })} - {current.length < maxLevels && (() => { - const remaining = fieldOptions.filter((f) => !usedFields.has(f.value)); - if (remaining.length === 0) return null; - return ( + {askingField && current.length < maxLevels && remaining.length > 0 && ( +
+ +
+ )} + {!askingField && current.length < maxLevels && remaining.length > 0 && ( + + )} + {/* 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 3bbffca603b..8f27117d26f 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, + isGroupableField, type ViewSettingsField, PHONE_TOUCH_TARGET, useBelowSm, @@ -59,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'; @@ -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 + // offer a field by (`groupFieldOptions`). + 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,67 @@ 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; + + // 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 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 + // 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) + : (() => { + const extra = Object.entries(definedFields).flatMap(([name, def]) => { + if (!def || allFields.some((f) => f.name === name)) 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), 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 => { + 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 @@ -7234,6 +7304,9 @@ export const ListView = React.forwardRef(({ showGroup={toolbarFlags.showGroup} groupingConfig={chosenGroupingConfig} setGroupingConfig={changeGrouping} + groupOptions={groupOptions} + groupOptionsLoading={groupOptionsLoading} + groupFieldLabel={groupFieldLabel} showColor={toolbarFlags.showColor} rowColorConfig={offeredRowColorConfig} setRowColorConfig={setRowColorConfig} @@ -7257,7 +7330,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,12 +7701,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 83bb0cf9181..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,9 +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 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(FIELD_LABELS); + expect(group).toEqual(['Status', 'Secret Status']); }); }); @@ -520,20 +523,26 @@ 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 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, and the new level does not offer it. + // "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: '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']); // 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..3c4d7dc6614 --- /dev/null +++ b/ui/packages/plugin-list/src/__tests__/ListView.groupAddDefault-36204.test.tsx @@ -0,0 +1,270 @@ +/** + * 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 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. 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, 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; + * 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 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'; +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, isGroupableField, 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' }, + 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' }] }, + owner_id: { type: 'lookup', label: 'Record owner', reference: 'sys_user', system: true }, + created_by: { type: 'lookup', label: 'Created by', reference: 'sys_user', system: true }, +}; + +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([]), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + ...(definition ? { getObjectSchema: vi.fn(() => definition) } : {}), + }; + 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 }) { + if (dataSource.getObjectSchema) 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; +} + +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 ?? ''); +} + +const level = (field: string) => ({ field, order: 'asc', collapsed: false }); + +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']; + + 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 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')] }); + // 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(`${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(`${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).not.toHaveBeenCalled(); + 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')] }); + }); + + 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((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); + 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', 'Record owner']); + fireEvent.click(within(screen.getByRole('listbox')).getByRole('option', { name: 'Industry' })); + 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; })); + await vi.waitFor(() => expect(dataSource.getObjectSchema).toHaveBeenCalled()); + const panel = await openToolbarGroup(); + 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('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); + fireEvent.click(within(await openToolbarGroup()).getByTestId('grouping-add')); + expect(await listboxLabels()).toEqual(['name', 'industry', 'notes']); + }); +}); + +describe('the offer, 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: 'people', label: 'People', type: 'user', multiple: true }, + { name: 'status', label: 'Status', type: 'select' }, + { name: 'untyped', label: '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('in the column order a reader set', () => { + expect(groupFieldOptions(fields, ['status', 'flag']).map((o) => o.value)).toEqual(['status', 'flag', 'parent']); + }); + + 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 44cb31c0fe2..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,12 +3512,22 @@ 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 — "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,17 +3538,18 @@ 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 () => { - 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'); - 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..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,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 the Group editors offer by: + // `status`, the one select, is the field offered. + 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,23 @@ function schemaWith(extra: Partial = {}): ListViewSchema { } as ListViewSchema; } +/** 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) => ( - + ); const result = render(view(schema)); @@ -85,12 +108,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')); + await pickNewLevel('Status'); 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 +149,12 @@ 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')); - fireEvent.click(await within(content).findByTestId('grouping-add')); + await definitionRead(); + 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'); 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..1fa63db96c7 100644 --- a/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx +++ b/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx @@ -98,6 +98,31 @@ 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 offer a field by them + * (objectstack#36204); absent ⇒ not offered there while types are known. + */ + type?: string; + multiple?: boolean; +} + +/** + * 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 GROUPABLE_TYPES = new Set([ + 'select', 'radio', + 'boolean', 'toggle', + 'user', 'lookup', 'master_detail', 'tree', +]); + +/** 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; } /** @@ -106,10 +131,20 @@ 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 — 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[]): Array<{ value: string; label: string }> { - return fields - .filter((f) => f.groupable !== false) +export function groupFieldOptions( + fields: readonly ViewSettingsField[], + order?: readonly string[], + typesKnown = true, +): Array<{ value: string; label: string }> { + return orderFields(fields, order) + .filter((f) => f.groupable !== false && (!typesKnown || isGroupableField(f))) .map((f) => ({ value: f.name, label: f.label || f.name })); } @@ -177,6 +212,20 @@ 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; + /** + * 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; @@ -509,6 +558,9 @@ export function ViewSettingsContent(props: ViewSettingsPopoverProps & { closeMen showGroup, groupingConfig, setGroupingConfig, + groupOptions, + groupOptionsLoading, + groupFieldLabel, showColor, rowColorConfig, setRowColorConfig, @@ -538,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) @@ -610,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" /> @@ -703,12 +756,16 @@ export function ViewSettingsContent(props: ViewSettingsPopoverProps & { closeMen
setGroupingConfig(next as any)} />