diff --git a/.changeset/35955-save-into-shared-view.md b/.changeset/35955-save-into-shared-view.md new file mode 100644 index 00000000000..ac0a7d4fbba --- /dev/null +++ b/.changeset/35955-save-into-shared-view.md @@ -0,0 +1,20 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +'@object-ui/plugin-list': patch +--- + +feat(console): Save to this view on a shared view asks once, then saves and publishes it; the layout and row colour are part of a list's draft + +Clause-②: yes (widening) — new `console.objectView.draft.*` keys in every `@object-ui/i18n` locale pack (`saveToViewConfirmTitle`, `saveToViewConfirm`, `saveToViewConfirmButton`, `savedForEveryone`, `pendingDraft`); `@object-ui/plugin-list` `ListView` gains the optional host prop `onRowColorChange` and two optional `viewDefaults` members, `viewType` and `rowColor`; nothing removed or renamed +Metadata-protocol: none + +On a Console object list, **Save to this view** is now offered on a shared view to a reader who may edit it (an administrator, on a stored view whose package takes saves). It asks once ("everyone who uses this view will see these changes"), then saves the view and publishes it in the same step, so other readers see it on their next read, and says "Saved, visible to everyone". The options menu's Save does the same. + +- When the view already has unpublished changes (a draft saved from the view settings, by anyone), nothing is written: the Console says so and points to the view settings to publish or discard that draft first. The draft write is sent with the first-write pin (`If-None-Match: *`), so the server refuses it when a draft is pending; that draft is never published on someone else's behalf. A publish the server refuses discards the draft the save wrote. +- The reader's row height and column widths are never written into a shared view: it keeps its own. +- The Display panel's layout and row colour are part of the list's draft: they survive opening a record and coming back, and both Save to this view and Save as my view keep them (a layout switch retypes the saved view). Discard puts back the view's own. + +`@object-ui/plugin-list`: `ListView` reports a pick in its row colour panel through the new optional host prop `onRowColorChange` (the rule in force, or `null` for none), never at mount or for a reset. A host that lays the reader's layout or row colour into `schema` passes the view's own in `viewDefaults.viewType` / `viewDefaults.rowColor`, and the `layout` / `rowColor` parts and the Display count are judged against them; each is read only when its key is present. Without them nothing changes. + +No metadata key, value or default changes. The view settings panel and the footer calculation still save a shared view as a draft that the view settings publish. diff --git a/content/docs/ui/views.mdx b/content/docs/ui/views.mdx index e94a8160c38..cab044ccd21 100644 --- a/content/docs/ui/views.mdx +++ b/content/docs/ui/views.mdx @@ -619,16 +619,26 @@ reader's right-column and panel choices on it, are described in ### A user's list state never writes the view -A header sort, a filter change, grouping, the search, Hide Fields, an added field and a -column drag apply at once and are a **draft**: they are kept nowhere and never write the -view metadata, so they work even where the tenant's metadata is read-only. While the list -holds a draft, **Discard** and **Save** sit at the end of the condition row (one **Save** -whose menu also holds Discard on a narrow list or a phone). - -- **Save** names what is unsaved and keeps the sort, filters, columns and hidden fields: - **Save to this view** on a view of the user's own, or **Save as my view**, which asks a - name first (the view's name with "copy") and then opens the new view. Either says - "Saved", and the buttons go while the conditions stay. +A header sort, a filter change, grouping, the search, Hide Fields, an added field, a +column drag and the Display panel's layout and row color apply at once and are a **draft**: +they are kept nowhere and never write the view metadata, so they work even where the +tenant's metadata is read-only. While the list holds a draft, **Discard** and **Save** sit at +the end of the condition row (one **Save** whose menu also holds Discard on a narrow list or +a phone). + +- **Save** names what is unsaved and keeps the sort, filters, columns, hidden fields, layout + and row color: **Save to this view**, or **Save as my view**, which asks a name first (the + view's name with "copy") and then opens the new view. Either says "Saved", and the buttons + go while the conditions stay. +- **Save to this view** on a view of the user's own saves it at once. On a shared view it is + offered to a user who may edit the view (an administrator, on a stored view whose package + takes saves). It asks once ("everyone who uses this view will see these changes"), then + saves the view and publishes it in the same step, so every user sees it on their next read, + and says "Saved, visible to everyone". It never writes the user's row height or column + widths into the view. When the view already has unpublished changes (a draft saved from + the view settings, by anyone), nothing is saved: the Console says so and points to the view + settings to publish or discard that draft first. Every other change to a shared view still + goes to a draft that the view settings publish. - **Discard** puts the list back as its view declares it, the Display panel's layout and row color included, and removes the list's `uf_*` parameters from the address bar. - The draft survives opening a record and coming back. Opening another view or object, diff --git a/docs/qa/platform-checklist/areas/records-forms.json b/docs/qa/platform-checklist/areas/records-forms.json index e574499564d..8bb59598f1f 100644 --- a/docs/qa/platform-checklist/areas/records-forms.json +++ b/docs/qa/platform-checklist/areas/records-forms.json @@ -2933,7 +2933,7 @@ "title": "User-built FilterBuilder/SortBuilder toolbar merges with the view filter, restores across nav, and reproduces rows from the URL", "since": "v16", "status": "active", - "revision": 13, + "revision": 14, "priority": "P1", "surface": "browser", "personas": [ @@ -2958,7 +2958,8 @@ "read where the toolbar filter and sort are kept: nowhere durable. Since objectstack#35955 they are the list's DRAFT, held in this tab's memory (ui/packages/app-shell/src/views/listDraftStore.ts): the signed-in user's sys_user_preference row keyed ui.list.showcase_task (GET /api/v1/data/sys_user_preference filtered to that key) gains no filters, sort or search from the change — it holds only what is remembered for the reader (perView..columnState.widths, rowHeight, viewOrder) — and localStorage gains no list-filters::showcase_task: key. Reload the page: the list opens as the view declares it", "sign out through the account menu (the avatar menu's Log out, user.logout in ui/packages/app-shell/src/layout/AppHeader.tsx; never by clearing storage). That Log out itself removes the signed-out user's list-state:* and list-filters:* keys from localStorage (purgeSignedOutUserClientState, ui/packages/auth/src/ActiveOrganizationStorage.ts, run by AuthProvider's sign-out), so the first account's keys are gone by the time the second signs in; the clause holds by that wipe AND by the user-keyed row. Sign in as the SECOND account; open the same object+view; confirm the first account's cached toolbar filter does NOT appear", "userFilters/URL: where UserFilters are hosted (an interface page or the userFilters surface — NOT a bare object list, ADR-0053), apply a quick-filter; copy the URL; open it in a fresh tab; confirm the uf_ params (comma-joined, URI-encoded) reproduce the same rows and uf__tab carries the active preset (ADR-0047)", - "negative sweep: confirm tabs-element userFilters (preset chips, uf__tab) do NOT leak onto the bare object list view — dropdown chips the object view itself declares are allowed there (ADR-0047 amendment) and their uf_ params are not a leak" + "negative sweep: confirm tabs-element userFilters (preset chips, uf__tab) do NOT leak onto the bare object list view — dropdown chips the object view itself declares are allowed there (ADR-0047 amendment) and their uf_ params are not a leak", + "shared-view save (objectstack#35955): as the seeded admin on the in_progress saved view (a stored view the showcase package takes saves into), change the sort, pick Kanban in the Display panel's layout and a row colour, open a record and come back with Back (the layout and the row colour are part of the draft and are still there), then set the row height to Spacious on the options menu's Row height level. Press 「Save」 at the condition row's end (Save to this view): it asks once, 「Save to this view?」, saying everyone who uses the view will see the changes. Confirm; capture the two writes: PUT /api/v1/meta/view/ as a draft carrying If-None-Match: *, then POST /api/v1/meta/view//publish. The console toasts 「Saved, visible to everyone」 and the condition row's 「Discard」/「Save」 go away. Sign in as the second account and open the same view: it shows the saved sort and the Kanban layout, with the second account's own row height. Back as the admin, change something in the view settings and save it there as a draft without publishing it; change the sort and press 「Save」 again: the console says the view has unpublished changes, to publish or discard them in the view settings first, and writes nothing. Discard that settings draft afterwards" ], "acceptance": [ { @@ -2990,13 +2991,20 @@ "oracle": "network", "verify": "opening the copied URL fresh issues the same filtered data request and returns the same rows (app-shell/src/views/userFilterUrlState.ts parseUserFilterParams/applyUserFilterParams)", "evidence": "the shared URL + the reproduced rows" + }, + { + "clause": "Save to this view on a shared view (objectstack#35955) is offered only to a reader who may edit the view, asks once, then saves the draft and publishes it in one step so every reader sees it on their next read; it never writes the saver's row height into the view, and it never publishes a draft someone else left pending: with one pending it writes nothing and says so", + "oracle": "network", + "verify": "the confirmed save issues PUT /api/v1/meta/view/ (a draft, If-None-Match: *) then POST /api/v1/meta/view//publish, and the published view carries the new sort, the kanban type and the row colour but not rowHeight tall; the second account's read of the view shows them; with a settings draft pending the second Save issues no PUT and no publish (or only a PUT the server refuses 409 METADATA_CONFLICT) and the pending draft is still there, unpublished (ui/packages/app-shell/src/views/runtime-metadata-persistence.ts saveAndPublishRuntimeMetadata)", + "evidence": "the two captured writes + the published view body + the second account's screenshot + the refused second save" } ], "negative": [ "a toolbar filter that REPLACES the view's stored filter (rows appear that the view filter should exclude) is a FAIL — buildEffectiveFilter merges, it does not overwrite the base", "tabs-element userFilters (preset chips, the uf__tab preset) leaking onto a bare OBJECT list view is a FAIL — ADR-0053 suppresses them there by design, as amended by ADR-0047: on an object list view only `element: 'tabs'` userFilters (and quickFilters) are ignored — objectui app-shell warnSuppressedListNav.ts, which logs the suppression — while `element: 'dropdown'` value chips ARE allowed there (examples/app-showcase/src/ui/views/project.view.ts ships them on All Projects, QA run #24616) (the list-view-capabilities item flags the same regression). The reserved list-state params an object list writes for ITSELF — uf__filter, uf__search, uf__sort, uf__group (objectui#11860, userFilterUrlState.ts), e.g. uf__sort after a toolbar sort — are the list's own state mirrored into the URL, not userFilters, and do not count", "a cached toolbar filter from account A visible to account B on the same browser (A signed out through the account menu's Log out, never by clearing storage) is a FAIL — the key embeds the user id precisely to prevent that leak", - "an incomplete FilterBuilder row emitted as [field, op, ''] (which matches only empty and silently excludes everything) instead of being dropped is a FAIL — convertFilterGroupToAST skips valueless rows (#1964)" + "an incomplete FilterBuilder row emitted as [field, op, ''] (which matches only empty and silently excludes everything) instead of being dropped is a FAIL — convertFilterGroupToAST skips valueless rows (#1964)", + "a Save to this view that publishes a view draft which was already pending before the save (saved from the view settings, by anyone) is a FAIL — the draft write carries the first-write pin, so a pending draft refuses it; a shared save that writes the saver's row height into the view is a FAIL too" ], "traps": [ "hydration-race", @@ -3092,6 +3100,12 @@ "date": "2026-11-21", "change": "steps[3], steps[4], acceptance[2] (clause, verify, evidence), acceptance[3] (clause, verify, evidence) and source[1] re-pointed to the list draft (objectstack#35955): a toolbar filter, sort and search are a draft held in the tab's memory, kept on opening a record and coming back and dropped on opening another object or view or on a reload; they are no longer stored in the user's ui.list. row. The in-app-navigation restore of revision 3 is replaced by the record round trip, and the user-scope clause now reads that nothing is stored at all. Not loosened: a second account must still see none of the first account's filters", "ref": "#35955" + }, + { + "revision": 14, + "date": "2026-11-21", + "change": "steps[8], acceptance[5] and negative[4] added for the shared-view save (objectstack#35955 PR 2): Save to this view on a stored view an administrator may edit asks once, then saves the draft and publishes it; the saver's row height stays theirs; a pending view draft is never published on anyone's behalf. steps[8] also reads the Display panel's layout and row colour back across a record round trip, since they are now part of the draft. Not loosened: every earlier clause is unchanged", + "ref": "#35955" } ] }, 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 62631fd7f18..376ec4ca484 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 @@ -396,6 +396,32 @@ describe('objectstack#35955 — a reload drops a list\'s address state only when await mountHost([address]); expect(filterOf(lastQuery())).toContain('"priority","=","urgent"'); }); + + // The two edges of the address match (objectstack#35955, PR 2's known + // edges): each is pinned as it behaves, not changed. + it('edge: a reload whose address is rewritten before the list seeds counts as no reload of the list, so the address state applies', async () => { + // The reload asked for one address; the list opens on another (a landing + // redirect, a view segment filled in) that carries the same `uf_*` state. + const reloaded = link(VIEW, { filter: URGENT }); + const address = link(`${VIEW}/all`, { filter: URGENT }); + stubNavigation('reload', new URL(reloaded, window.location.origin).href); + window.history.replaceState(null, '', address); + const host = await mountHost([address]); + expect(filterOf(lastQuery())).toContain('"priority","=","urgent"'); + expect(new URLSearchParams(host.search()).has(LIST_FILTER_PARAM)).toBe(true); + }); + + it('edge: a reload of a record page, then Back to the list: the list\'s history entry applies its `uf_*` state', async () => { + const record = `${VIEW}/all/record/1`; + const address = link(`${VIEW}/all`, { filter: URGENT }); + window.history.replaceState(null, '', record); + stubNavigation('reload', new URL(record, window.location.origin).href); + const host = await mountHost([record]); + window.history.replaceState(null, '', address); + await host.go(address); + expect(filterOf(lastQuery())).toContain('"priority","=","urgent"'); + expect(new URLSearchParams(host.search()).has(LIST_FILTER_PARAM)).toBe(true); + }); }); describe('a malformed or stale param is dropped — the list opens and nothing throws (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 adb040185ad..bda6daa438d 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 @@ -789,4 +789,48 @@ describe('objectstack#30073 — a personal view\'s conditions are Filter panel r await waitFor(() => expect(screen.queryByTestId('list-draft')).toBeNull()); expect(draftOf('v1')).toEqual({}); }); + + it.each([ + ['no label', undefined, 'Leads copy'], + ['a label given as a locale map', { en: 'Hot list', 'zh-CN': '热门' }, 'Hot list copy'], + ])('objectstack#35955 L1-b S1 — 「Save as my view」 names the copy by the view\'s tab label when it has %s', async (_case, label, expected) => { + const v1 = LEAD.listViews.v1 as Record; + const authored = v1.label; + if (label === undefined) delete v1.label; + else v1.label = label; + try { + mountLeads(romeLink('/apps/crm/crm_lead/view/v1')); + await listToolbar(); + fireEvent.pointerDown(await screen.findByTestId('list-draft-save'), { button: 0, ctrlKey: false, pointerType: 'mouse' }); + fireEvent.click(await screen.findByTestId('list-draft-save-as')); + // Never 「 copy」 or 「[object Object] copy」: the name the tab draws. + expect(await screen.findByDisplayValue(expected)).toBeInTheDocument(); + } finally { + v1.label = authored; + } + }); + + it('objectstack#35955 — the draft\'s row colour is saved too: into the reader\'s own view, and into a view of their own', async () => { + const RED = { field: 'status', colors: { open: 'red' } }; + storeListState({ perView: { pv_mine: { sort: [{ field: 'name', order: 'desc' }], rowColor: RED } } }); + const { dataSource } = mountLeads('/apps/crm/crm_lead/view/pv_mine'); + await listToolbar(); + await saveToThisView(); + await waitFor(() => expect(dataSource.update).toHaveBeenCalledTimes(1)); + const patch = dataSource.update.mock.calls[0][2]; + expect(patch.config.rowColor).toEqual(RED); + expect(patch.config.sort).toEqual([{ field: 'name', order: 'desc' }]); + expect(ListViewSchema.safeParse(patch.config).success).toBe(true); + cleanup(); + + storeListState({ perView: { v1: { sort: [{ field: 'name', order: 'desc' }], rowColor: RED } } }); + const second = mountLeads('/apps/crm/crm_lead/view/v1'); + await listToolbar(); + fireEvent.pointerDown(await screen.findByTestId('list-draft-save'), { button: 0, ctrlKey: false, pointerType: 'mouse' }); + fireEvent.click(await screen.findByTestId('list-draft-save-as')); + await screen.findByDisplayValue('View 1 copy'); + fireEvent.click(screen.getByTestId('personal-view-name-submit')); + await waitFor(() => expect(second.dataSource.create).toHaveBeenCalledTimes(1)); + expect(second.dataSource.create.mock.calls[0][1].config.rowColor).toEqual(RED); + }); }); diff --git a/ui/packages/app-shell/src/views/ObjectView.sharedViewSave-35955.test.tsx b/ui/packages/app-shell/src/views/ObjectView.sharedViewSave-35955.test.tsx new file mode 100644 index 00000000000..df9aae1d40d --- /dev/null +++ b/ui/packages/app-shell/src/views/ObjectView.sharedViewSave-35955.test.tsx @@ -0,0 +1,396 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#35955 — 「Save to this view」 on a shared view (ruling record + * 7058616478): offered to a reader who may edit the view, asked once (everyone + * using the view sees it), then saved and published at once. A view with a + * pending draft is not saved: that draft is never published on its saver's + * behalf. The reader's row height is never written into the view. + * + * What runs: the real `ObjectView` on a stub data source and a stub `/meta` + * client. `ListView` is a stand-in that records the props it is handed, so a + * sort is told through its `onSortChange` / `onPersonalizationChange`, and + * Save is pressed through its `onSaveView` (the options menu's Save, wired to + * the same handler as the condition row's Save to this view). No i18n + * provider is mounted, so copy reads as its key. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, cleanup, act, waitFor, screen, fireEvent } from '@testing-library/react'; +import { MemoryRouter, Routes, Route } from 'react-router-dom'; +// `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'; + +vi.mock('@object-ui/permissions', async (importOriginal) => { + const actual = await importOriginal(); + // Stable identities: `ListView` names `perms` in its fetch dependencies. + const perms = { + check: () => ({ allowed: true }), + checkField: () => true, + getFieldPermissions: () => [], + getRowFilter: () => undefined, + getObjectApiOperations: () => undefined, + roles: [], + isLoaded: false, + hasCapabilities: () => true, + can: () => true, + cannot: () => false, + }; + const fieldPerms = { canRead: () => true, canWrite: () => true, permissions: [] }; + return { ...actual, usePermissions: () => perms, useFieldPermissions: () => fieldPerms }; +}); + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: { id: 'org1', name: 'Acme' } }), + // The shared view's saves are an administrator's. + useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), + createAuthenticatedFetch: () => vi.fn(), +})); + +vi.mock('@object-ui/collaboration', async (importOriginal) => ({ + ...(await importOriginal>()), + useRealtimeSubscription: () => ({ lastMessage: null }), + useConflictResolution: () => ({ hasConflicts: false, resolveAllConflicts: () => {} }), +})); + +vi.mock('sonner', () => ({ + toast: Object.assign(vi.fn(), { + success: vi.fn(), error: vi.fn(), info: vi.fn(), + warning: vi.fn(), loading: vi.fn(), dismiss: vi.fn(), + }), +})); + +vi.mock('./MetadataInspector', () => ({ + MetadataPanel: () => null, + useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }), +})); +vi.mock('./RecordDetailView', () => ({ RecordDetailView: () => null })); + +// The harness has no i18n provider, so `t` answers keys. The confirm's +// question also carries the name it was handed, so the name can be read back +// (objectstack#35955 L1-b S1). +vi.mock('@object-ui/i18n', async (importOriginal) => { + const actual = await importOriginal(); + const React = await import('react'); + return { + ...actual, + useObjectTranslation: (...args: Parameters) => { + const bound = actual.useObjectTranslation(...args); + const t = React.useMemo(() => ((key: string, options?: Record) => { + const out = (bound.t as (k: string, o?: unknown) => unknown)(key, options); + return key === 'console.objectView.draft.saveToViewConfirm' ? `${String(out)} [${String(options?.name)}]` : out; + }) as typeof bound.t, [bound.t]); + return { ...bound, t }; + }, + }; +}); + +/** The props the list was last handed. */ +const listProps = vi.hoisted(() => ({ current: null as Record | null })); +vi.mock('@object-ui/plugin-list', async (importOriginal) => ({ + ...(await importOriginal()), + ListView: (props: any) => { + listProps.current = props; + return null; + }, +})); + +/** The `/meta` client the view saves go through. */ +const meta = vi.hoisted(() => ({ + client: { + save: vi.fn(async () => ({})), + publish: vi.fn(async () => ({})), + reset: vi.fn(async () => ({})), + get: vi.fn(async () => null), + list: vi.fn(async () => []), + } as Record, +})); +vi.mock('./metadata-admin/useMetadata', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataClient: () => meta.client, +})); + +/** The session-held package list, as `GET /api/v1/packages` answers it (parsed). */ +const packageList = vi.hoisted(() => ({ answer: (): Promise => Promise.resolve([]) })); +vi.mock('./studio-design/packages-io', async (importOriginal) => ({ + ...(await importOriginal>()), + fetchSessionPackages: vi.fn(() => packageList.answer()), +})); + +import { ObjectView } from './ObjectView'; +import { ExpressionProvider } from '../providers/ExpressionProvider'; +import { toast } from 'sonner'; +import { resetListDraftStoreForTests } from './listDraftStore'; + +const OBJECT = 'showcase_task'; +const CUSTOM_PACKAGE = 'com.example.showcase.custom'; +const SHIPPED_PACKAGE = 'com.example.showcase'; + +/** A shared view the console saved into the customization package. */ +const SHARED = { + name: `${OBJECT}.team_tasks`, object: OBJECT, label: 'Team tasks', type: 'grid', + columns: ['name', 'amount'], rowHeight: 'short', kanban: { groupByField: 'status' }, _packageId: CUSTOM_PACKAGE, +}; +/** A view the read-only code package ships. */ +const SHIPPED = { + name: `${OBJECT}.in_progress`, object: OBJECT, label: 'In progress', type: 'grid', + columns: ['name', 'amount'], _packageId: SHIPPED_PACKAGE, +}; +const PACKAGES = [ + { id: SHIPPED_PACKAGE, name: 'Showcase', writable: false, namespace: 'showcase' }, + { id: CUSTOM_PACKAGE, name: 'Showcase (custom)', writable: true, namespace: 'showcase' }, +]; + +function mount(viewId: string) { + const dataSource = { + find: vi.fn(async () => ({ data: [], total: 0 })), + findOne: vi.fn(async () => null), + create: vi.fn(async () => ({})), + update: vi.fn(async () => ({})), + delete: vi.fn(async () => ({})), + getObjectSchema: vi.fn(async () => ({ name: OBJECT, fields: {} })), + listViews: vi.fn(async () => [SHARED, SHIPPED]), + updateView: vi.fn(async () => ({})), + }; + const utils = render( + + + + {}} + /> + } + /> + + + , + ); + return { ...utils, dataSource }; +} + +const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 300))); + +/** A sort on the list: the draft holds it and the list reports the part. */ +async function sortByAmount() { + await act(async () => { + listProps.current?.onSortChange?.([{ field: 'amount', order: 'desc' }]); + listProps.current?.onPersonalizationChange?.(['sort']); + }); + await settle(); +} + +/** The options menu's Save (the condition row's Save to this view takes the same handler). */ +async function pressSave() { + await act(async () => { + listProps.current?.onSaveView?.(); + }); + await settle(); +} + +async function confirmSave() { + const button = await screen.findByRole('button', { name: 'console.objectView.draft.saveToViewConfirmButton' }); + await act(async () => { + fireEvent.click(button); + }); + await settle(); +} + +const metaConflict = () => Object.assign(new Error('A draft is pending'), { status: 409, code: 'METADATA_CONFLICT' }); + +beforeEach(() => { + listProps.current = null; + packageList.answer = () => Promise.resolve(PACKAGES); + localStorage.clear(); + resetListDraftStoreForTests(); + meta.client.save.mockReset().mockResolvedValue({}); + meta.client.publish.mockReset().mockResolvedValue({}); + meta.client.reset.mockReset().mockResolvedValue({}); + vi.mocked(toast.success).mockClear(); + vi.mocked(toast.error).mockClear(); +}); + +afterEach(() => { + cleanup(); +}); + +describe('objectstack#35955 — Save to this view on a shared view: confirm, then save and publish at once', () => { + it('an admin confirms: the draft is written over no pending draft and published; the reader\'s row height stays theirs', async () => { + // The reader's own row height (kept for them, never a draft) differs from the view's. + localStorage.setItem(`list-state:u1:${OBJECT}`, JSON.stringify({ perView: { [SHARED.name]: { rowHeight: 'tall' } } })); + mount(SHARED.name); + await settle(); + await waitFor(() => expect(listProps.current).not.toBeNull()); + expect(listProps.current?.onSaveView).toBeUndefined(); + + await sortByAmount(); + expect(typeof listProps.current?.onSaveView).toBe('function'); + await pressSave(); + // Nothing is written before the confirm. + expect(meta.client.save).not.toHaveBeenCalled(); + await confirmSave(); + + await waitFor(() => expect(meta.client.publish).toHaveBeenCalledWith('view', SHARED.name)); + expect(meta.client.save).toHaveBeenCalledTimes(1); + const [type, name, body, options] = meta.client.save.mock.calls[0] as any[]; + expect([type, name]).toEqual(['view', SHARED.name]); + // The first-write pin: the server refuses the write over a pending draft. + expect(options).toEqual({ mode: 'draft', ifNoneMatch: '*' }); + expect(body.config.sort).toEqual([{ field: 'amount', order: 'desc' }]); + // F5: the view keeps its own row height, not this reader's. + expect(body.config.rowHeight).toBe('short'); + expect(meta.client.save.mock.invocationCallOrder[0]).toBeLessThan(meta.client.publish.mock.invocationCallOrder[0]); + expect(meta.client.reset).not.toHaveBeenCalled(); + expect(toast.success).toHaveBeenCalledWith('console.objectView.draft.savedForEveryone'); + // The draft is the view now: Discard and Save go. + await waitFor(() => expect(listProps.current?.onSaveView).toBeUndefined()); + }); + + it.each([ + // A stored view with no label reaches the page named by its name, which is + // what its tab draws (`viewTabLabel`), never an empty 「“”」. + ['no label', undefined, `${OBJECT}.team_tasks`], + ['a label given as a locale map', { en: 'Team list', 'zh-CN': '团队列表' }, 'Team list'], + ['CONTROL: a plain label', 'Team tasks', 'Team tasks'], + ])('the confirm names the view as its tab does when it has %s (L1-b S1)', async (_case, label, expected) => { + const view = SHARED as Record; + const authored = view.label; + if (label === undefined) delete view.label; + else view.label = label; + try { + mount(SHARED.name); + await settle(); + await sortByAmount(); + await pressSave(); + // Never 「“”」 or 「[object Object]」. + expect(await screen.findByText(`console.objectView.draft.saveToViewConfirm [${expected}]`)).toBeInTheDocument(); + } finally { + view.label = authored; + } + }); + + it('cancelling the confirm writes nothing and keeps the draft', async () => { + mount(SHARED.name); + await settle(); + await sortByAmount(); + await pressSave(); + const cancel = await screen.findByRole('button', { name: 'console.objectView.cancel' }); + await act(async () => { + fireEvent.click(cancel); + }); + await settle(); + expect(meta.client.save).not.toHaveBeenCalled(); + expect(meta.client.publish).not.toHaveBeenCalled(); + expect(typeof listProps.current?.onSaveView).toBe('function'); + }); + + it('a view with a pending draft is not saved: nothing is published, the reader is sent to the view settings, the draft stays', async () => { + meta.client.save.mockRejectedValue(metaConflict()); + mount(SHARED.name); + await settle(); + await sortByAmount(); + await pressSave(); + await confirmSave(); + await waitFor(() => expect(meta.client.save).toHaveBeenCalledTimes(1)); + expect(meta.client.publish).not.toHaveBeenCalled(); + expect(meta.client.reset).not.toHaveBeenCalled(); + expect(toast.error).toHaveBeenCalledWith('console.objectView.draft.pendingDraft'); + expect(toast.success).not.toHaveBeenCalled(); + expect(typeof listProps.current?.onSaveView).toBe('function'); + }); + + it('a refused publish discards the draft this save wrote and keeps the list\'s draft', async () => { + meta.client.publish.mockRejectedValue(Object.assign(new Error('Publish refused'), { status: 400 })); + mount(SHARED.name); + await settle(); + await sortByAmount(); + await pressSave(); + await confirmSave(); + await waitFor(() => expect(meta.client.reset).toHaveBeenCalledWith('view', SHARED.name, { state: 'draft' })); + expect(toast.success).not.toHaveBeenCalled(); + expect(toast.error).toHaveBeenCalled(); + expect(typeof listProps.current?.onSaveView).toBe('function'); + }); + + it('a view a read-only package ships is offered no save into it (Save as my view stays the reader\'s)', async () => { + mount(SHIPPED.name); + await settle(); + await sortByAmount(); + expect(listProps.current?.onSaveView).toBeUndefined(); + }); +}); + +describe('objectstack#35955 — the layout and the row colour the reader picks are the list\'s draft', () => { + async function pickKanbanAndColour() { + await act(async () => { + listProps.current?.onViewChange?.('kanban'); + listProps.current?.onRowColorChange?.({ field: 'status', colors: {} }); + listProps.current?.onPersonalizationChange?.(['layout', 'rowColor']); + }); + await settle(); + } + + it('they are laid into the list over the view\'s own, which goes to `viewDefaults`, and outlive a record opened as a page', async () => { + mount(SHARED.name); + await settle(); + await waitFor(() => expect(listProps.current).not.toBeNull()); + expect(listProps.current?.schema.viewType).toBe('grid'); + await pickKanbanAndColour(); + expect(listProps.current?.schema.viewType).toBe('kanban'); + expect(listProps.current?.schema.rowColor).toEqual({ field: 'status', colors: {} }); + expect(listProps.current?.viewDefaults).toMatchObject({ viewType: 'grid', rowColor: undefined }); + expect('rowColor' in (listProps.current?.viewDefaults ?? {})).toBe(true); + + // The list page unmounts while a record is open as a page, and mounts again on Back. + cleanup(); + listProps.current = null; + mount(SHARED.name); + await settle(); + await waitFor(() => expect(listProps.current).not.toBeNull()); + // Read through a cast: the assignment above narrows `current` to `null` for the checker. + const remounted = listProps.current as Record | null; + expect(remounted?.schema.viewType).toBe('kanban'); + expect(remounted?.schema.rowColor).toEqual({ field: 'status', colors: {} }); + }); + + it('picking the view\'s own layout and colour again drops those parts', async () => { + mount(SHARED.name); + await settle(); + await pickKanbanAndColour(); + await act(async () => { + listProps.current?.onViewChange?.('grid'); + listProps.current?.onRowColorChange?.(null); + }); + await settle(); + expect(listProps.current?.schema.viewType).toBe('grid'); + expect(listProps.current?.schema.rowColor).toBeUndefined(); + }); + + it('Save to this view keeps them: the view is retyped (its kanban lists the columns) and coloured', async () => { + mount(SHARED.name); + await settle(); + await pickKanbanAndColour(); + await pressSave(); + await confirmSave(); + await waitFor(() => expect(meta.client.publish).toHaveBeenCalledTimes(1)); + const body = (meta.client.save.mock.calls[0] as any[])[2]; + expect(body.config.type).toBe('kanban'); + expect(body.config.kanban).toEqual({ groupByField: 'status', columns: ['name', 'amount'] }); + expect(body.config.rowColor).toEqual({ field: 'status', colors: {} }); + }); +}); diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index b4ce519a337..38e3b92ba94 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -107,6 +107,7 @@ import { PERSONAL_VIEW_OBJECT, buildInPlaceViewConfig, buildPersonalViewConfig, + layListStateOverView, personalViewEntry, personalViewPanelFilters, usePersonalViews, @@ -737,6 +738,11 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co /** The list on screen in the reader-state shape the view builders read (draft + kept widths and row height). */ const draftPreferenceOf = (id: string | undefined) => id ? listDraftPreference(listDraft.draft, listPrefs.preference.perView?.[id]) : undefined; + /** The Display panel's layout and row colour the draft holds, for the view builders. */ + const draftDisplay = { + ...(listDraft.draft.viewType ? { viewType: listDraft.draft.viewType } : {}), + ...(listDraft.draft.rowColor !== undefined ? { rowColor: listDraft.draft.rowColor } : {}), + }; // objectstack#25992 slice 8: the list's toolbar state in the URL (seed, write-back, // "Reset view") moved to `./objectViewListUrlState.ts`. const { @@ -783,6 +789,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co url: { ...parseListStateParams(searchParams, acceptListField), filters: readPanelFilters() }, preference: draftPreferenceOf(activeView.id), panelFilters: viewPanelFilters, + display: draftDisplay, }); if (!built.ok) { toast.error(t('form.saveError'), { description: t(FILTER_FOLD_REFUSAL_KEYS[built.reason]) }); @@ -803,23 +810,11 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co }); } }; - // objectstack#35955 — Discard and Save while the list holds a draft, at - // the end of the condition row (the phone draws the same slot). 「Save to - // this view」 writes one of the reader's own views here; a shared view's - // save is not offered on the list yet. 「Save as my view」 asks a name. // objectstack#29635 — the one test for creating one of the reader's own // views, shared by Save as my view here and the view switcher's create // card: a reader who cannot read the list's own object has no list to keep. const listReadable = !perms.isLoaded || perms.can(objectDef.name, 'read'); const canCreatePersonalView = personalViewsReady && personalGrant('create') && listReadable && !!activeView && !viewAccess.refusal; - const draftActions = !isEnvironmentList && listDraftParts.length > 0 ? ( - { void handleSaveToPersonalView(); } : undefined} - onSaveAsMyView={canCreatePersonalView ? () => setPersonalViewDialog({ mode: 'saveAs' }) : undefined} - /> - ) : null; // objectstack#25992 slice 11b: the view-config save and create handlers, view switching // and the view-tab CRUD callbacks moved to `./objectViewViewCrud.tsx` (the mobile view @@ -827,6 +822,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co const { handleViewConfigSave, handleDraftBarChange, + handleViewSaveAndPublish, handleViewCreate, handleViewUpdate, handleViewChange, @@ -899,6 +895,69 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co return saved; }; + // objectstack#35955 — 「Save to this view」 on a shared view: offered to + // the reader who may edit it (the footer pick's test above: an admin, on a + // view the metadata door stores, whose package takes saves). One confirm + // (everyone using the view sees it), then the list on screen is saved and + // published at once (ruling record 7058616478). A view with a pending + // draft is not saved: that draft is never published on its saver's + // behalf, and the reader is sent to the view settings. The reader's row + // height is theirs, never the view's: the view keeps its own. + const canSaveToSharedView = !isEnvironmentList && !activeIsPersonal && !!activeView && isAdmin + && !activeViewPackageRefusesSaves && isSavedViewId(savedViews, String(activeView.id)); + const handleSaveToSharedView = async () => { + if (!activeView || !canSaveToSharedView) return; + const confirmed = await confirmHandler( + // The view's name as its tab draws it (objectstack#35955 L1-b S1): a + // label is an I18nLabel with no default, so never the raw value. + t('console.objectView.draft.saveToViewConfirm', { name: listLabel }), + { + title: t('console.objectView.draft.saveToViewConfirmTitle'), + confirmText: t('console.objectView.draft.saveToViewConfirmButton'), + cancelText: t('console.objectView.cancel'), + }, + ); + if (!confirmed) return; + const pref = draftPreferenceOf(activeView.id); + const laid = layListStateOverView(activeView, { + url: { ...parseListStateParams(searchParams, acceptListField), filters: readPanelFilters() }, + preference: pref ? { ...pref, rowHeight: undefined } : undefined, + panelFilters: viewPanelFilters, + display: draftDisplay, + }); + if (!laid.ok) { + toast.error(t('form.saveError'), { description: t(FILTER_FOLD_REFUSAL_KEYS[laid.reason]) }); + return; + } + const outcome = await handleViewSaveAndPublish(laid.view); + if (outcome === 'pending-draft') { + toast.error(t('console.objectView.draft.pendingDraft')); + return; + } + if (outcome !== 'published') return; + // The draft is the view now, for everyone: Discard and Save go, and + // the list opens again on the saved view (its chips stay). + handleResetView(); + toast.success(t('console.objectView.draft.savedForEveryone')); + }; + // objectstack#35955 — Discard and Save while the list holds a draft, at + // the end of the condition row (the phone draws the same slot). 「Save to + // this view」 writes one of the reader's own views, or the shared view + // for a reader who may edit it; 「Save as my view」 asks a name. + const saveToThisView = canUpdatePersonalView + ? () => { void handleSaveToPersonalView(); } + : canSaveToSharedView + ? () => { void handleSaveToSharedView(); } + : undefined; + const draftActions = !isEnvironmentList && listDraftParts.length > 0 ? ( + setPersonalViewDialog({ mode: 'saveAs' }) : undefined} + /> + ) : null; + // 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 @@ -963,14 +1022,18 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co */ const handleSaveAsMyView = async (label: string): Promise => { if (!activeView) return false; + // objectstack#35955 — the draft's layout is the new view's type (so + // the type's own field list is filled as the create card fills it), + // and its row colour is laid over the body. const built = buildInPlaceViewConfig( objectDef.name, activeView, - { type: String((activeView as any).type ?? 'grid') }, + { type: listDraft.draft.viewType ?? String((activeView as any).type ?? 'grid') }, { url: { ...parseListStateParams(searchParams, acceptListField), filters: readPanelFilters() }, preference: draftPreferenceOf(activeView.id), panelFilters: viewPanelFilters, + ...(listDraft.draft.rowColor !== undefined ? { display: { rowColor: listDraft.draft.rowColor } } : {}), }, ); if (!built.ok) { @@ -1227,7 +1290,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co : 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 && listDraftParts.length > 0 ? () => { void handleSaveToPersonalView(); } : undefined, + save: !isEnvironmentList && listDraftParts.length > 0 ? saveToThisView : undefined, reset: !isEnvironmentList && listDraftParts.length > 0 ? handleResetView : undefined, // objectstack#35702 — the footer's calculation, saved on the open // view (ruling 7045525672): a personal view at once; a shared one, @@ -1595,7 +1658,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co ? t('console.objectView.draft.saveAsMyView') : t('view.rename', { defaultValue: 'Rename' })} initialName={personalViewDialog?.mode === 'saveAs' - ? t('console.objectView.draft.copyName', { name: activeView?.label ?? '' }) + ? t('console.objectView.draft.copyName', { name: listLabel }) : renamingPersonalView?.label ?? ''} onSubmit={(name) => (personalViewDialog?.mode === 'rename' ? handleRenamePersonalView(personalViewDialog.viewId, name) diff --git a/ui/packages/app-shell/src/views/ObjectView.userListState-12418.test.tsx b/ui/packages/app-shell/src/views/ObjectView.userListState-12418.test.tsx index f6636a599e6..1e70c7896f9 100644 --- a/ui/packages/app-shell/src/views/ObjectView.userListState-12418.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.userListState-12418.test.tsx @@ -765,7 +765,7 @@ describe('the list is handed the view\'s own density and hidden fields beside th expect(listProps.schema.rowHeight).toBe('compact'); expect(listProps.schema.hiddenFields).toEqual(['name']); - expect(listProps.viewDefaults).toEqual({ hiddenFields: AUTHORED_HIDDEN, rowHeight: AUTHORED_ROW_HEIGHT, sort: AUTHORED_SORT }); + expect(listProps.viewDefaults).toEqual({ hiddenFields: AUTHORED_HIDDEN, rowHeight: AUTHORED_ROW_HEIGHT, sort: AUTHORED_SORT, viewType: 'grid' }); }); it('a choice equal to the view\'s own, made through the controls\' doors, is still the reader\'s choice', async () => { @@ -786,7 +786,7 @@ describe('the list is handed the view\'s own density and hidden fields beside th expect(draftOf().hiddenFields).toEqual(AUTHORED_HIDDEN); expect(listProps.schema.rowHeight).toBe(AUTHORED_ROW_HEIGHT); expect(listProps.schema.hiddenFields).toEqual(AUTHORED_HIDDEN); - expect(listProps.viewDefaults).toEqual({ hiddenFields: AUTHORED_HIDDEN, rowHeight: AUTHORED_ROW_HEIGHT, sort: AUTHORED_SORT }); + expect(listProps.viewDefaults).toEqual({ hiddenFields: AUTHORED_HIDDEN, rowHeight: AUTHORED_ROW_HEIGHT, sort: AUTHORED_SORT, viewType: 'grid' }); }); it('CONTROL: another user, with no state of their own, is handed the same value twice', async () => { @@ -800,6 +800,8 @@ describe('the list is handed the view\'s own density and hidden fields beside th expect(listProps.schema.rowHeight).toBe(AUTHORED_ROW_HEIGHT); expect(listProps.viewDefaults).toEqual({ hiddenFields: listProps.schema.hiddenFields, rowHeight: listProps.schema.rowHeight, sort: listProps.schema.sort, + // objectstack#35955 — the layout too: no draft, so the same value twice. + viewType: listProps.schema.viewType, }); }); diff --git a/ui/packages/app-shell/src/views/listDraftStore.ts b/ui/packages/app-shell/src/views/listDraftStore.ts index a9439cf1e2d..d1309db4eb9 100644 --- a/ui/packages/app-shell/src/views/listDraftStore.ts +++ b/ui/packages/app-shell/src/views/listDraftStore.ts @@ -8,7 +8,7 @@ * * What a draft holds: the sort, the Filter panel's group, the grouping, the * search term, the columns shown (hidden ones, added ones), the column order - * and (from PR 2) the Display panel's layout and row colour. What it never holds: the + * and the Display panel's layout and row colour. What it never holds: the * column widths and the row height, which are remembered for the reader * (`ListPreferencesProvider`), and the view tab order. * @@ -54,15 +54,11 @@ export interface ListDraft { hiddenFields?: string[]; /** The object's fields the reader added as columns. */ addedFields?: string[]; - /** - * The visualization the reader switched to (`ListView`'s layout control). - * Nothing writes it yet: the list hands its layout out from PR 2 of - * objectstack#35955, and Save keeps it from then. - */ + /** The visualization the reader switched to (`ListView`'s layout control, `onViewChange`). */ viewType?: string; /** - * The row colour the reader picked, or `null` for "none" over a view that - * colours its rows. Written from PR 2 of objectstack#35955, as `viewType`. + * The row colour the reader picked (`ListView`'s `onRowColorChange`), or + * `null` for "none" over a view that colours its rows. */ rowColor?: { field: string; colors?: Record } | null; } diff --git a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx index d7eff6f3479..b4ff058e687 100644 --- a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx +++ b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx @@ -331,6 +331,7 @@ export function useObjectViewListRenderer({ // its columns and their order here. The column widths and the row // height are the reader's own (`listPrefs`), never a draft: they are // laid in from what the reader stored, and nothing else stored is. + const viewOwnRowColor = viewDef.rowColor ?? listSchema.rowColor; const viewPref: ListViewPreference | undefined = listDraftPreference( listDraft.draft, listPrefs.preference.perView?.[viewDef.id], @@ -857,7 +858,14 @@ export function useObjectViewListRenderer({ * a different nesting level ('may the user open the colour panel' * versus 'what the colours are'). */ - rowColor: viewDef.rowColor ?? listSchema.rowColor, + // objectstack#35955 — the reader's unsaved row colour (the list's + // draft, `null` for "none") over the view's own; the view's own + // goes to `viewDefaults` below, for Discard and Save. + rowColor: listDraft.draft.rowColor !== undefined + ? (listDraft.draft.rowColor ?? undefined) + : viewOwnRowColor, + // objectstack#35955 — and the reader's unsaved layout. + viewType: listDraft.draft.viewType ?? listSchema.viewType, // objectui#11013 — the seven renderer flags this relay used to read // off the active view (`wrapHeaders`, `clickIntoRecordDetails`, // `addRecordViaForm`, `addDeleteRecordsInline`, @@ -1081,13 +1089,22 @@ export function useObjectViewListRenderer({ // objectstack#28950 — and the view's own grouping, under a // grouping the URL carries (the `grouping` rung above), so the // list can tell the reader's from the view's. - viewDefaults={{ hiddenFields: viewHiddenFields, rowHeight: viewRowHeight, sort: viewSort, grouping: listSchema.grouping, filters: viewPanelFilters }} + // objectstack#35955 — and the view's own layout and row colour, + // under the draft's (`viewType` / `rowColor` above). + viewDefaults={{ hiddenFields: viewHiddenFields, rowHeight: viewRowHeight, sort: viewSort, grouping: listSchema.grouping, filters: viewPanelFilters, viewType: listSchema.viewType, rowColor: viewOwnRowColor }} // objectstack#28948 — those resets clear the user's state. onRestoreViewDefaults={restoreViewDefaults} // objectstack#28950 — what of the list differs from the view, // for Discard and Save (objectstack#35955), which then own the // one reset (the Display control draws none of its own). onPersonalizationChange={(parts) => handleListPersonalizationChange(identityKey, parts)} + // objectstack#35955 — the layout and the row colour the reader + // picks are the list's draft; picking the view's own again + // drops that part. + onViewChange={(view: string) => listDraft.patch({ viewType: view === listSchema.viewType ? undefined : view })} + onRowColorChange={(rowColor: { field: string; colors?: Record } | null) => listDraft.patch({ + rowColor: (rowColor?.field ?? '') === (viewOwnRowColor?.field ?? '') ? undefined : rowColor, + })} // 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} diff --git a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx index bac5e656520..a10e55945a5 100644 --- a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx +++ b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx @@ -19,8 +19,8 @@ import type { usePreviewDrafts } from '../preview/PreviewModeContext.js'; import { isSavedViewId } from '../utils/viewIdentity.js'; import type { useConsoleActionRuntime } from '../hooks/useConsoleActionRuntime.js'; import type { useMetadataClient } from './metadata-admin/useMetadata.js'; -import { persistRuntimeMetadata, createRuntimeMetadata, viewEnvelope } from './runtime-metadata-persistence.js'; -import type { RuntimeCreateApp } from './runtime-metadata-persistence.js'; +import { persistRuntimeMetadata, createRuntimeMetadata, saveAndPublishRuntimeMetadata, viewEnvelope } from './runtime-metadata-persistence.js'; +import type { RuntimeCreateApp, SaveAndPublishOutcome } from './runtime-metadata-persistence.js'; import { draftBarPackageOf } from '../preview/DraftPreviewBar.js'; import { useMetadata } from '../providers/MetadataProvider.js'; import { buildAddViewSpec, setDefaultViewPatches, buildViewConfigSaveBody } from './objectViewTabs.js'; @@ -188,6 +188,42 @@ export function useObjectViewViewCrud({ setViewDraft(null); }, [savedViews, setViewDraft]); + /** + * objectstack#35955 — 「Save to this view」 on a shared view, after its + * confirm: the body is saved and published at once (ruling record + * 7058616478), so everyone sees it on their next read. Over a pending + * draft nothing is written (`'pending-draft'`, the caller says so); a + * refusal is said with the door's own message (`'failed'`). On + * `'published'` the list shows the saved body at once and keeps it until + * the saved views have been read again ({@link handleDraftBarChange}). + */ + const handleViewSaveAndPublish = useCallback(async (view: Record): Promise => { + const vid = view.id; + if (!metadataClient || !vid) { + console.warn('[ObjectView] Cannot save the view: missing metadataClient or viewId.'); + return 'failed'; + } + try { + const outcome = await saveAndPublishRuntimeMetadata('view', vid, buildViewConfigSaveBody(objectName, view), { + metadataClient, + dataSource, + objectName, + }); + if (outcome === 'published') { + setViewDraft(view); + handleDraftBarChange(); + } + return outcome; + } catch (err) { + console.error('[ObjectView] Failed to save and publish a view:', err); + toast.error(t('form.saveError'), { + description: formatMetadataError(err), + classNames: { description: 'whitespace-pre-line' }, + }); + return 'failed'; + } + }, [metadataClient, dataSource, objectName, t, setViewDraft, handleDraftBarChange]); + /** * Create a new view: the Create View dialog's door and the view-config * panel's create mode. Resolves whether the view was saved, so the dialog @@ -466,6 +502,7 @@ export function useObjectViewViewCrud({ return { handleViewConfigSave, handleDraftBarChange, + handleViewSaveAndPublish, handleViewCreate, handleViewUpdate, handleViewChange, diff --git a/ui/packages/app-shell/src/views/personalViews.ts b/ui/packages/app-shell/src/views/personalViews.ts index 31f28e5901a..41166d76995 100644 --- a/ui/packages/app-shell/src/views/personalViews.ts +++ b/ui/packages/app-shell/src/views/personalViews.ts @@ -171,6 +171,13 @@ export interface PersonalViewListState { * the view's conditions included, and is not laid over them a second time. */ panelFilters?: FilterBuilderRowGroup; + /** + * objectstack#35955 — the Display panel's layout and row colour the list's + * draft holds (`ListDraft.viewType` / `rowColor`). `viewType` retypes the + * body; `rowColor: null` is "none" over a view that colours its rows. An + * absent part is the view's own. + */ + display?: { viewType?: string; rowColor?: { field: string; colors?: Record } | null }; } /** The column a `columns` entry names: a bare name, or an entry's `field`. */ @@ -206,6 +213,25 @@ export function buildPersonalViewConfig( view: Record, state: PersonalViewListState, ): { ok: true; config: Record } | { ok: false; reason: FilterFoldRefusal } { + const laid = layListStateOverView(view, state); + if (!laid.ok) return laid; + return { ok: true, config: buildViewConfigSaveBody(objectName, laid.view).config }; +} + +/** + * The open view's own entry (the view tab's shape, the one the view config + * panel saves) with the list on screen laid over it, as + * {@link buildPersonalViewConfig} lays it: what 「Save to this view」 writes + * into a shared view (objectstack#35955), and the body a personal view's + * config is narrowed from. The layout and row colour of `state.display` + * apply too; a retype to a type whose block lists fields of its own fills + * that list from the columns when the block holds none, as + * {@link buildInPlaceViewConfig} does. + */ +export function layListStateOverView( + view: Record, + state: PersonalViewListState, +): { ok: true; view: Record } | { ok: false; reason: FilterFoldRefusal } { const own: unknown[] = Array.isArray(view.filter) ? view.filter : []; let filter: unknown[]; if (state.panelFilters && state.url.filters === undefined) { @@ -255,7 +281,18 @@ export function buildPersonalViewConfig( fieldOrder: undefined, rowHeight: pref?.rowHeight ?? view.rowHeight, }; - return { ok: true, config: buildViewConfigSaveBody(objectName, draft).config }; + const display = state.display; + if (display && 'rowColor' in display) draft.rowColor = display.rowColor ?? undefined; + if (display?.viewType && display.viewType !== view.type) { + draft.type = display.viewType; + const mirrorKey = IN_PLACE_COLUMN_MIRRORS[display.viewType]; + const block = isRecord(view[display.viewType]) ? (view[display.viewType] as Record) : undefined; + if (mirrorKey && block && !(Array.isArray(block[mirrorKey]) && (block[mirrorKey] as unknown[]).length > 0)) { + const names = (columns ?? []).map(columnName).filter((n): n is string => !!n); + if (names.length > 0) draft[display.viewType] = { ...block, [mirrorKey]: names }; + } + } + return { ok: true, view: draft }; } /** The read's state: `off` (nothing read), `loading`, `ready`, or `refused`. */ diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.test.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.test.ts index be380903b17..05b7f592b82 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.test.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.test.ts @@ -12,6 +12,7 @@ import { recordPageEnvelope, viewEnvelope, deriveViewKey, + saveAndPublishRuntimeMetadata, } from './runtime-metadata-persistence'; /** @@ -336,3 +337,41 @@ describe('runtime-metadata-persistence seam (ADR-0034)', () => { }); }); }); + +describe('saveAndPublishRuntimeMetadata — a confirmed save everyone sees at once (objectstack#35955)', () => { + const conflict = () => Object.assign(new Error('pending'), { status: 409, code: 'METADATA_CONFLICT' }); + + it('stages the draft under the first-write pin, then publishes it', async () => { + const metadataClient = makeMetadataClient(); + const body = { name: 'task.all', config: { sort: [{ field: 'name', order: 'asc' }] } }; + await expect(saveAndPublishRuntimeMetadata('view', 'task.all', body, { metadataClient })).resolves.toBe('published'); + expect(metadataClient.save).toHaveBeenCalledWith('view', 'task.all', body, { mode: 'draft', ifNoneMatch: '*' }); + expect(metadataClient.publish).toHaveBeenCalledWith('view', 'task.all'); + expect(metadataClient.save.mock.invocationCallOrder[0]).toBeLessThan(metadataClient.publish.mock.invocationCallOrder[0]); + expect(metadataClient.reset).not.toHaveBeenCalled(); + }); + + it('over a pending draft (the pin\'s 409 METADATA_CONFLICT) nothing is published or discarded', async () => { + const metadataClient = makeMetadataClient(); + metadataClient.save.mockRejectedValue(conflict()); + await expect(saveAndPublishRuntimeMetadata('view', 'task.all', {}, { metadataClient })).resolves.toBe('pending-draft'); + expect(metadataClient.publish).not.toHaveBeenCalled(); + expect(metadataClient.reset).not.toHaveBeenCalled(); + }); + + it('CONTROL: the door\'s other 409 (DESTRUCTIVE_CHANGE) is a refusal, not a pending draft', async () => { + const metadataClient = makeMetadataClient(); + const destructive = Object.assign(new Error('destructive'), { status: 409, code: 'DESTRUCTIVE_CHANGE' }); + metadataClient.save.mockRejectedValue(destructive); + await expect(saveAndPublishRuntimeMetadata('view', 'task.all', {}, { metadataClient })).rejects.toBe(destructive); + expect(metadataClient.publish).not.toHaveBeenCalled(); + }); + + it('a refused publish discards the draft this call wrote, and the refusal is rethrown', async () => { + const metadataClient = makeMetadataClient(); + const refused = Object.assign(new Error('refused'), { status: 400, code: 'VALIDATION_ERROR' }); + metadataClient.publish.mockRejectedValue(refused); + await expect(saveAndPublishRuntimeMetadata('view', 'task.all', {}, { metadataClient })).rejects.toBe(refused); + expect(metadataClient.reset).toHaveBeenCalledWith('view', 'task.all', { state: 'draft' }); + }); +}); diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts index 5a4f2ab7e21..b61a26a2c44 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts @@ -41,6 +41,7 @@ import { stripReadDecorations } from '@objectstack/spec/kernel'; import { emitMetadataRefresh } from '../assistant/assistantBus.js'; import { slugify } from './metadata-admin/createDerive.js'; +import { isDraftVersionConflict } from './metadata-admin/DraftConflictDialog.js'; import { ensureCustomizationPackage, fetchListedPackageManifests } from './studio-design/packages-io.js'; /** The runtime-editable artifact types ADR-0034 unifies. `page` (a record @@ -511,3 +512,54 @@ export async function publishRuntimeMetadata( invalidateViewCaches(type, name, ctx); announceDraftLedgerWrite(); } + +/** What {@link saveAndPublishRuntimeMetadata} did. */ +export type SaveAndPublishOutcome = 'published' | 'pending-draft'; + +/** + * objectstack#35955 — a confirmed save that everyone sees at once (ruling + * record 7058616478 on that card): the body is staged as the item's draft and + * published in the same act. + * + * Only over NO pending draft. The draft write carries the first-write pin + * (`ifNoneMatch: '*'`), so the server refuses it `409 METADATA_CONFLICT` when + * a draft is already pending — whoever saved it, the reader included: the + * door does not say who did — and nothing is written: resolves + * `'pending-draft'`. That draft is never published on its saver's behalf. + * + * A publish the server refuses leaves no draft of this call behind: the draft + * it wrote is discarded (it was the only one, by the pin) and the refusal is + * rethrown. Any other refusal is rethrown as it came. + */ +export async function saveAndPublishRuntimeMetadata( + type: RuntimeArtifactType, + name: string, + body: any, + ctx: RuntimePersistCtx, +): Promise { + try { + await ctx.metadataClient.save(type, name, body, { mode: 'draft', ifNoneMatch: '*' }); + } catch (err) { + if (isDraftVersionConflict(err)) { + return 'pending-draft'; + } + throw err; + } + try { + await ctx.metadataClient.publish(type, name); + } catch (err) { + try { + await ctx.metadataClient.reset(type, name, { state: 'draft' }); + } catch (discardErr) { + // The draft this call wrote stays pending: the view settings' draft + // bar shows it, and its Discard removes it. + console.error('[runtime-metadata] a refused publish left its draft pending:', discardErr); + } + invalidateViewCaches(type, name, ctx); + announceDraftLedgerWrite(); + throw err; + } + invalidateViewCaches(type, name, ctx); + announceDraftLedgerWrite(); + return 'published'; +} diff --git a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts index c65cf7663e9..5160e9a4e74 100644 --- a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts +++ b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts @@ -452,7 +452,10 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // 120 once objectstack-ai/objectstack#35688 added `fields.tags.add`, the // grid cell editor's row adding the typed tag („{{value}}“) — one // interpolated span, user input. - expect(okSpans, 'correctly paired spans').toBe(120); + // 121 once objectstack-ai/objectstack#35955 added + // `console.objectView.draft.saveToViewConfirm`, the shared-view save's + // question naming the view („{{name}}“) — one interpolated span, view data. + expect(okSpans, 'correctly paired spans').toBe(121); }); it('keeps the count identity that replaces the card’s count(„) === count(“)', () => { @@ -569,8 +572,9 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // after objectstack-ai/objectstack#35357 added // `approvalsInbox.slaCalendarNotFound`, one more matched pair. 120 / 120 / 0 // after objectstack-ai/objectstack#35688 added `fields.tags.add`, one more - // matched pair. - expect({ open, close, rdq }).toEqual({ open: 120, close: 120, rdq: 0 }); + // matched pair. 121 / 121 / 0 after objectstack-ai/objectstack#35955 added + // `console.objectView.draft.saveToViewConfirm`, one more matched pair. + expect({ open, close, rdq }).toEqual({ open: 121, close: 121, rdq: 0 }); // The durable shape: every „ closed by a “, every surplus “ an English // opener answered by a ”. Survived translating the two English values. expect(close).toBe(open + rdq); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 58f4d20e37f..87152e1cef8 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -2985,6 +2985,11 @@ const ar = { saveAsMyView: "حفظ كعرض خاص بي", copyName: "نسخة من {{name}}", saved: "تم الحفظ", + saveToViewConfirmTitle: "حفظ في هذا العرض؟", + saveToViewConfirm: "سيرى كل من يستخدم \"{{name}}\" هذه التغييرات.", + saveToViewConfirmButton: "حفظ للجميع", + savedForEveryone: "تم الحفظ، مرئي للجميع", + pendingDraft: "يحتوي هذا العرض على تغييرات غير منشورة. انشرها أو تجاهلها أولاً في إعدادات العرض.", }, linkFilterRefused: 'لم يُطبَّق عامل التصفية في هذا الرابط، لأنه يذكر حقلًا لا يمكنك التصفية حسبه هنا، لذا تعرض القائمة طريقة العرض دونه.', personalizedParts: { diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index ccf10ab9582..cd97d4103a7 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -2697,6 +2697,11 @@ const de = { saveAsMyView: "Als meine Ansicht speichern", copyName: "{{name}} (Kopie)", saved: "Gespeichert", + saveToViewConfirmTitle: "In dieser Ansicht speichern?", + saveToViewConfirm: "Alle, die „{{name}}“ verwenden, sehen diese Änderungen.", + saveToViewConfirmButton: "Für alle speichern", + savedForEveryone: "Gespeichert, für alle sichtbar", + pendingDraft: "Diese Ansicht hat unveröffentlichte Änderungen. Veröffentliche oder verwirf sie zuerst in den Ansichtseinstellungen.", }, linkFilterRefused: 'Der Filter dieses Links wurde nicht angewendet. Er nennt ein Feld, nach dem Sie hier nicht filtern können, daher zeigt die Liste die Ansicht ohne ihn.', personalizedParts: { diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index c1a53af99c0..ba3f5485ff8 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -3294,6 +3294,11 @@ const en = { saveAsMyView: 'Save as my view', copyName: '{{name}} copy', saved: 'Saved', + saveToViewConfirmTitle: 'Save to this view?', + saveToViewConfirm: 'Everyone who uses “{{name}}” will see these changes.', + saveToViewConfirmButton: 'Save for everyone', + savedForEveryone: 'Saved, visible to everyone', + pendingDraft: 'This view has unpublished changes. Publish or discard them in the view settings first.', }, linkFilterRefused: 'This link’s filter was not applied. It names a field you can’t filter on here, so the list shows the view without it.', personalizedParts: { diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 7020c607946..be9eac5c6d2 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -2771,6 +2771,11 @@ const es = { saveAsMyView: "Guardar como mi vista", copyName: "{{name}} (copia)", saved: "Guardado", + saveToViewConfirmTitle: "¿Guardar en esta vista?", + saveToViewConfirm: "Todas las personas que usan «{{name}}» verán estos cambios.", + saveToViewConfirmButton: "Guardar para todos", + savedForEveryone: "Guardado, visible para todos", + pendingDraft: "Esta vista tiene cambios sin publicar. Publícalos o descártalos primero en la configuración de la vista.", }, linkFilterRefused: 'No se aplicó el filtro de este enlace. Incluye un campo por el que no puede filtrar aquí, así que la lista muestra la vista sin él.', personalizedParts: { diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index a6c8de9becc..07f428fff0e 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -2767,6 +2767,11 @@ const fr = { saveAsMyView: "Enregistrer comme ma vue", copyName: "{{name}} (copie)", saved: "Enregistré", + saveToViewConfirmTitle: "Enregistrer dans cette vue ?", + saveToViewConfirm: "Toutes les personnes qui utilisent « {{name}} » verront ces modifications.", + saveToViewConfirmButton: "Enregistrer pour tous", + savedForEveryone: "Enregistré, visible par tous", + pendingDraft: "Cette vue contient des modifications non publiées. Publiez-les ou abandonnez-les d’abord dans les paramètres de la vue.", }, linkFilterRefused: 'Le filtre de ce lien n’a pas été appliqué. Il cite un champ sur lequel vous ne pouvez pas filtrer ici, la liste affiche donc la vue sans ce filtre.', personalizedParts: { diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 5198fe0fe10..8d97476c22c 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -2699,6 +2699,11 @@ const ja = { saveAsMyView: "マイビューとして保存", copyName: "{{name}} のコピー", saved: "保存しました", + saveToViewConfirmTitle: "このビューに保存しますか?", + saveToViewConfirm: "「{{name}}」を使うすべての人にこの変更が表示されます。", + saveToViewConfirmButton: "全員に保存", + savedForEveryone: "保存しました。全員に表示されます", + pendingDraft: "このビューには未公開の変更があります。先にビューの設定で公開するか破棄してください。", }, linkFilterRefused: 'このリンクのフィルターは適用されませんでした。ここでは絞り込めないフィールドが含まれているため、ビュー本来の内容を表示しています。', personalizedParts: { diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 6e6e09d71a9..2e894aaf22d 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -2697,6 +2697,11 @@ const ko = { saveAsMyView: "내 보기로 저장", copyName: "{{name}} 사본", saved: "저장했습니다", + saveToViewConfirmTitle: "이 보기에 저장할까요?", + saveToViewConfirm: "“{{name}}” 보기를 사용하는 모든 사람에게 이 변경 사항이 표시됩니다.", + saveToViewConfirmButton: "모두에게 저장", + savedForEveryone: "저장했습니다. 모두에게 표시됩니다", + pendingDraft: "이 보기에 게시되지 않은 변경 사항이 있습니다. 먼저 보기 설정에서 게시하거나 취소하세요.", }, linkFilterRefused: '이 링크의 필터가 적용되지 않았습니다. 여기서 필터링할 수 없는 필드가 포함되어 있어 뷰를 그대로 표시합니다.', personalizedParts: { diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index a4ef5a2bbb2..231dd28d19a 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -2766,6 +2766,11 @@ const pt = { saveAsMyView: "Salvar como minha exibição", copyName: "{{name}} (cópia)", saved: "Salvo", + saveToViewConfirmTitle: "Salvar nesta exibição?", + saveToViewConfirm: "Todos que usam “{{name}}” verão estas alterações.", + saveToViewConfirmButton: "Salvar para todos", + savedForEveryone: "Salvo, visível para todos", + pendingDraft: "Esta exibição tem alterações não publicadas. Publique ou descarte-as primeiro nas configurações da exibição.", }, linkFilterRefused: 'O filtro deste link não foi aplicado. Ele cita um campo pelo qual você não pode filtrar aqui, então a lista mostra a visualização sem ele.', personalizedParts: { diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 5f3b652b17f..d550bf41f17 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -2847,6 +2847,11 @@ const ru = { saveAsMyView: "Сохранить как моё представление", copyName: "{{name}} (копия)", saved: "Сохранено", + saveToViewConfirmTitle: "Сохранить в это представление?", + saveToViewConfirm: "Все, кто пользуется «{{name}}», увидят эти изменения.", + saveToViewConfirmButton: "Сохранить для всех", + savedForEveryone: "Сохранено, видно всем", + pendingDraft: "В этом представлении есть неопубликованные изменения. Сначала опубликуйте или отмените их в настройках представления.", }, linkFilterRefused: 'Фильтр из этой ссылки не применён: в нём есть поле, по которому здесь нельзя фильтровать, поэтому список показан по представлению без него.', personalizedParts: { diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 5329fb456b3..402095cc2ad 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -2784,6 +2784,11 @@ const zh = { saveAsMyView: '另存为我的视图', copyName: '{{name}} 副本', saved: '已保存', + saveToViewConfirmTitle: '保存到这个视图?', + saveToViewConfirm: '所有用「{{name}}」的人都会看到这些改动。', + saveToViewConfirmButton: '保存,所有人可见', + savedForEveryone: '已保存,所有人可见', + pendingDraft: '这个视图有未发布的修改,请先在视图设置里发布或放弃。', }, linkFilterRefused: '此链接的筛选条件未应用:其中包含你在此处无法筛选的字段,因此列表按视图本身显示。', personalizedParts: { diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 41c49ce39d1..6a232f16660 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -2784,6 +2784,11 @@ const zhHant = { saveAsMyView: '另存為我的檢視', copyName: '{{name}} 副本', saved: '已儲存', + saveToViewConfirmTitle: '儲存到這個檢視?', + saveToViewConfirm: '所有用「{{name}}」的人都會看到這些改動。', + saveToViewConfirmButton: '儲存,所有人可見', + savedForEveryone: '已儲存,所有人可見', + pendingDraft: '這個檢視有未釋出的修改,請先在檢視設定裡釋出或放棄。', }, linkFilterRefused: '此連結的篩選條件未應用:其中包含你在此處無法篩選的欄位,因此列表按檢視本身顯示。', personalizedParts: { diff --git a/ui/packages/plugin-list/README.md b/ui/packages/plugin-list/README.md index c873de5d07e..f8108e4a866 100644 --- a/ui/packages/plugin-list/README.md +++ b/ui/packages/plugin-list/README.md @@ -287,6 +287,32 @@ import { ListView } from '@object-ui/plugin-list'; /> ``` +### Host props: the unsaved layout and row colour (`onRowColorChange`) + +A host that keeps the reader's layout and row colour as an unsaved change +(the console's list draft) wires `onViewChange` and `onRowColorChange`. +`onRowColorChange` is called with the colour rule a pick in the toolbar's row +colour panel puts in force, or `null` for "none" (Clear, or the None entry); +it is called for a pick only, never at mount, for a reset or for a prop +change. The host lays the reader's choice into `schema.viewType` / +`schema.rowColor` when the list mounts again, and passes the view's own in +`viewDefaults.viewType` / `viewDefaults.rowColor`, so the Display control's +count and the `layout` / `rowColor` parts of `onPersonalizationChange` are +judged against the view. Like `viewDefaults.grouping`, each is read only when +its key is present. These are React props for the host app, not schema keys. + +```tsx +import { ListView } from '@object-ui/plugin-list'; + +// The view colours nothing; the reader picked a colour by `stage`. + console.log('Layout:', view)} + onRowColorChange={(rowColor) => console.log('Row colour:', rowColor)} +/> +``` + ### Host props: `addedFields` and `onAddedFieldsChange` A host that lets a reader add fields to their own list wires diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 65f8beee39e..b148b399844 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -571,9 +571,18 @@ export interface ListViewProps { * finished conditions are then judged against these, so the view's own * rows are not a personalization and an edit, a removal or a "Clear all" * is. Absent ⇒ any finished panel condition is the reader's own, as before. + * + * `viewType` and `rowColor` (objectstack#35955) are the view's own layout + * and row colour, for a host that lays the reader's unsaved choice of + * either into `schema` (`onViewChange`, `onRowColorChange`): the Display + * control's count and the `layout` / `rowColor` parts are judged against + * these. Like `grouping`, each is read only when its key is present; + * without it `schema` holds the view's own. */ viewDefaults?: Pick & { filters?: FilterBuilderRowGroup; + viewType?: ListViewSchema['viewType']; + rowColor?: ListViewSchema['rowColor']; }; /** * A reset to the view's own, told apart from a choice (objectstack#28948). @@ -619,6 +628,15 @@ export interface ListViewProps { * keeps its reset, exactly as before. */ onPersonalizationChange?: (parts: ReadonlyArray) => void; + /** + * The reader's pick in the toolbar's row colour panel (objectstack#35955): + * the colour rule now in force, or `null` for "none" (Clear, or the None + * entry). Told for a pick only, never for a reset or a prop change, so a + * host can keep the reader's choice as an unsaved change and lay it back + * into `schema.rowColor` when the list mounts again. A HOST prop, never a + * schema key. Absent ⇒ the pick stays the list's own, as before. + */ + onRowColorChange?: (rowColor: NonNullable | null) => 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 @@ -2354,6 +2372,7 @@ export const ListView = React.forwardRef(({ viewDefaults, onRestoreViewDefaults, onPersonalizationChange, + onRowColorChange, onRenameView, onSaveView, onResetView, @@ -6620,12 +6639,16 @@ export const ListView = React.forwardRef(({ const viewDefaultDensity = viewDefaults ? rowHeightToDensityMode(viewDefaults.rowHeight) ?? 'compact' : resolvedDensity; + // objectstack#35955 — the view's own layout and row colour, when the host + // lays the reader's unsaved choice into `schema` (see `viewDefaults`). + const viewDefaultViewType = viewDefaults && 'viewType' in viewDefaults ? viewDefaults.viewType : schema.viewType; + const viewDefaultRowColor = viewDefaults && 'rowColor' in viewDefaults ? viewDefaults.rowColor : schema.rowColor; const sortedNames = (names: Iterable | undefined) => JSON.stringify([...(names ?? [])].sort()); const displayDeviation = { - layout: viewSwitcherOffered && !!schema.viewType && currentView !== schema.viewType, + layout: viewSwitcherOffered && !!viewDefaultViewType && currentView !== viewDefaultViewType, group: toolbarFlags.showGroup && JSON.stringify(chosenGroupingConfig?.fields ?? []) !== JSON.stringify(initialGroupingConfig?.fields ?? []), - color: toolbarFlags.showColor && (rowColorConfig?.field ?? '') !== (schema.rowColor?.field ?? ''), + color: toolbarFlags.showColor && (rowColorConfig?.field ?? '') !== (viewDefaultRowColor?.field ?? ''), hiddenFields: toolbarFlags.showHideFields && sortedNames(hiddenFields) !== sortedNames(viewDefaultHiddenFields), density: toolbarFlags.showDensity && (currentView === 'gallery' ? galleryCardSize !== authoredGalleryCardSize @@ -6681,9 +6704,9 @@ export const ListView = React.forwardRef(({ */ const resetDisplayToViewDefault = () => { const restoredParts: Array<'hiddenFields' | 'rowHeight'> = []; - if (displayDeviation.layout) handleViewChange(schema.viewType as ListViewVisualization); + if (displayDeviation.layout) handleViewChange(viewDefaultViewType as ListViewVisualization); if (displayDeviation.group) changeGrouping(initialGroupingConfig); - if (displayDeviation.color) setRowColorConfig(schema.rowColor); + if (displayDeviation.color) setRowColorConfig(viewDefaultRowColor); if (displayDeviation.hiddenFields) { if (onRestoreViewDefaults) { setHiddenFields(new Set(viewDefaultHiddenFields || [])); @@ -7635,7 +7658,7 @@ export const ListView = React.forwardRef(({

{t('list.rowColor')}

{offeredRowColorConfig && ( - )} @@ -7657,8 +7680,11 @@ export const ListView = React.forwardRef(({ onPick={(field) => { if (!field) { setRowColorConfig(undefined); + onRowColorChange?.(null); } else { - setRowColorConfig({ field, colors: offeredRowColorConfig?.colors || {} }); + const picked = { field, colors: offeredRowColorConfig?.colors || {} }; + setRowColorConfig(picked); + onRowColorChange?.(picked); } }} /> 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 fdee228b501..62614b1fac0 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 @@ -277,3 +277,55 @@ describe('the view\'s own conditions as panel rows (`viewDefaults.filters`, obje await waitFor(() => expect(reported()).toEqual(['filters'])); }); }); + +describe('the host\'s unsaved layout and row colour (objectstack#35955)', () => { + const COLOR_ACTIONS = { ...BASE.userActions, rowColor: true }; + + it('a row colour the host laid over the view\'s is `rowColor`, judged against `viewDefaults.rowColor`', async () => { + const { reported } = mount( + { compactToolbar: false, userActions: COLOR_ACTIONS, rowColor: { field: 'stage', colors: {} } } as Partial, + { viewDefaults: { ...VIEW_DEFAULTS, rowColor: undefined } }, + ); + await screen.findByTestId('grid-stub'); + await waitFor(() => expect(reported()).toEqual(['rowColor'])); + }); + + it('CONTROL: the view\'s own row colour, handed in both places, is no part', async () => { + const rowColor = { field: 'stage', colors: {} }; + const { reported } = mount( + { compactToolbar: false, userActions: COLOR_ACTIONS, rowColor } as Partial, + { viewDefaults: { ...VIEW_DEFAULTS, rowColor } }, + ); + await screen.findByTestId('grid-stub'); + await waitFor(() => expect(reported()).toEqual([])); + }); + + it('a pick in the row colour panel is told to `onRowColorChange`, and Clear as `null`', async () => { + const onRowColorChange = vi.fn(); + mount( + { compactToolbar: false, userActions: COLOR_ACTIONS } as Partial, + { onRowColorChange }, + ); + await screen.findByTestId('grid-stub'); + fireEvent.click(screen.getByRole('button', { name: /^color/i })); + const trigger = await screen.findByTestId('color-field-select'); + fireEvent.keyDown(trigger, { key: 'ArrowDown' }); + const listbox = await screen.findByRole('listbox'); + fireEvent.click(within(listbox).getByRole('option', { name: 'Stage' })); + await waitFor(() => expect(onRowColorChange).toHaveBeenLastCalledWith({ field: 'stage', colors: {} })); + fireEvent.click(await screen.findByTestId('clear-row-color')); + await waitFor(() => expect(onRowColorChange).toHaveBeenLastCalledWith(null)); + expect(onRowColorChange).toHaveBeenCalledTimes(2); + }); + + it('CONTROL: a mount and a prop change tell `onRowColorChange` nothing', async () => { + const onRowColorChange = vi.fn(); + mount( + { compactToolbar: false, userActions: COLOR_ACTIONS, rowColor: { field: 'stage', colors: {} } } as Partial, + { onRowColorChange }, + ); + await screen.findByTestId('grid-stub'); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 50)); }); + expect(onRowColorChange).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/types/src/__tests__/object-view-unmirrored-keys-7779.test.ts b/ui/packages/types/src/__tests__/object-view-unmirrored-keys-7779.test.ts index cdb3fa1698f..44cb8bb6625 100644 --- a/ui/packages/types/src/__tests__/object-view-unmirrored-keys-7779.test.ts +++ b/ui/packages/types/src/__tests__/object-view-unmirrored-keys-7779.test.ts @@ -2313,7 +2313,8 @@ describe('objectui#7924 — the retirement: seventeen `?: never` tombstones, obj expect(appShell).not.toContain('viewDef.prefixField'); expect(appShell).not.toContain('viewDef.allowExport'); // Firing control on the same file: the relay still reads other keys off the view. - expect(appShell).toContain('rowColor: viewDef.rowColor ?? listSchema.rowColor,'); + // objectstack#35955 — the view's own rule is read once, so the draft's can lie over it. + expect(appShell).toContain('const viewOwnRowColor = viewDef.rowColor ?? listSchema.rowColor;'); const listView = readRepo(LISTVIEW); expect(listView).not.toMatch(/\bprefixField\b/); expect(listView).toMatch(/\ballowExport\b/);