diff --git a/.changeset/35551-35553-list-options-view-create.md b/.changeset/35551-35553-list-options-view-create.md new file mode 100644 index 00000000000..7d9e25d5116 --- /dev/null +++ b/.changeset/35551-35553-list-options-view-create.md @@ -0,0 +1,16 @@ +--- +'@object-ui/plugin-list': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(list): the list's options panel is a menu of second levels, and the view dropdown creates a view in place + +Clause-②: no +Metadata-protocol: none + +**The options panel (选项) is a menu.** Each row names a setting on the left and shows its current value on the right, and opens a second level: the view name, Layout, Fields (「已显示 N 个」), Grouping, Row color, Row height (紧凑 / 标准 / 宽松), and More (how records open, row numbers, inline edit). On a phone a Sort row is added, as before. The Layout level lists every layout the view offers as one choice each, at any count. The Fields level is the list's shared field list (the one 筛选 and 排序 open), as the view's field manager: a search box on top; the shown fields are listed in their order, can be dragged (or moved with the arrow keys) and hidden by their eye, and the hidden fields sit below, where one click shows a field again or adds a readable field the view does not list. Only fields the reader may read are offered. The footer reads 「恢复默认」 and 「刷新」, and — on one of the reader's own views that differs from what it stores — 「保存」 beside 「恢复默认」, which writes the list on screen into that view (as the 「已个性化」 marker's 保存 does); in the console 「恢复默认」 is the marker's reset, dimmed while there is nothing to restore. The view name at the top is renamed in place by the view's owner, or by an admin on a saved shared view; opening the menu does not put the cursor in it. Fields reorders the grid's columns through the same state a header drag writes, and Row height on a gallery picks its card size by name; every icon button has a name; the developer note under Open records is gone. These settings stay the reader's own preference, stored as before. + +**The view dropdown** keeps its search and lists one row per view, led by its type's icon, with the reader's own views (我的视图) and the shared views in groups of their own; a long name wraps instead of being cut. 「添加视图」 at the bottom turns the dropdown into a create card (the separate 「另存为我的视图」 entry and its name dialog are folded into it; the full Create View dialog stays reachable from 「管理视图」): a name, the view type (with icons), the one field the type needs (kanban: the group field; calendar: the date field), 「包含当前的筛选和排序」 while the list holds unsaved conditions (on by default), and — for a reader who may create shared views — a personal / shared switch. The one field a type needs defaults to one the list shows (a kanban groups by 阶段 on a list that shows it, not by a hidden status-like field). 「创建」 creates one of the reader's own views by default and opens it; a shared view goes through the existing draft-and-publish door unchanged. No machine name is asked for: a unique one is generated from the name. A kanban or gallery created this way lists the view's columns as its card fields, as the add-view door does. + +The fields count label (`list.optionsMenu.fieldsShown`) is a count family in every pack. Keys no surface reads any more are dropped from every pack: `list.recordOpenNote`, `list.recordOpenDeclaredPage`, `view.switcher.all` and `view.switcher.saveAsMyView`. diff --git a/docs/qa/platform-checklist/areas/records-forms.json b/docs/qa/platform-checklist/areas/records-forms.json index 70c3b74aee3..53285359f79 100644 --- a/docs/qa/platform-checklist/areas/records-forms.json +++ b/docs/qa/platform-checklist/areas/records-forms.json @@ -3523,7 +3523,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": 7, + "revision": 8, "priority": "P2", "surface": "browser", "personas": [ @@ -3548,7 +3548,7 @@ ], "steps": [ "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 density with the list's one density control, a button that steps to the next mode on each click (its title 'Density: MODE (click to cycle)', ui/packages/plugin-list/src/ListView.tsx; QA run #33861 met it in the Display popover), not a menu of options — three modes, Compact / Comfortable / Spacious, 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)", + "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 columnState (widths, and the order where reorder is enabled) and row-height restored — they now persist in the signed-in user's own list preference, sys_user_preference ui.list.showcase_task (perView..columnState / rowHeight, objectui#12418), 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", "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)", @@ -3563,7 +3563,7 @@ "evidence": "before/after-reload screenshots + the storage value" }, { - "clause": "the toolbar density persists across reload (Compact / Comfortable / Spacious — the runtime control offers three modes over the spec's five rowHeight values)", + "clause": "the toolbar row height persists across reload (Compact / Standard / Spacious — the runtime control offers three modes over the spec's five rowHeight values)", "oracle": "dom", "verify": "the reloaded grid renders at the chosen density (ObjectGrid rowHeightMode), and the preference row's rowHeight reads compact / medium / tall for the three modes", "evidence": "before/after screenshots" @@ -3644,6 +3644,12 @@ "date": "2026-11-15", "change": "steps[1] names the density control as one cycling button, and steps[3] says a runtime group-by persists in the URL (uf__group), not in the user's list preference, so a bare-URL reload drops it by design; 'Add group field' groups by the first field at once. QA run #33861, ledger row 142. No clause changed. Ledger 6896511848 of the v18.5.0 sweep anchor #33761, carried by batch-A card #33963; read at base 895783a1.", "ref": "#33990" + }, + { + "revision": 8, + "date": "2026-11-19", + "change": "steps[1] and acceptance[1].clause re-pointed to the options menu's Row height level: three named choices (紧凑 / 标准 / 宽松, Compact / Standard / Spacious) replace the cycling density button, on a grid and on a gallery (its card size). Stored values unchanged (rowHeight compact / medium / tall). No clause's meaning changed.", + "ref": "#35551" } ] }, @@ -3652,7 +3658,7 @@ "title": "Admin saved-view lifecycle: create kanban via dialog (staged as a per-item draft, live only after Publish), rename/set-default/pin/delete each hit the meta overlay and survive reload; non-admin affordances absent and server-refused", "since": "v16", "status": "active", - "revision": 3, + "revision": 4, "priority": "P2", "surface": "browser", "personas": [ @@ -3671,19 +3677,21 @@ }, "variants": [ "create-kanban", + "create-in-place", "rename", "set-default", "pin", "delete" ], "steps": [ - "as admin, open showcase_task; open the Create View dialog; choose kanban; set groupByField = status; create — capture PUT /api/v1/meta/view/?mode=draft (the console's create handler → createRuntimeMetadata → metadataClient.save(…, {mode:'draft'}): ADR-0034 stages every runtime-created view as an invisible per-item draft under the qualified name showcase_task.) carrying {type:'kanban', kanban:{groupByField:'status'}}; the console lands on view/?preview=draft", + "as admin, open showcase_task; open the Create View dialog (the view dropdown's 管理视图 / Manage views, then its Add new view: the dropdown's own 添加视图 creates in place since #35553, steps[6]); choose kanban; set groupByField = status; create — capture PUT /api/v1/meta/view/?mode=draft (the console's create handler → createRuntimeMetadata → metadataClient.save(…, {mode:'draft'}): ADR-0034 stages every runtime-created view as an invisible per-item draft under the qualified name showcase_task.) carrying {type:'kanban', kanban:{groupByField:'status'}}; the console lands on view/?preview=draft", "click Publish on the draft-preview bar — capture POST /api/v1/meta/view//publish (meta.publishItem); then reload WITHOUT ?preview=draft and confirm the new kanban view is live and groups by status. Before the publish, a plain (published-only) read does not serve it — the draft isolation itself is studio-authoring.view-authoring-live's to score", "rename the view via Manage Views; capture the PUT; reload confirms the new label", "set the view as default (unsets the prior default); capture the PUT(s). Where the prior default is a packaged view, its unset goes through the customization pair, POST /api/v1/packages/BASE/ensure-customization (BASE the view's package, com.example.showcase) then a PUT with ?package=com.example.showcase.custom, so the PUTs come in two shapes (QA run #33861); reload confirms the default moved", "pin the view; capture the PUT (isPinned); reload confirms it pinned", "delete the view; capture DELETE /api/v1/meta/view/; reload confirms it is gone", - "as the non-admin, open the same object; confirm the create-view and manage-views (rename/default/pin/delete) affordances are ABSENT", + "as the admin, open the view dropdown (the view bar's switcher) and use 添加视图 / Add view at its foot: the dropdown turns into the create card (name, view type with icons, the one field the type needs — kanban: the group field — 包含当前的筛选和排序 while the list holds unsaved filters or sort, on by default, and a personal / shared switch for a reader who may create shared views). Create a kanban grouped by status with the switch left on personal: capture the write — one of the reader's own views, a sys_personal_view row whose config carries {type:'kanban', kanban:{groupByField:'status', columns:[…]}} — and confirm the list opens on it and it is listed under 我的视图 / My views in the dropdown. Repeat once with the switch on shared: the same draft PUT …?mode=draft and ?preview=draft landing as steps[0], under a machine key generated from the name (no key field is asked for). Count the clicks from the dropdown to the open new view", + "as the non-admin, open the same object; confirm the shared-view create (the Create View dialog, and the create card's personal / shared switch — the dropdown's 添加视图 stays where the reader may save views of their own, and creates only those) and the manage-views (rename/default/pin/delete) affordances are ABSENT", "as the non-admin, forge a direct PUT /api/v1/meta/view/; capture the refusal" ], "acceptance": [ @@ -3700,7 +3708,13 @@ "evidence": "the four traces + post-reload states" }, { - "clause": "the non-admin lacks the mutation affordances: the create-view control and the Manage Views rename/default/pin/delete actions are ABSENT (ManageViewsDialog suppresses mutation affordances for system/read-only)", + "clause": "the dropdown's Add view creates in place: by default one of the reader's OWN views (a sys_personal_view row, no metadata write), opened at once; with the shared switch, the same draft-first create as acceptance[0], its machine key generated (unique among the object's views) and never asked for. The card offers the shared switch only to a reader who may create shared views", + "oracle": "network", + "verify": "the captured sys_personal_view create (personal) and the draft PUT + ?preview=draft landing (shared); the dropdown lists the new view under My views (personal) after a reload; the non-admin's card shows no shared switch", + "evidence": "the two create traces + the dropdown screenshot + the click count" + }, + { + "clause": "the non-admin lacks the mutation affordances: the shared-view create (the Create View dialog and the create card's shared switch; 添加视图 itself stays, for the reader's own views only) and the Manage Views rename/default/pin/delete actions are ABSENT (ManageViewsDialog suppresses mutation affordances for system/read-only)", "oracle": "dom", "verify": "after a screenshot confirms the object opened, the DOM shows no create-view / manage mutation controls for the non-admin", "evidence": "the non-admin screenshot" @@ -3745,6 +3759,12 @@ "date": "2026-11-15", "change": "steps[3] names the two PUT shapes: unsetting a packaged prior default goes through the customization pair (ensure-customization, then PUT ?package=com.example.showcase.custom), not a plain PUT. The clause still holds. QA run #33861, ledger row 151. No clause changed. Ledger 6896511848 of the v18.5.0 sweep anchor #33761, carried by batch-A card #33963; read at base 895783a1.", "ref": "#33990" + }, + { + "revision": 4, + "date": "2026-11-19", + "change": "added the create-in-place variant, a step before the non-admin steps and an acceptance clause before the non-admin clause: the view dropdown's Add view turns into a create card that makes one of the reader's own views by default (sys_personal_view, opened at once) or, through the shared switch for a reader allowed to, the same draft-first create as acceptance[0] under a generated machine key. The non-admin clause (acceptance[3]) and steps[7] now name the SHARED-view create as the absent affordance, since 添加视图 stays for a reader who may save views of their own and creates only those (the separate Save as my view entry folded into the card); steps[0] says the Create View dialog opens from Manage views. The other clauses are unchanged.", + "ref": "#35553" } ] }, diff --git a/ui/e2e/live/user-filters.spec.ts b/ui/e2e/live/user-filters.spec.ts index ab50146bcfd..3cf37dbe6cb 100644 --- a/ui/e2e/live/user-filters.spec.ts +++ b/ui/e2e/live/user-filters.spec.ts @@ -43,27 +43,25 @@ test.describe('ADR-0053 interface mode — Task Triage tabs element', () => { }); test.describe('ADR-0047 data mode — viz dropdown', () => { - test('visualization switcher is a single dropdown offering the whitelist', async ({ page }) => { + test('visualization switcher is a single list offering the whitelist', async ({ page }) => { await page.goto('/apps/showcase_app/showcase_task'); - // The switcher lives in the toolbar's Display popover. + // The switcher is the Layout level of the toolbar's Display menu. await page.getByTestId('toolbar-display-trigger').click(); - const trigger = page.getByTestId('view-switcher-dropdown'); - await expect(trigger).toBeVisible(); - await trigger.click(); - // The open switcher's own list, found through the trigger's aria-controls. - const menu = page.locator(`[id="${await trigger.getAttribute('aria-controls')}"]`); + await page.getByTestId('options-row-layout').click(); + const menu = page.getByTestId('view-switcher-list'); + await expect(menu).toBeVisible(); // Whitelist: the default task list's `appearance.allowedVisualizations` // (grid, kanban, gallery, calendar, timeline, gantt) — and nothing else. // Map and chart are declared on this object as their own named views and // stay out of the switcher. - await expect(menu.getByRole('button')).toHaveText(['Grid', 'Kanban', 'Gallery', 'Calendar', 'Timeline', 'Gantt']); + await expect(menu.getByRole('radio')).toHaveText(['Grid', 'Kanban', 'Gallery', 'Calendar', 'Timeline', 'Gantt']); - // Switching actually swaps the renderer; the trigger names the new one. - await menu.getByRole('button', { name: 'Kanban' }).click(); + // Switching actually swaps the renderer; the Layout row names the new one. + await menu.getByRole('radio', { name: 'Kanban' }).click(); await page.getByTestId('toolbar-display-trigger').click(); - await expect(trigger).toContainText('Kanban'); + await expect(page.getByTestId('options-row-layout-value')).toContainText('Kanban'); }); }); diff --git a/ui/packages/app-shell/src/views/CreateViewDialog.tsx b/ui/packages/app-shell/src/views/CreateViewDialog.tsx index 457847506fa..dac679f337c 100644 --- a/ui/packages/app-shell/src/views/CreateViewDialog.tsx +++ b/ui/packages/app-shell/src/views/CreateViewDialog.tsx @@ -74,6 +74,7 @@ import { ListTree, CalendarClock, AlertCircle, + ChevronLeft, } from 'lucide-react'; export interface CreateViewDialogProps { @@ -481,80 +482,38 @@ const REQUIRED_FIELDS_BY_TYPE: Record = { // grid has no strictly required fields at create time }; -export function CreateViewDialog({ - open, - onOpenChange, - onCreate, - existingLabels, - availableTypes, +/** + * The type-specific picks of a new view (the group-by field of a kanban, the + * date field of a calendar, the chart's dataset binding, …): what each type + * requires, the options each pick offers, the smart defaults, and the block + * the picks write under the type's key. Shared by {@link CreateViewDialog} and + * the switcher's in-place {@link CreateViewCard}, so both create the same + * views. `enabled` gates the dataset catalog read: a closed surface reads + * nothing. + */ +function useRequiredPicks({ + enabled, objectDef, -}: CreateViewDialogProps) { + types, + selectedType, + shownFields, +}: { + enabled: boolean; + objectDef?: CreateViewDialogProps['objectDef']; + types: readonly ViewTypeMeta[]; + selectedType: string; + /** + * The fields the list on screen shows. A field pick's default is taken + * among them first (the same preferred names, then their order), and from + * the whole object only when none of them is eligible. + */ + shownFields?: readonly string[]; +}) { const { t } = useObjectTranslation(); - // Prefix for the type cards' label / text ids (aria-labelledby, -describedby). - const typeGridId = useId(); - const allTypes = useMemo(() => buildViewTypeMeta(t), [t]); - const types = useMemo( - () => (availableTypes && availableTypes.length > 0 - ? allTypes.filter(v => availableTypes.includes(v.type)) - : allTypes), - [allTypes, availableTypes], - ); - // Stabilise the existing-labels list across renders so we don't churn the - // `existingSet` memo (and the dependent useEffects) on every parent render. - // Callers commonly pass `views.map(v => v.label)` inline, which is a fresh - // array each render — without this normalisation, the name-suggest effect - // below would re-fire indefinitely and could trigger "Maximum update depth" - // when the array contents are stable but the reference is not. - const existingKey = (existingLabels ?? []).join('\u0000'); - const existingSet = useMemo( - () => new Set(existingLabels ?? []), - // eslint-disable-next-line react-hooks/exhaustive-deps - [existingKey], - ); const fieldOptions = useMemo(() => (objectDef ? deriveFieldOptions(objectDef) : []), [objectDef]); - - const [selectedType, setSelectedType] = useState(types[0]?.type ?? 'grid'); - const [label, setLabel] = useState(''); - const [touched, setTouched] = useState(false); - // Machine `name` (metadata key) + whether the user has typed into it. Auto- - // derived from `label` via slugify until the user edits it directly. - const [name, setName] = useState(''); - const [nameTouched, setNameTouched] = useState(false); /** Map of `${type}.${fieldKey}` → selected field name. Per-type so switching * view types preserves the user's earlier choices in case they switch back. */ const [requiredFieldValues, setRequiredFieldValues] = useState>({}); - /** A save is in flight (objectui#11578). The ref turns away a second press - * in the same tick, before the disabled Create button has rendered. */ - const [submitting, setSubmitting] = useState(false); - const submittingRef = useRef(false); - - // Reset when the dialog opens, and re-suggest name whenever type changes - // (only while the user hasn't manually edited it yet). - useEffect(() => { - if (open) { - setSelectedType(types[0]?.type ?? 'grid'); - setTouched(false); - setNameTouched(false); - setRequiredFieldValues({}); - } - }, [open, types]); - - useEffect(() => { - if (!touched) { - const meta = types.find(v => v.type === selectedType); - setLabel(suggestName(meta?.label ?? 'View', existingSet)); - } - }, [selectedType, touched, types, existingSet]); - - // Derive the machine name from the label until the user edits it. A Chinese - // label derives through its pinyin, re-deriving when the dictionary lands - // (`romanizerVersion`); a label that still yields '' leaves the field empty - // and the user is prompted to fill it in (rather than a silent random key — - // #2767 P5). - const romanizerVersion = useHanRomanizer(label); - useEffect(() => { - if (!nameTouched) setName(slugify(romanizeHan(label))); - }, [label, nameTouched, romanizerVersion]); // Required fields for the currently selected type const requiredFields = REQUIRED_FIELDS_BY_TYPE[selectedType] ?? []; @@ -572,7 +531,7 @@ export function CreateViewDialog({ datasets: objectDatasets, bound: boundDataset, semantics, - } = useObjectDatasetBinding(objectName, chosenDataset, { enabled: open }); + } = useObjectDatasetBinding(objectName, chosenDataset, { enabled }); // What the effects below re-run on: the NAMES offered, never the identity // of a memoised list (AGENTS.md #10). const datasetKey = objectDatasets.map((d) => d.name).join('\u0000'); @@ -667,16 +626,7 @@ export function CreateViewDialog({ }); }; - const trimmed = label.trim(); - const isDuplicate = trimmed.length > 0 && existingSet.has(trimmed); const allRequiredFilled = requiredFields.every(f => f.optional || pickedValue(f).length > 0); - // Machine name: same snake_case shape slugify emits and the metadata `name` - // pattern (`^[a-z_][a-z0-9_]*$`) accepts. Empty → prompt; malformed → hint. - const NAME_RE = /^[a-z_][a-z0-9_]*$/; - const nameKey = name.trim(); - const nameMissing = nameKey.length === 0; - const nameInvalid = nameKey.length > 0 && !NAME_RE.test(nameKey); - const canSubmit = trimmed.length > 0 && !isDuplicate && allRequiredFilled && !nameMissing && !nameInvalid; // Auto-pick a sensible default for any pick. Runs whenever the type or the // available options change, but only fills slots that hold nothing yet. @@ -700,24 +650,151 @@ export function CreateViewDialog({ return; } if (rf.kind && rf.kind !== 'field') return; // `preferred` names object fields only - const picked = pickPreferredField(eligibleFields(rf), rf.preferred ?? []); + const eligibleObjectFields = eligibleFields(rf); + const shown = eligibleObjectFields.filter((o) => shownFields?.includes(o.value)); + const picked = pickPreferredField(shown.length > 0 ? shown : eligibleObjectFields, rf.preferred ?? []); if (picked) setRequiredValue(rf.key, picked); }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [selectedType, fieldOptions, datasetKey, measureKey, dimensionKey]); + /** + * The picks bundled under their type's key, the spec ListView block of that + * name (e.g. `{ groupByField }` for `kanban`). A `list` pick is written as a + * one-element array: the chart's `values` and `dimensions` are lists in the + * spec. + */ + const subConfig = (): Record => { + const out: Record = {}; + requiredFields.forEach((rf) => { + const v = pickedValue(rf); + if (!v) return; + out[rf.key] = rf.list ? [v] : v; + }); + return out; + }; + + return { + fieldOptions, + requiredFields, + optionsFor, + pickedValue, + choose, + typeUnavailability, + allRequiredFilled, + subConfig, + reset: () => setRequiredFieldValues({}), + catalog, + boundDataset, + semantics, + }; +} + +export function CreateViewDialog({ + open, + onOpenChange, + onCreate, + existingLabels, + availableTypes, + objectDef, +}: CreateViewDialogProps) { + const { t } = useObjectTranslation(); + // Prefix for the type cards' label / text ids (aria-labelledby, -describedby). + const typeGridId = useId(); + const allTypes = useMemo(() => buildViewTypeMeta(t), [t]); + const types = useMemo( + () => (availableTypes && availableTypes.length > 0 + ? allTypes.filter(v => availableTypes.includes(v.type)) + : allTypes), + [allTypes, availableTypes], + ); + // Stabilise the existing-labels list across renders so we don't churn the + // `existingSet` memo (and the dependent useEffects) on every parent render. + // Callers commonly pass `views.map(v => v.label)` inline, which is a fresh + // array each render — without this normalisation, the name-suggest effect + // below would re-fire indefinitely and could trigger "Maximum update depth" + // when the array contents are stable but the reference is not. + const existingKey = (existingLabels ?? []).join('\u0000'); + const existingSet = useMemo( + () => new Set(existingLabels ?? []), + // eslint-disable-next-line react-hooks/exhaustive-deps + [existingKey], + ); + const [selectedType, setSelectedType] = useState(types[0]?.type ?? 'grid'); + const [label, setLabel] = useState(''); + const [touched, setTouched] = useState(false); + // Machine `name` (metadata key) + whether the user has typed into it. Auto- + // derived from `label` via slugify until the user edits it directly. + const [name, setName] = useState(''); + const [nameTouched, setNameTouched] = useState(false); + /** A save is in flight (objectui#11578). The ref turns away a second press + * in the same tick, before the disabled Create button has rendered. */ + const [submitting, setSubmitting] = useState(false); + const submittingRef = useRef(false); + + // Reset when the dialog opens, and re-suggest name whenever type changes + // (only while the user hasn't manually edited it yet). + useEffect(() => { + if (open) { + setSelectedType(types[0]?.type ?? 'grid'); + setTouched(false); + setNameTouched(false); + resetPicks(); + } + // `resetPicks` only clears state; the dialog resets on opening. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [open, types]); + + useEffect(() => { + if (!touched) { + const meta = types.find(v => v.type === selectedType); + setLabel(suggestName(meta?.label ?? 'View', existingSet)); + } + }, [selectedType, touched, types, existingSet]); + + // Derive the machine name from the label until the user edits it. A Chinese + // label derives through its pinyin, re-deriving when the dictionary lands + // (`romanizerVersion`); a label that still yields '' leaves the field empty + // and the user is prompted to fill it in (rather than a silent random key — + // #2767 P5). + const romanizerVersion = useHanRomanizer(label); + useEffect(() => { + if (!nameTouched) setName(slugify(romanizeHan(label))); + }, [label, nameTouched, romanizerVersion]); + + const { + fieldOptions, + requiredFields, + optionsFor, + pickedValue, + choose, + typeUnavailability, + allRequiredFilled, + subConfig: buildSubConfig, + reset: resetPicks, + catalog, + boundDataset, + semantics, + } = useRequiredPicks({ enabled: open, objectDef, types, selectedType }); + + const trimmed = label.trim(); + const isDuplicate = trimmed.length > 0 && existingSet.has(trimmed); + // Machine name: same snake_case shape slugify emits and the metadata `name` + // pattern (`^[a-z_][a-z0-9_]*$`) accepts. Empty → prompt; malformed → hint. + const NAME_RE = /^[a-z_][a-z0-9_]*$/; + const nameKey = name.trim(); + const nameMissing = nameKey.length === 0; + const nameInvalid = nameKey.length > 0 && !NAME_RE.test(nameKey); + const canSubmit = trimmed.length > 0 && !isDuplicate && allRequiredFilled && !nameMissing && !nameInvalid; + + const handleSubmit = async () => { if (!canSubmit || submittingRef.current) return; // Bundle the picks under their type-specific sub-key, the spec ListView // block of that name (e.g. { type: "kanban", kanban: { groupByField } }). // A `list` pick is written as a one-element array: the chart's `values` // and `dimensions` are lists in the spec. - const subConfig: Record = {}; - requiredFields.forEach((rf) => { - const v = pickedValue(rf); - if (!v) return; - subConfig[rf.key] = rf.list ? [v] : v; - }); + const subConfig = buildSubConfig(); const payload: Record & { type: string; label: string; name: string } = { type: selectedType, label: trimmed, @@ -960,3 +1037,318 @@ export function CreateViewDialog({ ); } + +// --------------------------------------------------------------------------- +// The view switcher's in-place create card +// --------------------------------------------------------------------------- + +/** The longest machine key the generator writes, before a numeric suffix. */ +const VIEW_KEY_MAX = 48; + +/** + * A view's machine key, generated from its name and never shown: the name's + * snake_case form (a Chinese name through its pinyin, `romanizeHan`), else + * `view`, made unique against `taken` with a `_2`, `_3`, … suffix. `taken` + * holds bare keys or qualified `object.key` names; both spellings collide. + */ +export function uniqueViewKey(label: string, taken: Iterable): string { + const used = new Set(); + for (const name of taken) { + if (typeof name !== 'string' || !name) continue; + used.add(name); + const dot = name.lastIndexOf('.'); + if (dot !== -1) used.add(name.slice(dot + 1)); + } + let base = slugify(romanizeHan(label)).slice(0, VIEW_KEY_MAX).replace(/_+$/g, ''); + if (!/^[a-z_][a-z0-9_]*$/.test(base)) base = 'view'; + if (!used.has(base)) return base; + for (let i = 2; i < 10_000; i++) { + const candidate = `${base}_${i}`; + if (!used.has(candidate)) return candidate; + } + return `${base}_${Date.now()}`; +} + +/** What the in-place create card asks its host to create. */ +export interface InPlaceViewRequest { + /** + * The new view: its type, the name the reader gave it, the machine key + * generated from that name ({@link uniqueViewKey}; a shared view's + * metadata key, unused by one of the reader's own views) and the type's + * picks under the type's key, as {@link CreateViewDialog} hands them. + */ + config: Record & { type: string; label: string; name: string }; + /** `personal`: one of the reader's own views; `shared`: a view of the object. */ + scope: 'personal' | 'shared'; + /** Carry the list's unsaved filters and sort into the new view. */ + includeCurrent: boolean; +} + +export interface CreateViewCardProps { + /** Fields for the type's pick (group-by, date, …), as {@link CreateViewDialogProps}. */ + objectDef?: CreateViewDialogProps['objectDef']; + /** The views' names, to suggest a default name no view has and to refuse a taken one. */ + existingLabels?: string[]; + /** The views' ids or keys, to generate a machine key no view has. */ + existingKeys?: string[]; + /** Restrict the view types. Defaults to every type the dialog offers. */ + availableTypes?: string[]; + /** + * The fields the list on screen shows (the open view's columns): the one + * pick the type needs defaults to one of them (kanban: a status-like field + * the list shows, so 阶段 over a hidden 审批状态). + */ + shownFields?: readonly string[]; + /** The reader may create one of their own views. */ + canCreatePersonal: boolean; + /** The reader may create a shared view: the card then offers the switch. */ + canCreateShared: boolean; + /** The list holds filters or a sort its view does not: offer to include them (on by default). */ + hasUnsavedConditions: boolean; + /** + * Create the view and enter it. Resolves `true` once created; `false` when + * refused (the host has said why), and the card keeps what was entered. + */ + onCreate: (request: InPlaceViewRequest) => boolean | Promise; + /** Back to the view list. */ + onBack: () => void; +} + +/** + * The in-place create card of the view switcher: the switcher's dropdown turns + * into it on 「Add view」. Name (beside the chosen type's icon), the view type, + * the one pick the type needs (kanban: the group-by field; calendar: the date + * field; a type that needs none shows none), whether to include the list's + * unsaved filters and sort, and — for a reader who may — personal or shared. + * No machine name is asked for: {@link uniqueViewKey} generates it. + * + * Picks beyond the type's first are filled with the same defaults the dialog + * picks, and shown only while they hold nothing, so a type that needs more + * than one binding (a gantt's two dates, a map's two coordinates) is never + * dropped from the card. Writes nothing itself: `onCreate` does. + */ +export function CreateViewCard({ + objectDef, + existingLabels, + existingKeys, + availableTypes, + canCreatePersonal, + canCreateShared, + hasUnsavedConditions, + shownFields, + onCreate, + onBack, +}: CreateViewCardProps) { + const { t } = useObjectTranslation(); + const allTypes = useMemo(() => buildViewTypeMeta(t), [t]); + const types = useMemo( + () => (availableTypes && availableTypes.length > 0 + ? allTypes.filter((v) => availableTypes.includes(v.type)) + : allTypes), + [allTypes, availableTypes], + ); + const existingKey = (existingLabels ?? []).join('\u0000'); + const existingSet = useMemo( + () => new Set(existingLabels ?? []), + // eslint-disable-next-line react-hooks/exhaustive-deps + [existingKey], + ); + const [selectedType, setSelectedType] = useState(types[0]?.type ?? 'grid'); + const [label, setLabel] = useState(''); + const [touched, setTouched] = useState(false); + const [includeCurrent, setIncludeCurrent] = useState(true); + const [scope, setScope] = useState<'personal' | 'shared'>(canCreatePersonal ? 'personal' : 'shared'); + const [submitting, setSubmitting] = useState(false); + const submittingRef = useRef(false); + const baseId = useId(); + // Loads the pinyin dictionary for a Chinese name, so the key reads as it. + useHanRomanizer(label); + + const { + requiredFields, + optionsFor, + pickedValue, + choose, + typeUnavailability, + allRequiredFilled, + subConfig, + catalog, + boundDataset, + semantics, + } = useRequiredPicks({ enabled: true, objectDef, types, selectedType, shownFields }); + + const meta = types.find((v) => v.type === selectedType); + useEffect(() => { + if (!touched) setLabel(suggestName(meta?.label ?? 'View', existingSet)); + }, [meta?.label, touched, existingSet]); + + const primary = requiredFields.find((rf) => !rf.optional && rf.kind !== 'enum'); + const shownPicks = requiredFields.filter((rf) => rf === primary || (!rf.optional && !pickedValue(rf))); + const trimmed = label.trim(); + const isDuplicate = trimmed.length > 0 && existingSet.has(trimmed); + const typeBlocked = !!typeUnavailability[selectedType]; + const canSubmit = trimmed.length > 0 && !isDuplicate && !typeBlocked && allRequiredFilled && (canCreatePersonal || canCreateShared); + const TypeIcon = meta?.icon ?? LayoutGrid; + + const submit = async () => { + if (!canSubmit || submittingRef.current) return; + const block = subConfig(); + const config: InPlaceViewRequest['config'] = { + type: selectedType, + label: trimmed, + name: uniqueViewKey(trimmed, existingKeys ?? []), + ...(Object.keys(block).length > 0 ? { [selectedType]: block } : {}), + }; + submittingRef.current = true; + setSubmitting(true); + try { + await onCreate({ config, scope, includeCurrent: hasUnsavedConditions && includeCurrent }); + } finally { + submittingRef.current = false; + setSubmitting(false); + } + }; + + const nameId = `${baseId}-name`; + const typeId = `${baseId}-type`; + const includeId = `${baseId}-include`; + return ( +
+
+ +
+
+
+ + { if (!touched) e.currentTarget.select(); }} + onChange={(e) => { setLabel(e.target.value); setTouched(true); }} + onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); void submit(); } }} + className="h-8 text-[13px] max-sm:h-11" + data-testid="create-view-card-name" + /> +
+ {isDuplicate && ( +

+ {t('console.objectView.duplicateViewName')} +

+ )} + +
+ + +
+ + {shownPicks.map((rf) => { + const options = optionsFor(rf); + const isField = !rf.kind || rf.kind === 'field'; + const ofDataset = rf.kind === 'measure' || rf.kind === 'dimension'; + const pending = (rf.kind === 'dataset' && catalog.loading) + || (ofDataset && (!boundDataset || semantics.loading)); + const id = `create-view-card-pick-${rf.key}`; + return ( +
+ + choose(rf, value)} + disabled={pending || options.length === 0} + /> +
+ ); + })} + + {hasUnsavedConditions && ( + + )} + + {canCreatePersonal && canCreateShared && ( +
+
+ {(['personal', 'shared'] as const).map((value) => ( + + ))} +
+
+ )} + {scope === 'shared' && ( +

+ {t('view.switcher.scopeHint', { defaultValue: 'Shared views are seen by everyone who can see this list' })} +

+ )} + + +
+
+ ); +} diff --git a/ui/packages/app-shell/src/views/ObjectView.chartRelay-7823.test.tsx b/ui/packages/app-shell/src/views/ObjectView.chartRelay-7823.test.tsx index 9aa973ae27b..b9c82289c31 100644 --- a/ui/packages/app-shell/src/views/ObjectView.chartRelay-7823.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.chartRelay-7823.test.tsx @@ -88,7 +88,10 @@ import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, cleanup, waitFor, screen, fireEvent } from '@testing-library/react'; +// `ObjectView` reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; +import { render, cleanup, waitFor, screen, fireEvent, within } from '@testing-library/react'; import { MemoryRouter, Routes, Route } from 'react-router-dom'; vi.mock('@object-ui/permissions', async (importOriginal) => { @@ -236,13 +239,14 @@ async function mountObjectList(view: Record) { } /** - * Find a visualization option by accessible name, in either switcher form — + * Find a visualization option by accessible name, in any switcher form — + * the Display menu's Layout level lists each as `role="radio"`; on the bar * two-to-four resolvable types render an inline segmented control exposing * `role="tab"`, five or more collapse into a dropdown of plain buttons. * Mirrors the helper in `plugin-list`'s `ListView.chart-capability-7544`. */ const queryViewOption = (name: string) => - screen.queryByRole('tab', { name }) ?? screen.queryByRole('button', { name }); + screen.queryByRole('radio', { name }) ?? screen.queryByRole('tab', { name }) ?? screen.queryByRole('button', { name }); /** * Is the Chart toggle offered for a view whitelisting exactly @@ -252,11 +256,13 @@ const queryViewOption = (name: string) => */ async function chartOffered(view: Record): Promise { await mountObjectList({ appearance: { allowedVisualizations: ['grid', 'chart'] }, ...view }); - // objectui#12423 — the switcher is the Display panel's Layout row by default. + // objectui#12423 — the switcher is the Display menu's Layout level by default. const display = screen.queryByTestId('toolbar-display-trigger'); if (display) { fireEvent.click(display); - await screen.findByTestId('view-settings-content'); + const content = await screen.findByTestId('view-settings-content'); + const layout = within(content).queryByTestId('options-row-layout'); + if (layout) fireEvent.click(layout); } const trigger = screen.queryByTestId('view-switcher-dropdown'); if (trigger) fireEvent.click(trigger); diff --git a/ui/packages/app-shell/src/views/ObjectView.createChartView-11576.test.tsx b/ui/packages/app-shell/src/views/ObjectView.createChartView-11576.test.tsx index c50e7325e43..2267a26c0e2 100644 --- a/ui/packages/app-shell/src/views/ObjectView.createChartView-11576.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.createChartView-11576.test.tsx @@ -22,6 +22,9 @@ import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +// `ObjectView` reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; import { render, cleanup, act, screen, fireEvent, waitFor, within } from '@testing-library/react'; import { MemoryRouter, Routes, Route } from 'react-router-dom'; import { ListViewSchema, ViewItemSchema } from '@objectstack/spec/ui'; @@ -178,13 +181,15 @@ async function optionLabels(key: string): Promise { return labels; } -/** Create a chart view through the view switcher's New view; return the saved body. */ +/** Create a chart view through the Create View dialog; return the saved body. */ async function createChartViewThroughTheSwitcher() { mount({ [`${OBJECT_NAME}.all`]: { name: `${OBJECT_NAME}.all`, label: 'All', type: 'grid', columns: ['name'] } }); await settle(); - // New view, from the page title's view switcher (objectstack#27594). + // The Create View dialog, from the view switcher's Manage views (its + // 「Add view」 creates in place since objectstack#35553). fireEvent.click(screen.getByTestId('list-view-switcher')); - fireEvent.click(screen.getByTestId('list-view-switcher-new')); + fireEvent.click(screen.getByTestId('list-view-switcher-manage')); + fireEvent.click(await screen.findByTestId('manage-views-add')); const card = await screen.findByTestId('create-view-type-chart'); await waitFor(() => expect((card as HTMLButtonElement).disabled).toBe(false)); fireEvent.click(card); diff --git a/ui/packages/app-shell/src/views/ObjectView.createKanbanView-11581.test.tsx b/ui/packages/app-shell/src/views/ObjectView.createKanbanView-11581.test.tsx index cbafbd714f0..6feec9671cc 100644 --- a/ui/packages/app-shell/src/views/ObjectView.createKanbanView-11581.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.createKanbanView-11581.test.tsx @@ -20,6 +20,9 @@ import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +// `ObjectView` reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; import { render, cleanup, act, screen, fireEvent, waitFor } from '@testing-library/react'; import { MemoryRouter, Routes, Route } from 'react-router-dom'; import { ListViewSchema, ViewItemSchema } from '@objectstack/spec/ui'; @@ -145,9 +148,11 @@ describe('ObjectView.handleViewCreate persists a kanban through the one builder , ); await settle(); - // New view, from the page title's view switcher (objectstack#27594). + // The Create View dialog, from the view switcher's Manage views (its + // 「Add view」 creates in place since objectstack#35553). fireEvent.click(screen.getByTestId('list-view-switcher')); - fireEvent.click(screen.getByTestId('list-view-switcher-new')); + fireEvent.click(screen.getByTestId('list-view-switcher-manage')); + fireEvent.click(await screen.findByTestId('manage-views-add')); const card = (await screen.findByTestId('create-view-type-kanban')) as HTMLButtonElement; await waitFor(() => expect(card.disabled).toBe(false)); fireEvent.click(card); diff --git a/ui/packages/app-shell/src/views/ObjectView.createViewRefusal-11578.test.tsx b/ui/packages/app-shell/src/views/ObjectView.createViewRefusal-11578.test.tsx index 8df3a9c3388..ac3d7e6a927 100644 --- a/ui/packages/app-shell/src/views/ObjectView.createViewRefusal-11578.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.createViewRefusal-11578.test.tsx @@ -30,6 +30,9 @@ import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +// `ObjectView` reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; import { render, cleanup, act, screen, fireEvent, waitFor } from '@testing-library/react'; import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom'; import { MetadataClient } from '@object-ui/data-objectstack'; @@ -189,9 +192,11 @@ async function createViewThroughTheSwitcher() { , ); await settle(); - // New view, from the page title's view switcher (objectstack#27594). + // The Create View dialog, from the view switcher's Manage views (its + // 「Add view」 creates in place since objectstack#35553). fireEvent.click(screen.getByTestId('list-view-switcher')); - fireEvent.click(screen.getByTestId('list-view-switcher-new')); + fireEvent.click(screen.getByTestId('list-view-switcher-manage')); + fireEvent.click(await screen.findByTestId('manage-views-add')); await screen.findByTestId('create-view-dialog'); fireEvent.change(labelInput(), { target: { value: 'Pipeline board' } }); await waitFor(() => expect(nameInput().value).toBe('pipeline_board')); diff --git a/ui/packages/app-shell/src/views/ObjectView.emptyColumnsNoProjection-10694.test.tsx b/ui/packages/app-shell/src/views/ObjectView.emptyColumnsNoProjection-10694.test.tsx index e9a46f36795..2005577cd07 100644 --- a/ui/packages/app-shell/src/views/ObjectView.emptyColumnsNoProjection-10694.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.emptyColumnsNoProjection-10694.test.tsx @@ -292,21 +292,18 @@ async function drawView(view: Record): Promise { if (!screen.queryByTestId('view-settings-content')) { fireEvent.click(screen.getByTestId('toolbar-display-trigger')); } const panel = await screen.findByTestId('view-settings-content'); - const name = new RegExp(`^${field}$`, 'i'); - if (!within(panel).queryByText(name)) { - fireEvent.click(within(panel).getByRole('button', { name: 'Hide Fields' })); + if (!within(panel).queryByTestId('options-page-fields')) { + fireEvent.click(within(panel).getByTestId('options-row-fields')); } - const label = await within(panel).findByText(name); - fireEvent.click(label.closest('label')!.querySelector('input')!); + fireEvent.click(await within(panel).findByTestId(`options-fields-hide-${field}`)); } /** The data source's view writes, each a spy: what a write to the shared view would call. */ @@ -528,7 +525,7 @@ describe('an unprojected view applies neither hiddenFields nor fieldOrder on the expect(drawn).not.toContain('owner'); fireEvent.click(screen.getByTestId('toolbar-display-trigger')); const panel = await screen.findByTestId('view-settings-content'); - fireEvent.click(within(panel).getByRole('button', { name: 'Hide Fields' })); + fireEvent.click(within(panel).getByTestId('options-row-fields')); await within(panel).findByText(/^region$/i); expect(within(panel).queryByText(/^owner$/i)).toBeNull(); @@ -591,7 +588,7 @@ describe('an unprojected view applies neither hiddenFields nor fieldOrder on the await mountRoute(listViews, PROBE_ID, makeDataSource()); fireEvent.click(screen.getByTestId('toolbar-display-trigger')); const panel = await screen.findByTestId('view-settings-content'); - fireEvent.click(within(panel).getByRole('button', { name: 'Hide Fields' })); + fireEvent.click(within(panel).getByTestId('options-row-fields')); await within(panel).findByText(/^region$/i); expect(within(panel).queryByText(/^owner$/i)).toBeNull(); 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 4b3ba33e013..350bd633e75 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 @@ -659,17 +659,18 @@ const groupParamOf = (host: Host) => { }; const BY_PRIORITY = { fields: [{ field: 'priority', order: 'desc', collapsed: false }] }; -/** Since objectui#12423 the Group editor is a section of the toolbar's Display panel. */ +/** The Group editor is the Group level of the toolbar's Display menu. */ async function openGroupPanel() { fireEvent.click(screen.getByTestId('toolbar-display-trigger')); await settle(); + fireEvent.click(within(screen.getByTestId('view-settings-content')).getByTestId('options-row-group')); + await settle(); } -/** The Group section's own Clear, inside the Display panel. */ +/** The Group level's own Clear, inside the Display menu. */ function clearGrouping() { const panel = screen.getByTestId('view-settings-content'); - const title = within(panel).getByRole('button', { name: /^group/i }); - fireEvent.click(within(title.parentElement!).getByRole('button', { name: 'Clear' })); + fireEvent.click(within(panel).getByTestId('options-group-clear')); } describe('the toolbar grouping is in the URL too (objectui#11860)', () => { diff --git a/ui/packages/app-shell/src/views/ObjectView.personalViews-29635.test.tsx b/ui/packages/app-shell/src/views/ObjectView.personalViews-29635.test.tsx index 6b2a4cf0f25..c44cc1e5798 100644 --- a/ui/packages/app-shell/src/views/ObjectView.personalViews-29635.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.personalViews-29635.test.tsx @@ -11,9 +11,10 @@ * WHAT IS PINNED. * - The My views section lists the reader's own rows of this object, read * through the data API filtered by object and owner, and no one else's. - * - Save as my view creates a row whose `config` is a spec `ListView` for - * this object carrying the list on screen, and opens it: its body reaches - * the list's query. + * - Save as my view (since objectstack#35553 the dropdown's 「Add view」 + * card, personal by default) creates a row whose `config` is a spec + * `ListView` for this object carrying the list on screen, and opens it: + * its body reaches the list's query. * - Rename goes through the data API's update; Delete through the owner's * door, `DELETE /api/v1/personal-views/:id`, never the data API's delete. * - 📌 on a personal row is the reader's default: it writes the per-object @@ -24,7 +25,7 @@ * the list paints while the read is still out. It waits only for a pinned * view it does not hold yet. * - A refused read (no grant on the object) draws neither the section nor - * Save as my view, and the list is unaffected. + * 「Add view」, and the list is unaffected. * - objectstack#30034 — a personal view opened by its address is not seeded * from, and its address bar never carries, the default view's stored list * state, whichever of the two reads (the reader's own views, the list @@ -33,6 +34,9 @@ import * as React from 'react'; import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; +// `ObjectView` reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; import { render, cleanup, screen, waitFor, within, fireEvent } from '@testing-library/react'; import { MemoryRouter, @@ -213,6 +217,18 @@ const openSwitcher = () => { fireEvent.click(switcher()); return screen.getByTestId('list-view-switcher-menu'); }; +/** + * Save the list on screen as one of the reader's own views: the dropdown's + * 「Add view」 turns into the in-place create card (objectstack#35553, which + * folded Save as my view into it), personal by default. + */ +const saveAsMyView = async (menu: HTMLElement, name: string) => { + await waitFor(() => expect(within(menu).getByTestId('list-view-switcher-new')).toBeInTheDocument()); + fireEvent.click(within(menu).getByTestId('list-view-switcher-new')); + const card = await screen.findByTestId('create-view-card'); + fireEvent.change(within(card).getByTestId('create-view-card-name'), { target: { value: name } }); + return card; +}; const sectionRowIds = (testId: string) => Array.from(screen.getByTestId(testId).querySelectorAll('[data-testid^="view-switcher-row-"]')).map((el) => el.getAttribute('data-testid')!.replace('view-switcher-row-', '')); @@ -268,13 +284,11 @@ describe('objectstack#29635 — My views in the list view switcher', () => { const { dataSource } = mountLeads(`/apps/crm/crm_lead/view/v1?uf__sort=${sort}`); await listToolbar(); - const menu = openSwitcher(); - await waitFor(() => expect(within(menu).getByTestId('list-view-switcher-save-mine')).toBeInTheDocument()); - fireEvent.click(within(menu).getByTestId('list-view-switcher-save-mine')); - const dialog = await screen.findByTestId('personal-view-name-dialog'); - fireEvent.change(within(dialog).getByTestId('personal-view-name-input'), { target: { value: ' Hot leads ' } }); + const card = await saveAsMyView(openSwitcher(), ' Hot leads '); + // The list holds a sort its view does not: the card offers to keep it, on. + expect(within(card).getByTestId('create-view-card-include-current')).toBeChecked(); const readsBefore = leadReads(dataSource).length; - fireEvent.click(within(dialog).getByTestId('personal-view-name-submit')); + fireEvent.click(within(card).getByTestId('create-view-card-submit')); await waitFor(() => expect(dataSource.create).toHaveBeenCalledTimes(1)); const [resource, row] = dataSource.create.mock.calls[0]; @@ -289,7 +303,7 @@ describe('objectstack#29635 — My views in the list view switcher', () => { // It opens at once, on an address that carries no list state of its own, // so the sort the list then reads by is the stored body's. await waitFor(() => expect(switcher()).toHaveTextContent('Hot leads')); - await waitFor(() => expect(screen.queryByTestId('personal-view-name-dialog')).toBeNull()); + await waitFor(() => expect(screen.queryByTestId('create-view-card')).toBeNull()); await waitFor(() => expect(leadReads(dataSource).length).toBeGreaterThan(readsBefore)); expect(leadReads(dataSource).at(-1).$orderby).toEqual([{ field: 'status', order: 'desc' }]); }); @@ -320,6 +334,26 @@ describe('objectstack#29635 — My views in the list view switcher', () => { expect(dataSource.delete).not.toHaveBeenCalled(); }); + it('Options names the open personal view and renames it in place through the data API\'s update (objectstack#35551)', async () => { + const { dataSource } = mountLeads('/apps/crm/crm_lead/view/pv_mine'); + await listToolbar(); + fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + const name = await screen.findByTestId('options-view-name-input'); + expect(name).toHaveValue('Paris leads'); + fireEvent.change(name, { target: { value: 'Paris only' } }); + fireEvent.keyDown(name, { key: 'Enter' }); + await waitFor(() => expect(dataSource.update).toHaveBeenCalledTimes(1)); + expect(dataSource.update.mock.calls[0].slice(0, 3)).toEqual(['sys_personal_view', 'pv_mine', { label: 'Paris only' }]); + }); + + it('CONTROL: on a package view a reader who is no admin sees its name, not a rename', async () => { + mountLeads('/apps/crm/crm_lead/view/v1'); + await listToolbar(); + fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + await screen.findByTestId('view-settings-content'); + expect(screen.queryByTestId('options-view-name-input')).toBeNull(); + }); + it('📌 on a personal row is the reader\'s default: it writes the pin, and the next open of the bare address opens it', async () => { const first = mountLeads('/apps/crm/crm_lead'); await listToolbar(); @@ -377,7 +411,7 @@ describe('objectstack#29635 — My views in the list view switcher', () => { const menu = openSwitcher(); await new Promise((r) => setTimeout(r, 0)); expect(within(menu).queryByTestId('list-view-switcher-mine')).toBeNull(); - expect(within(menu).queryByTestId('list-view-switcher-save-mine')).toBeNull(); + expect(within(menu).queryByTestId('list-view-switcher-new')).toBeNull(); expect(sectionRowIds('list-view-switcher-all')).toEqual(['v1', 'v2']); }); @@ -387,9 +421,10 @@ describe('objectstack#29635 — My views in the list view switcher', () => { mountLeads('/apps/crm/crm_lead/view/v1'); await listToolbar(); const menu = openSwitcher(); - // The reader's own views were read: the section is drawn, Save is not. + // The reader's own views were read: the section is drawn, 「Add view」 is + // not (a reader who is no admin creates only views of their own). await waitFor(() => expect(within(menu).getByTestId('list-view-switcher-mine')).toBeInTheDocument()); - expect(within(menu).queryByTestId('list-view-switcher-save-mine')).toBeNull(); + expect(within(menu).queryByTestId('list-view-switcher-new')).toBeNull(); }); it('CONTROL: with the same loaded grants and the list\'s object readable, Save as my view is offered', async () => { @@ -398,7 +433,7 @@ describe('objectstack#29635 — My views in the list view switcher', () => { await listToolbar(); const menu = openSwitcher(); await waitFor(() => expect(within(menu).getByTestId('list-view-switcher-mine')).toBeInTheDocument()); - expect(within(menu).getByTestId('list-view-switcher-save-mine')).toBeInTheDocument(); + expect(within(menu).getByTestId('list-view-switcher-new')).toBeInTheDocument(); }); }); @@ -604,6 +639,48 @@ describe('objectstack#30073 — a personal view\'s conditions are Filter panel r expect(lastLeadRead(dataSource)).not.toContain('Paris'); }); + it('Options offers the same 保存 beside 恢复默认 (objectstack#35551): it writes the panel into that view', async () => { + const { dataSource } = mountLeads(romeLink('/apps/crm/crm_lead/view/pv_mine')); + await listToolbar(); + await screen.findByTestId('list-personalized-marker'); + fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + const reset = await screen.findByTestId('display-reset-button'); + expect(reset).toBeEnabled(); + fireEvent.click(screen.getByTestId('display-save-button')); + + await waitFor(() => expect(dataSource.update).toHaveBeenCalledTimes(1)); + const [resource, id, patch] = dataSource.update.mock.calls[0]; + expect([resource, id, Object.keys(patch)]).toEqual(['sys_personal_view', 'pv_mine', ['config']]); + expect(patch.config.filter).toEqual([{ field: 'city', operator: 'equals', value: 'Rome' }]); + await waitFor(() => expect(screen.queryByTestId('list-personalized-marker')).toBeNull()); + // Nothing differs from the view now: no 保存, and 恢复默认 is dimmed. + fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + await waitFor(() => expect(screen.getByTestId('display-reset-button')).toBeDisabled()); + expect(screen.queryByTestId('display-save-button')).toBeNull(); + }); + + it('Options\' 恢复默认 is the marker\'s reset: the view opens as its own again', async () => { + const { dataSource } = mountLeads(romeLink('/apps/crm/crm_lead/view/pv_mine')); + await listToolbar(); + await screen.findByTestId('list-personalized-marker'); + fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + fireEvent.click(await screen.findByTestId('display-reset-button')); + await waitFor(() => expect(screen.queryByTestId('list-personalized-marker')).toBeNull()); + await waitFor(() => expect(lastLeadRead(dataSource)).toContain('Paris')); + expect(dataSource.update).not.toHaveBeenCalled(); + }); + + it('a reader without update on their views is offered no 保存 in Options either', async () => { + grants.isLoaded = true; + grants.denied.add('sys_personal_view:update'); + mountLeads(romeLink('/apps/crm/crm_lead/view/pv_mine')); + await listToolbar(); + await screen.findByTestId('list-personalized-marker'); + fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + expect(await screen.findByTestId('display-reset-button')).toBeEnabled(); + expect(screen.queryByTestId('display-save-button')).toBeNull(); + }); + it('a reader without update on their views is not offered 保存', async () => { grants.isLoaded = true; grants.denied.add('sys_personal_view:update'); @@ -651,12 +728,8 @@ describe('objectstack#30073 — a personal view\'s conditions are Filter panel r await listToolbar(); await screen.findByTestId('list-personalized-marker'); - const menu = openSwitcher(); - await waitFor(() => expect(within(menu).getByTestId('list-view-switcher-save-mine')).toBeInTheDocument()); - fireEvent.click(within(menu).getByTestId('list-view-switcher-save-mine')); - const dialog = await screen.findByTestId('personal-view-name-dialog'); - fireEvent.change(within(dialog).getByTestId('personal-view-name-input'), { target: { value: 'Rome leads' } }); - fireEvent.click(within(dialog).getByTestId('personal-view-name-submit')); + const card = await saveAsMyView(openSwitcher(), 'Rome leads'); + fireEvent.click(within(card).getByTestId('create-view-card-submit')); await waitFor(() => expect(first.dataSource.create).toHaveBeenCalledTimes(1)); expect(first.dataSource.create.mock.calls[0][1].config.filter).toEqual([{ field: 'city', operator: 'equals', value: 'Rome' }]); diff --git a/ui/packages/app-shell/src/views/ObjectView.recordOpenDisplay-26681.test.tsx b/ui/packages/app-shell/src/views/ObjectView.recordOpenDisplay-26681.test.tsx index eb349db0333..7b08f5d6259 100644 --- a/ui/packages/app-shell/src/views/ObjectView.recordOpenDisplay-26681.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.recordOpenDisplay-26681.test.tsx @@ -31,6 +31,9 @@ import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +// `ObjectView` reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; import { render, cleanup, screen, fireEvent, waitFor, within } from '@testing-library/react'; import { MemoryRouter, Routes, Route } from 'react-router-dom'; import { createI18n, I18nProvider } from '@object-ui/i18n'; @@ -167,14 +170,16 @@ async function openList(objects: ReturnType) { await screen.findByTestId('primary-field-link', undefined, { timeout: 5000 }); } -function openDisplay() { +/** Open records is a section of the Display menu's More level. */ +async function openDisplay() { fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + fireEvent.click(await screen.findByTestId('options-row-more')); } describe('objectstack#26681 — Open records in the Display menu', () => { it('objectstack#28915 — a drawer object: the section offers Drawer and Full page only', async () => { await openList(objectsWith()); - openDisplay(); + await openDisplay(); const drawerSegment = await screen.findByRole('radio', { name: 'Drawer' }); expect(drawerSegment.getAttribute('aria-checked')).toBe('true'); const segments = within(screen.getByTestId('display-record-open')).getAllByRole('radio'); @@ -193,7 +198,7 @@ describe('objectstack#26681 — Open records in the Display menu', () => { it('objectstack#28915 — a stored `split`: the section reads Drawer, and the row opens the drawer', async () => { window.localStorage.setItem(RECORD_OPEN_PREFERENCE_KEY, 'split'); await openList(objectsWith()); - openDisplay(); + await openDisplay(); expect((await screen.findByRole('radio', { name: 'Drawer' })).getAttribute('aria-checked')).toBe('true'); fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' }); fireEvent.click(screen.getByTestId('primary-field-link')); @@ -203,7 +208,7 @@ describe('objectstack#26681 — Open records in the Display menu', () => { it('a reader who prefers the page chooses Drawer: the preference is kept, and the next row click opens the drawer', async () => { window.localStorage.setItem(RECORD_OPEN_PREFERENCE_KEY, 'page'); await openList(objectsWith()); - openDisplay(); + await openDisplay(); const pageSegment = await screen.findByRole('radio', { name: 'Full page' }); expect(pageSegment.getAttribute('aria-checked')).toBe('true'); fireEvent.click(screen.getByRole('radio', { name: 'Drawer' })); @@ -222,7 +227,7 @@ describe('objectstack#26681 — Open records in the Display menu', () => { it('objectstack#27545 — choosing Full page: the next row click lands on the record page', async () => { await openList(objectsWith()); - openDisplay(); + await openDisplay(); fireEvent.click(await screen.findByRole('radio', { name: 'Full page' })); expect(window.localStorage.getItem(RECORD_OPEN_PREFERENCE_KEY)).toBe('page'); fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' }); @@ -235,7 +240,7 @@ describe('objectstack#26681 — Open records in the Display menu', () => { window.localStorage.setItem(RECORD_OPEN_PREFERENCE_KEY, 'drawer'); await openList(objectsWith({ mode: 'page' })); expect(screen.queryByTestId('record-open-as-page')).toBeNull(); - openDisplay(); + await openDisplay(); expect(await screen.findByTestId('display-record-open-declared')).toBeTruthy(); expect(within(screen.getByTestId('display-record-open')).queryByRole('radio')).toBeNull(); }); diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index 291e6d4311c..81372b72973 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -827,50 +827,19 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co baseView, }); - // objectstack#29635 — Save as my view, and Rename and Delete on the - // reader's own views. Save is offered to any reader the server lets save - // one (`sys_personal_view` read and create), not to admins only; the name - // is asked in `PersonalViewNameDialog`. A reader who cannot read the - // list's own object is offered no Save: there is no list to keep. + // objectstack#29635 — creating one of the reader's own views, and Rename + // and Delete on them. Creating is offered to any reader the server lets + // save one (`sys_personal_view` read and create), not to admins only, in + // the view switcher's in-place create card (objectstack#35553, which + // folded Save as my view into it); a rename's name is asked in + // `PersonalViewNameDialog`. A reader who cannot read the list's own object + // is offered no create: there is no list to keep. const listReadable = !perms.isLoaded || perms.can(objectDef.name, 'read'); - const [personalViewDialog, setPersonalViewDialog] = useState<{ mode: 'save' } | { mode: 'rename'; viewId: string } | null>(null); + const [personalViewDialog, setPersonalViewDialog] = useState<{ mode: 'rename'; viewId: string } | null>(null); const openPersonalView = (id: string) => { if (viewId) navigate(`../${id}`, { relative: 'path' }); else navigate(`view/${id}`); }; - /** Save the list on screen as one of the reader's own views, and open it. */ - const handleSavePersonalView = async (label: string): Promise => { - if (!activeView) return false; - // The list's toolbar state is the address's (`uf_*`), through the same - // field gate its seed reads it with. - const built = buildPersonalViewConfig(objectDef.name, activeView, { - // The panel's group is the one the list shows (an emptied panel - // included), not the address's copy of it. - url: { ...parseListStateParams(searchParams, acceptListField), filters: readPanelFilters() }, - preference: listPrefs.preference.perView?.[activeView.id], - panelFilters: viewPanelFilters, - }); - if (!built.ok) { - toast.error(t('form.saveError'), { description: t(FILTER_FOLD_REFUSAL_KEYS[built.reason]) }); - return false; - } - try { - const savedId = await personalViews.save(label, built.config); - // objectstack#30073 — the list now lives in the saved view; the - // view it came from returns to its own (no temporary conditions, - // not personalized). - clearSourceListState(activeView.id); - openPersonalView(savedId); - return true; - } catch (err) { - console.error('[ObjectView] Failed to save a personal view:', err); - toast.error(t('form.saveError'), { - description: err instanceof Error ? err.message : String(err), - classNames: { description: 'whitespace-pre-line' }, - }); - return false; - } - }; const handleRenamePersonalView = async (id: string, label: string): Promise => { try { await personalViews.rename(id, label); @@ -1049,9 +1018,22 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co setPinnedViewId: setPinnedViewChoice, appSegment: appName, personalViewIds, - onSavePersonalView: personalViewsReady && personalGrant('create') && listReadable && !!activeView && !viewAccess.refusal - ? () => setPersonalViewDialog({ mode: 'save' }) - : undefined, + // objectstack#35553 — the dropdown's 「Add view」 creates in place. + create: { + activeView, + readListState: () => ({ + url: { ...parseListStateParams(searchParams, acceptListField), filters: readPanelFilters() }, + preference: activeView ? listPrefs.preference.perView?.[activeView.id] : undefined, + panelFilters: viewPanelFilters, + }), + savePersonal: personalViews.save, + openPersonal: openPersonalView, + createShared: handleViewCreate, + clearSourceListState, + canCreatePersonal: personalViewsReady && personalGrant('create') && listReadable && !!activeView && !viewAccess.refusal, + canCreateShared: isAdmin, + hasUnsavedConditions: listPersonalizedParts.some((part) => part === 'filters' || part === 'sort'), + }, onRenamePersonalView: personalViewsReady && personalGrant('update') ? (id: string) => setPersonalViewDialog({ mode: 'rename', viewId: id }) : undefined, @@ -1106,6 +1088,19 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co initialUfSelections, handleUserFilterSelectionsChange, viewPanelFilters, + // objectstack#35551 — the Options menu names the view (renamed in + // place by its owner or an admin on a saved shared view) and, while + // the list differs from its view, offers 保存 and 恢复默认: the + // personalization marker's two acts (objectstack#30073). + listViewActions: { + rename: activeView && activeIsPersonal && personalViewsReady && personalGrant('update') + ? (label: string) => handleRenamePersonalView(String(activeView.id), label) + : activeView && isAdmin && savedViews.some((sv: any) => viewRowId(sv) === activeView.id) + ? async (label: string) => { await handleRenameView(String(activeView.id), label); return true; } + : undefined, + save: !isEnvironmentList && canUpdatePersonalView && listPersonalizedParts.length > 0 ? () => { void handleSaveToPersonalView(); } : undefined, + reset: !isEnvironmentList && listPersonalizedParts.length > 0 ? handleResetView : undefined, + }, }); // objectstack#25992 slice 9: the merged views and the plugin's `ObjectViewSchema` @@ -1396,13 +1391,11 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co { if (!open) setPersonalViewDialog(null); }} - title={personalViewDialog?.mode === 'rename' - ? t('view.rename', { defaultValue: 'Rename' }) - : t('view.switcher.saveAsMyView', { defaultValue: 'Save as my view' })} + title={t('view.rename', { defaultValue: 'Rename' })} initialName={renamingPersonalView?.label ?? ''} - onSubmit={(name) => (personalViewDialog?.mode === 'rename' + onSubmit={(name) => (personalViewDialog ? handleRenamePersonalView(personalViewDialog.viewId, name) - : handleSavePersonalView(name))} + : Promise.resolve(false))} t={t} /> diff --git a/ui/packages/app-shell/src/views/inPlaceViewCreate-35553.test.tsx b/ui/packages/app-shell/src/views/inPlaceViewCreate-35553.test.tsx new file mode 100644 index 00000000000..cfb51ff7e7a --- /dev/null +++ b/ui/packages/app-shell/src/views/inPlaceViewCreate-35553.test.tsx @@ -0,0 +1,487 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#35553 — the view dropdown's body and its in-place create card. + * + * What is pinned: + * - the dropdown groups the reader's own views and the shared ones, leads + * every row with its type's icon, keeps the whole name (a `title` and a + * wrapping label, never a cut), keeps the search, and offers 「Add view」 + * and Manage views at the bottom; + * - 「Add view」 turns the dropdown into the card: name, type, the one pick + * the type needs, 「include the current filters and sort」 only while + * the list holds some (on by default), and the personal / shared switch + * only for a reader who may create both. The default is one of the + * reader's own views, and no machine name is asked for: one is generated; + * - a create closes the dropdown; a refused one keeps the card and its input; + * - the generated key, the body built from the open view, and the host + * hook that saves a personal view and opens it or hands a shared one to + * the add-view door (its draft rules unchanged). + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, cleanup, fireEvent, waitFor, screen, within, act, renderHook } from '@testing-library/react'; +import { ListViewSchema } from '@objectstack/spec/ui'; +import { MetadataClient } from '@object-ui/data-objectstack'; + +vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } })); + +/** No dataset is served: the chart's catalog answers empty, without a network. */ +let client: MetadataClient; +vi.mock('./metadata-admin/useMetadata', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataClient: () => client, +})); + +import { toast } from 'sonner'; +import { CreateViewCard, uniqueViewKey, type InPlaceViewRequest } from './CreateViewDialog'; +import { buildInPlaceViewConfig } from './personalViews'; +import { useCreateViewInPlace } from './objectViewViewCrud'; +import { ObjectViewSwitcherMenu } from './objectViewSwitcherMenu'; +import type { TitleSwitcherView } from './objectViewTitleSwitcher'; + +const DEAL = { + name: 'crm_deal', + label: 'Deal', + fields: { + name: { type: 'text', label: 'Name' }, + stage: { type: 'select', label: 'Stage', options: [{ value: 'open', label: 'Open' }] }, + priority: { type: 'select', label: 'Priority', options: [{ value: 'high', label: 'High' }] }, + close_date: { type: 'date', label: 'Close date' }, + amount: { type: 'number', label: 'Amount' }, + }, +}; + +const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 30))); + +beforeEach(() => { + client = new MetadataClient({ + baseUrl: 'http://localhost', + fetch: (async () => new Response('[]', { status: 200, headers: { 'content-type': 'application/json' } })) as unknown as typeof fetch, + }); + vi.mocked(toast.error).mockClear(); +}); +afterEach(cleanup); + +// --------------------------------------------------------------------------- +// The generated key +// --------------------------------------------------------------------------- + +describe('uniqueViewKey: no machine name is asked for', () => { + it('is the name as a key, and a taken one (bare or object-qualified) gets the next free suffix', () => { + expect(uniqueViewKey('Open deals', [])).toBe('open_deals'); + expect(uniqueViewKey('Open deals', ['open_deals'])).toBe('open_deals_2'); + expect(uniqueViewKey('Open deals', ['crm_deal.open_deals', 'open_deals_2'])).toBe('open_deals_3'); + }); + + it('a name with nothing to spell a key from is `view`, made unique the same way', () => { + expect(uniqueViewKey('!!!', [])).toBe('view'); + expect(uniqueViewKey(' ', ['view'])).toBe('view_2'); + }); + + it('any name gives a key the spec accepts', () => { + for (const label of ['我的商机', '2024 pipeline', 'Ünïcode — deals', 'a'.repeat(200)]) { + expect(uniqueViewKey(label, [])).toMatch(/^[a-z_][a-z0-9_]*$/); + } + }); +}); + +// --------------------------------------------------------------------------- +// The body built from the open view +// --------------------------------------------------------------------------- + +describe('buildInPlaceViewConfig', () => { + const VIEW = { + id: 'crm_deal.all', + name: 'all', + label: 'All deals', + type: 'grid', + columns: ['name', 'stage', 'amount'], + filter: [{ field: 'stage', operator: 'equals', value: 'open' }], + sort: [{ field: 'name', order: 'asc' }], + }; + + it('retypes the open view, adds the type\'s picks, and is a spec ListView bound to the object', () => { + const built = buildInPlaceViewConfig('crm_deal', VIEW, { type: 'kanban', block: { groupByField: 'priority' } }, { url: {} }); + expect(built.ok).toBe(true); + if (!built.ok) return; + expect(ListViewSchema.safeParse(built.config).success).toBe(true); + // The spec requires a kanban's card fields: the body's columns, as the add-view door mirrors them. + expect(built.config).toMatchObject({ + type: 'kanban', + kanban: { groupByField: 'priority', columns: ['name', 'stage', 'amount'] }, + columns: ['name', 'stage', 'amount'], + }); + for (const key of ['id', 'name', 'label']) expect(built.config).not.toHaveProperty(key); + }); + + it('a gallery gets the columns as its card fields; a block that lists its own keeps them', () => { + const gallery = buildInPlaceViewConfig('crm_deal', VIEW, { type: 'gallery' }, { url: {} }); + expect(gallery.ok && gallery.config.gallery).toEqual({ visibleFields: ['name', 'stage', 'amount'] }); + const board = { ...VIEW, type: 'kanban', kanban: { groupByField: 'stage', columns: ['name'] } }; + const kept = buildInPlaceViewConfig('crm_deal', board, { type: 'kanban', block: { groupByField: 'priority' } }, { url: {} }); + expect(kept.ok && kept.config.kanban).toEqual({ groupByField: 'priority', columns: ['name'] }); + const grid = buildInPlaceViewConfig('crm_deal', board, { type: 'grid' }, { url: {} }); + expect(grid.ok && ListViewSchema.safeParse(grid.config).success).toBe(true); + }); + + it('with the list\'s conditions it carries them; without, the view\'s own', () => { + const url = { sort: [{ field: 'amount', order: 'desc' as const }] }; + const withCurrent = buildInPlaceViewConfig('crm_deal', VIEW, { type: 'grid' }, { url }); + const without = buildInPlaceViewConfig('crm_deal', VIEW, { type: 'grid' }, { preference: undefined }); + expect(withCurrent.ok && withCurrent.config.sort).toEqual([{ field: 'amount', order: 'desc' }]); + expect(without.ok && without.config.sort).toEqual(VIEW.sort); + expect(without.ok && without.config.filter).toEqual(VIEW.filter); + }); +}); + +// --------------------------------------------------------------------------- +// The host hook +// --------------------------------------------------------------------------- + +describe('useCreateViewInPlace', () => { + const ACTIVE = { id: 'crm_deal.all', name: 'all', label: 'All deals', type: 'grid', columns: ['name', 'stage'] }; + const t = ((key: string) => key) as never; + + function setup(over: Partial[0]> = {}) { + const savePersonal = vi.fn(async () => 'pv_9'); + const openPersonal = vi.fn(); + const createShared = vi.fn(async () => true); + const readListState = vi.fn(() => ({ url: { sort: [{ field: 'stage', order: 'asc' as const }] } })); + const { result } = renderHook(() => useCreateViewInPlace({ + objectName: 'crm_deal', activeView: ACTIVE, readListState, savePersonal, openPersonal, createShared, t, ...over, + })); + return { create: result.current, savePersonal, openPersonal, createShared }; + } + + const request = (scope: 'personal' | 'shared', includeCurrent = true): InPlaceViewRequest => ({ + config: { type: 'kanban', label: 'By priority', name: 'by_priority', kanban: { groupByField: 'priority' } }, + scope, + includeCurrent, + }); + + it('personal: saves one of the reader\'s own views under the name given, and opens it', async () => { + const { create, savePersonal, openPersonal, createShared } = setup(); + await expect(create(request('personal'))).resolves.toBe(true); + expect(savePersonal).toHaveBeenCalledTimes(1); + const [label, config] = savePersonal.mock.calls[0] as unknown as [string, Record]; + expect(label).toBe('By priority'); + expect(config).toMatchObject({ type: 'kanban', kanban: { groupByField: 'priority' }, sort: [{ field: 'stage', order: 'asc' }] }); + expect(ListViewSchema.safeParse(config).success).toBe(true); + expect(openPersonal).toHaveBeenCalledWith('pv_9'); + expect(createShared).not.toHaveBeenCalled(); + }); + + it('without the current conditions the list\'s sort stays out', async () => { + const { create, savePersonal } = setup(); + await create(request('personal', false)); + const config = (savePersonal.mock.calls[0] as unknown as [string, Record])[1]; + expect(config).not.toHaveProperty('sort'); + }); + + it('shared: hands the add-view door the body under the generated key and the name, never the open view\'s id', async () => { + const { create, savePersonal, createShared } = setup(); + await expect(create(request('shared'))).resolves.toBe(true); + const body = (createShared.mock.calls[0] as unknown as [Record])[0]; + expect(body).toMatchObject({ type: 'kanban', label: 'By priority', name: 'by_priority', kanban: { groupByField: 'priority' } }); + expect(body).not.toHaveProperty('id'); + expect(savePersonal).not.toHaveBeenCalled(); + }); + + it('a refused save says why and resolves false, and opens nothing', async () => { + const { create, openPersonal } = setup({ savePersonal: vi.fn(async () => { throw new Error('denied'); }) }); + await expect(create(request('personal'))).resolves.toBe(false); + expect(toast.error).toHaveBeenCalledTimes(1); + expect(openPersonal).not.toHaveBeenCalled(); + }); + + it('a list it cannot fold is refused before anything is written', async () => { + const nested = { logic: 'and', conditions: [{ logic: 'or', conditions: [{ field: 'stage', operator: 'equals', value: 'open' }] }] }; + const savePersonal = vi.fn(async () => 'x'); + const { create } = setup({ savePersonal, readListState: () => ({ url: { filters: nested as never } }) }); + await expect(create(request('personal'))).resolves.toBe(false); + expect(savePersonal).not.toHaveBeenCalled(); + expect(toast.error).toHaveBeenCalledTimes(1); + }); +}); + +// --------------------------------------------------------------------------- +// The card +// --------------------------------------------------------------------------- + +function mountCard(props: Partial> = {}) { + const onCreate = vi.fn(async (_request: InPlaceViewRequest) => true); + const onBack = vi.fn(); + render( + , + ); + return { onCreate, onBack }; +} + +async function chooseType(type: string) { + fireEvent.keyDown(screen.getByTestId('create-view-card-type'), { key: 'ArrowDown' }); + const listbox = await screen.findByRole('listbox'); + fireEvent.click(within(listbox).getByTestId(`create-view-card-type-${type}`)); + await waitFor(() => expect(screen.queryByRole('listbox')).not.toBeInTheDocument()); + await settle(); +} + +const name = () => screen.getByTestId('create-view-card-name') as HTMLInputElement; +const submit = () => screen.getByTestId('create-view-card-submit') as HTMLButtonElement; + +describe('the in-place create card', () => { + it('opens with a free name and a grid, asks no machine name, and creates one of the reader\'s own views', async () => { + const { onCreate } = mountCard(); + await settle(); + expect(name().value).not.toBe(''); + expect(name().value).not.toBe('All deals'); + // Name, type, Create: no key field, no include box, no scope switch for this reader. + expect(screen.getByTestId('create-view-card').querySelectorAll('input').length).toBe(1); + expect(screen.queryByTestId('create-view-card-include-current')).toBeNull(); + expect(screen.queryByTestId('create-view-card-scope')).toBeNull(); + + fireEvent.change(name(), { target: { value: 'Pipeline' } }); + fireEvent.click(submit()); + await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1)); + expect(onCreate.mock.calls[0][0]).toEqual({ + config: { type: 'grid', label: 'Pipeline', name: 'pipeline' }, + scope: 'personal', + includeCurrent: false, + }); + }); + + it('lists every offered type with its icon', async () => { + mountCard(); + fireEvent.keyDown(screen.getByTestId('create-view-card-type'), { key: 'ArrowDown' }); + const listbox = await screen.findByRole('listbox'); + for (const type of ['grid', 'kanban', 'calendar', 'gallery']) { + expect(within(listbox).getByTestId(`create-view-card-type-${type}`).querySelector('svg')).not.toBeNull(); + } + fireEvent.keyDown(listbox, { key: 'Escape' }); + }); + + it('kanban asks for its group field, and the pick lands in the request', async () => { + const { onCreate } = mountCard(); + await chooseType('kanban'); + const pick = screen.getByTestId('create-view-card-pick-groupByField'); + fireEvent.keyDown(pick, { key: 'ArrowDown' }); + const listbox = await screen.findByRole('listbox'); + fireEvent.click(within(listbox).getByRole('option', { name: 'Priority' })); + await settle(); + fireEvent.change(name(), { target: { value: 'By priority' } }); + fireEvent.click(submit()); + await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1)); + expect(onCreate.mock.calls[0][0].config).toEqual({ + type: 'kanban', label: 'By priority', name: 'by_priority', kanban: { groupByField: 'priority' }, + }); + }); + + it('kanban defaults its group field to a status-like field the list shows, before one it hides', async () => { + const withApproval = { + ...DEAL, + fields: { approval_status: { type: 'select', label: 'Approval status', options: [{ value: 'ok', label: 'OK' }] }, ...DEAL.fields }, + }; + const { onCreate } = mountCard({ objectDef: withApproval, shownFields: ['name', 'stage', 'amount'] }); + await chooseType('kanban'); + expect(screen.getByTestId('create-view-card-pick-groupByField')).toHaveTextContent('Stage'); + fireEvent.click(submit()); + await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1)); + expect(onCreate.mock.calls[0][0].config.kanban).toEqual({ groupByField: 'stage' }); + }); + + it('CONTROL: without the shown fields it is the first status-like field of the object', async () => { + const withApproval = { + ...DEAL, + fields: { approval_status: { type: 'select', label: 'Approval status', options: [{ value: 'ok', label: 'OK' }] }, ...DEAL.fields }, + }; + mountCard({ objectDef: withApproval }); + await chooseType('kanban'); + expect(screen.getByTestId('create-view-card-pick-groupByField')).toHaveTextContent('Approval status'); + }); + + it('calendar asks for its date field alone; a type that needs none shows no pick', async () => { + mountCard(); + await chooseType('calendar'); + expect(screen.getByTestId('create-view-card-pick-startDateField')).toBeInTheDocument(); + expect(screen.getByTestId('create-view-card').querySelectorAll('[data-testid^="create-view-card-pick-"]').length).toBe(1); + await chooseType('grid'); + expect(screen.queryAllByTestId(/^create-view-card-pick-/)).toHaveLength(0); + }); + + it('with unsaved filters or sort, offers to include them, on by default', async () => { + const { onCreate } = mountCard({ hasUnsavedConditions: true }); + const box = screen.getByTestId('create-view-card-include-current') as HTMLInputElement; + expect(box.checked).toBe(true); + fireEvent.click(submit()); + await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1)); + expect(onCreate.mock.calls[0][0].includeCurrent).toBe(true); + }); + + it('…and unticked, the request leaves them out', async () => { + const { onCreate } = mountCard({ hasUnsavedConditions: true }); + fireEvent.click(screen.getByTestId('create-view-card-include-current')); + fireEvent.click(submit()); + await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1)); + expect(onCreate.mock.calls[0][0].includeCurrent).toBe(false); + }); + + it('a reader who may create shared views gets the switch, on personal by default', async () => { + const { onCreate } = mountCard({ canCreateShared: true }); + const personal = screen.getByTestId('create-view-card-scope-personal'); + expect(personal).toHaveAttribute('aria-checked', 'true'); + expect(screen.queryByTestId('create-view-card-shared-hint')).toBeNull(); + fireEvent.click(screen.getByTestId('create-view-card-scope-shared')); + expect(screen.getByTestId('create-view-card-shared-hint')).toBeInTheDocument(); + fireEvent.click(submit()); + await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1)); + expect(onCreate.mock.calls[0][0].scope).toBe('shared'); + }); + + it('a taken name is refused in place; Enter creates', async () => { + const { onCreate } = mountCard(); + fireEvent.change(name(), { target: { value: 'All deals' } }); + expect(screen.getByTestId('create-view-card-duplicate')).toBeInTheDocument(); + expect(submit()).toBeDisabled(); + fireEvent.change(name(), { target: { value: 'All deals, mine' } }); + fireEvent.keyDown(name(), { key: 'Enter' }); + await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1)); + }); + + it('back returns to the list', () => { + const { onBack } = mountCard(); + fireEvent.click(screen.getByTestId('create-view-card-back')); + expect(onBack).toHaveBeenCalledTimes(1); + }); +}); + +// --------------------------------------------------------------------------- +// The dropdown body +// --------------------------------------------------------------------------- + +const VIEWS: TitleSwitcherView[] = [ + { id: 'crm_deal.all', label: 'All deals', type: 'grid', authored: true }, + { id: 'crm_deal.board', label: 'Pipeline board', type: 'kanban', authored: true }, + { + id: 'pv_1', + label: 'Deals closing this quarter in the northern region, owned by my team', + type: 'calendar', + authored: false, + personal: true, + }, +]; + +function mountMenu(props: Partial> = {}) { + const onChoose = vi.fn(); + const onClose = vi.fn(); + const onManageViews = vi.fn(); + const t = ((key: string, opts?: { defaultValue?: string }) => opts?.defaultValue ?? key) as never; + render( + , + ); + return { onChoose, onClose, onManageViews }; +} + +describe('the view dropdown body', () => { + it('groups My views and the shared views, each row led by its type icon', () => { + mountMenu(); + const mine = screen.getByTestId('list-view-switcher-mine'); + const shared = screen.getByTestId('list-view-switcher-all'); + expect(within(mine).getByText('My views')).toBeInTheDocument(); + expect(within(shared).getByText('Shared views')).toBeInTheDocument(); + const rows = (group: HTMLElement) => Array.from(group.querySelectorAll('[data-section]')).map((r) => r.dataset.testid); + expect(rows(mine)).toEqual(['view-switcher-row-pv_1']); + expect(rows(shared)).toEqual(['view-switcher-row-crm_deal.all', 'view-switcher-row-crm_deal.board']); + for (const icon of screen.getAllByTestId('view-switcher-type-icon')) expect(icon.querySelector('svg')).not.toBeNull(); + }); + + it('a long name is kept whole: it wraps, and the row names it in full', () => { + mountMenu(); + const row = screen.getByTestId('view-switcher-row-pv_1'); + const label = within(row).getByTestId('view-switcher-name'); + expect(label).toHaveTextContent(VIEWS[2].label); + expect(label.className).not.toMatch(/\btruncate\b/); + expect(label.className).toMatch(/break-words/); + expect(within(row).getByRole('button', { name: VIEWS[2].label })).toHaveAttribute('title', VIEWS[2].label); + }); + + it('search narrows the rows; choosing one hands its id to the host', () => { + const { onChoose } = mountMenu(); + fireEvent.change(screen.getByTestId('list-view-switcher-search'), { target: { value: 'board' } }); + expect(screen.queryByTestId('view-switcher-row-crm_deal.all')).toBeNull(); + fireEvent.click(within(screen.getByTestId('view-switcher-row-crm_deal.board')).getAllByRole('button')[0]); + expect(onChoose).toHaveBeenCalledWith('crm_deal.board'); + }); + + it('Manage views stays; with no create door there is no Add view', () => { + const { onManageViews, onClose } = mountMenu(); + expect(screen.queryByTestId('list-view-switcher-new')).toBeNull(); + fireEvent.click(screen.getByTestId('list-view-switcher-manage')); + expect(onClose).toHaveBeenCalled(); + expect(onManageViews).toHaveBeenCalled(); + }); + + it('Add view turns the dropdown into the card; a create closes it, a refusal keeps the card', async () => { + let answer = false; + const onCreate = vi.fn(async () => answer); + const { onClose } = mountMenu({ + create: { objectDef: DEAL, canCreatePersonal: true, canCreateShared: false, hasUnsavedConditions: false, onCreate }, + }); + fireEvent.click(screen.getByTestId('list-view-switcher-new')); + await screen.findByTestId('create-view-card'); + fireEvent.change(screen.getByTestId('create-view-card-name'), { target: { value: 'Mine' } }); + fireEvent.click(screen.getByTestId('create-view-card-submit')); + await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1)); + await settle(); + expect(onClose).not.toHaveBeenCalled(); + expect(screen.getByTestId('create-view-card-name')).toHaveValue('Mine'); + + answer = true; + fireEvent.click(screen.getByTestId('create-view-card-submit')); + await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1)); + }); + + it('the card\'s generated key avoids every view\'s id, bare or object-qualified', async () => { + const onCreate = vi.fn(async () => true); + mountMenu({ + views: [...VIEWS, { id: 'crm_deal.mine', label: 'Other', type: 'grid', authored: false }], + create: { objectDef: DEAL, canCreatePersonal: true, canCreateShared: false, hasUnsavedConditions: false, onCreate }, + }); + fireEvent.click(screen.getByTestId('list-view-switcher-new')); + await screen.findByTestId('create-view-card'); + fireEvent.change(screen.getByTestId('create-view-card-name'), { target: { value: 'Mine' } }); + fireEvent.click(screen.getByTestId('create-view-card-submit')); + await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1)); + expect((onCreate.mock.calls[0] as unknown as [InPlaceViewRequest])[0].config.name).toBe('mine_2'); + }); + + it('back from the card returns to the list', async () => { + mountMenu({ + create: { objectDef: DEAL, canCreatePersonal: true, canCreateShared: false, hasUnsavedConditions: false, onCreate: vi.fn() }, + }); + fireEvent.click(screen.getByTestId('list-view-switcher-new')); + fireEvent.click(await screen.findByTestId('create-view-card-back')); + expect(screen.getByTestId('list-view-switcher-body')).toBeInTheDocument(); + }); +}); diff --git a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx index f6194338c93..981886da995 100644 --- a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx +++ b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx @@ -108,6 +108,7 @@ export function useObjectViewListRenderer({ initialUfSelections, handleUserFilterSelectionsChange, viewPanelFilters, + listViewActions, }: { objectName: string | undefined; inSetup: ReturnType; @@ -162,7 +163,24 @@ export function useObjectViewListRenderer({ * time, and the list judges its 「Personalized」 filters against them. */ viewPanelFilters?: FilterBuilderRowGroup; + /** + * objectstack#35551 — the open view's rename, 保存 and full reset, for + * the list's options menu (`ListView`'s `onRenameView` / `onSaveView` / + * `onResetView`). Each is wired only when the reader may use it. + */ + listViewActions?: { + rename?: (label: string) => boolean | Promise; + save?: () => void; + reset?: () => void; + }; }) { + // objectstack#35551 — the host hands fresh closures every render; the list + // reads the latest through a ref, and re-renders only when one appears or goes. + const listViewActionsRef = useRef(listViewActions); + listViewActionsRef.current = listViewActions; + const offersRename = !!listViewActions?.rename; + const offersSave = !!listViewActions?.save; + const offersReset = !!listViewActions?.reset; // objectstack#27058 — below `sm` the title switcher is the phone's one // view control, so the list offers no layout switcher of its own there. const wideViewport = useViewTabsFit(); @@ -1018,6 +1036,10 @@ export function useObjectViewListRenderer({ // for the 「Personalized」 marker, which then owns the one reset // (the Display control draws none of its own). onPersonalizationChange={(parts) => handleListPersonalizationChange(identityKey, parts)} + // objectstack#35551 — the view's rename, 保存 and full reset in the options menu. + onRenameView={offersRename ? (label: string) => listViewActionsRef.current?.rename?.(label) ?? false : undefined} + onSaveView={offersSave ? () => listViewActionsRef.current?.save?.() : undefined} + onResetView={offersReset ? () => listViewActionsRef.current?.reset?.() : undefined} className={className} onEdit={editHandler} // objectui#13089 — the view's Add button is the header New: @@ -1124,7 +1146,7 @@ export function useObjectViewListRenderer({ dataSource={ds} /> ); - }, [inSetup, activeView, activeViewDeclaresColumns, activeViewIsSaved, objectDef, objectName, refreshKey, createRecord, urlFilters, initialUfSelections, handleUserFilterSelectionsChange, writeListUrlState, listPage, user?.id, pageOffersCreate, listAddRecordOpensCreate, listIdentityKey, listPrefs.ready, listPrefs.preference, listPrefs.patchView, managedUsers, managedUserMarker, recordOpen, openAsPage, rowOpensRecord, handleListRowsChange, hasPhoneTitle, leadStore, wideViewport, handleListPersonalizationChange, workspaceTimeZone, viewPanelFilters, previewDrafts, previewDataSource, unpublishedObjects]); + }, [inSetup, activeView, activeViewDeclaresColumns, activeViewIsSaved, objectDef, objectName, refreshKey, createRecord, urlFilters, initialUfSelections, handleUserFilterSelectionsChange, writeListUrlState, listPage, user?.id, pageOffersCreate, listAddRecordOpensCreate, listIdentityKey, listPrefs.ready, listPrefs.preference, listPrefs.patchView, managedUsers, managedUserMarker, recordOpen, openAsPage, rowOpensRecord, handleListRowsChange, hasPhoneTitle, leadStore, wideViewport, handleListPersonalizationChange, workspaceTimeZone, viewPanelFilters, offersRename, offersSave, offersReset, previewDrafts, previewDataSource, unpublishedObjects]); return { renderListView }; } diff --git a/ui/packages/app-shell/src/views/objectViewSwitcherMenu.tsx b/ui/packages/app-shell/src/views/objectViewSwitcherMenu.tsx new file mode 100644 index 00000000000..8f228130770 --- /dev/null +++ b/ui/packages/app-shell/src/views/objectViewSwitcherMenu.tsx @@ -0,0 +1,328 @@ +/** + * The body of the list's view dropdown (the view bar's switcher opens it): + * + * - a search box over every view's name; + * - the reader's pinned view and the views they opened lately, then their own + * views (My views) and the shared views, each a group of its own; every row + * leads with its view type's icon, and a long name wraps rather than being + * cut, so two names that share their first words still read apart; + * - 「Add view」 at the bottom, which turns the dropdown into the in-place + * create card ({@link CreateViewCard}) — Save as my view folds into it — and + * Manage views for a reader the host offers it to. + * + * Each row offers on hover the reader's ☆ (sidebar Favorites) and 📌 (the + * view this object's list opens by default), and on the reader's own views + * Rename and Delete. The trigger (type icon, name, count, caret) and the + * popover around this body are the switcher's (`./objectViewTitleSwitcher.tsx`). + */ + +import { lazy, Suspense, useState, type ComponentType, type ReactNode } from 'react'; +import { cn, Input } from '@object-ui/components'; +import type { useObjectTranslation } from '@object-ui/i18n'; +import { Check, ListOrdered, Pencil, Pin, Plus, Star, Trash2 } from 'lucide-react'; +import type { ListViewFavorites } from '../layout/listViewFavorites.js'; +import { VIEW_TYPE_ICONS } from './objectViewHelpers.js'; +import type { CreateViewCardProps } from './CreateViewDialog.js'; +import type { TitleSwitcherView } from './objectViewTitleSwitcher.js'; + +// The create card shares its module with the Create View dialog, which loads +// on demand; the card does too, when the reader asks to add a view. +const CreateViewCard = lazy(() => + import('./CreateViewDialog.js').then((m) => ({ default: m.CreateViewCard })), +); + +type TFn = ReturnType['t']; + +/** How many views the Recent group lists at most. */ +const RECENT_VIEW_LIMIT = 3; + +/** What the create card needs from the host; the card's names and keys come from `views`. */ +export type SwitcherCreateOptions = Omit; + +export interface ObjectViewSwitcherMenuProps { + /** The views, in the order the list keeps them. */ + views: readonly TitleSwitcherView[]; + /** The open view, or `''` when none is. */ + activeViewId: string; + /** Switch to a view; the host closes the dropdown. */ + onChoose: (viewId: string) => void; + /** Close the dropdown (after a create, or before a dialog opens). */ + onClose: () => void; + pinnedViewId?: string | null; + /** Pin a view, or `null` to unpin. Absent ⇒ no 📌 and no Pinned group. */ + onPinnedViewChange?: (viewId: string | null) => void; + recentViewIds?: readonly string[]; + favorites: ListViewFavorites | null; + viewTypeIcons?: Record>; + /** Manage views. Absent ⇒ not offered. */ + onManageViews?: () => void; + onRenamePersonalView?: (viewId: string) => void; + onDeletePersonalView?: (viewId: string) => void; + /** 「Add view」 and its card. Absent ⇒ `onAddView`, if any. */ + create?: SwitcherCreateOptions; + /** 「Add view」 for a host with no card to offer: the dropdown closes and this runs (the Create View dialog). */ + onAddView?: () => void; + t: TFn; +} + +/** The authored views first, then the saved ones, each in the list's order; the reader's own last. */ +function authoredFirst(views: readonly TitleSwitcherView[]): TitleSwitcherView[] { + return [ + ...views.filter((v) => v.authored), + ...views.filter((v) => !v.authored && !v.personal), + ...views.filter((v) => v.personal), + ]; +} + +function GroupLabel({ children, icon }: { children: ReactNode; icon?: ReactNode }) { + return ( +
+ {icon} + {children} +
+ ); +} + +const FOOTER_ITEM = 'flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-[13px] hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring max-sm:min-h-11'; + +export function ObjectViewSwitcherMenu({ + views, + activeViewId, + onChoose, + onClose, + pinnedViewId = null, + onPinnedViewChange, + recentViewIds = [], + favorites, + viewTypeIcons = VIEW_TYPE_ICONS, + onManageViews, + onRenamePersonalView, + onDeletePersonalView, + create, + onAddView, + t, +}: ObjectViewSwitcherMenuProps) { + const [mode, setMode] = useState<'list' | 'create'>('list'); + const [query, setQuery] = useState(''); + + const byId = new Map(views.map((v) => [v.id, v])); + const all = authoredFirst(views); + const shared = all.filter((v) => !v.personal); + const mine = all.filter((v) => v.personal); + const pinned = pinnedViewId && onPinnedViewChange ? byId.get(pinnedViewId) : undefined; + const recent = recentViewIds + .filter((id) => id !== pinned?.id) + .map((id) => byId.get(id)) + .filter((v): v is TitleSwitcherView => !!v) + .slice(0, RECENT_VIEW_LIMIT); + const needle = query.trim().toLocaleLowerCase(); + const matches = needle ? all.filter((v) => v.label.toLocaleLowerCase().includes(needle)) : all; + + if (mode === 'create' && create) { + return ( + }> + v.label)} + existingKeys={views.map((v) => v.id)} + onBack={() => setMode('list')} + onCreate={async (request) => { + const created = await create.onCreate(request); + if (created) onClose(); + return created; + }} + /> + + ); + } + + const row = (view: TitleSwitcherView, group: string) => { + const Icon = viewTypeIcons[view.type]; + const active = view.id === activeViewId; + const isPinned = view.id === pinned?.id; + const inMenu = !!favorites?.inMenu(view.id); + const starred = !inMenu && !!favorites?.isFavorite(view.id); + const starLabel = inMenu + ? t('view.switcher.inMenu', { defaultValue: 'Already in the menu' }) + : starred + ? t('common.removeFromFavorites', { defaultValue: 'Remove from favorites' }) + : t('common.addToFavorites', { defaultValue: 'Add to favorites' }); + const pinLabel = isPinned + ? t('view.switcher.unpin', { defaultValue: 'Unpin: the list opens its default view again' }) + : t('view.switcher.pin', { defaultValue: 'Pin: open this view by default' }); + const renameLabel = t('view.rename', { defaultValue: 'Rename' }); + const deleteLabel = t('view.deleteView', { defaultValue: 'Delete View' }); + const iconButton = 'flex h-7 w-7 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground max-sm:h-11 max-sm:w-11 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'; + // Shown on hover or focus, and always while set; a touch screen has no + // hover, so there they always show. + const reveal = 'opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 focus-visible:opacity-100 pointer-coarse:opacity-100'; + return ( +
+ + {favorites && ( + + )} + {onPinnedViewChange && ( + + )} + {view.personal && onRenamePersonalView && ( + + )} + {view.personal && onDeletePersonalView && ( + + )} +
+ ); + }; + + return ( +
+
+ setQuery(e.target.value)} + placeholder={t('view.searchViews', { defaultValue: 'Search views' })} + aria-label={t('view.searchViews', { defaultValue: 'Search views' })} + data-testid="list-view-switcher-search" + className="h-8 text-[13px] max-sm:h-11" + /> +
+
+ {needle ? ( + matches.length > 0 + ? matches.map((v) => row(v, 'match')) + : ( +

+ {t('view.noViewsFound', { defaultValue: 'No views match your search.' })} +

+ ) + ) : ( + <> + {pinned && ( +
+ + {row(pinned, 'pinned')} +
+ )} + {recent.length > 0 && ( +
+ {t('view.switcher.recent', { defaultValue: 'Recent' })} + {recent.map((v) => row(v, 'recent'))} +
+ )} + {mine.length > 0 && ( +
+ {t('view.switcher.myViews', { defaultValue: 'My views' })} + {mine.map((v) => row(v, 'mine'))} +
+ )} + {shared.length > 0 && ( +
+ {t('view.switcher.sharedViews', { defaultValue: 'Shared views' })} + {shared.map((v) => row(v, 'all'))} +
+ )} + + )} +
+ {(create || onAddView || onManageViews) && ( +
+ {(create || onAddView) && ( + + )} + {onManageViews && ( + + )} +
+ )} +
+ ); +} diff --git a/ui/packages/app-shell/src/views/objectViewTitleSwitcher.test.tsx b/ui/packages/app-shell/src/views/objectViewTitleSwitcher.test.tsx index b6462e87736..45ee01ec57e 100644 --- a/ui/packages/app-shell/src/views/objectViewTitleSwitcher.test.tsx +++ b/ui/packages/app-shell/src/views/objectViewTitleSwitcher.test.tsx @@ -167,7 +167,7 @@ describe('objectstack#27594 — the title switcher dropdown', () => { expect(within(menu).getAllByTestId('view-switcher-pin')).toHaveLength(VIEWS.length); }); - it('the foot offers New view and Manage views when handed, and each closes the dropdown', () => { + it('the foot offers Add view and Manage views when handed, and each closes the dropdown', () => { const onAddView = vi.fn(); const onManageViews = vi.fn(); mount({ onAddView, onManageViews }); @@ -180,6 +180,22 @@ describe('objectstack#27594 — the title switcher dropdown', () => { expect(onManageViews).toHaveBeenCalledTimes(1); }); + it('with `create` handed, 「Add view」 turns the dropdown into the in-place card, not the dialog (objectstack#35553)', async () => { + const onAddView = vi.fn(); + const onCreate = vi.fn().mockResolvedValue(true); + const { menu } = mount({ + onAddView, + create: { canCreatePersonal: true, canCreateShared: false, hasUnsavedConditions: false, onCreate }, + }); + expect(within(menu).getByTestId('list-view-switcher-new')).toHaveTextContent('Add view'); + fireEvent.click(within(menu).getByTestId('list-view-switcher-new')); + expect(onAddView).not.toHaveBeenCalled(); + const card = await within(screen.getByTestId('list-view-switcher-menu')).findByTestId('create-view-card'); + // Back returns to the views. + fireEvent.click(within(card).getByTestId('create-view-card-back')); + expect(screen.getByTestId('list-view-switcher-body')).toBeInTheDocument(); + }); + it('CONTROL: with neither handed (a reader who is no admin), the dropdown has no foot', () => { const { menu } = mount(); expect(within(menu).queryByTestId('list-view-switcher-new')).toBeNull(); diff --git a/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx b/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx index 1c8ba877bfb..35b35b5071e 100644 --- a/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx +++ b/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx @@ -22,11 +22,12 @@ * packages and environment declare. Their rows offer Rename and Delete too, * and their 📌 is the same pin: a personal view pinned is the reader's default. * - * The dropdown ends with Save as my view (the list on screen saved as one of - * the reader's own views, offered to any reader the server lets save one), - * New view (the Create View dialog) and, for an admin, Manage views - * (`ManageViewsDialog`): the rename, delete, shared default and configure acts - * that each tab's ▾ menu used to carry. + * The dropdown's body is `./objectViewSwitcherMenu.tsx` (objectstack#35553). + * It ends with 「Add view」, which turns the dropdown into the in-place create + * card (Save as my view folds into it: one of the reader's own views by + * default, a shared draft for a reader who may create one), and, for an + * admin, Manage views (`ManageViewsDialog`): the rename, delete, shared + * default and configure acts that each tab's ▾ menu used to carry. * * At every width the switcher leads the list's toolbar row (`ListView`'s * `toolbarLeading`) or heads a chart (objectstack#27058, objectstack#35548): @@ -34,13 +35,13 @@ * a view dropdown of its own. */ -import { createContext, createElement, useContext, useMemo, useState, type ComponentType, type Dispatch, type ReactNode, type SetStateAction } from 'react'; -import { cn, Input, Popover, PopoverContent, PopoverTrigger } from '@object-ui/components'; +import { createContext, createElement, useContext, useMemo, useState, type ComponentType, type Dispatch, type SetStateAction } from 'react'; +import { cn, Popover, PopoverContent, PopoverTrigger } from '@object-ui/components'; import type { ViewTabItem } from '@object-ui/plugin-view'; import { resolveViewId } from '@object-ui/core'; import { useDisplayLocale, pickLocalized } from '@object-ui/i18n'; import type { useObjectLabel, useObjectTranslation } from '@object-ui/i18n'; -import { BookmarkPlus, Check, ChevronDown, ListOrdered, Pencil, Pin, Plus, Star, Trash2 } from 'lucide-react'; +import { ChevronDown } from 'lucide-react'; import { viewRowId } from '../utils/viewIdentity.js'; import { useRecentItems } from '../hooks/useRecentItems.js'; import { useListViewFavorites, type ListViewFavorites } from '../layout/listViewFavorites.js'; @@ -50,6 +51,8 @@ import { VIEW_TYPE_ICONS } from './objectViewHelpers.js'; import { viewTabLabel } from './viewTabLabel.js'; import type { buildViewTabs } from './objectViewTabs.js'; import type { ConsoleObjectViewProps } from './ObjectView.js'; +import { ObjectViewSwitcherMenu, type SwitcherCreateOptions } from './objectViewSwitcherMenu.js'; +import { useCreateViewInPlace } from './objectViewViewCrud.js'; type TFn = ReturnType['t']; @@ -67,9 +70,6 @@ export interface ListRecordCountState { export const ListRecordCountContext = createContext(null); -/** How many views the dropdown's Recent section lists at most. */ -const RECENT_VIEW_LIMIT = 3; - /** One view the switcher offers. */ export interface TitleSwitcherView { id: string; @@ -104,37 +104,22 @@ export interface ObjectViewTitleSwitcherProps { /** The ☆ of each row; absent off an app route, where no row offers one. */ favorites: ListViewFavorites | null; viewTypeIcons?: Record>; - /** New view: the Create View dialog. Absent ⇒ not offered. */ + /** 「Add view」 with no create card: the Create View dialog. Absent ⇒ only the card, if any. */ onAddView?: () => void; /** Manage views: the admin's dialog. Absent ⇒ not offered. */ onManageViews?: () => void; - /** Save as my view: the list on screen as one of the reader's own views. Absent ⇒ not offered. */ - onSavePersonalView?: () => void; /** Rename one of the reader's own views. Absent ⇒ not offered. */ onRenamePersonalView?: (viewId: string) => void; /** Delete one of the reader's own views. Absent ⇒ not offered. */ onDeletePersonalView?: (viewId: string) => void; + /** + * 「Add view」 as the in-place create card (objectstack#35553); Save as my + * view folds into it. Absent ⇒ `onAddView`, if any. + */ + create?: SwitcherCreateOptions; t: TFn; } -/** The authored views first, then the saved ones, each in the list's order; the reader's own last. */ -function authoredFirst(views: readonly TitleSwitcherView[]): TitleSwitcherView[] { - return [ - ...views.filter((v) => v.authored), - ...views.filter((v) => !v.authored && !v.personal), - ...views.filter((v) => v.personal), - ]; -} - -function SectionLabel({ children, icon }: { children: ReactNode; icon?: ReactNode }) { - return ( -
- {icon} - {children} -
- ); -} - export function ObjectViewTitleSwitcher({ views, activeViewId, @@ -148,155 +133,28 @@ export function ObjectViewTitleSwitcher({ viewTypeIcons = VIEW_TYPE_ICONS, onAddView, onManageViews, - onSavePersonalView, onRenamePersonalView, onDeletePersonalView, + create, t, }: ObjectViewTitleSwitcherProps) { const [open, setOpen] = useState(false); - const [query, setQuery] = useState(''); const listState = useContext(ListRecordCountContext); const displayLocale = useDisplayLocale(); const byId = useMemo(() => new Map(views.map((v) => [v.id, v])), [views]); - const all = useMemo(() => authoredFirst(views), [views]); - const shared = all.filter((v) => !v.personal); - const mine = all.filter((v) => v.personal); - const pinned = pinnedViewId && onPinnedViewChange ? byId.get(pinnedViewId) : undefined; - const recent = recentViewIds - .filter((id) => id !== pinned?.id) - .map((id) => byId.get(id)) - .filter((v): v is TitleSwitcherView => !!v) - .slice(0, RECENT_VIEW_LIMIT); - const needle = query.trim().toLocaleLowerCase(); - const matches = needle ? all.filter((v) => v.label.toLocaleLowerCase().includes(needle)) : all; - const activeType = listState?.layout ?? byId.get(activeViewId)?.type; const ActiveIcon = activeType ? viewTypeIcons[activeType] : undefined; const count = listState?.count ?? null; - const onOpenChange = (next: boolean) => { - setOpen(next); - if (!next) setQuery(''); - }; const choose = (viewId: string) => { - onOpenChange(false); + setOpen(false); if (viewId !== activeViewId) onViewChange(viewId); }; - const row = (view: TitleSwitcherView, section: string) => { - const Icon = viewTypeIcons[view.type]; - const active = view.id === activeViewId; - const isPinned = view.id === pinned?.id; - const inMenu = !!favorites?.inMenu(view.id); - const starred = !inMenu && !!favorites?.isFavorite(view.id); - const starLabel = inMenu - ? t('view.switcher.inMenu', { defaultValue: 'Already in the menu' }) - : starred - ? t('common.removeFromFavorites', { defaultValue: 'Remove from favorites' }) - : t('common.addToFavorites', { defaultValue: 'Add to favorites' }); - const pinLabel = isPinned - ? t('view.switcher.unpin', { defaultValue: 'Unpin: the list opens its default view again' }) - : t('view.switcher.pin', { defaultValue: 'Pin: open this view by default' }); - const renameLabel = t('view.rename', { defaultValue: 'Rename' }); - const deleteLabel = t('view.deleteView', { defaultValue: 'Delete View' }); - const iconButton = 'flex h-7 w-7 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground max-sm:h-11 max-sm:w-11 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'; - // Shown on hover or focus, and always while set, so a starred or pinned - // view says so without a hover. - // A touch screen has no hover, so there they always show. - const reveal = 'opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 focus-visible:opacity-100 pointer-coarse:opacity-100'; - return ( -
- - {favorites && ( - - )} - {onPinnedViewChange && ( - - )} - {view.personal && onRenamePersonalView && ( - - )} - {view.personal && onDeletePersonalView && ( - - )} -
- ); - }; - return ( - + + {/* The dropdown's body (objectstack#35553): the views, grouped, and + 「Add view」, which turns it into the in-place create card. */} -
- setQuery(e.target.value)} - placeholder={t('view.searchViews', { defaultValue: 'Search views' })} - aria-label={t('view.searchViews', { defaultValue: 'Search views' })} - data-testid="list-view-switcher-search" - className="h-8 max-sm:h-11" - /> -
-
- {needle ? ( - matches.length > 0 - ? matches.map((v) => row(v, 'match')) - : ( -

- {t('view.noViewsFound', { defaultValue: 'No views match your search.' })} -

- ) - ) : ( - <> - {pinned && ( -
- - {row(pinned, 'pinned')} -
- )} - {recent.length > 0 && ( -
- {t('view.switcher.recent', { defaultValue: 'Recent' })} - {recent.map((v) => row(v, 'recent'))} -
- )} - {mine.length > 0 && ( -
- {t('view.switcher.myViews', { defaultValue: 'My views' })} - {mine.map((v) => row(v, 'mine'))} -
- )} - {shared.length > 0 && ( -
- {t('view.switcher.all', { defaultValue: 'All views' })} - {shared.map((v) => row(v, 'all'))} -
- )} - - )} -
- {(onSavePersonalView || onAddView || onManageViews) && ( -
- {onSavePersonalView && ( - - )} - {onAddView && ( - - )} - {onManageViews && ( - - )} -
- )} + setOpen(false)} + pinnedViewId={pinnedViewId} + onPinnedViewChange={onPinnedViewChange} + recentViewIds={recentViewIds} + favorites={favorites} + viewTypeIcons={viewTypeIcons} + onManageViews={onManageViews} + onRenamePersonalView={onRenamePersonalView} + onDeletePersonalView={onDeletePersonalView} + create={create} + onAddView={onAddView} + t={t} + />
); } +/** The field names an open view's columns list (a name, or `{ field }`). */ +function shownFieldsOf(view: Record | undefined): string[] { + const columns = Array.isArray(view?.columns) ? view.columns : []; + return columns + .map((column: unknown) => (typeof column === 'string' ? column : (column as { field?: unknown })?.field)) + .filter((name: unknown): name is string => typeof name === 'string' && name.length > 0); +} + +// The doors of a host that offers no in-place create: never called, since no +// card is drawn without `create`. +const NO_LIST_STATE = () => ({ url: {} }); +const REFUSE_SAVE = async (): Promise => { throw new Error('no personal views here'); }; +const IGNORE = () => {}; +const REFUSE_CREATE = async (): Promise => false; + /** * The view items (which `ManageViewsDialog` lists too) and the title switcher * of an object's list. Every input is passed in; the component reads the @@ -452,7 +256,7 @@ export function useObjectViewTitleSwitcher({ setPinnedViewId, appSegment, personalViewIds, - onSavePersonalView, + create, onRenamePersonalView, onDeletePersonalView, }: { @@ -477,10 +281,40 @@ export function useObjectViewTitleSwitcher({ appSegment: string | undefined; /** The ids of the reader's own views among `views` (objectstack#29635). */ personalViewIds: ReadonlySet; - onSavePersonalView?: () => void; + /** + * The in-place create of the dropdown's 「Add view」 (objectstack#35553): + * who may create which kind, whether the list holds unsaved filters or + * sort, and the host's doors (`useCreateViewInPlace`). Neither kind + * allowed ⇒ no card, and an admin keeps the Create View dialog. + */ + create?: Omit[0], 'objectName' | 't'> & { + canCreatePersonal: boolean; + canCreateShared: boolean; + hasUnsavedConditions: boolean; + }; onRenamePersonalView?: (viewId: string) => void; onDeletePersonalView?: (viewId: string) => void; }) { + const createInPlace = useCreateViewInPlace({ + objectName: objectDef.name, + activeView: create?.activeView, + readListState: create?.readListState ?? NO_LIST_STATE, + savePersonal: create?.savePersonal ?? REFUSE_SAVE, + openPersonal: create?.openPersonal ?? IGNORE, + createShared: create?.createShared ?? REFUSE_CREATE, + clearSourceListState: create?.clearSourceListState, + t, + }); + const createOptions: SwitcherCreateOptions | undefined = create && (create.canCreatePersonal || create.canCreateShared) + ? { + objectDef, + canCreatePersonal: create.canCreatePersonal, + canCreateShared: create.canCreateShared, + hasUnsavedConditions: create.hasUnsavedConditions, + shownFields: shownFieldsOf(create.activeView), + onCreate: createInPlace, + } + : undefined; // objectui#12528 — the view's description is shown once. It rides on the // switcher, as the trigger's tooltip, on every face: since // objectstack#35548 the switcher leads the list's view bar (the list's @@ -569,7 +403,7 @@ export function useObjectViewTitleSwitcher({ favorites={favorites} onAddView={isAdmin ? handleAddView : undefined} onManageViews={isAdmin ? () => setManageViewsOpen(true) : undefined} - onSavePersonalView={onSavePersonalView} + create={createOptions} onRenamePersonalView={onRenamePersonalView} onDeletePersonalView={onDeletePersonalView} t={t} diff --git a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx index c73c16ebbff..e4a927652ad 100644 --- a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx +++ b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx @@ -24,6 +24,9 @@ import { buildAddViewSpec, setDefaultViewPatches, buildViewConfigSaveBody } from import type { buildViewTabs } from './objectViewTabs.js'; import { dispatchViewPatches } from './objectViewOptions.js'; import type { ConsoleObjectViewProps } from './ObjectView.js'; +import type { InPlaceViewRequest } from './CreateViewDialog.js'; +import { buildInPlaceViewConfig, type PersonalViewListState } from './personalViews.js'; +import { FILTER_FOLD_REFUSAL_KEYS } from './viewFilterFold.js'; export function useObjectViewViewCrud({ dataSource, @@ -425,3 +428,83 @@ export function useObjectViewViewCrud({ handleAddView, }; } + +/** + * The switcher's in-place create (the create card's `onCreate`): build the new + * view's body from the open view ({@link buildInPlaceViewConfig}), then + * + * - `personal` — save it as one of the reader's own views (`sys_personal_view`) + * and open it; + * - `shared` — hand it to the add-view door (`createShared`, the view-config + * panel's create: an invisible draft opened in draft preview, published + * explicitly), under the machine key the card generated. The draft and + * publish rules are that door's, unchanged. + * + * Resolves `true` once the view exists; on a refusal it says why (a toast with + * the door's own words) and resolves `false`, so the card keeps its input. + */ +export function useCreateViewInPlace({ + objectName, + activeView, + readListState, + savePersonal, + openPersonal, + createShared, + clearSourceListState, + t, +}: { + objectName: string; + /** The open view, the new view's starting point. */ + activeView: Record | undefined; + /** The list on screen, read at create time (the address's toolbar state, the panel, the reader's state). */ + readListState: () => PersonalViewListState; + /** Save one of the reader's own views; resolves its id. */ + savePersonal: (label: string, config: Record) => Promise; + /** Open one of the reader's own views by id. */ + openPersonal: (id: string) => void; + /** The add-view door for a shared view (`handleViewCreate`). */ + createShared: (config: Record) => Promise; + /** + * Clear the reader's temporary list state on the view the new one came + * from, once a personal view took it over (as Save as my view does, + * objectstack#30073): that view then opens as its own again. + */ + clearSourceListState?: (viewId: string) => void; + t: ReturnType['t']; +}) { + return useCallback(async ({ config, scope, includeCurrent }: InPlaceViewRequest): Promise => { + const { type, label, name } = config; + const block = config[type]; + const listState = readListState(); + const built = buildInPlaceViewConfig( + objectName, + activeView ?? {}, + { type, ...(block && typeof block === 'object' ? { block } : {}) }, + includeCurrent ? listState : { preference: listState.preference }, + ); + if (!built.ok) { + toast.error(t('form.saveError'), { description: t(FILTER_FOLD_REFUSAL_KEYS[built.reason]) }); + return false; + } + if (scope === 'shared') { + // The body's own identity is the open view's; the new view's is + // the name and key the card gave it. + const body: Record = { ...built.config, type, label, name }; + delete body.id; + return createShared(body); + } + try { + const id = await savePersonal(label, built.config); + if (includeCurrent && activeView?.id) clearSourceListState?.(String(activeView.id)); + openPersonal(id); + return true; + } catch (err) { + console.error('[ObjectView] Failed to create a personal view:', err); + toast.error(t('form.saveError'), { + description: err instanceof Error ? err.message : String(err), + classNames: { description: 'whitespace-pre-line' }, + }); + return false; + } + }, [objectName, activeView, readListState, savePersonal, openPersonal, createShared, clearSourceListState, t]); +} diff --git a/ui/packages/app-shell/src/views/personalViews.ts b/ui/packages/app-shell/src/views/personalViews.ts index 220b8157ecc..7481aa77dcc 100644 --- a/ui/packages/app-shell/src/views/personalViews.ts +++ b/ui/packages/app-shell/src/views/personalViews.ts @@ -403,3 +403,65 @@ export function usePersonalViews({ return { status, views, save, update, rename, remove }; } + +/** What a new view created in place is made of (the switcher's create card). */ +export interface InPlaceViewPicks { + /** The new view's type. */ + type: string; + /** The type's picks, the spec block under the type's key (e.g. `{ groupByField }`). */ + block?: Record; +} + +/** + * The `ListView` body of a view created in place from the open view: the open + * view's own body (its columns, filter, sort, grouping, row height) as the + * starting point, retyped to the chosen type with the type's picks laid over + * that type's block, and — when `state` is given, i.e. the reader kept 「include + * the current filters and sort」 — the list on screen laid over it the way Save + * as my view lays it ({@link buildPersonalViewConfig}). Without `state` only + * the reader's column layout and row height carry over; their unsaved filter, + * sort and grouping stay behind. + * + * One body for both scopes: it is what one of the reader's own views stores + * as `config`, and what the add-view door creates a shared view from. The + * fold refusal of Save as my view applies unchanged. + * + * A type whose block carries a field list of its own gets the body's columns + * there when the block holds none, as the add-view door's builder does + * (`buildNewViewSpec`): a kanban's `columns` (required by the spec), a + * gallery's `visibleFields` (its card body). + */ +export function buildInPlaceViewConfig( + objectName: string, + view: Record, + picks: InPlaceViewPicks, + state: PersonalViewListState | { preference?: ListViewPreference }, +): { ok: true; config: Record } | { ok: false; reason: FilterFoldRefusal } { + const own = isRecord(view[picks.type]) ? (view[picks.type] as Record) : {}; + const draft: Record = { + ...view, + type: picks.type, + ...(picks.block && Object.keys(picks.block).length > 0 ? { [picks.type]: { ...own, ...picks.block } } : {}), + }; + const listState: PersonalViewListState = 'url' in state ? state : { url: {}, preference: state.preference }; + const built = buildPersonalViewConfig(objectName, draft, listState); + if (!built.ok) return built; + const mirrorKey = IN_PLACE_COLUMN_MIRRORS[picks.type]; + if (mirrorKey) { + const block = isRecord(built.config[picks.type]) ? (built.config[picks.type] as Record) : {}; + const held = block[mirrorKey]; + if (!Array.isArray(held) || held.length === 0) { + const names = (Array.isArray(built.config.columns) ? built.config.columns : []) + .map(columnName) + .filter((n): n is string => !!n); + built.config[picks.type] = { ...block, [mirrorKey]: names }; + } + } + return built; +} + +/** The view types whose spec block lists fields of its own, by that list's key. */ +const IN_PLACE_COLUMN_MIRRORS: Record = { + kanban: 'columns', + gallery: 'visibleFields', +}; diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 5bf33806b5b..05c1d44924f 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1058,8 +1058,6 @@ const ar = { recordOpen: "فتح السجلات", recordOpenDrawer: "درج جانبي", recordOpenPage: "صفحة كاملة", - recordOpenNote: "تفضيلك الشخصي، وليس جزءًا من تعريف الكائن. يفتح ↗ الخاص بالسجل الصفحة الكاملة دائمًا.", - recordOpenDeclaredPage: "هذا الكائن مُعرَّف ليُفتح كصفحة كاملة", addGroup: "إضافة حقل مجموعة", collapsedByDefault: "مطوي افتراضياً", removeGroup: "إزالة", @@ -1069,6 +1067,25 @@ const ar = { withheldFieldsLeftOut: "لا يتم العرض أو التصفية أو الفرز أو التجميع حسب {{fields}}: الحزمة التي تضيف هذا الحقل معطلة. سيعود عند تفعيل الحزمة.", inlineEditShort: "تحرير مضمّن", inlineEditLabel: "حرّر السجلات مباشرة (انقر خلية للتحرير)", + // The list's Options menu. + optionsMenu: { + viewName: 'اسم العرض', + fields: 'الحقول', + fieldsShown: 'الحقول المعروضة: {{count}}', + fieldsShown_zero: '{{count}} حقل معروض', + fieldsShown_one: '{{count}} حقل معروض', + fieldsShown_two: 'حقلان معروضان ({{count}})', + fieldsShown_few: '{{count}} حقول معروضة', + fieldsShown_many: '{{count}} حقلًا معروضًا', + fieldsShown_other: '{{count}} حقل معروض', + rowHeight: 'ارتفاع الصف', + rowHeightCompact: 'مضغوط', + rowHeightStandard: 'قياسي', + rowHeightSpacious: 'واسع', + more: 'المزيد', + restoreDefaults: 'استعادة الافتراضي', + recordOpenAlwaysPage: 'تُفتح السجلات دائمًا في صفحة كاملة', + }, }, managedByBadge: { systemWritable: { @@ -1317,14 +1334,20 @@ const ar = { label: "العروض", pinned: "مثبّت", recent: "الأخيرة", - all: "كل العروض", pin: "تثبيت: فتح هذا العرض افتراضيًا", unpin: "إلغاء التثبيت: تفتح القائمة عرضها الافتراضي مجددًا", inMenu: "موجود بالفعل في القائمة", // objectstack#29635 — the reader's own views (My views). myViews: "طرق العرض الخاصة بي", - saveAsMyView: "حفظ كطريقة عرض خاصة بي", myViewName: "اسم طريقة العرض", + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: 'العروض المشتركة', + addView: 'إضافة عرض', + typeLabel: 'نوع العرض', + includeCurrent: 'تضمين عوامل التصفية والفرز الحالية', + scopeShared: 'مشترك', + scopeHint: 'العروض المشتركة يراها كل من يمكنه رؤية هذه القائمة', + create: 'إنشاء', }, dragToReorder: "اسحب لإعادة الترتيب", defaultView: "العرض الافتراضي", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 8eab046684c..c945d69760f 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -941,8 +941,6 @@ const de = { recordOpen: "Datensätze öffnen", recordOpenDrawer: "Seitenleiste", recordOpenPage: "Ganze Seite", - recordOpenNote: "Ihre persönliche Einstellung, nicht Teil der Objektdeklaration. Das ↗ eines Datensatzes öffnet immer die ganze Seite.", - recordOpenDeclaredPage: "Dieses Objekt ist so deklariert, dass es als ganze Seite geöffnet wird", addGroup: "Gruppenfeld hinzufügen", collapsedByDefault: "Standardmäßig eingeklappt", removeGroup: "Entfernen", @@ -952,6 +950,21 @@ const de = { withheldFieldsLeftOut: "Nicht angezeigt, gefiltert, sortiert oder gruppiert nach {{fields}}: Das Paket, das das Feld hinzufügt, ist deaktiviert. Es kehrt zurück, sobald das Paket aktiviert wird.", inlineEditShort: "Inline bearbeiten", inlineEditLabel: "Datensätze inline bearbeiten (Zelle anklicken zum Bearbeiten)", + // The list's Options menu. + optionsMenu: { + viewName: 'Ansichtsname', + fields: 'Felder', + fieldsShown: '{{count}} angezeigt', + fieldsShown_one: '{{count}} angezeigt', + fieldsShown_other: '{{count}} angezeigt', + rowHeight: 'Zeilenhöhe', + rowHeightCompact: 'Kompakt', + rowHeightStandard: 'Standard', + rowHeightSpacious: 'Großzügig', + more: 'Mehr', + restoreDefaults: 'Standard wiederherstellen', + recordOpenAlwaysPage: 'Datensätze öffnen sich immer als ganze Seite', + }, }, managedByBadge: { systemWritable: { @@ -1188,14 +1201,20 @@ const de = { label: "Ansichten", pinned: "Angeheftet", recent: "Zuletzt", - all: "Alle Ansichten", pin: "Anheften: diese Ansicht standardmäßig öffnen", unpin: "Lösen: die Liste öffnet wieder ihre Standardansicht", inMenu: "Bereits im Menü", // objectstack#29635 — the reader's own views (My views). myViews: "Meine Ansichten", - saveAsMyView: "Als meine Ansicht speichern", myViewName: "Name der Ansicht", + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: 'Geteilte Ansichten', + addView: 'Ansicht hinzufügen', + typeLabel: 'Ansichtstyp', + includeCurrent: 'Aktuelle Filter und Sortierung übernehmen', + scopeShared: 'Geteilt', + scopeHint: 'Geteilte Ansichten sieht jeder, der diese Liste sehen kann', + create: 'Erstellen', }, dragToReorder: "Zum Neuanordnen ziehen", defaultView: "Standardansicht", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index d248388b03f..35dcddd9092 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1230,8 +1230,6 @@ const en = { recordOpen: 'Open records', recordOpenDrawer: 'Drawer', recordOpenPage: 'Full page', - recordOpenNote: 'Your own preference, not part of the object’s declaration. A record’s ↗ always opens the full page.', - recordOpenDeclaredPage: 'This object is declared to open as a full page', addGroup: 'Add group field', collapsedByDefault: 'Collapsed by default', removeGroup: 'Remove', @@ -1241,6 +1239,21 @@ const en = { withheldFieldsLeftOut: 'Not shown, filtered, sorted or grouped by {{fields}}: the package that adds it is disabled. It comes back when the package is enabled.', inlineEditShort: 'Edit inline', inlineEditLabel: 'Edit records inline (click a cell to edit)', + // The list's Options menu. + optionsMenu: { + viewName: 'View name', + fields: 'Fields', + fieldsShown: '{{count}} shown', + fieldsShown_one: '{{count}} shown', + fieldsShown_other: '{{count}} shown', + rowHeight: 'Row height', + rowHeightCompact: 'Compact', + rowHeightStandard: 'Standard', + rowHeightSpacious: 'Spacious', + more: 'More', + restoreDefaults: 'Restore defaults', + recordOpenAlwaysPage: 'Records always open as a full page', + }, }, managedByBadge: { config: { @@ -1483,14 +1496,20 @@ const en = { label: 'Views', pinned: 'Pinned', recent: 'Recent', - all: 'All views', pin: 'Pin: open this view by default', unpin: 'Unpin: the list opens its default view again', inMenu: 'Already in the menu', // objectstack#29635 — the reader's own views (My views). myViews: 'My views', - saveAsMyView: 'Save as my view', myViewName: 'View name', + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: 'Shared views', + addView: 'Add view', + typeLabel: 'View type', + includeCurrent: 'Include the current filters and sort', + scopeShared: 'Shared', + scopeHint: 'Shared views are seen by everyone who can see this list', + create: 'Create', }, dragToReorder: 'Drag to reorder', defaultView: 'Default view', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 2360eb992c4..0148d9e0251 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -973,8 +973,6 @@ const es = { recordOpen: "Abrir registros", recordOpenDrawer: "Panel lateral", recordOpenPage: "Página completa", - recordOpenNote: "Tu preferencia personal, no forma parte de la declaración del objeto. El ↗ de un registro siempre abre la página completa.", - recordOpenDeclaredPage: "Este objeto está declarado para abrirse como página completa", addGroup: "Agregar campo de grupo", collapsedByDefault: "Contraído por defecto", removeGroup: "Eliminar", @@ -984,6 +982,22 @@ const es = { withheldFieldsLeftOut: "Sin mostrar, filtrar, ordenar ni agrupar por {{fields}}: el paquete que lo añade está desactivado. Vuelve cuando se activa el paquete.", inlineEditShort: "Edición en línea", inlineEditLabel: "Editar registros en línea (haga clic en una celda para editar)", + // The list's Options menu. + optionsMenu: { + viewName: 'Nombre de la vista', + fields: 'Campos', + fieldsShown: 'Visibles: {{count}}', + fieldsShown_one: '{{count}} visible', + fieldsShown_many: '{{count}} visibles', + fieldsShown_other: '{{count}} visibles', + rowHeight: 'Alto de fila', + rowHeightCompact: 'Compacto', + rowHeightStandard: 'Estándar', + rowHeightSpacious: 'Amplio', + more: 'Más', + restoreDefaults: 'Restaurar valores predeterminados', + recordOpenAlwaysPage: 'Los registros siempre se abren a página completa', + }, }, managedByBadge: { systemWritable: { @@ -1223,14 +1237,20 @@ const es = { label: "Vistas", pinned: "Fijada", recent: "Recientes", - all: "Todas las vistas", pin: "Fijar: abrir esta vista de forma predeterminada", unpin: "Desfijar: la lista vuelve a abrir su vista predeterminada", inMenu: "Ya está en el menú", // objectstack#29635 — the reader's own views (My views). myViews: "Mis vistas", - saveAsMyView: "Guardar como mi vista", myViewName: "Nombre de la vista", + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: 'Vistas compartidas', + addView: 'Añadir vista', + typeLabel: 'Tipo de vista', + includeCurrent: 'Incluir los filtros y el orden actuales', + scopeShared: 'Compartida', + scopeHint: 'Las vistas compartidas las ve cualquiera que pueda ver esta lista', + create: 'Crear', }, dragToReorder: "Arrastrar para reordenar", defaultView: "Vista predeterminada", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 2060313ebec..a70f933c7b9 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -968,8 +968,6 @@ const fr = { recordOpen: "Ouvrir les enregistrements", recordOpenDrawer: "Panneau latéral", recordOpenPage: "Pleine page", - recordOpenNote: "Votre préférence personnelle, hors de la déclaration de l’objet. Le ↗ d’un enregistrement ouvre toujours la pleine page.", - recordOpenDeclaredPage: "Cet objet est déclaré pour s’ouvrir en pleine page", addGroup: "Ajouter un champ de groupe", collapsedByDefault: "Réduit par défaut", removeGroup: "Supprimer", @@ -979,6 +977,22 @@ const fr = { withheldFieldsLeftOut: "Non affiché, filtré, trié ni groupé par {{fields}} : le paquet qui ajoute ce champ est désactivé. Il revient lorsque le paquet est réactivé.", inlineEditShort: "Édition en ligne", inlineEditLabel: "Modifier les enregistrements en ligne (cliquez sur une cellule pour modifier)", + // The list's Options menu. + optionsMenu: { + viewName: 'Nom de la vue', + fields: 'Champs', + fieldsShown: 'Affichés : {{count}}', + fieldsShown_one: '{{count}} affiché', + fieldsShown_many: '{{count}} affichés', + fieldsShown_other: '{{count}} affichés', + rowHeight: 'Hauteur des lignes', + rowHeightCompact: 'Compacte', + rowHeightStandard: 'Standard', + rowHeightSpacious: 'Spacieuse', + more: 'Plus', + restoreDefaults: 'Rétablir les valeurs par défaut', + recordOpenAlwaysPage: 'Les enregistrements s’ouvrent toujours en pleine page', + }, }, managedByBadge: { systemWritable: { @@ -1218,14 +1232,20 @@ const fr = { label: "Vues", pinned: "Épinglée", recent: "Récentes", - all: "Toutes les vues", pin: "Épingler : ouvrir cette vue par défaut", unpin: "Désépingler : la liste rouvre sa vue par défaut", inMenu: "Déjà dans le menu", // objectstack#29635 — the reader's own views (My views). myViews: "Mes vues", - saveAsMyView: "Enregistrer comme ma vue", myViewName: "Nom de la vue", + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: 'Vues partagées', + addView: 'Ajouter une vue', + typeLabel: 'Type de vue', + includeCurrent: 'Inclure les filtres et le tri actuels', + scopeShared: 'Partagée', + scopeHint: 'Les vues partagées sont visibles par tous ceux qui voient cette liste', + create: 'Créer', }, dragToReorder: "Glisser pour réorganiser", defaultView: "Vue par défaut", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 552c49d0804..33304c0d610 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -941,8 +941,6 @@ const ja = { recordOpen: "レコードを開く", recordOpenDrawer: "ドロワー", recordOpenPage: "フルページ", - recordOpenNote: "個人の設定で、オブジェクトの宣言には含まれません。レコードの ↗ はいつでもフルページを開きます。", - recordOpenDeclaredPage: "このオブジェクトはフルページで開くよう宣言されています", addGroup: "グループフィールドを追加", collapsedByDefault: "デフォルトで折りたたむ", removeGroup: "削除", @@ -952,6 +950,21 @@ const ja = { withheldFieldsLeftOut: "{{fields}} は表示、絞り込み、並べ替え、グループ化されていません。この項目を追加するパッケージが無効になっています。パッケージを有効にすると戻ります。", inlineEditShort: "インライン編集", inlineEditLabel: "レコードをインラインで編集(セルをクリックして編集)", + // The list's Options menu. + optionsMenu: { + viewName: 'ビュー名', + fields: 'フィールド', + fieldsShown: '{{count}} 件表示中', + fieldsShown_one: '{{count}} 件表示中', + fieldsShown_other: '{{count}} 件表示中', + rowHeight: '行の高さ', + rowHeightCompact: 'コンパクト', + rowHeightStandard: '標準', + rowHeightSpacious: 'ゆったり', + more: 'その他', + restoreDefaults: 'デフォルトに戻す', + recordOpenAlwaysPage: 'レコードは常にページ全体で開きます', + }, }, managedByBadge: { systemWritable: { @@ -1188,14 +1201,20 @@ const ja = { label: "ビュー", pinned: "固定", recent: "最近", - all: "すべてのビュー", pin: "固定:このビューを既定で開く", unpin: "固定を解除:リストは既定のビューを再び開きます", inMenu: "すでにメニューにあります", // objectstack#29635 — the reader's own views (My views). myViews: "マイビュー", - saveAsMyView: "マイビューとして保存", myViewName: "ビュー名", + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: '共有ビュー', + addView: 'ビューを追加', + typeLabel: 'ビューの種類', + includeCurrent: '現在のフィルターと並べ替えを含める', + scopeShared: '共有', + scopeHint: '共有ビューはこのリストを見られる全員に表示されます', + create: '作成', }, dragToReorder: "ドラッグして並べ替え", defaultView: "デフォルトビュー", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index b1053135ea8..c23d7f320da 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -941,8 +941,6 @@ const ko = { recordOpen: "레코드 열기", recordOpenDrawer: "서랍", recordOpenPage: "전체 페이지", - recordOpenNote: "개인 설정이며 객체 선언에 포함되지 않습니다. 레코드의 ↗는 항상 전체 페이지를 엽니다.", - recordOpenDeclaredPage: "이 객체는 전체 페이지로 열리도록 선언되어 있습니다", addGroup: "그룹 필드 추가", collapsedByDefault: "기본적으로 접힘", removeGroup: "제거", @@ -952,6 +950,21 @@ const ko = { withheldFieldsLeftOut: "{{fields}} 기준 표시, 필터, 정렬, 그룹화가 적용되지 않았습니다. 이 필드를 추가하는 패키지가 비활성화되어 있습니다. 패키지를 활성화하면 다시 나타납니다.", inlineEditShort: "인라인 편집", inlineEditLabel: "레코드를 인라인으로 편집(셀을 클릭하여 편집)", + // The list's Options menu. + optionsMenu: { + viewName: '보기 이름', + fields: '필드', + fieldsShown: '{{count}}개 표시됨', + fieldsShown_one: '{{count}}개 표시됨', + fieldsShown_other: '{{count}}개 표시됨', + rowHeight: '행 높이', + rowHeightCompact: '좁게', + rowHeightStandard: '표준', + rowHeightSpacious: '넓게', + more: '더 보기', + restoreDefaults: '기본값 복원', + recordOpenAlwaysPage: '레코드는 항상 전체 페이지로 열립니다', + }, }, managedByBadge: { systemWritable: { @@ -1188,14 +1201,20 @@ const ko = { label: "보기", pinned: "고정됨", recent: "최근", - all: "모든 보기", pin: "고정: 이 보기를 기본으로 열기", unpin: "고정 해제: 목록이 기본 보기를 다시 엽니다", inMenu: "이미 메뉴에 있음", // objectstack#29635 — the reader's own views (My views). myViews: "내 뷰", - saveAsMyView: "내 뷰로 저장", myViewName: "뷰 이름", + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: '공유 보기', + addView: '보기 추가', + typeLabel: '보기 유형', + includeCurrent: '현재 필터와 정렬 포함', + scopeShared: '공유', + scopeHint: '공유 보기는 이 목록을 볼 수 있는 모든 사람에게 표시됩니다', + create: '만들기', }, dragToReorder: "드래그하여 순서 변경", defaultView: "기본 보기", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 6f84702ff57..1fa13b3e472 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -968,8 +968,6 @@ const pt = { recordOpen: "Abrir registros", recordOpenDrawer: "Painel lateral", recordOpenPage: "Página inteira", - recordOpenNote: "Sua preferência pessoal, não faz parte da declaração do objeto. O ↗ de um registro sempre abre a página inteira.", - recordOpenDeclaredPage: "Este objeto está declarado para abrir como página inteira", addGroup: "Adicionar campo de grupo", collapsedByDefault: "Recolhido por padrão", removeGroup: "Remover", @@ -979,6 +977,22 @@ const pt = { withheldFieldsLeftOut: "Sem exibir, filtrar, ordenar nem agrupar por {{fields}}: o pacote que o adiciona está desativado. Ele volta quando o pacote for ativado.", inlineEditShort: "Edição em linha", inlineEditLabel: "Editar registros em linha (clique em uma célula para editar)", + // The list's Options menu. + optionsMenu: { + viewName: 'Nome da visualização', + fields: 'Campos', + fieldsShown: 'Exibidos: {{count}}', + fieldsShown_one: '{{count}} exibido', + fieldsShown_many: '{{count}} exibidos', + fieldsShown_other: '{{count}} exibidos', + rowHeight: 'Altura da linha', + rowHeightCompact: 'Compacta', + rowHeightStandard: 'Padrão', + rowHeightSpacious: 'Espaçosa', + more: 'Mais', + restoreDefaults: 'Restaurar padrões', + recordOpenAlwaysPage: 'Os registros sempre abrem em página inteira', + }, }, managedByBadge: { systemWritable: { @@ -1218,14 +1232,20 @@ const pt = { label: "Exibições", pinned: "Fixada", recent: "Recentes", - all: "Todas as exibições", pin: "Fixar: abrir esta exibição por padrão", unpin: "Desafixar: a lista volta a abrir a exibição padrão", inMenu: "Já está no menu", // objectstack#29635 — the reader's own views (My views). myViews: "Minhas visualizações", - saveAsMyView: "Salvar como minha visualização", myViewName: "Nome da visualização", + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: 'Visualizações compartilhadas', + addView: 'Adicionar visualização', + typeLabel: 'Tipo de visualização', + includeCurrent: 'Incluir os filtros e a ordenação atuais', + scopeShared: 'Compartilhada', + scopeHint: 'Visualizações compartilhadas são vistas por todos que podem ver esta lista', + create: 'Criar', }, dragToReorder: "Arrastar para reordenar", defaultView: "Exibição padrão", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 33581932a24..88f078726f5 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1001,8 +1001,6 @@ const ru = { recordOpen: "Открытие записей", recordOpenDrawer: "Боковая панель", recordOpenPage: "Вся страница", - recordOpenNote: "Ваша личная настройка, не входит в объявление объекта. ↗ у записи всегда открывает её на всю страницу.", - recordOpenDeclaredPage: "Этот объект объявлен для открытия на всю страницу", addGroup: "Добавить поле группировки", collapsedByDefault: "Свёрнуто по умолчанию", removeGroup: "Удалить", @@ -1012,6 +1010,23 @@ const ru = { withheldFieldsLeftOut: "Не показано, без фильтрации, сортировки и группировки по {{fields}}: пакет, который добавляет это поле, отключён. Поле вернётся, когда пакет будет включён.", inlineEditShort: "Встроенное редактирование", inlineEditLabel: "Редактировать записи в таблице (щёлкните ячейку для редактирования)", + // The list's Options menu. + optionsMenu: { + viewName: 'Название представления', + fields: 'Поля', + fieldsShown: 'Показано: {{count}}', + fieldsShown_one: 'Показано: {{count}}', + fieldsShown_few: 'Показано: {{count}}', + fieldsShown_many: 'Показано: {{count}}', + fieldsShown_other: 'Показано: {{count}}', + rowHeight: 'Высота строк', + rowHeightCompact: 'Компактная', + rowHeightStandard: 'Стандартная', + rowHeightSpacious: 'Просторная', + more: 'Ещё', + restoreDefaults: 'Восстановить по умолчанию', + recordOpenAlwaysPage: 'Записи всегда открываются на всю страницу', + }, }, managedByBadge: { systemWritable: { @@ -1254,14 +1269,20 @@ const ru = { label: "Представления", pinned: "Закреплено", recent: "Недавние", - all: "Все представления", pin: "Закрепить: открывать это представление по умолчанию", unpin: "Открепить: список снова открывает представление по умолчанию", inMenu: "Уже в меню", // objectstack#29635 — the reader's own views (My views). myViews: "Мои представления", - saveAsMyView: "Сохранить как моё представление", myViewName: "Название представления", + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: 'Общие представления', + addView: 'Добавить представление', + typeLabel: 'Тип представления', + includeCurrent: 'Включить текущие фильтры и сортировку', + scopeShared: 'Общее', + scopeHint: 'Общие представления видны всем, кто видит этот список', + create: 'Создать', }, dragToReorder: "Перетащите для изменения порядка", defaultView: "Представление по умолчанию", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index f0fb71d6b41..d8e916a5013 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -968,8 +968,6 @@ const zh = { recordOpen: '打开记录', recordOpenDrawer: '抽屉', recordOpenPage: '整页', - recordOpenNote: '个人偏好,不进对象声明;记录的 ↗ 总能打开整页', - recordOpenDeclaredPage: '此对象声明为整页打开', addGroup: '添加分组字段', collapsedByDefault: '默认折叠', removeGroup: '删除', @@ -979,6 +977,21 @@ const zh = { withheldFieldsLeftOut: '未显示 {{fields}},也未按其筛选、排序或分组:添加该字段的软件包已停用,启用后即恢复。', inlineEditShort: '行内编辑', inlineEditLabel: '行内编辑记录(点击单元格进行编辑)', + // The list's Options menu. + optionsMenu: { + viewName: '视图名称', + fields: '字段', + fieldsShown: '已显示 {{count}} 个', + fieldsShown_one: '已显示 {{count}} 个', + fieldsShown_other: '已显示 {{count}} 个', + rowHeight: '行高', + rowHeightCompact: '紧凑', + rowHeightStandard: '标准', + rowHeightSpacious: '宽松', + more: '更多', + restoreDefaults: '恢复默认', + recordOpenAlwaysPage: '记录总是整页打开', + }, }, managedByBadge: { config: { @@ -1215,14 +1228,20 @@ const zh = { label: '视图', pinned: '固定', recent: '最近', - all: '全部', pin: '固定:默认打开此视图', unpin: '取消固定:列表恢复打开默认视图', inMenu: '已在菜单中', // objectstack#29635 — the reader's own views (My views). myViews: '我的视图', - saveAsMyView: '另存为我的视图', myViewName: '视图名称', + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: '共享视图', + addView: '添加视图', + typeLabel: '视图类型', + includeCurrent: '包含当前的筛选和排序', + scopeShared: '共享', + scopeHint: '共享视图对能看到此列表的所有人可见', + create: '创建', }, dragToReorder: '拖动排序', defaultView: '默认视图', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 1e1228fca0f..66068ee941c 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -968,8 +968,6 @@ const zhHant = { recordOpen: '開啟記錄', recordOpenDrawer: '抽屜', recordOpenPage: '整頁', - recordOpenNote: '個人偏好,不進物件宣告;記錄的 ↗ 總能開啟整頁', - recordOpenDeclaredPage: '此物件宣告為整頁開啟', addGroup: '新增分組欄位', collapsedByDefault: '預設摺疊', removeGroup: '刪除', @@ -979,6 +977,21 @@ const zhHant = { withheldFieldsLeftOut: '未顯示 {{fields}},也未按其篩選、排序或分組:新增該欄位的軟體包已停用,啟用後即恢復。', inlineEditShort: '行內編輯', inlineEditLabel: '行內編輯記錄(點選單元格進行編輯)', + // The list's Options menu. + optionsMenu: { + viewName: '檢視名稱', + fields: '欄位', + fieldsShown: '已顯示 {{count}} 個', + fieldsShown_one: '已顯示 {{count}} 個', + fieldsShown_other: '已顯示 {{count}} 個', + rowHeight: '行高', + rowHeightCompact: '緊湊', + rowHeightStandard: '標準', + rowHeightSpacious: '寬鬆', + more: '更多', + restoreDefaults: '恢復預設', + recordOpenAlwaysPage: '記錄總是整頁開啟', + }, }, managedByBadge: { config: { @@ -1215,14 +1228,20 @@ const zhHant = { label: '檢視', pinned: '固定', recent: '最近', - all: '全部', pin: '固定:預設開啟此檢視', unpin: '取消固定:列表恢復開啟預設檢視', inMenu: '已在選單中', // objectstack#29635 — the reader's own views (My views). myViews: '我的檢視', - saveAsMyView: '另存為我的檢視', myViewName: '檢視名稱', + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: '共享檢視', + addView: '新增檢視', + typeLabel: '檢視型別', + includeCurrent: '包含當前的篩選和排序', + scopeShared: '共享', + scopeHint: '共享檢視對能看到此列表的所有人可見', + create: '建立', }, dragToReorder: '拖動排序', defaultView: '預設檢視', diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index ab168985d85..c55f1729a25 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -584,6 +584,31 @@ export interface ListViewProps { * keeps its reset, exactly as before. */ onPersonalizationChange?: (parts: ReadonlyArray) => void; + /** + * Rename the open view from the options menu's first row, its name + * (`schema.label`, objectstack#35551). Wired only for a reader who may + * rename the view: the owner of one of their own views, or someone who may + * edit a shared one; without it the name row is read-only. Resolve `false` + * on a refused rename and the field reverts. A HOST prop, never a schema + * key. The name row is drawn for a host that wires this or + * `onPersonalizationChange` (a host that shows views), and a label. + */ + onRenameView?: (label: string) => boolean | Promise; + /** + * 保存 in the options menu (objectstack#35551, the 「已个性化」 marker's + * save, objectstack#30073): the list on screen becomes the open view's + * stored body. A host wires it only for a view the reader owns and may + * update, and only while the list differs from the view. Absent ⇒ none. + */ + onSaveView?: () => void; + /** + * The host's full reset (the 「已个性化」 marker's), drawn as the options + * menu's 恢复默认 in place of the list's own reset. A host that reports + * `onPersonalizationChange` and wires this only while the list differs + * from the view gives the reset its home in the menu. Absent ⇒ the list's + * own reset, or, under `onPersonalizationChange`, 恢复默认 dimmed. + */ + onResetView?: () => void; /** * Draw the COMPACT posture (objectui#12703): a header with the list's title * and record count over two-line rows (the view's first visible column, its @@ -1482,8 +1507,6 @@ export const LIST_DEFAULT_TRANSLATIONS: Record = { 'list.recordOpen': 'Open records', 'list.recordOpenDrawer': 'Drawer', 'list.recordOpenPage': 'Full page', - 'list.recordOpenNote': 'Your own preference, not part of the object’s declaration. A record’s ↗ always opens the full page.', - 'list.recordOpenDeclaredPage': 'This object is declared to open as a full page', // The draft preview's note on a sort or filter it left out (objectstack#34807). 'list.draftOnlyQueryDropped': 'Not filtered or sorted by {{fields}}: it exists only in the draft until you publish.', // The note on view fields a disabled package withholds (objectstack#34901). @@ -2103,6 +2126,9 @@ export const ListView = React.forwardRef(({ viewDefaults, onRestoreViewDefaults, onPersonalizationChange, + onRenameView, + onSaveView, + onResetView, recordOpen, page, onPageChange, @@ -3362,6 +3388,12 @@ export const ListView = React.forwardRef(({ return next; }); }, [galleryDensityKey]); + // The options menu's Row height level picks a gallery card size by name. + const setGalleryDensityMode = React.useCallback((mode: 'compact' | 'comfortable' | 'spacious') => { + const next: GalleryCardSize = mode === 'compact' ? 'small' : mode === 'comfortable' ? 'medium' : 'large'; + try { window.localStorage.setItem(galleryDensityKey, next); } catch { /* ignore */ } + setGalleryCardSize(next); + }, [galleryDensityKey]); const handlePullRefresh = React.useCallback(async () => { setRefreshKey(k => k + 1); @@ -7403,6 +7435,10 @@ export const ListView = React.forwardRef(({ { + const type = (objectDef?.fields as Record | undefined)?.[name]?.type; + return typeof type === 'string' ? type : undefined; + }} layout={viewSwitcherOffered ? (closeMenu) => ( (({ ? { mode: galleryCardSize === 'small' ? 'compact' : galleryCardSize === 'medium' ? 'comfortable' : 'spacious', cycle: cycleGalleryDensity, + setMode: setGalleryDensityMode, } : density as any} showHideFields={toolbarFlags.showHideFields} @@ -7447,9 +7484,23 @@ export const ListView = React.forwardRef(({ inlineEdit={inlineEdit} setInlineEdit={updateInlineEdit} changedCount={displayChangedCount} + // objectstack#35551 — the view's name and its rename head the + // menu; the field order is the grid's column order, the state + // the header's column drag writes. + 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} + onFieldOrderChange={currentView === 'grid' && onColumnStateChange + ? (order) => onColumnStateChange({ ...(schema.columnState as { order?: string[]; widths?: Record } | undefined), order }) + : undefined} // objectstack#28950 — a host that marks a personalized list owns - // the one reset; the Display control then offers none of its own. - onReset={onPersonalizationChange ? undefined : resetDisplayToViewDefault} + // the one reset. It hands it over while there is something to + // restore, and the menu draws it as 恢复默认, dimmed between + // times (objectstack#35551); the list offers none of its own. + onReset={onResetView ?? (onPersonalizationChange ? () => {} : resetDisplayToViewDefault)} + resetDisabled={onResetView ? false : onPersonalizationChange ? true : undefined} + onSave={onSaveView} onRefresh={toolbarFlags.showRefresh ? () => setRefreshKey(k => k + 1) : undefined} refreshing={loading} exportFormats={resolvedExportOptions && exportPermitted && exportableFormats.length > 0 ? exportableFormats : undefined} diff --git a/ui/packages/plugin-list/src/ViewSwitcher.tsx b/ui/packages/plugin-list/src/ViewSwitcher.tsx index bd6ac8e292e..a3be9822715 100644 --- a/ui/packages/plugin-list/src/ViewSwitcher.tsx +++ b/ui/packages/plugin-list/src/ViewSwitcher.tsx @@ -171,6 +171,23 @@ function useViewLabels(): Record { }, [t]); } +/** + * The face a {@link ViewSwitcherDropdown} draws, chosen by where it is + * mounted rather than by its host: the Options menu lists the layouts as a + * second-level page and names the current one on its Layout row, while the + * host hands the menu one switcher element. The menu wraps that element in + * this context: + * + * - `auto` (no provider): the segmented control for two to four + * visualizations, the compact dropdown for more; + * - `list`: every offered visualization as a row of icon and words, the + * current one checked, so a layout is never named by an icon alone; + * - `value`: the current visualization's icon and words, not interactive. + */ +export type ViewSwitcherFace = 'auto' | 'list' | 'value'; + +export const ViewSwitcherFaceContext = React.createContext('auto'); + /** * Compact dropdown form of the visualization switcher (Airtable-style): * a single "List ▾" button in the toolbar's right cluster that opens a @@ -186,6 +203,7 @@ export const ViewSwitcherDropdown: React.FC = ({ }) => { const [open, setOpen] = React.useState(false); const VIEW_LABELS = useViewLabels(); + const face = React.useContext(ViewSwitcherFaceContext); const handleViewChange = React.useCallback( (view: ListViewVisualization) => { @@ -202,6 +220,45 @@ export const ViewSwitcherDropdown: React.FC = ({ [animated, currentView, onViewChange], ); + if (face === 'value') { + return ( + + {VIEW_ICONS[currentView]} + {VIEW_LABELS[currentView]} + + ); + } + + if (face === 'list') { + return ( +
+ {availableViews.map((view) => { + const active = view === currentView; + return ( + + ); + })} +
+ ); + } + // Few visualizations (2–4): render an iOS/Linear-style segmented control // inline — a unified rounded track where the active segment lifts onto a // white thumb. Clearer and more tactile than a dropdown for a short set. diff --git a/ui/packages/plugin-list/src/__tests__/ListView.displayPopover-12423.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.displayPopover-12423.test.tsx index 5ae877e904c..03e2e2f0931 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.displayPopover-12423.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.displayPopover-12423.test.tsx @@ -88,6 +88,16 @@ async function openDisplay(): Promise { return screen.findByTestId('view-settings-content'); } +/** Open one of the Options menu's second levels (objectstack#35551). */ +function openLevel(content: HTMLElement, row: string): void { + fireEvent.click(within(content).getByTestId(`options-row-${row}`)); +} + +/** Back to the Options menu's first level. */ +function back(content: HTMLElement): void { + fireEvent.click(within(content).getByTestId('options-back')); +} + beforeEach(() => { gridProps = undefined; previousGrid = ComponentRegistry.get('object-grid'); @@ -144,10 +154,16 @@ describe('the list toolbar defaults to Filter · Sort · Display · Search (obje const content = await openDisplay(); expect(trigger).toHaveAttribute('aria-expanded', 'true'); const panel = within(content); - expect(panel.getByTestId('display-layout-row')).toContainElement(panel.getByTestId('view-switcher-segmented')); - expect(panel.getByRole('button', { name: 'Group' })).toBeInTheDocument(); - expect(panel.getByRole('button', { name: 'Hide Fields' })).toBeInTheDocument(); - expect(panel.getByTestId('view-settings-density-cycle')).toBeInTheDocument(); + // objectstack#35551 — one row per setting, each opening its level. + expect(panel.getByTestId('options-row-layout')).toContainElement(panel.getByTestId('view-switcher-value')); + expect(panel.getByTestId('options-row-group')).toBeInTheDocument(); + expect(panel.getByTestId('options-row-color')).toBeInTheDocument(); + expect(panel.getByTestId('options-row-fields')).toBeInTheDocument(); + expect(panel.getByTestId('options-row-row-height')).toBeInTheDocument(); + expect(panel.getByTestId('display-reset-button')).toHaveTextContent('Restore defaults'); + expect(panel.getByTestId('refresh-button')).toHaveTextContent('Refresh'); + expect(panel.getByTestId('display-export-csv')).toHaveTextContent('Export as CSV'); + openLevel(content, 'more'); for (const id of ['display-row-numbers-toggle', 'toolbar-inline-edit-toggle']) { const toggle = panel.getByTestId(id); expect(toggle).toHaveAttribute('role', 'switch'); @@ -155,18 +171,15 @@ describe('the list toolbar defaults to Filter · Sort · Display · Search (obje } expect(panel.getByRole('switch', { name: 'Row numbers' })).toBe(panel.getByTestId('display-row-numbers-toggle')); expect(panel.getByRole('switch', { name: 'Edit inline' })).toBe(panel.getByTestId('toolbar-inline-edit-toggle')); - expect(panel.getByTestId('display-reset-button')).toHaveTextContent('Reset to view default'); - expect(panel.getByTestId('refresh-button')).toBeInTheDocument(); - expect(panel.getByTestId('display-export-csv')).toHaveTextContent('Export as CSV'); }); it('the Layout row is drawn only when the list offers a visualization switch', async () => { mount({ appearance: { allowedVisualizations: ['grid'] } } as Partial); await screen.findByTestId('grid-stub'); const content = await openDisplay(); - expect(within(content).queryByTestId('display-layout-row')).toBeNull(); + expect(within(content).queryByTestId('options-row-layout')).toBeNull(); // Its neighbours are still there: the absence is the row's, not the panel's. - expect(within(content).getByTestId('view-settings-density-cycle')).toBeInTheDocument(); + expect(within(content).getByTestId('options-row-row-height')).toBeInTheDocument(); }); it('the count is absent by default, reads 1 after density changes, and Reset removes it', async () => { @@ -176,12 +189,15 @@ describe('the list toolbar defaults to Filter · Sort · Display · Search (obje const content = await openDisplay(); expect(within(content).getByTestId('display-reset-button')).toBeDisabled(); - fireEvent.click(within(content).getByTestId('view-settings-density-cycle')); + expect(within(content).getByTestId('options-row-row-height-value')).toHaveTextContent('Compact'); + openLevel(content, 'row-height'); + fireEvent.click(within(content).getByTestId('options-row-height-comfortable')); await waitFor(() => expect(screen.getByTestId('toolbar-display-count')).toHaveTextContent('1')); + back(content); fireEvent.click(within(content).getByTestId('display-reset-button')); await waitFor(() => expect(screen.queryByTestId('toolbar-display-count')).toBeNull()); - expect(within(content).getByTestId('view-settings-density-cycle')).toHaveTextContent('Compact'); + expect(within(content).getByTestId('options-row-row-height-value')).toHaveTextContent('Compact'); }); it('Row numbers is on by default, reaches the grid, counts when off, and Reset turns it back on', async () => { @@ -189,6 +205,7 @@ describe('the list toolbar defaults to Filter · Sort · Display · Search (obje await screen.findByTestId('grid-stub'); expect(gridProps?.showRowNumbers).toBe(true); const content = await openDisplay(); + openLevel(content, 'more'); const toggle = within(content).getByTestId('display-row-numbers-toggle'); expect(toggle).toHaveAttribute('aria-checked', 'true'); @@ -197,6 +214,7 @@ describe('the list toolbar defaults to Filter · Sort · Display · Search (obje expect(toggle).toHaveAttribute('aria-checked', 'false'); expect(screen.getByTestId('toolbar-display-count')).toHaveTextContent('1'); + back(content); fireEvent.click(within(content).getByTestId('display-reset-button')); await waitFor(() => expect(gridProps?.showRowNumbers).toBe(true)); expect(screen.queryByTestId('toolbar-display-count')).toBeNull(); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.displayResetBaseline-12949.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.displayResetBaseline-12949.test.tsx index aee4fc7486c..4df93f28491 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.displayResetBaseline-12949.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.displayResetBaseline-12949.test.tsx @@ -110,7 +110,7 @@ describe('a host that lays the user\'s preference over the view resets to the vi { viewDefaults: { rowHeight: 'tall' } }, ); const content = await openDisplay(); - expect(within(content).getByTestId('view-settings-density-cycle')).toHaveTextContent('Compact'); + expect(within(content).getByTestId('options-row-row-height-value')).toHaveTextContent('Compact'); expect(screen.getByTestId('toolbar-display-count')).toHaveTextContent('1'); const reset = within(content).getByTestId('display-reset-button'); expect(reset).toBeEnabled(); @@ -119,7 +119,7 @@ describe('a host that lays the user\'s preference over the view resets to the vi await waitFor(() => expect(onDensityChange).toHaveBeenCalledWith('spacious')); expect(onDensityChange).toHaveBeenCalledTimes(1); await waitFor(() => expect(screen.queryByTestId('toolbar-display-count')).toBeNull()); - expect(within(content).getByTestId('view-settings-density-cycle')).toHaveTextContent('Spacious'); + expect(within(content).getByTestId('options-row-row-height-value')).toHaveTextContent('Spacious'); }); it('both differ: the count reads 2', async () => { @@ -154,11 +154,14 @@ describe('CONTROL: a host passing no `viewDefaults` compares against `schema`, a const onDensityChange = vi.fn(); mount({ rowHeight: 'tall', onDensityChange } as Partial); const content = await openDisplay(); - fireEvent.click(within(content).getByTestId('view-settings-density-cycle')); + // objectstack#35551 — Row height is a level of the Options menu. + fireEvent.click(within(content).getByTestId('options-row-row-height')); + fireEvent.click(within(content).getByTestId('options-row-height-compact')); await waitFor(() => expect(screen.getByTestId('toolbar-display-count')).toHaveTextContent('1')); await waitFor(() => expect(onDensityChange).toHaveBeenCalledTimes(1)); expect(onDensityChange).not.toHaveBeenLastCalledWith('spacious'); + fireEvent.click(within(content).getByTestId('options-back')); fireEvent.click(within(content).getByTestId('display-reset-button')); await waitFor(() => expect(onDensityChange).toHaveBeenLastCalledWith('spacious')); await waitFor(() => expect(screen.queryByTestId('toolbar-display-count')).toBeNull()); 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 93209926343..1d0347134c2 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 @@ -195,6 +195,32 @@ function checkboxLabels(scope: HTMLElement): string[] { .map((box) => text(box.closest('label'))); } +/** The Options menu's Fields level: the shown fields' names, then the hidden and addable ones'. */ +function fieldsLevelLabels(scope: HTMLElement): string[] { + const shown = Array.from(scope.querySelectorAll('[data-testid="options-fields-shown"] li')).map(text); + const hidden = Array.from(scope.querySelectorAll('[data-testid="options-fields-hidden"] li, [data-testid="options-fields-addable"] li')).map(text); + return [...shown, ...hidden]; +} + +/** + * Open one level of the Options menu, read it, and go back to the menu. The + * Display panel is a menu whose rows open a second level, so Group, Row + * color and the field list sit one click below the panel. + */ +async function optionsLevel(content: HTMLElement, row: string, read: (level: HTMLElement) => Promise | T): Promise { + fireEvent.click(within(content).getByTestId(`options-row-${row}`)); + const level = await within(content).findByTestId(`options-page-${row}`); + try { + return await read(level); + } finally { + fireEvent.click(within(content).getByTestId('options-back')); + await within(content).findByTestId('options-menu'); + } +} + +/** The Options menu levels that carry a field list. */ +const FIELD_LEVELS = ['fields', 'group', 'color'] as const; + /** * Both Row color pickers, the toolbar's and the View settings popover's, are * the shared `Select` (objectui#11865), not native selects: read the fields @@ -248,6 +274,23 @@ async function sweepToolbar(): Promise { for (const combobox of Array.from(content.querySelectorAll('[role="combobox"]'))) { items.push(...(await comboboxOptions(combobox))); } + // The Options menu draws its field lists one level down: walk each level. + if (within(content).queryByTestId('options-menu')) { + for (const row of FIELD_LEVELS) { + if (!within(content).queryByTestId(`options-row-${row}`)) continue; + items.push(...(await optionsLevel(content, row, async (level) => { + const found = [ + ...Array.from(level.querySelectorAll('option')).map(text), + ...checkboxLabels(level), + ...fieldsLevelLabels(level), + ]; + for (const combobox of Array.from(level.querySelectorAll('[role="combobox"]'))) { + found.push(...(await comboboxOptions(combobox))); + } + return found; + }))); + } + } offered.set(name, items); await closePopover(trigger); } @@ -341,17 +384,17 @@ const POSITIONS: Position[] = [ { name: 'View settings: the Group editor', schemaExtra: { compactToolbar: true, grouping: { fields: [{ field: 'status', order: 'asc', collapsed: false }] } }, - read: () => inPopover(viewSettings(), (c) => comboboxOptions(within(c).getByTestId('grouping-field-0'))), + read: () => inPopover(viewSettings(), (c) => optionsLevel(c, 'group', (l) => comboboxOptions(within(l).getByTestId('grouping-field-0')))), }, { name: 'View settings: the Row color select', schemaExtra: { compactToolbar: true, rowColor: { field: 'status', colors: {} } }, - read: () => inPopover(viewSettings(), (c) => pickerLabels(within(c).getByTestId('color-field-select'))), + read: () => inPopover(viewSettings(), (c) => optionsLevel(c, 'color', (l) => pickerLabels(within(l).getByTestId('color-field-select')))), }, { - name: 'View settings: the hide-fields section', + name: 'View settings: the Fields level', schemaExtra: { compactToolbar: true, hiddenFields: ['priority'] }, - read: () => inPopover(viewSettings(), checkboxLabels), + read: () => inPopover(viewSettings(), (c) => optionsLevel(c, 'fields', fieldsLevelLabels)), }, ]; @@ -584,19 +627,14 @@ describe('both hide-fields lists offer the fields a reader may add, and only fie ); } - /** The Display panel's Hide Fields section, opened when it starts closed. */ - async function displayHideFields(read: (content: HTMLElement) => Promise | string[] | void): Promise { - return inPopover(viewSettings(), async (content) => { - if (content.querySelectorAll('input[type="checkbox"]').length === 0) { - fireEvent.click(within(content).getByRole('button', { name: /^Hide Fields/ })); - } - return read(content); - }); + /** The Options menu's Fields level. */ + async function displayHideFields(read: (level: HTMLElement) => Promise | string[] | void): Promise { + return inPopover(viewSettings(), (content) => optionsLevel(content, 'fields', read)); } const LAYOUTS = { wide: { schemaExtra: {}, read: () => inPopover(toolbarButton(/^hide fields/i), checkboxLabels) }, - compact: { schemaExtra: { compactToolbar: true }, read: () => displayHideFields(checkboxLabels) as Promise }, + compact: { schemaExtra: { compactToolbar: true }, read: () => displayHideFields(fieldsLevelLabels) as Promise }, } as const; for (const [layout, { schemaExtra, read }] of Object.entries(LAYOUTS)) { @@ -678,9 +716,9 @@ describe('both hide-fields lists offer the fields a reader may add, and only fie const onAddedFieldsChange = vi.fn(); mount(FULL_READ, { columns: TITLE_ONLY, compactToolbar: true }, { onAddedFieldsChange }); await definitionLoaded(); - await waitFor(async () => expect(await displayHideFields(checkboxLabels)).toContain('Priority')); - await displayHideFields((content) => { - fireEvent.click(within(content).getByRole('checkbox', { name: 'Priority' })); + await waitFor(async () => expect(await displayHideFields(fieldsLevelLabels)).toContain('Priority')); + await displayHideFields((level) => { + fireEvent.click(within(level).getByTestId('options-fields-item-priority')); }); expect(onAddedFieldsChange).toHaveBeenLastCalledWith(['priority']); }); 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 1b837806fc4..0ab6d7cf891 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx @@ -2232,7 +2232,8 @@ describe('ListView.switcherChrome-7547', () => { * objectui#12621 — the list toolbar's Display menu closes once a layout is * chosen, and on Escape, returning focus to the Display trigger. The panel's * toggles keep it open: the control below flips Row numbers and density and - * finds the panel still drawn. + * finds the panel still drawn. The panel is a menu whose rows open a second + * level; the Layout level lists every layout as a radio, at any count. */ describe('ListView.displayMenuClose-12621', () => { restoreAfterBlock(); @@ -2308,22 +2309,27 @@ describe('ListView.displayMenuClose-12621', () => { await waitFor(() => expect(document.activeElement).toBe(trigger)); } + /** Open the menu's Layout level and choose Kanban among its radios. */ + async function chooseKanban(content: HTMLElement, layouts: string[]) { + fireEvent.click(within(content).getByTestId('options-row-layout')); + const list = await within(content).findByTestId('view-switcher-list'); + expect(within(list).getAllByRole('radio').map((r) => r.textContent?.trim())).toEqual(layouts); + fireEvent.click(within(list).getByRole('radio', { name: 'Kanban' })); + } + describe('the Display menu closes when its work is done (objectui#12621)', () => { - it('choosing Kanban in the segmented Layout row closes the menu and focuses the trigger', async () => { + it('choosing Kanban on the Layout level closes the menu and focuses the trigger', async () => { mount(TWO); const { trigger, content } = await openDisplay(); - const row = within(content).getByTestId('display-layout-row'); - fireEvent.click(within(row).getByRole('tab', { name: 'Kanban' })); + await chooseKanban(content, ['Grid', 'Kanban']); await screen.findByTestId('object-kanban-stub'); await expectClosedWithFocusOn(trigger); }); - it('choosing Kanban in the nested Layout dropdown closes the menu and focuses the trigger', async () => { + it('with five layouts the level is the same list, and choosing Kanban closes the menu and focuses the trigger', async () => { mount(FIVE); const { trigger, content } = await openDisplay(); - const row = within(content).getByTestId('display-layout-row'); - fireEvent.click(within(row).getByTestId('view-switcher-dropdown')); - fireEvent.click(await screen.findByRole('button', { name: 'Kanban' })); + await chooseKanban(content, ['Grid', 'Kanban', 'Gallery', 'Calendar', 'Timeline']); await screen.findByTestId('object-kanban-stub'); await expectClosedWithFocusOn(trigger); }); @@ -2331,17 +2337,20 @@ describe('ListView.displayMenuClose-12621', () => { it('Escape closes the menu and focuses the trigger', async () => { mount(TWO); const { trigger, content } = await openDisplay(); - fireEvent.keyDown(within(content).getByTestId('display-row-numbers-toggle'), { key: 'Escape' }); + fireEvent.keyDown(within(content).getByTestId('options-row-more'), { key: 'Escape' }); await expectClosedWithFocusOn(trigger); }); - it('control: toggling Row numbers and cycling density keep the menu open', async () => { + it('control: toggling Row numbers and choosing a row height keep the menu open', async () => { mount(TWO); const { trigger, content } = await openDisplay(); - const toggle = within(content).getByTestId('display-row-numbers-toggle'); + fireEvent.click(within(content).getByTestId('options-row-more')); + const toggle = await within(content).findByTestId('display-row-numbers-toggle'); fireEvent.click(toggle); await waitFor(() => expect(toggle).toHaveAttribute('aria-checked', 'false')); - fireEvent.click(within(content).getByTestId('view-settings-density-cycle')); + fireEvent.click(within(content).getByTestId('options-back')); + fireEvent.click(await within(content).findByTestId('options-row-row-height')); + fireEvent.click(await within(content).findByTestId('options-row-height-spacious')); await waitFor(() => expect(screen.getByTestId('toolbar-display-count')).toHaveTextContent('2')); expect(screen.getByTestId('view-settings-content')).toBe(content); expect(trigger).toHaveAttribute('aria-expanded', 'true'); @@ -3109,12 +3118,13 @@ describe('ListView.groupPickerUnstored-32631', () => { expect(await openOptions(screen.getByTestId('grouping-field-0'))).toEqual(['Subject', 'Status']); }); - it('the Display popover\'s Group section offers the same', async () => { + it('the Display popover\'s Group level offers the same', async () => { const { onGroupingChange } = mount({ compactToolbar: true }); await screen.findByTestId('grid-stub'); fireEvent.click(screen.getByTestId('toolbar-display-trigger')); const content = await screen.findByTestId('view-settings-content'); - fireEvent.click(within(content).getByTestId('grouping-add')); + 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']); }); 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 79c76b3d2b3..ff8a0e731b2 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 @@ -27,7 +27,7 @@ import * as React from 'react'; import { describe, it, expect, vi, afterEach } from 'vitest'; -import { render, screen, fireEvent, cleanup, act } from '@testing-library/react'; +import { render, screen, fireEvent, cleanup, act, within } from '@testing-library/react'; import { GroupingConfigSchema } from '@objectstack/spec/ui'; import type { GroupingConfig } from '@objectstack/spec/ui'; import type { DataSource, ListViewSchema } from '@object-ui/types'; @@ -123,7 +123,9 @@ describe('ListView reports a user grouping change to its host (objectui#11860)', await vi.waitFor(() => expect(screen.getByTestId('view-settings-content')).toBeInTheDocument()); const content = screen.getByTestId('view-settings-content'); - fireEvent.click(content.querySelector('[data-testid="grouping-add"]')!); + // Grouping is a level of the Display menu. + fireEvent.click(within(content).getByTestId('options-row-group')); + fireEvent.click(await within(content).findByTestId('grouping-add')); expect(onGroupingChange).toHaveBeenCalledTimes(1); expectSpecShape(onGroupingChange.mock.calls[0][0]); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.optionsHost-35551.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.optionsHost-35551.test.tsx new file mode 100644 index 00000000000..7d0f5a98224 --- /dev/null +++ b/ui/packages/plugin-list/src/__tests__/ListView.optionsHost-35551.test.tsx @@ -0,0 +1,135 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35551 — what `ListView` hands its Options menu. + * + * - Fields: the grid's column order is the order the Fields level shows, and + * moving a field writes the whole order through `onColumnStateChange`, + * the door a header drag writes through, keeping the widths beside it. + * - Row height on a gallery picks its card size by name, and it is + * remembered for the object (the toolbar's density key). + * + * The view's name and the host's 保存 / 恢复默认 are pinned beside the + * reset rules in `ListView.personalization-28950.test.tsx`. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, fireEvent, cleanup } from '@testing-library/react'; +import React from 'react'; +import { ComponentRegistry } from '@object-ui/core'; +import { SchemaRendererProvider } from '@object-ui/react'; +import type { ListViewSchema } from '@object-ui/types'; +import { ListView, type ListViewProps } from '../ListView'; + +const OBJECT_DEF = { + name: 'account', + fields: { + name: { type: 'text', label: 'Name' }, + stage: { type: 'text', label: 'Stage' }, + amount: { type: 'number', label: 'Amount' }, + }, +}; + +function makeDataSource() { + return { + find: vi.fn().mockResolvedValue({ data: [{ id: '1', name: 'Acme', stage: 'won', amount: 3 }], total: 1 }), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + getObjectSchema: vi.fn().mockResolvedValue(OBJECT_DEF), + }; +} + +function mount(schema: Partial, props: Partial = {}) { + const dataSource = makeDataSource(); + render( + + + , + ); +} + +const previous: Record> = {}; + +beforeEach(() => { + for (const type of ['object-grid', 'object-gallery']) { + previous[type] = ComponentRegistry.get(type); + ComponentRegistry.register(type, () =>
); + } + try { window.localStorage.clear(); } catch { /* ignore */ } +}); + +afterEach(() => { + cleanup(); + for (const [type, component] of Object.entries(previous)) { + if (component) ComponentRegistry.register(type, component as never); + } +}); + +describe('Options — Fields writes the column order (objectstack#35551)', () => { + it('shows the grid\'s column order, and a move writes the whole order beside the widths', async () => { + const onColumnStateChange = vi.fn(); + mount( + { columnState: { order: ['amount', 'name', 'stage'], widths: { name: 120 } } } as Partial, + { onColumnStateChange }, + ); + await screen.findByTestId('object-grid-stub'); + fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + fireEvent.click(await screen.findByTestId('options-row-fields')); + const shown = Array.from(document.querySelectorAll('[data-testid^="options-fields-move-"]')) + .map((el) => el.getAttribute('data-testid')!.replace('options-fields-move-', '')); + expect(shown).toEqual(['amount', 'name', 'stage']); + fireEvent.keyDown(screen.getByTestId('options-fields-move-amount'), { key: 'ArrowDown' }); + expect(onColumnStateChange).toHaveBeenCalledWith({ order: ['name', 'amount', 'stage'], widths: { name: 120 } }); + }); + + it('CONTROL: without a host to write the order, nothing is draggable', async () => { + mount({}); + await screen.findByTestId('object-grid-stub'); + fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + fireEvent.click(await screen.findByTestId('options-row-fields')); + expect(screen.queryByTestId('options-fields-move-name')).toBeNull(); + }); + + it('draws each row with its declared field type, not the text default for all', async () => { + mount({}); + await screen.findByTestId('object-grid-stub'); + fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + fireEvent.click(await screen.findByTestId('options-row-fields')); + expect(screen.getByTestId('options-fields-item-amount').getAttribute('data-field-type')).toBe('number'); + expect(screen.getByTestId('options-fields-item-name').getAttribute('data-field-type')).toBe('text'); + }); +}); + +describe('Options — Row height on a gallery (objectstack#35551)', () => { + it('picks the card size by name, and the pick is remembered for the object', async () => { + mount({ viewType: 'gallery' } as Partial); + await screen.findByTestId('object-gallery-stub'); + fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + fireEvent.click(await screen.findByTestId('options-row-row-height')); + fireEvent.click(screen.getByTestId('options-row-height-spacious')); + expect(window.localStorage.getItem('objectui:gallery:density:account')).toBe('large'); + // The level stays open on the pick, which it marks. + expect(screen.getByTestId('options-row-height-spacious')).toHaveAttribute('aria-checked', 'true'); + fireEvent.click(screen.getByTestId('options-row-height-compact')); + expect(screen.getByTestId('options-row-height-compact')).toHaveAttribute('aria-checked', 'true'); + expect(window.localStorage.getItem('objectui:gallery:density:account')).toBe('small'); + }); +}); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.permissions.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.permissions.test.tsx index 8a54312a02c..8b0eb01d43e 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.permissions.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.permissions.test.tsx @@ -358,6 +358,18 @@ function renderInlineEdit( ); } +/** + * Open the Display menu and its More level, where the Edit inline switch + * lives: an absence read before this level is open would hold for any input. + */ +async function openDisplayMore(): Promise { + fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + const content = await screen.findByTestId('view-settings-content'); + fireEvent.click(within(content).getByTestId('options-row-more')); + await within(content).findByTestId('options-page-more'); + return content; +} + describe('ListView – inline-edit toggle vs the principal permission gate (#4647)', () => { let prevGrid: ReturnType; @@ -418,8 +430,9 @@ describe('ListView – inline-edit toggle vs the principal permission gate (#464 // The panel has to be opened before an absence means anything, or the // assertion passes for every input including a completely ungated one: the // entry lives inside `PopoverContent`, closed until the trigger is clicked. - // Since objectui#12423 it is a switch row of the Display panel rather than - // a collapsible section, so no second layer hides it. The seeded + // Since objectui#12423 it is a switch row of the Display panel; the panel + // is a menu now, and the switch sits on its More level, which + // `openDisplayMore` opens before anything is read. The seeded // `inlineEdit: true` is the realistic shape of this regression: a stored // view already in inline-edit mode, reopened by a principal who has since // lost `update`. @@ -428,8 +441,7 @@ describe('ListView – inline-edit toggle vs the principal permission gate (#464 inlineEdit: true, } as Partial); await waitFor(() => expect(screen.getByTestId('grid-stub')).toBeInTheDocument()); - fireEvent.click(screen.getByTestId('toolbar-display-trigger')); - await screen.findByTestId('view-settings-content'); + await openDisplayMore(); expect(screen.queryByTestId('toolbar-inline-edit-toggle')).toBeNull(); }); @@ -441,8 +453,7 @@ describe('ListView – inline-edit toggle vs the principal permission gate (#464 inlineEdit: true, } as Partial); await waitFor(() => expect(screen.getByTestId('grid-stub')).toBeInTheDocument()); - fireEvent.click(screen.getByTestId('toolbar-display-trigger')); - await screen.findByTestId('view-settings-content'); + await openDisplayMore(); expect(screen.queryByTestId('toolbar-inline-edit-toggle')).not.toBeNull(); }); }); @@ -514,8 +525,7 @@ describe('ListView – the declared userActions.editInline switch (#4647 gap 2)' compactToolbar: true, } as Partial); await waitFor(() => expect(screen.getByTestId('grid-stub')).toBeInTheDocument()); - fireEvent.click(screen.getByTestId('toolbar-display-trigger')); - const content = await screen.findByTestId('view-settings-content'); + const content = await openDisplayMore(); expect(within(content).getByTestId('toolbar-inline-edit-toggle')).toHaveAttribute('role', 'switch'); }); @@ -525,8 +535,7 @@ describe('ListView – the declared userActions.editInline switch (#4647 gap 2)' ...OPTED_OUT, } as Partial); await waitFor(() => expect(screen.getByTestId('grid-stub')).toBeInTheDocument()); - fireEvent.click(screen.getByTestId('toolbar-display-trigger')); - const content = await screen.findByTestId('view-settings-content'); + const content = await openDisplayMore(); expect(within(content).queryByTestId('toolbar-inline-edit-toggle')).toBeNull(); }); }); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.personalization-28950.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.personalization-28950.test.tsx index 28ad31b625e..e989244336f 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.personalization-28950.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.personalization-28950.test.tsx @@ -14,8 +14,9 @@ * Every part is judged against the VIEW: where the host lays the reader's * state over the view's in `schema` (the console), the sort and the grouping * compare against `viewDefaults`, as hidden fields and density already do. - * With the callback wired the Display control draws no reset of its own; the - * sort popover's per-control reset stays. The host half (the marker, the reset + * With the callback wired the Display control draws no live reset of its own + * (恢复默认 is dimmed until the host hands its reset over, with its 保存: + * objectstack#35551); the sort popover's per-control reset stays. The host half (the marker, the reset * that clears the stored entry, the search cache and the `uf_*` params) is * pinned in app-shell's `ObjectView.listPersonalized-28950.test.tsx`. */ @@ -162,6 +163,9 @@ describe('the list reports what of it differs from the view (objectstack#28950)' const { reported } = mount({}, { defaultRowNumbers: true }); const content = await openDisplay(); await waitFor(() => expect(reported()).toEqual([])); + // Row numbers sit on the Display menu's More level. + fireEvent.click(within(content).getByTestId('options-row-more')); + await within(content).findByTestId('options-page-more'); fireEvent.click(within(content).getByTestId('display-row-numbers-toggle')); await waitFor(() => expect(reported()).toEqual(['rowNumbers'])); @@ -189,10 +193,42 @@ describe('the list reports what of it differs from the view (objectstack#28950)' }); describe('with the callback wired, the host owns the one reset (objectstack#28950)', () => { - it('the Display control draws no "Reset to view default" of its own', async () => { + it('the Display control draws no live reset of its own: 恢复默认 stays dimmed until the host hands its reset over', async () => { mount({ hiddenFields: ['amount'] } as Partial); const content = await openDisplay(); - expect(within(content).queryByTestId('display-reset-button')).toBeNull(); + expect(within(content).getByTestId('display-reset-button')).toBeDisabled(); + expect(within(content).queryByTestId('display-save-button')).toBeNull(); + }); + + it('the host\'s reset and save (objectstack#35551) are 恢复默认 and 保存 in Options', async () => { + const onResetView = vi.fn(); + const onSaveView = vi.fn(); + mount({ hiddenFields: ['amount'] } as Partial, { onResetView, onSaveView }); + let content = await openDisplay(); + expect(within(content).getByTestId('display-reset-button')).toBeEnabled(); + fireEvent.click(within(content).getByTestId('display-reset-button')); + expect(onResetView).toHaveBeenCalledTimes(1); + content = await screen.findByTestId('view-settings-content'); + fireEvent.click(within(content).getByTestId('display-save-button')); + expect(onSaveView).toHaveBeenCalledTimes(1); + }); + + it('the view\'s name heads Options; the host\'s rename (objectstack#35551) renames it in place', async () => { + const onRenameView = vi.fn().mockResolvedValue(true); + mount({ label: 'Hot accounts' } as Partial, { onRenameView }); + const content = await openDisplay(); + const name = within(content).getByTestId('options-view-name-input'); + expect(name).toHaveValue('Hot accounts'); + fireEvent.change(name, { target: { value: 'Warm accounts' } }); + fireEvent.keyDown(name, { key: 'Enter' }); + await waitFor(() => expect(onRenameView).toHaveBeenCalledWith('Warm accounts')); + }); + + it('CONTROL: without a rename the name is shown, not edited', async () => { + mount({ label: 'Hot accounts' } as Partial); + const content = await openDisplay(); + expect(within(content).queryByTestId('options-view-name-input')).toBeNull(); + expect(within(content).getByTestId('options-view-name')).toHaveTextContent('Hot accounts'); }); it('CONTROL: without the callback the Display control keeps its reset', async () => { diff --git a/ui/packages/plugin-list/src/__tests__/ListView.phoneSortSearch-28911.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.phoneSortSearch-28911.test.tsx index d8686777b7a..8bc23feda1f 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.phoneSortSearch-28911.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.phoneSortSearch-28911.test.tsx @@ -10,7 +10,8 @@ * objectstack#28911 — a phone list offers Sort and its own search. * * Below `sm` the bar keeps Filter and Display. Sort rides in the Display - * panel there (the same Sort panel the toolbar popover draws), and the list + * menu there, as its Sort row's level (the same Sort panel the toolbar + * popover draws), and the list * search is an icon that expands into a field in place. Both follow the same * `userActions` flags as the desktop toolbar. * @@ -116,7 +117,10 @@ describe('phone list: Sort in the Display panel (objectstack#28911)', () => { expect(screen.getByTestId('toolbar-sort-trigger')).not.toBeVisible(); const content = await openDisplay(); - const block = within(content).getByTestId('display-sort'); + const row = within(content).getByTestId('options-row-sort'); + expect(row).toBeVisible(); + fireEvent.click(row); + const block = await within(content).findByTestId('display-sort'); expect(block).toBeVisible(); expect(within(block).getByText('Sort Records')).toBeVisible(); @@ -129,14 +133,14 @@ describe('phone list: Sort in the Display panel (objectstack#28911)', () => { expect(JSON.stringify(ds.find.mock.lastCall)).toContain('name'); }); - it('wide: the Sort button is on the bar and the Display panel draws no Sort block', async () => { + it('wide: the Sort button is on the bar and the Display menu shows no Sort row', async () => { fromSm(); mount(); await screen.findByTestId('grid-stub'); expect(screen.getByTestId('toolbar-sort-trigger')).toBeVisible(); const content = await openDisplay(); - expect(within(content).getByTestId('display-sort')).not.toBeVisible(); + expect(within(content).getByTestId('options-row-sort')).not.toBeVisible(); }); it('`userActions.sort: false` withholds Sort on the phone too', async () => { @@ -146,6 +150,7 @@ describe('phone list: Sort in the Display panel (objectstack#28911)', () => { expect(screen.queryByTestId('toolbar-sort-trigger')).toBeNull(); const content = await openDisplay(); + expect(within(content).queryByTestId('options-row-sort')).toBeNull(); expect(within(content).queryByTestId('display-sort')).toBeNull(); }); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.phoneWidth-29074.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.phoneWidth-29074.test.tsx index b042d3377dc..8fcdc22a031 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.phoneWidth-29074.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.phoneWidth-29074.test.tsx @@ -139,13 +139,14 @@ describe('an active sort shows on the phone bar (objectstack#29057)', () => { expect(screen.getByTestId('toolbar-sort-trigger')).toBeVisible(); }); - it('the Display panel still carries the Sort block while the bar shows the indicator', async () => { + it('the Display menu still carries the Sort level while the bar shows the indicator', async () => { belowSm(); mount({ sort: [{ field: 'name', order: 'asc' }] } as Partial); await screen.findByTestId('grid-stub'); fireEvent.click(screen.getByTestId('toolbar-display-trigger')); const content = await screen.findByTestId('view-settings-content'); - expect(within(content).getByTestId('display-sort')).toBeInTheDocument(); + fireEvent.click(within(content).getByTestId('options-row-sort')); + expect(await within(content).findByTestId('display-sort')).toBeInTheDocument(); }); }); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.restoreViewDefaults-28948.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.restoreViewDefaults-28948.test.tsx index fbf4b3d4f6d..d4017bd8e50 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.restoreViewDefaults-28948.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.restoreViewDefaults-28948.test.tsx @@ -127,7 +127,7 @@ describe('a host wiring `onRestoreViewDefaults` is told the reset, not handed th const props = { viewDefaults: { rowHeight: 'tall' as const }, onRestoreViewDefaults }; const { rerender } = mount({ rowHeight: 'compact', onDensityChange } as Partial, props); const content = await openDisplay(); - expect(within(content).getByTestId('view-settings-density-cycle')).toHaveTextContent('Compact'); + expect(within(content).getByTestId('options-row-row-height-value')).toHaveTextContent('Compact'); fireEvent.click(within(content).getByTestId('display-reset-button')); expect(onRestoreViewDefaults).toHaveBeenCalledTimes(1); @@ -138,7 +138,7 @@ describe('a host wiring `onRestoreViewDefaults` is told the reset, not handed th // The host clears the stored density: `schema.rowHeight` is the view's own again. rerender({ rowHeight: 'tall', onDensityChange } as Partial, props); await waitFor(() => - expect(within(screen.getByTestId('view-settings-content')).getByTestId('view-settings-density-cycle')).toHaveTextContent('Spacious'), + expect(within(screen.getByTestId('view-settings-content')).getByTestId('options-row-row-height-value')).toHaveTextContent('Spacious'), ); expect(screen.queryByTestId('toolbar-display-count')).toBeNull(); expect(onDensityChange).not.toHaveBeenCalled(); @@ -203,7 +203,10 @@ describe('a host wiring `onRestoreViewDefaults` is told the reset, not handed th const onRestoreViewDefaults = vi.fn(); mount({}, { viewDefaults: {}, onRestoreViewDefaults, defaultRowNumbers: true }); const content = await openDisplay(); - fireEvent.click(within(content).getByTestId('display-row-numbers-toggle')); + // Row numbers sit on the menu's More level; the reset is on the menu itself. + fireEvent.click(within(content).getByTestId('options-row-more')); + fireEvent.click(await within(content).findByTestId('display-row-numbers-toggle')); + fireEvent.click(within(content).getByTestId('options-back')); await waitFor(() => expect(within(content).getByTestId('display-reset-button')).toBeEnabled()); fireEvent.click(within(content).getByTestId('display-reset-button')); expect(onRestoreViewDefaults).not.toHaveBeenCalled(); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.toolbarIconButtons-12695.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.toolbarIconButtons-12695.test.tsx index 790934c7c1b..c5e26dee57e 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.toolbarIconButtons-12695.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.toolbarIconButtons-12695.test.tsx @@ -82,8 +82,12 @@ function mount(schema: Partial = {}, props: Record expect(screen.getByTestId('toolbar-display-count')).toHaveTextContent('2')); fireEvent.keyDown(content, { key: 'Escape' }); await waitFor(() => expect(screen.queryByTestId('view-settings-content')).toBeNull()); diff --git a/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.layoutFold.test.tsx b/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.layoutFold.test.tsx deleted file mode 100644 index 1aa0cc5f36b..00000000000 --- a/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.layoutFold.test.tsx +++ /dev/null @@ -1,220 +0,0 @@ -/** - * 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. - */ - -/** - * The Display popover's Layout row folds its segments to icons when they would - * not fit (objectstack#26637). - * - * Walked on a zh-CN list offering four layouts, the row read - * 「布局 | 表格 | 看板 | 日历 | 时间线」 and each label broke onto two lines: the - * panel is a fixed width and the row shares it with its title. The ruling is a - * MEASURED fold, never a count or a breakpoint, in every locale; the popover - * does not widen. Folded, the unselected segments keep their icon, accessible - * name and tooltip, and the selected one keeps its label. - * - * jsdom has no layout, so the widths are a model of the console's tokens: a - * segment is `px-2.5` (20) + a 16 px icon, plus `gap-1.5` (6) and its words - * when they show; the track adds `p-0.5` (4) and `gap-0.5` (2) between - * segments; `text-xs` draws a CJK character 12 px wide and a Latin one about - * 7 px. The model reads the fold the way the class does (an unselected tab's - * words are gone while the slot carries `data-layout-fold`), so a measurement - * that forgot to lift the fold would read the folded width, unfold, read the - * full width and fold again until React gives up. - */ -import { describe, it, expect, afterEach, beforeEach } from 'vitest'; -import * as React from 'react'; -import { render, screen, fireEvent, cleanup } from '@testing-library/react'; -import { I18nProvider, useObjectTranslation } from '@object-ui/i18n'; -import type { ListViewVisualization } from '@object-ui/core'; -import { ViewSettingsPopover, type ViewSettingsPopoverProps } from '../components/ViewSettingsPopover'; -import { ViewSwitcherDropdown } from '../ViewSwitcher'; - -/** `w-80`: the popover's width, which this card must not change. */ -const POPOVER_WIDTH = 320; -/** The row's `px-3` on both sides and the `gap-3` between title and slot. */ -const ROW_CHROME = 24 + 12; - -function textWidth(text: string): number { - let w = 0; - // CJK punctuation through the unified ideographs: one em wide at `text-xs`. - for (const ch of text) w += ch.codePointAt(0)! >= 0x3000 && ch.codePointAt(0)! <= 0x9fff ? 12 : 7; - return w; -} - -/** Whether a tab's words are drawn: the fold hides an unselected tab's, nothing else does. */ -function labelShows(tab: Element): boolean { - return !(tab.closest('[data-layout-fold]') && tab.getAttribute('aria-selected') === 'false'); -} - -/** The model width of a segmented control as the DOM now stands. */ -function tablistWidth(list: Element): number { - const tabs = Array.from(list.querySelectorAll('[role="tab"]')); - let w = 4 + 2 * Math.max(0, tabs.length - 1); - for (const tab of tabs) { - w += 20 + 16; - const words = tab.querySelector(':scope > span')?.textContent ?? ''; - if (words && labelShows(tab)) w += 6 + textWidth(words); - } - return w; -} - -let slotWidth = 0; -let readsWhileFolded = 0; -const saved: Record<'scrollWidth' | 'clientWidth', PropertyDescriptor | undefined> = { - scrollWidth: undefined, - clientWidth: undefined, -}; - -beforeEach(() => { - readsWhileFolded = 0; - saved.scrollWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollWidth'); - saved.clientWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'clientWidth'); - Object.defineProperty(HTMLElement.prototype, 'scrollWidth', { - configurable: true, - get(this: HTMLElement) { - if (this.getAttribute('role') !== 'tablist') return 0; - if (this.closest('[data-layout-fold]')) readsWhileFolded += 1; - return tablistWidth(this); - }, - }); - Object.defineProperty(HTMLElement.prototype, 'clientWidth', { - configurable: true, - get(this: HTMLElement) { - return this.dataset.testid === 'display-layout-slot' ? slotWidth : 0; - }, - }); -}); - -afterEach(() => { - cleanup(); - for (const key of ['scrollWidth', 'clientWidth'] as const) { - if (saved[key]) Object.defineProperty(HTMLElement.prototype, key, saved[key]!); - else delete (HTMLElement.prototype as unknown as Record)[key]; - } -}); - -/** The slot's width inside the popover, beside the row's title in this locale. */ -function slotAtPopoverWidth(title: string): number { - return POPOVER_WIDTH - ROW_CHROME - textWidth(title); -} - -/** - * Five layouts as a host would draw them: the segmented shape the popover folds - * (`role="tab"`, name in `aria-label` and `title`, words in a child span). - * `ViewSwitcherDropdown` itself turns five into a dropdown, so the five-segment - * row is drawn here. - */ -function FiveSegments({ labels, current }: { labels: string[]; current: number }) { - return ( -
- {labels.map((label, i) => ( - - ))} -
- ); -} - -function Harness({ layout }: { layout: React.ReactNode }) { - const { t } = useObjectTranslation(); - return ( - layout} - /> - ); -} - -function inLocale(language: string, layout: React.ReactNode) { - const tree = (node: React.ReactNode) => ( - - - - ); - const view = render(tree(layout)); - fireEvent.click(screen.getByTestId('toolbar-display-trigger')); - return { rerender: (node: React.ReactNode) => view.rerender(tree(node)) }; -} - -function switcher(views: ListViewVisualization[]) { - return {}} animated={false} />; -} - -const FOUR: ListViewVisualization[] = ['grid', 'kanban', 'calendar', 'timeline']; - -function slot() { - return screen.getByTestId('display-layout-slot'); -} - -/** Every segment fits on one line: the row's segments take no more than the slot. */ -function expectFits() { - expect(tablistWidth(screen.getByRole('tablist'))).toBeLessThanOrEqual(slotWidth); -} - -describe('Display popover: the Layout row folds to icons when its segments would not fit (objectstack#26637)', () => { - it('zh-CN, the walked row 「布局 | 表格 | 看板 | 日历 | 时间线」: folds, and every segment keeps its name and tooltip', () => { - slotWidth = slotAtPopoverWidth('布局'); - inLocale('zh', switcher(FOUR)); - - expect(slot().getAttribute('data-layout-fold')).toBe('icons'); - expectFits(); - for (const name of ['表格', '看板', '日历', '时间线']) { - const tab = screen.getByRole('tab', { name }); - expect(tab.getAttribute('title')).toBe(name); - } - // The selected segment keeps its words; the others show their icon only. - const shown = screen.getAllByRole('tab').filter(labelShows).map((tab) => tab.getAttribute('aria-label')); - expect(shown).toEqual(['表格']); - expect(readsWhileFolded).toBe(0); - }); - - it('en: the same four layouts fold too, where the labels are longer still', () => { - slotWidth = slotAtPopoverWidth('Layout'); - inLocale('en', switcher(FOUR)); - - expect(slot().getAttribute('data-layout-fold')).toBe('icons'); - expectFits(); - expect(screen.getByRole('tab', { name: 'Timeline' }).getAttribute('title')).toBe('Timeline'); - expect(readsWhileFolded).toBe(0); - }); - - it('five layouts at the popover width: the fold engages and the row fits', () => { - slotWidth = slotAtPopoverWidth('布局'); - inLocale('zh', ); - - expect(slot().getAttribute('data-layout-fold')).toBe('icons'); - expectFits(); - const shown = screen.getAllByRole('tab').filter(labelShows).map((tab) => tab.getAttribute('aria-label')); - expect(shown).toEqual(['时间线']); - }); - - it('measured, not counted: the same five layouts do not fold where they fit, and two never fold at the popover width', () => { - slotWidth = 600; - const { rerender } = inLocale('zh', ); - expect(slot().hasAttribute('data-layout-fold')).toBe(false); - - slotWidth = slotAtPopoverWidth('布局'); - rerender(switcher(['grid', 'kanban'])); - expect(slot().hasAttribute('data-layout-fold')).toBe(false); - expectFits(); - }); - - it('re-measures with every label shown: a row that fits again unfolds', () => { - slotWidth = slotAtPopoverWidth('布局'); - const { rerender } = inLocale('zh', switcher(FOUR)); - expect(slot().getAttribute('data-layout-fold')).toBe('icons'); - - rerender(switcher(['grid', 'kanban'])); - expect(slot().hasAttribute('data-layout-fold')).toBe(false); - expect(screen.getAllByRole('tab').every(labelShows)).toBe(true); - expect(readsWhileFolded).toBe(0); - }); -}); diff --git a/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.optionsMenu-35551.test.tsx b/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.optionsMenu-35551.test.tsx new file mode 100644 index 00000000000..f1365d4b243 --- /dev/null +++ b/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.optionsMenu-35551.test.tsx @@ -0,0 +1,329 @@ +/** + * 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. + */ + +/** + * The list's Options menu: one row per setting, its name on the left and its + * current value on the right, each opening a second level. + * + * Pinned here: + * - the first level's rows and values, and the view's name at the top + * (renamed in place only where the host passes `onRename`); + * - Fields: search, the eye hides a shown field, one click shows a hidden + * one or adds an addable one; three clicks from the trigger hide a column + * and three show it again; + * - dragging (and the arrow keys on the handle) reorders the SHOWN fields + * and writes the whole order, a hidden field keeping its relative place + * (the level is the list's shared `FieldList`); + * - Row height lists three heights when the host can set one; + * - 保存 sits beside 恢复默认 when the host hands a save over, and the host + * may say when 恢复默认 is live (`resetDisabled`); + * - no control of the menu is an icon without a name, and no line speaks + * the developer wording the menu dropped (asserted against the zh pack). + */ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, fireEvent, cleanup, within, act } from '@testing-library/react'; +import { I18nProvider, useObjectTranslation } from '@object-ui/i18n'; +import { en, zh as zhPack } from '@object-ui/i18n/locales'; +import { + ViewSettingsPopover, + orderFields, + type ViewSettingsPopoverProps, +} from '../components/ViewSettingsPopover'; +import { ViewSwitcherDropdown } from '../ViewSwitcher'; + +afterEach(cleanup); + +const FIELDS = [ + { name: 'name', label: 'Name' }, + { name: 'stage', label: 'Stage' }, + { name: 'amount', label: 'Amount' }, + { name: 'probability', label: 'Probability' }, +]; + +type Overrides = Partial>; + +function Harness(props: Overrides) { + const { t } = useObjectTranslation(); + return ( + string} + allFields={FIELDS} + showHideFields + hiddenFields={new Set()} + updateHiddenFields={() => {}} + {...props} + /> + ); +} + +function openMenu(props: Overrides = {}, language = 'en') { + const view = render( + + + , + ); + fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + return view; +} + +const value = (testId: string) => screen.getByTestId(`${testId}-value`).textContent; + +describe('Options menu — the first level', () => { + it('draws one row per offered setting, its current value on the right', () => { + openMenu({ + hiddenFields: new Set(['amount']), + layout: (closeMenu) => ( + + ), + showGroup: true, + setGroupingConfig: () => {}, + groupingConfig: { fields: [{ field: 'stage', order: 'asc' }] }, + showDensity: true, + density: { mode: 'comfortable', cycle: () => {}, setMode: () => {} }, + setRowNumbers: () => {}, + }); + expect(value('options-row-layout')).toBe('Grid'); + expect(value('options-row-fields')).toBe('3 shown'); + expect(value('options-row-group')).toBe('Stage'); + expect(value('options-row-row-height')).toBe('Standard'); + expect(screen.getByTestId('options-row-more')).toBeTruthy(); + }); + + it('opens a second level per row, and its back control returns to the menu', () => { + openMenu({ showDensity: true, density: { mode: 'compact', cycle: () => {}, setMode: () => {} } }); + fireEvent.click(screen.getByTestId('options-row-row-height')); + expect(screen.getByTestId('options-page-row-height')).toBeTruthy(); + expect(screen.queryByTestId('options-menu')).toBeNull(); + fireEvent.click(screen.getByTestId('options-back')); + expect(screen.getByTestId('options-menu')).toBeTruthy(); + }); + + it('the layout level lists every layout by its words, and choosing one closes the menu', () => { + const onViewChange = vi.fn(); + openMenu({ + layout: (closeMenu) => ( + { closeMenu(); onViewChange(v); }} + animated={false} + /> + ), + }); + fireEvent.click(screen.getByTestId('options-row-layout')); + const list = screen.getByTestId('view-switcher-list'); + expect(within(list).getAllByRole('radio').map((r) => r.textContent)).toEqual(['Grid', 'Kanban', 'Calendar', 'Gallery', 'Map']); + fireEvent.click(within(list).getByRole('radio', { name: 'Kanban' })); + expect(onViewChange).toHaveBeenCalledWith('kanban'); + expect(screen.queryByTestId('view-settings-content')).toBeNull(); + }); + + it('a host that can only step through heights gets a row that steps', () => { + const cycle = vi.fn(); + openMenu({ showDensity: true, density: { mode: 'spacious', cycle } }); + expect(screen.queryByTestId('options-row-row-height')).toBeNull(); + fireEvent.click(screen.getByTestId('view-settings-density-cycle')); + expect(cycle).toHaveBeenCalledTimes(1); + }); + + it('Row height lists compact, standard and spacious and sets the one picked', () => { + const setMode = vi.fn(); + openMenu({ showDensity: true, density: { mode: 'comfortable', cycle: () => {}, setMode } }); + fireEvent.click(screen.getByTestId('options-row-row-height')); + const radios = screen.getAllByRole('radio'); + expect(radios.map((r) => r.textContent)).toEqual(['Compact', 'Standard', 'Spacious']); + expect(radios[1].getAttribute('aria-checked')).toBe('true'); + fireEvent.click(radios[0]); + expect(setMode).toHaveBeenCalledWith('compact'); + }); +}); + +describe('Options menu — 保存 and 恢复默认', () => { + it('a host with a save gets 保存 beside 恢复默认; it closes the menu and saves', () => { + const onSave = vi.fn(); + const onReset = vi.fn(); + openMenu({ onSave, onReset, resetDisabled: false }, 'zh'); + const save = screen.getByTestId('display-save-button'); + const reset = screen.getByTestId('display-reset-button'); + expect(save).toHaveTextContent('保存'); + expect(reset).toHaveTextContent('恢复默认'); + // Side by side, 保存 first. + expect(save.parentElement).toBe(reset.parentElement); + expect(save.compareDocumentPosition(reset) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + fireEvent.click(save); + expect(onSave).toHaveBeenCalledTimes(1); + expect(onReset).not.toHaveBeenCalled(); + expect(screen.queryByTestId('display-save-button')).toBeNull(); + }); + + it('no save, no 保存; the host decides when 恢复默认 is live', () => { + openMenu({ onReset: () => {}, resetDisabled: true }); + expect(screen.queryByTestId('display-save-button')).toBeNull(); + expect(screen.getByTestId('display-reset-button')).toBeDisabled(); + cleanup(); + openMenu({ onReset: () => {}, resetDisabled: false }); + expect(screen.getByTestId('display-reset-button')).toBeEnabled(); + }); + + it('without `resetDisabled`, 恢复默认 is live only once a setting changed', () => { + openMenu({ onReset: () => {} }); + expect(screen.getByTestId('display-reset-button')).toBeDisabled(); + }); +}); + +describe('Options menu — the view name', () => { + it('is renamed in place: Enter keeps a changed name', async () => { + const onRename = vi.fn().mockResolvedValue(true); + openMenu({ viewName: { label: 'Open deals', onRename } }); + const input = screen.getByTestId('options-view-name-input') as HTMLInputElement; + expect(input.value).toBe('Open deals'); + fireEvent.change(input, { target: { value: 'My open deals' } }); + await act(async () => { fireEvent.keyDown(input, { key: 'Enter' }); }); + expect(onRename).toHaveBeenCalledWith('My open deals'); + }); + + it('opening the menu does not put the cursor in the name: a key pressed then renames nothing', () => { + const onRename = vi.fn(); + openMenu({ viewName: { label: 'Hot deals', onRename } }); + const input = screen.getByTestId('options-view-name-input'); + expect(document.activeElement).not.toBe(input); + expect(screen.getByTestId('view-settings-content').contains(document.activeElement)).toBe(true); + }); + + it('a refused rename shows the name it had; Escape puts it back too', async () => { + const onRename = vi.fn().mockResolvedValue(false); + openMenu({ viewName: { label: 'Open deals', onRename } }); + const input = screen.getByTestId('options-view-name-input') as HTMLInputElement; + fireEvent.change(input, { target: { value: 'Taken' } }); + await act(async () => { fireEvent.keyDown(input, { key: 'Enter' }); }); + expect(input.value).toBe('Open deals'); + fireEvent.change(input, { target: { value: 'Draft' } }); + fireEvent.keyDown(input, { key: 'Escape' }); + expect(input.value).toBe('Open deals'); + }); + + it('without `onRename` the name is shown, not edited', () => { + openMenu({ viewName: { label: 'All deals' } }); + expect(screen.getByTestId('options-view-name').textContent).toBe('All deals'); + expect(screen.queryByTestId('options-view-name-input')).toBeNull(); + }); +}); + +describe('Options menu — Fields', () => { + it('hides a column in three clicks from the trigger, and shows it again in three', () => { + const updateHiddenFields = vi.fn(); + openMenu({ updateHiddenFields }); + // 1 = the trigger (openMenu), 2 = Fields, 3 = the eye. + fireEvent.click(screen.getByTestId('options-row-fields')); + fireEvent.click(screen.getByTestId('options-fields-hide-probability')); + expect([...updateHiddenFields.mock.calls[0][0]]).toEqual(['probability']); + cleanup(); + + const show = vi.fn(); + openMenu({ hiddenFields: new Set(['probability']), updateHiddenFields: show }); + fireEvent.click(screen.getByTestId('options-row-fields')); + fireEvent.click(screen.getByTestId('options-fields-item-probability')); + expect([...show.mock.calls[0][0]]).toEqual([]); + }); + + it('search narrows both lists; an addable field is added with one click', () => { + const onAddField = vi.fn(); + openMenu({ addableFields: [{ name: 'close_date', label: 'Close date' }], onAddField }); + fireEvent.click(screen.getByTestId('options-row-fields')); + fireEvent.change(screen.getByTestId('options-fields-search'), { target: { value: 'clo' } }); + expect(screen.queryByTestId('options-fields-shown')).toBeNull(); + fireEvent.click(screen.getByTestId('options-fields-item-close_date')); + expect(onAddField).toHaveBeenCalledWith('close_date'); + fireEvent.change(screen.getByTestId('options-fields-search'), { target: { value: 'zzz' } }); + expect(screen.getByTestId('options-fields-empty')).toBeTruthy(); + }); + + it('dragging a shown field writes the whole order, a hidden field keeping its relative place', () => { + const onFieldOrderChange = vi.fn(); + openMenu({ hiddenFields: new Set(['stage']), onFieldOrderChange, fieldOrder: ['name', 'stage', 'amount', 'probability'] }); + fireEvent.click(screen.getByTestId('options-row-fields')); + const dataTransfer = { setData: vi.fn(), getData: vi.fn(() => 'probability'), effectAllowed: '', dropEffect: '' }; + fireEvent.dragStart(screen.getByTestId('options-fields-row-probability'), { dataTransfer }); + fireEvent.dragOver(screen.getByTestId('options-fields-row-name'), { dataTransfer }); + fireEvent.drop(screen.getByTestId('options-fields-row-name'), { dataTransfer }); + expect(onFieldOrderChange).toHaveBeenCalledWith(['probability', 'name', 'stage', 'amount']); + }); + + it('the handle moves a field with the arrow keys', () => { + const onFieldOrderChange = vi.fn(); + openMenu({ onFieldOrderChange }); + fireEvent.click(screen.getByTestId('options-row-fields')); + fireEvent.keyDown(screen.getByTestId('options-fields-move-name'), { key: 'ArrowDown' }); + expect(onFieldOrderChange).toHaveBeenCalledWith(['stage', 'name', 'amount', 'probability']); + }); + + it('offers no drag without a host to write the order, and none while searching', () => { + openMenu({ onFieldOrderChange: undefined }); + fireEvent.click(screen.getByTestId('options-row-fields')); + expect(screen.queryByTestId('options-fields-move-name')).toBeNull(); + cleanup(); + openMenu({ onFieldOrderChange: () => {} }); + fireEvent.click(screen.getByTestId('options-row-fields')); + expect(screen.getByTestId('options-fields-move-name')).toBeTruthy(); + fireEvent.change(screen.getByTestId('options-fields-search'), { target: { value: 'a' } }); + expect(screen.queryByTestId('options-fields-move-name')).toBeNull(); + }); +}); + +describe('Options menu — words', () => { + it('every control in the menu and on each level has a name', () => { + openMenu({ + viewName: { label: 'Open deals', onRename: () => true }, + onFieldOrderChange: () => {}, + hiddenFields: new Set(['amount']), + onReset: () => {}, + changedCount: 1, + onRefresh: () => {}, + setRowNumbers: () => {}, + }, 'zh'); + const named = (root: HTMLElement) => { + for (const control of within(root).queryAllByRole('button').concat(within(root).queryAllByRole('textbox'))) { + const name = control.getAttribute('aria-label') || control.textContent?.trim(); + expect(name, control.outerHTML).toBeTruthy(); + } + }; + named(screen.getByTestId('view-settings-content')); + expect(screen.getByTestId('display-reset-button').textContent).toBe(zhPack.list.optionsMenu.restoreDefaults); + expect(screen.getByTestId('refresh-button').textContent).toBe(zhPack.list.refresh); + fireEvent.click(screen.getByTestId('options-row-fields')); + named(screen.getByTestId('view-settings-content')); + fireEvent.click(screen.getByTestId('options-back')); + fireEvent.click(screen.getByTestId('options-row-more')); + named(screen.getByTestId('view-settings-content')); + }); + + it('speaks no developer wording on the Open records level', () => { + openMenu({ recordOpen: { resolvedMode: 'drawer', preference: 'drawer', setPreference: () => {} } }, 'zh'); + fireEvent.click(screen.getByTestId('options-row-more')); + const text = screen.getByTestId('view-settings-content').textContent ?? ''; + // The note the menu dropped (its key is gone from every pack). + expect(text).not.toContain('个人偏好'); + expect(text).not.toContain('对象声明'); + cleanup(); + openMenu({ recordOpen: { resolvedMode: 'page', preference: 'drawer', setPreference: () => {} } }, 'zh'); + fireEvent.click(screen.getByTestId('options-row-more')); + expect(screen.getByTestId('display-record-open-declared').textContent).toBe(zhPack.list.optionsMenu.recordOpenAlwaysPage); + expect(screen.getByTestId('view-settings-content').textContent).not.toContain('对象声明'); + }); + + it('every new key is in the en pack', () => { + expect(Object.keys(en.list.optionsMenu).sort()).toEqual(Object.keys(zhPack.list.optionsMenu).sort()); + }); +}); + +describe('field order helpers', () => { + it('orderFields puts the listed names first, the rest in their own order', () => { + expect(orderFields(FIELDS, ['amount', 'name']).map((f) => f.name)).toEqual(['amount', 'name', 'stage', 'probability']); + expect(orderFields(FIELDS, undefined).map((f) => f.name)).toEqual(['name', 'stage', 'amount', 'probability']); + }); +}); diff --git a/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.recordOpen-26681.test.tsx b/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.recordOpen-26681.test.tsx index 19ce5b78dac..8dbc16e4c96 100644 --- a/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.recordOpen-26681.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.recordOpen-26681.test.tsx @@ -15,13 +15,14 @@ * * - `drawer`: two segments, Drawer | Full page — the split pane retired * (objectstack#28915, 「默认改抽屉,分屏彻底退役,只留抽屉和整页」) — each - * writing the reader's preference through the host's setter, with the - * note that the choice is the reader's own; + * writing the reader's preference through the host's setter; the note + * that the choice is the reader's own retired with the Options menu + * (objectstack#35551: no developer wording in the menu); * - `page`: one read-only line — the declaration wins, nothing to choose; * - `new_window` / `none`, or no `recordOpen` at all: no section. * - * The note and the read-only line are read against the packs, not spelled - * here: what is pinned is which line is drawn, not its wording. Rendered in + * The read-only line is read against the packs, not spelled here: what is + * pinned is which line is drawn, not its wording. Rendered in * zh-CN as well, the language the ruling was given in. */ import { describe, it, expect, vi, afterEach } from 'vitest'; @@ -51,6 +52,9 @@ function openDisplay(recordOpen: ViewSettingsRecordOpen | undefined, language = , ); fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + // Open records lives on the Options menu's More level (objectstack#35551). + const more = screen.queryByTestId('options-row-more'); + if (more) fireEvent.click(more); } const drawer = (preference: 'drawer' | 'page', setPreference = vi.fn()): ViewSettingsRecordOpen => ({ @@ -74,7 +78,7 @@ describe('ViewSettingsPopover — Open records (objectstack#26681)', () => { expect(screen.queryByTestId('display-record-open-split')).toBeNull(); expect(screen.getByRole('radio', { name: 'Drawer' }).getAttribute('aria-checked')).toBe('true'); expect(screen.getByRole('radio', { name: 'Full page' }).getAttribute('aria-checked')).toBe('false'); - expect(screen.getByTestId('display-record-open-note').textContent).toBe(en.list.recordOpenNote); + expect(screen.queryByTestId('display-record-open-note')).toBeNull(); expect(screen.queryByTestId('display-record-open-declared')).toBeNull(); }); @@ -106,7 +110,7 @@ describe('ViewSettingsPopover — Open records (objectstack#26681)', () => { it('a `page` object: the read-only line, no segments, no note', async () => { openDisplay({ resolvedMode: 'page', preference: 'drawer', setPreference: vi.fn() }); expect((await screen.findByTestId('display-record-open-declared')).textContent).toBe( - en.list.recordOpenDeclaredPage, + en.list.optionsMenu.recordOpenAlwaysPage, ); expect(screen.queryByRole('radio')).toBeNull(); expect(screen.queryByTestId('display-record-open-note')).toBeNull(); @@ -131,9 +135,9 @@ describe('ViewSettingsPopover — Open records (objectstack#26681)', () => { expect(await screen.findByRole('radio', { name: zh.recordOpenDrawer })).toBeTruthy(); expect(screen.getByRole('radio', { name: zh.recordOpenPage })).toBeTruthy(); expect(screen.getByTestId('display-record-open').textContent).toContain(zh.recordOpen); - expect(screen.getByTestId('display-record-open-note').textContent).toBe(zh.recordOpenNote); + expect(screen.queryByTestId('display-record-open-note')).toBeNull(); cleanup(); openDisplay({ resolvedMode: 'page', preference: 'drawer', setPreference: vi.fn() }, 'zh'); - expect((await screen.findByText(zh.recordOpenDeclaredPage)).getAttribute('data-testid')).toBe('display-record-open-declared'); + expect((await screen.findByText(zh.optionsMenu.recordOpenAlwaysPage)).getAttribute('data-testid')).toBe('display-record-open-declared'); }); }); diff --git a/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.rowColorTitle.test.tsx b/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.rowColorTitle.test.tsx index 862d479e2e3..dfbfbe99d04 100644 --- a/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.rowColorTitle.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.rowColorTitle.test.tsx @@ -37,9 +37,7 @@ function Harness() { t={t as (key: string, opts?: any) => string} allFields={[{ name: 'status', label: 'Status' }]} showColor - // A configured row colour is what makes the section render EXPANDED - // (`defaultOpen={!!rowColorConfig}`), so its body — the `Color by field` - // label the exact-match assertion below leans on — is in the DOM. + // A configured row colour: the level then offers Clear beside its title. rowColorConfig={{ field: 'status', colors: {} }} setRowColorConfig={vi.fn()} /> @@ -56,6 +54,8 @@ function openPopover() { , ); fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + // The colour picker is the Options menu's Row color level (objectstack#35551). + fireEvent.click(screen.getByTestId('options-row-color')); } describe('ViewSettingsPopover — the colour section takes the section key (objectui#4118)', () => { diff --git a/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.sharedSelect-11865.test.tsx b/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.sharedSelect-11865.test.tsx index 0843d4919e9..ba28cae237a 100644 --- a/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.sharedSelect-11865.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.sharedSelect-11865.test.tsx @@ -73,8 +73,8 @@ function renderPopover(config: RowColor) { />, ); fireEvent.click(screen.getByTestId('toolbar-display-trigger')); - // With no config the section starts collapsed, as it did with the native control. - if (!config) fireEvent.click(screen.getByRole('button', { name: 'Row Color' })); + // The colour picker is the Options menu's Row color level (objectstack#35551). + fireEvent.click(screen.getByTestId('options-row-color')); return { setRowColorConfig, trigger: screen.getByTestId('color-field-select') }; } diff --git a/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx b/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx index 2245d9670f8..bc253114b6d 100644 --- a/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx +++ b/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx @@ -1,30 +1,26 @@ /** - * ViewSettingsPopover — the list toolbar's "Display" control. + * ViewSettingsPopover — the list's Options menu. * - * Since objectui#12423 this is the DEFAULT desktop shape of the list toolbar: - * the bar keeps Filter, Sort, Display and Search, and everything else sits - * here, in this order — - * - Layout (the visualization switcher; only when the list offers a choice) - * - Open records (how a row opens its record; only when the host passes it) - * - Sort (below `sm` only, when the host passes it: the bar's Sort button - * is not drawn there) - * - Group, Row color, Hide fields - * - Density - * - Row numbers (a session-only switch, grid only) - * - Edit inline (a switch, grid only, when the principal may edit) - * - footer: Reset to view default · Refresh, then the export entries on a - * row of their own that wraps, so every format stays inside the panel + * Opened from the view bar's Options trigger, it is a short menu: each row + * names one setting on the left and its current value on the right, and opens + * a second level that changes it. At the top, the view's name (renamed in + * place where the host allows it). Then, each only when the host offers it: * - * It began as UX Sprint 2 (P1-4)'s "View settings" gear behind - * `compactToolbar: true`; the wide form — one toolbar button per control — is - * what a host gets with `compactToolbar: false`, and ListView.tsx keeps it. - * Content is duplicated between the two forms: change one, change both. One - * exception: Open records is drawn here only — see `recordOpen`. + * - Layout: the visualizations, each by icon AND words; + * - Fields: 「N shown」 → the shown fields (search, drag to reorder, eye to + * hide) above the hidden ones (one click shows a field again); + * - Group, Row color; + * - Row height: compact, standard, spacious; + * - Sort (below `sm` only, where the bar draws no Sort button); + * - More: how a record opens, row numbers, inline edit. * - * Every control persists exactly what its wide-form twin persists; this - * component writes nothing itself. The trigger's count is the number of - * settings that differ from the view's own (the host computes it), and Reset - * hands every one of them back. + * The footer keeps Restore defaults, Refresh and the export entries. + * + * Every setting here is the reader's own: this component writes nothing + * itself, each control hands its change to the host, which keeps it as the + * reader's preference. The wide toolbar form (`compactToolbar: false`) keeps + * one button per control in ListView.tsx; content is duplicated between the + * two forms, so change one, change both. Open records is drawn here only. * * @module */ @@ -33,6 +29,7 @@ import * as React from 'react'; import { cn, Button, + Input, Popover, PopoverContent, PopoverTrigger, @@ -51,13 +48,18 @@ import { Rows4, Rows3, Rows2, - ChevronDown, + Check, + ChevronLeft, + ChevronRight, RotateCw, Download, Loader2, Undo2, + Save, } from 'lucide-react'; import { TOOLBAR_TEXT_TRIGGER } from '../listToolbarRow'; +import { ViewSwitcherFaceContext } from '../ViewSwitcher'; +import { FieldList, type FieldListItem } from '../conditions/FieldList'; /** * A bar or panel control's touch size below `sm`: 44 px on both sides (WCAG @@ -115,9 +117,28 @@ export function groupFieldOptions(fields: readonly ViewSettingsField[]): Array<{ .map((f) => ({ value: f.name, label: f.label || f.name })); } +export type ViewSettingsDensityMode = 'compact' | 'comfortable' | 'spacious'; + export interface ViewSettingsDensity { - mode: 'compact' | 'comfortable' | 'spacious'; + mode: ViewSettingsDensityMode; cycle: () => void; + /** + * Choose one height. Wired ⇒ Row height is a second level listing the three + * heights; absent ⇒ the row steps to the next height on each click. + */ + setMode?: (mode: ViewSettingsDensityMode) => void; +} + +/** + * The view's name at the top of the menu. `onRename` is passed only to a + * reader who may rename this view (the owner of one of their own views, or a + * reader who may edit the shared view); without it the name is shown, not + * edited. Resolves `false` when the rename was refused (the host has said + * why), and the field then shows the name it had. + */ +export interface ViewSettingsViewName { + label: string; + onRename?: (next: string) => boolean | Promise; } /** @@ -137,11 +158,9 @@ export type ViewSettingsRecordOpenPreference = 'drawer' | 'page'; * section answers by the mode the host resolved for this object and view: * * - `drawer`: two segments, Drawer | Full page, writing the reader's - * preference through `setPreference`, with a one-line note that the - * choice is the reader's own and that a record's `↗` always opens the - * full page; - * - `page`: one read-only line saying the object is declared to open as a - * full page — the declaration wins, so there is nothing to choose; + * preference through `setPreference`; + * - `page`: one read-only line saying records always open as a full page — + * the object's declaration wins, so there is nothing to choose; * - `new_window` / `none`: no section. The preference changes nothing there * and the ruling gives those declarations no line of their own. */ @@ -162,6 +181,25 @@ export interface ViewSettingsPopoverProps { t: (key: string, opts?: any) => string; allFields: ViewSettingsField[]; + /** The view's name, at the top of the menu. Absent ⇒ no name row. */ + viewName?: ViewSettingsViewName; + + /** + * The order the reader's columns are drawn in: the same list the grid's + * header drag keeps (its column state's `order`, by column key). Names it + * does not list keep the `allFields` order after the listed ones. + */ + fieldOrder?: readonly string[]; + /** A field's type (the object's declaration), for the icon the Fields level draws beside it. */ + fieldType?: (name: string) => string | undefined; + /** + * Store a new column order: the whole list, every field of `allFields` + * (hidden ones in place) and any other key `fieldOrder` held, kept as it + * was. Wired ⇒ the shown fields can be dragged; the host writes it where the + * header drag writes, so the two are one state. + */ + onFieldOrderChange?: (order: string[]) => void; + /** * The Layout row: the visualization switcher. The host passes it only when * the list offers more than one visualization, as a function of `closeMenu`: @@ -169,10 +207,10 @@ export interface ViewSettingsPopoverProps { * `closeMenu` when a layout is picked (objectui#12621). The panel's toggles * (row numbers, inline edit, density, hidden fields) never close it. * - * The row folds a segmented control that would not fit to icons (see - * `LayoutSlot`). It folds what it can read: a `role="tablist"` whose tabs - * carry their name in `aria-label` and `title` and their words in a direct - * child ``, the shape `ViewSwitcherDropdown` draws. + * The menu draws the element twice through `ViewSwitcherFaceContext`: as + * the current layout's name on the Layout row (`value`) and as the list of + * layouts on the second level (`list`), the faces `ViewSwitcherDropdown` + * draws. */ layout?: (closeMenu: () => void) => React.ReactNode; @@ -245,6 +283,18 @@ export interface ViewSettingsPopoverProps { changedCount?: number; /** Hand every changed setting back to the view's own. Drawn when wired. */ onReset?: () => void; + /** + * Whether 恢复默认 is disabled. Defaults to "nothing counted" + * (`changedCount === 0`); a host that owns the reset and wires it only + * while the list differs from the view passes `false`. + */ + resetDisabled?: boolean; + /** + * 保存: the list on screen becomes the open view's stored body. A host + * wires it only for a view the reader owns and may update, and only while + * the list differs from it (objectstack#30073). Drawn beside 恢复默认. + */ + onSave?: () => void; /** Footer: re-fetch the list. Drawn when wired. */ onRefresh?: () => void; @@ -257,46 +307,78 @@ export interface ViewSettingsPopoverProps { exportError?: string | null; } -interface SectionProps { - title: string; - badge?: number; - onClear?: () => void; - clearLabel?: string; - defaultOpen?: boolean; - children: React.ReactNode; +/** The second levels of the menu; `root` is the menu itself. */ +type MenuPage = 'root' | 'layout' | 'fields' | 'group' | 'color' | 'rowHeight' | 'sort' | 'more'; + +/** + * One row of the menu: the setting's name on the left, its current value on + * the right, and a chevron, for a row that opens a second level. + */ +function MenuRow({ + label, + value, + onOpen, + testId, +}: { + label: string; + value?: React.ReactNode; + onOpen: () => void; + testId: string; +}) { + return ( + + ); } -function Section({ title, badge, onClear, clearLabel, defaultOpen = true, children }: SectionProps) { - const [open, setOpen] = React.useState(defaultOpen); +/** + * A second level: a back control, worded with the level's title, over the + * level's content. `action` is drawn at the right of the title row. + */ +function SubPage({ + title, + onBack, + action, + children, + testId, +}: { + title: string; + onBack: () => void; + action?: React.ReactNode; + children: React.ReactNode; + testId: string; +}) { return ( -
-
+
+
- {onClear && ( - - )} + {action &&
{action}
}
- {open &&
{children}
} + {children}
); } @@ -431,88 +513,159 @@ function RecordOpenSection({ ) : ( - {t('list.recordOpenDeclaredPage', { defaultValue: 'This object is declared to open as a full page' })} + {t('list.optionsMenu.recordOpenAlwaysPage', { defaultValue: 'Records always open as a full page' })} )}
- {resolvedMode === 'drawer' && ( -

- {t('list.recordOpenNote', { - defaultValue: 'Your own preference, not part of the object’s declaration. A record’s ↗ always opens the full page.', - })} -

- )}
); } -/** Set on the layout slot while its segments show icons only; the class below reads it. */ -const LAYOUT_FOLD_ATTR = 'data-layout-fold'; - /** - * The Layout row's control, folded to icons when its segments would not fit - * (objectstack#26637). The panel is a fixed width and the row shares it with - * its title, so four or five icon + label segments ran out of room and broke - * each label onto two lines, in zh-CN and longer still in en. - * - * The fold is MEASURED, never a count or a breakpoint: what decides it is the - * width the segments need with every label shown against the width the slot - * has, in whatever locale is rendering. Folded, every segment but the selected - * one hides its words; its icon stays, and its `aria-label` and `title` stay - * its accessible name and tooltip. The selected segment keeps its label. - * - * Labels never wrap here (`whitespace-nowrap`, `shrink-0`), so the width the - * segments need is the slot's children's `scrollWidth`. While folded the - * hidden labels add nothing to it, so each measurement lifts the fold for one - * synchronous read and puts it back before the browser paints. It runs after - * every render (labels, locale and the views offered all arrive as props) and - * whenever the slot itself resizes. + * The fields of `allFields`, in the order the reader's columns are drawn: + * the names `order` lists first, in its order, then the rest in their own. */ -function LayoutSlot({ children }: { children: React.ReactNode }) { - const ref = React.useRef(null); - const [folded, setFolded] = React.useState(false); - - const measure = React.useCallback(() => { - const slot = ref.current; - if (!slot) return; - const fold = slot.getAttribute(LAYOUT_FOLD_ATTR); - if (fold !== null) slot.removeAttribute(LAYOUT_FOLD_ATTR); - let needed = 0; - for (const child of Array.from(slot.children)) needed += (child as HTMLElement).scrollWidth; - if (fold !== null) slot.setAttribute(LAYOUT_FOLD_ATTR, fold); - setFolded(needed > slot.clientWidth); - }, []); - - React.useLayoutEffect(measure); +export function orderFields( + fields: readonly ViewSettingsField[], + order: readonly string[] | undefined, +): ViewSettingsField[] { + if (!order || order.length === 0) return [...fields]; + const rank = new Map(order.map((name, i) => [name, i])); + const rankOf = (fieldName: string): number => rank.get(fieldName) ?? Number.MAX_SAFE_INTEGER; + return fields + .map((entry, i) => ({ entry, i })) + .sort((a, b) => rankOf(a.entry.name) - rankOf(b.entry.name) || a.i - b.i) + .map(({ entry }) => entry); +} - React.useEffect(() => { - const slot = ref.current; - if (!slot || typeof ResizeObserver === 'undefined') return; - const observer = new ResizeObserver(() => measure()); - observer.observe(slot); - return () => observer.disconnect(); - }, [measure]); +/** The words a density mode is shown by, on the Row height row and its level. */ +function rowHeightLabel(t: ViewSettingsPopoverProps['t'], mode: ViewSettingsDensityMode): string { + return mode === 'compact' + ? t('list.optionsMenu.rowHeightCompact', { defaultValue: 'Compact' }) + : mode === 'comfortable' + ? t('list.optionsMenu.rowHeightStandard', { defaultValue: 'Standard' }) + : t('list.optionsMenu.rowHeightSpacious', { defaultValue: 'Spacious' }); +} + +const ROW_HEIGHT_MODES: readonly ViewSettingsDensityMode[] = ['compact', 'comfortable', 'spacious']; +/** + * The view's name at the top of the menu, renamed in place: Enter or leaving + * the field keeps a changed, non-blank name; Escape puts the name back. A + * rename the host refuses shows the name it had. + */ +function ViewNameField({ t, viewName }: { t: ViewSettingsPopoverProps['t']; viewName: ViewSettingsViewName }) { + const { label, onRename } = viewName; + const [draft, setDraft] = React.useState(label); + const [busy, setBusy] = React.useState(false); + React.useEffect(() => setDraft(label), [label]); + const title = t('list.optionsMenu.viewName', { defaultValue: 'View name' }); + if (!onRename) { + return ( +
+ {label} +
+ ); + } + const commit = async () => { + const next = draft.trim(); + if (!next || next === label) { + setDraft(label); + return; + } + setBusy(true); + try { + const ok = await onRename(next); + if (!ok) setDraft(label); + } finally { + setBusy(false); + } + }; return ( -
span]:hidden', - )} - data-testid="display-layout-slot" - > - {children} +
+ setDraft(e.target.value)} + onBlur={() => { void commit(); }} + onKeyDown={(e) => { + if (e.key === 'Enter') { + e.preventDefault(); + void commit(); + } else if (e.key === 'Escape') { + // Escape reverts the name; the menu stays open. + e.stopPropagation(); + setDraft(label); + } + }} + className="h-8 text-[13px] font-medium max-sm:h-11" + data-testid="options-view-name-input" + />
); } +/** + * The Fields level: the list's shared field list (`../conditions/FieldList`, + * the one the Filter and Sort controls open) as the view's field manager. A + * search box; the shown fields in column order, reordered by drag or by a grip + * handle and the arrow keys, each hidden by its eye; then the view's columns + * the reader hid and the object's fields they may add, each shown or added + * with one click. Every change applies at once. `allFields` holds only the + * fields the reader may read: the host withholds the rest. + */ +function FieldsPage({ + allFields, + hiddenFields, + updateHiddenFields, + addableFields, + onAddField, + fieldOrder, + onFieldOrderChange, + fieldType, +}: { + allFields: readonly ViewSettingsField[]; + hiddenFields: Set; + updateHiddenFields: (next: Set) => void; + addableFields?: readonly ViewSettingsField[]; + onAddField?: (name: string) => void; + fieldOrder?: readonly string[]; + onFieldOrderChange?: (order: string[]) => void; + fieldType?: (name: string) => string | undefined; +}) { + const addable = onAddField ? addableFields ?? [] : []; + const columns = new Set(allFields.map((f) => f.name)); + const items: FieldListItem[] = [ + ...allFields, + ...addable.filter((f) => !columns.has(f.name)), + ].map((f) => ({ value: f.name, label: f.label || f.name, type: fieldType?.(f.name) })); + const shown = orderFields(allFields, fieldOrder).filter((f) => !hiddenFields.has(f.name)).map((f) => f.name); + return ( + updateHiddenFields(new Set([...hiddenFields, name]))} + onShow={(name) => updateHiddenFields(new Set([...hiddenFields].filter((n) => n !== name)))} + addable={addable.map((f) => f.name)} + onAdd={onAddField} + testId="options-fields" + className="w-full" + /> + ); +} + export function ViewSettingsPopover(props: ViewSettingsPopoverProps) { const { t, allFields, + viewName, + fieldOrder, + onFieldOrderChange, + fieldType, layout, recordOpen, sort, @@ -536,6 +689,8 @@ export function ViewSettingsPopover(props: ViewSettingsPopoverProps) { setInlineEdit, changedCount = 0, onReset, + resetDisabled, + onSave, onRefresh, refreshing, exportFormats, @@ -545,18 +700,274 @@ export function ViewSettingsPopover(props: ViewSettingsPopoverProps) { } = props; const [open, setOpen] = React.useState(false); + const [page, setPage] = React.useState('root'); const belowSm = useBelowSm(); // Closing through the controlled state lets Radix return focus to the - // Display trigger, as Escape and an outside click do. + // Options trigger, as Escape and an outside click do. const closeMenu = React.useCallback(() => setOpen(false), []); - - const DensityIcon = - density?.mode === 'compact' ? Rows4 : density?.mode === 'comfortable' ? Rows3 : Rows2; + // The menu opens on its first level every time. + React.useEffect(() => { + if (!open) setPage('root'); + }, [open]); + const back = () => setPage('root'); // The trigger is named 「Options」 on the view bar (objectstack#35548). const triggerLabel = t('list.options', { defaultValue: 'Options' }); const hasExport = !!onExport && !!exportFormats && exportFormats.length > 0; - const hasFooter = !!onReset || !!onRefresh || hasExport; + const hasFooter = !!onSave || !!onReset || !!onRefresh || hasExport; + + const fieldLabel = (name: string) => allFields.find((f) => f.name === name)?.label || 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) + : []; + const recordOpenDrawn = !!recordOpen && (recordOpen.resolvedMode === 'drawer' || recordOpen.resolvedMode === 'page'); + const hasMore = recordOpenDrawn || !!setRowNumbers || (!!showInlineEdit && !!setInlineEdit); + const fieldsOffered = !!showHideFields && !!hiddenFields && !!updateHiddenFields; + const shownCount = fieldsOffered ? allFields.filter((f) => !hiddenFields!.has(f.name)).length : 0; + const DensityIcon = + density?.mode === 'compact' ? Rows4 : density?.mode === 'comfortable' ? Rows3 : Rows2; + + const titles: Record, string> = { + layout: t('list.layout', { defaultValue: 'Layout' }), + fields: t('list.optionsMenu.fields', { defaultValue: 'Fields' }), + group: t('list.group', { defaultValue: 'Group' }), + color: t('list.rowColor', { defaultValue: 'Row Color' }), + rowHeight: t('list.optionsMenu.rowHeight', { defaultValue: 'Row height' }), + sort: t('list.sort', { defaultValue: 'Sort' }), + more: t('list.optionsMenu.more', { defaultValue: 'More' }), + }; + const clearAction = (onClear: () => void, testId: string) => ( + + ); + + const rootMenu = ( +
+ {viewName && } +
+ {layout && ( + {layout(closeMenu)}} + onOpen={() => setPage('layout')} + testId="options-row-layout" + /> + )} + {fieldsOffered && ( + setPage('fields')} + testId="options-row-fields" + /> + )} + {showGroup && setGroupingConfig && ( + 0 ? groupFields.map(fieldLabel).join(' › ') : none} + onOpen={() => setPage('group')} + testId="options-row-group" + /> + )} + {showColor && setRowColorConfig && ( + setPage('color')} + testId="options-row-color" + /> + )} + {showDensity && density && (density.setMode ? ( + setPage('rowHeight')} + testId="options-row-row-height" + /> + ) : ( + // A host that can only step through the heights gets a row that steps. + + ))} + {sort && ( +
+ setPage('sort')} testId="options-row-sort" /> +
+ )} + {hasMore && ( + setPage('more')} testId="options-row-more" /> + )} +
+
+ ); + + let body: React.ReactNode = rootMenu; + if (page === 'layout' && layout) { + body = ( + + {layout(closeMenu)} + + ); + } else if (page === 'fields' && fieldsOffered) { + body = ( + 0 + ? ( + + ) + : undefined} + > + + + ); + } else if (page === 'group' && showGroup && setGroupingConfig) { + body = ( + setGroupingConfig(undefined), 'options-group-clear') : undefined} + > +
+ setGroupingConfig(next as any)} + /> +
+
+ ); + } else if (page === 'color' && showColor && setRowColorConfig) { + // `list.rowColor` names this level: it is the counterpart of the wide + // toolbar's Row color panel, which takes the same key (objectui#4118). + body = ( + setRowColorConfig(undefined), 'options-color-clear') : undefined} + > +
+ + ({ value: field.name, label: field.label || field.name })), + ]} + onPick={(field) => { + if (!field) { + setRowColorConfig(undefined); + } else { + setRowColorConfig({ field, colors: rowColorConfig?.colors || {} }); + } + }} + /> +
+
+ ); + } else if (page === 'rowHeight' && density?.setMode) { + const setMode = density.setMode; + body = ( + +
+ {ROW_HEIGHT_MODES.map((mode) => { + const active = density.mode === mode; + return ( + + ); + })} +
+
+ ); + } else if (page === 'sort' && sort) { + body = ( + +
{sort}
+
+ ); + } else if (page === 'more' && hasMore) { + body = ( + + {recordOpen && } + {setRowNumbers && ( + + )} + {showInlineEdit && setInlineEdit && ( + + )} + + ); + } return ( @@ -587,209 +998,66 @@ export function ViewSettingsPopover(props: ViewSettingsPopoverProps) { )} - {/* Below `sm` the panel takes the phone's width, as Filter and Sort do, so - the Sort block's rows keep their words. */} + {/* Below `sm` the menu takes the phone's width, as Filter and Sort do. */} { + event.preventDefault(); + (event.currentTarget as HTMLElement | null)?.focus?.(); + }} > -
- {layout && ( -
- - {t('list.layout', { defaultValue: 'Layout' })} - - {layout(closeMenu)} -
- )} - - {recordOpen && } - - {sort && ( -
- {sort} -
- )} - - {showGroup && setGroupingConfig && ( -
setGroupingConfig(undefined) : undefined} - clearLabel={t('list.clear', { defaultValue: 'Clear' })} - > - setGroupingConfig(next as any)} - /> -
- )} +
{body}
- {/* `list.rowColor` names the SECTION; `list.color` is the wide - toolbar-BUTTON label for the same feature — ListView renders the - button with `list.color` and the panel it opens with - `list.rowColor`. This Section is that panel's counterpart here, - so it takes the panel's key (objectui#4118). */} - {showColor && setRowColorConfig && ( -
setRowColorConfig(undefined) : undefined} - clearLabel={t('list.clear', { defaultValue: 'Clear' })} - defaultOpen={!!rowColorConfig} - > - - ({ value: field.name, label: field.label || field.name })), - ]} - onPick={(field) => { - if (!field) { - setRowColorConfig(undefined); - } else { - setRowColorConfig({ field, colors: rowColorConfig?.colors || {} }); - } - }} - /> -
- )} - - {showHideFields && hiddenFields && updateHiddenFields && ( -
0 ? () => updateHiddenFields(new Set()) : undefined} - clearLabel={t('list.showAll', { defaultValue: 'Show all' })} - defaultOpen={hiddenFields.size > 0} - > -
- {allFields.map((field) => ( - - ))} - {onAddField && addableFields && addableFields.length > 0 && ( -
- {addableFields.map((field) => ( - - ))} -
- )} -
-
- )} - - {showDensity && density && ( -
- - {t('grid.toolbar.densityMode', { defaultValue: 'Density' })} - + {page === 'root' && hasFooter && ( +
+ {onSave && ( -
- )} - - {setRowNumbers && ( - - )} - - {showInlineEdit && setInlineEdit && ( - - )} -
- - {hasFooter && ( -
+ )} {onReset && ( )} {onRefresh && ( )} - {/* The export entries take a full row and wrap within it: the panel + {/* The export entries take a full row and wrap within it: the menu is a fixed width, and one entry per format can outgrow it. */} {hasExport && (
{exportBusy - ? - : } + ?