From ef54913f248f9f8ab2b24114b95c80dcf27a001a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 23:17:18 +0000 Subject: [PATCH] feat(console): a footer calculation is a part of the list's draft Picking, changing or removing a column's footer calculation applies at once and writes nothing: it joins the list's draft (Discard / Save, one line in Save's unsaved list) and Save to this view / Save as my view store it on the columns the saved body keeps. A view the reader cannot change in place offers Save as my view alone, so no pick reaches the door that refuses a package's view. That refusal (NOT_OVERRIDABLE) is said in the reader's words in every locale instead of the door's text. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgX7ez5A7JDsmzTy9Ks --- .changeset/36194-footer-calculation-draft.md | 17 + content/docs/ui/views.mdx | 21 +- ...pContent.draftSaveKeepsList-35932.test.tsx | 54 +-- .../app-shell/src/views/ListDraftActions.tsx | 12 +- ...View.footerCalculationDraft-36194.test.tsx | 344 ++++++++++++++++++ ...ectView.readOnlyPackageView-35933.test.tsx | 223 ------------ .../app-shell/src/views/ObjectView.tsx | 83 +---- .../footerCalculationDraft-36194.test.ts | 100 +++++ .../app-shell/src/views/columnSummaryWrite.ts | 60 ++- .../app-shell/src/views/listDraftStore.ts | 15 +- .../src/views/objectViewListRenderer.tsx | 47 ++- .../src/views/objectViewListUrlState.ts | 5 + .../src/views/objectViewViewCrud.tsx | 19 +- .../app-shell/src/views/personalViews.ts | 14 +- .../app-shell/src/views/viewSaveRefusal.ts | 30 ++ ui/packages/i18n/src/locales/ar.ts | 4 + ui/packages/i18n/src/locales/de.ts | 4 + ui/packages/i18n/src/locales/en.ts | 4 + ui/packages/i18n/src/locales/es.ts | 4 + ui/packages/i18n/src/locales/fr.ts | 4 + ui/packages/i18n/src/locales/ja.ts | 4 + ui/packages/i18n/src/locales/ko.ts | 4 + ui/packages/i18n/src/locales/pt-BR.ts | 4 + ui/packages/i18n/src/locales/ru.ts | 4 + ui/packages/i18n/src/locales/zh-Hans.ts | 4 + ui/packages/i18n/src/locales/zh-Hant.ts | 4 + ui/packages/plugin-grid/src/ObjectGrid.tsx | 10 +- ui/packages/plugin-list/src/ListView.tsx | 16 +- 28 files changed, 738 insertions(+), 376 deletions(-) create mode 100644 .changeset/36194-footer-calculation-draft.md create mode 100644 ui/packages/app-shell/src/views/ObjectView.footerCalculationDraft-36194.test.tsx delete mode 100644 ui/packages/app-shell/src/views/ObjectView.readOnlyPackageView-35933.test.tsx create mode 100644 ui/packages/app-shell/src/views/__tests__/footerCalculationDraft-36194.test.ts create mode 100644 ui/packages/app-shell/src/views/viewSaveRefusal.ts diff --git a/.changeset/36194-footer-calculation-draft.md b/.changeset/36194-footer-calculation-draft.md new file mode 100644 index 00000000000..d19bcdaa36e --- /dev/null +++ b/.changeset/36194-footer-calculation-draft.md @@ -0,0 +1,17 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(console): a footer calculation is a part of the list's draft; a refused save of a package's view says why in the reader's words + +Clause-②: yes (widening) — new keys in every `@object-ui/i18n` locale pack: `console.objectView.personalizedParts.summaries` and `console.objectView.saveRefused.packaged`; nothing removed or renamed +Metadata-protocol: none + +On a Console object list, picking, changing or removing a column's footer calculation (「+ 添加统计」) applies at once and writes nothing. It used to be saved at once: on the reader's own view straight into it, on a shared view as a draft of the view (`PUT /api/v1/meta/view/?mode=draft`), which the server refuses on a view an app package ships. + +- The calculation is a part of the list's draft, like the sort and the filter: **Discard** and **Save** appear, Save's menu names it (「统计」), and Discard takes it off. The draft lives as long as the others: kept on opening a record and coming back, dropped on another view, object or a reload. +- **Save to this view** (on the reader's own view) and **Save as my view** store it on the columns the saved view keeps. +- On a view the reader cannot change in place (one an app package ships, or a shared view of a reader who is no admin), the pick goes into the draft too and Save offers **Save as my view** alone. +- The menu is offered on every column the saved view would carry: the columns the list draws and the fields the reader added. +- When the server refuses to save a view an app package ships (`NOT_OVERRIDABLE`), the toast says in the reader's language that the view comes with an app package, cannot be changed directly and can be saved as the reader's own view. The server's text goes to the console only. Every other refusal is said as before. diff --git a/content/docs/ui/views.mdx b/content/docs/ui/views.mdx index e94a8160c38..4e49a7b864c 100644 --- a/content/docs/ui/views.mdx +++ b/content/docs/ui/views.mdx @@ -619,16 +619,25 @@ 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 +A header sort, a filter change, grouping, the search, Hide Fields, an added field, a +column drag and a footer calculation picked under a column 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. +- **Save** names what is unsaved and keeps the sort, filters, columns, hidden fields and + footer calculations: **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 view the user + cannot change in place (one an app package ships, or a shared view they may not edit) + offers **Save as my view** alone. +- A footer calculation is offered on every column the saved view would carry: the columns + the list draws and the fields the user added. Picking the view's own calculation again + takes that column out of the draft. +- When the server refuses to save a view an app package ships, the list says so in the + user's language (it cannot be changed directly; save it as your own view), never the + server's own text. - **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/ui/packages/app-shell/src/console/__tests__/AppContent.draftSaveKeepsList-35932.test.tsx b/ui/packages/app-shell/src/console/__tests__/AppContent.draftSaveKeepsList-35932.test.tsx index 485a01b0003..8c7063781f5 100644 --- a/ui/packages/app-shell/src/console/__tests__/AppContent.draftSaveKeepsList-35932.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/AppContent.draftSaveKeepsList-35932.test.tsx @@ -21,12 +21,14 @@ * mounts, so a remount of the route is read as a second mount. * * Pinned: - * - an admin's footer pick on a shared view: no skeleton, no remount, the - * list keeps the picked calculation while the refresh is on the wire and - * after it lands; - * - two successive picks: the second draft carries both; - * - the writes are draft saves; a reader (not an admin) served the published - * view draws it, without the admin's calculations. + * - an admin's footer pick on a shared view, then the refresh pulse a draft + * save announces: no skeleton, no remount, the list keeps the picked + * calculation while the refresh is on the wire and after it lands. Since + * objectstack#36194 the pick itself is a part of the list's draft and + * writes nothing, so the pulse is announced here as a save announces it; + * - two successive picks: the list draws both, and nothing is written; + * - a reader (not an admin) served the published view draws it, without the + * admin's calculations. * CONTROL: a whole-type invalidation of `view` (the provider dropping its * items, not refetching in place) still sends the route back to waiting. * @@ -199,6 +201,7 @@ import '../../views/ObjectView.js'; import { AppContent } from '../AppContent'; import { MetadataProvider, useMetadata } from '../../providers/MetadataProvider'; import { publishRuntimeMetadata } from '../../views/runtime-metadata-persistence.js'; +import { emitMetadataRefresh } from '../../assistant/assistantBus.js'; interface Server { /** Hold every `/meta/view` list read until `releaseViews`, as a request on the wire. */ @@ -362,12 +365,8 @@ const pick = (field: string, summary: string) => act(async () => { await list.props!.onColumnSummaryPick(field, summary); }); -const storedSummaries = (body: any) => - Object.fromEntries( - ((body?.config?.columns ?? body?.columns ?? []) as Array) - .filter((c): c is { field: string; summary?: unknown } => typeof c === 'object' && c.summary !== undefined) - .map((c) => [c.field, c.summary]), - ); +/** The refresh pulse every write of the persistence seam announces (`emitMetadataRefresh`). */ +const announceSave = () => act(() => emitMetadataRefresh()); beforeEach(() => { server.holdViews = false; @@ -400,7 +399,9 @@ describe('objectstack#35932 — a shared view\'s draft save keeps the list on sc // The refresh the save announces re-reads `/meta/view`; held, as a request on the wire. server.holdViews = true; await pick('amount', 'sum'); - expect(saves).toHaveLength(1); + // objectstack#36194 — the pick is the list's draft: nothing is written. + expect(saves).toHaveLength(0); + announceSave(); await act(async () => { await new Promise((resolve) => setTimeout(resolve, 50)); }); @@ -417,28 +418,25 @@ describe('objectstack#35932 — a shared view\'s draft save keeps the list on sc expect(summaryOf('amount')).toBe('sum'); }); - it('two successive picks: the second draft carries both', async () => { + it('two successive picks: the list draws both, nothing is written', async () => { boot(true); await waitFor(() => expect(typeof list.props?.onColumnSummaryPick).toBe('function'), { timeout: 5000 }); server.holdViews = true; await pick('amount', 'sum'); + announceSave(); await act(async () => { await new Promise((resolve) => setTimeout(resolve, 50)); }); await pick('closed_at', 'latest'); + announceSave(); server.holdViews = false; act(() => server.releaseViews()); await act(async () => { await new Promise((resolve) => setTimeout(resolve, 50)); }); - expect(saves.map((s) => [s.type, s.name, s.options?.mode])).toEqual([ - ['view', VIEW, 'draft'], - ['view', VIEW, 'draft'], - ]); - expect(storedSummaries(saves[0].body)).toEqual({ amount: 'sum' }); - expect(storedSummaries(saves[1].body)).toEqual({ amount: 'sum', closed_at: 'latest' }); + expect(saves).toEqual([]); expect(list.mounts).toBe(1); expect(summaryOf('amount')).toBe('sum'); expect(summaryOf('closed_at')).toBe('latest'); @@ -448,15 +446,15 @@ describe('objectstack#35932 — a shared view\'s draft save keeps the list on sc boot(true); await waitFor(() => expect(typeof list.props?.onColumnSummaryPick).toBe('function'), { timeout: 5000 }); await pick('amount', 'sum'); - expect(saves.map((s) => s.options?.mode)).toEqual(['draft']); + expect(saves).toEqual([]); cleanup(); forgetList(); boot(false); await waitFor(() => expect(list.props?.schema?.columns).toBeDefined(), { timeout: 5000 }); expect(summaryOf('amount')).toBeUndefined(); - // Offered to an admin only. - expect(list.props?.onColumnSummaryPick).toBeUndefined(); + // objectstack#36194 — a reader's pick is their own draft too. + expect(typeof list.props?.onColumnSummaryPick).toBe('function'); }); it('CONTROL: a whole-type invalidation of `view` still sends the route back to waiting', async () => { @@ -486,6 +484,7 @@ describe('objectstack#35932 — the same, on an app with a bundle', () => { appBundle.hold = true; await pick('amount', 'sum'); + announceSave(); await settle(); // The pulse dropped the bundle and its reload is on the wire. expect(appBundle.items).toBeNull(); @@ -502,18 +501,21 @@ describe('objectstack#35932 — the same, on an app with a bundle', () => { expect(summaryOf('amount')).toBe('sum'); }); - it('two successive picks, then Publish: both picks in the second draft, one mount throughout', async () => { + it('two successive picks, then Publish: both picks drawn, one mount throughout', async () => { boot(true, { bundle: true }); await waitFor(() => expect(typeof list.props?.onColumnSummaryPick).toBe('function'), { timeout: 5000 }); appBundle.hold = true; await pick('amount', 'sum'); + announceSave(); await settle(); await pick('closed_at', 'latest'); + announceSave(); await settle(); expect(skeletonUp()).toBe(false); - expect(storedSummaries(saves[0].body)).toEqual({ amount: 'sum' }); - expect(storedSummaries(saves[1].body)).toEqual({ amount: 'sum', closed_at: 'latest' }); + expect(saves).toEqual([]); + expect(summaryOf('amount')).toBe('sum'); + expect(summaryOf('closed_at')).toBe('latest'); appBundle.hold = false; act(() => releaseBundle()); diff --git a/ui/packages/app-shell/src/views/ListDraftActions.tsx b/ui/packages/app-shell/src/views/ListDraftActions.tsx index a390bff701b..7628bdcfa67 100644 --- a/ui/packages/app-shell/src/views/ListDraftActions.tsx +++ b/ui/packages/app-shell/src/views/ListDraftActions.tsx @@ -34,8 +34,14 @@ import { useObjectTranslation } from '@object-ui/i18n'; import { ConditionDiscardButton, type ListViewProps } from '@object-ui/plugin-list'; import { ChevronDown, CopyPlus, RotateCcw, Save } from 'lucide-react'; -/** One part of a list that can differ from its view (`ListView`'s vocabulary). */ -export type ListPersonalizationPart = Parameters>[0][number]; +/** + * One part of a list that can differ from its view: `ListView`'s vocabulary, + * plus the footer's calculations (objectstack#36194), a part only this page's + * draft knows (the grid hands the pick to the host, which holds it). + */ +export type ListPersonalizationPart = + | Parameters>[0][number] + | 'summaries'; /** The order the menu names the unsaved parts in: the toolbar's, then the Display panel's. */ const LIST_DRAFT_PART_ORDER: readonly ListPersonalizationPart[] = [ @@ -44,6 +50,7 @@ const LIST_DRAFT_PART_ORDER: readonly ListPersonalizationPart[] = [ 'grouping', 'columns', 'hiddenFields', + 'summaries', 'layout', 'rowColor', 'inlineEdit', @@ -76,6 +83,7 @@ export function ListDraftActions({ grouping: t('console.objectView.personalizedParts.grouping'), columns: t('console.objectView.personalizedParts.columns'), hiddenFields: t('console.objectView.personalizedParts.hiddenFields'), + summaries: t('console.objectView.personalizedParts.summaries'), density: t('console.objectView.personalizedParts.density'), layout: t('console.objectView.personalizedParts.layout'), rowColor: t('console.objectView.personalizedParts.rowColor'), diff --git a/ui/packages/app-shell/src/views/ObjectView.footerCalculationDraft-36194.test.tsx b/ui/packages/app-shell/src/views/ObjectView.footerCalculationDraft-36194.test.tsx new file mode 100644 index 00000000000..c3f58e5aed4 --- /dev/null +++ b/ui/packages/app-shell/src/views/ObjectView.footerCalculationDraft-36194.test.tsx @@ -0,0 +1,344 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36194 + objectstack#36195 — the footer's calculation is a part of + * the list's DRAFT (objectstack#35955), like the sort and the filter. + * + * A pick applies at once (the columns the list is handed carry it) and writes + * nothing: no view save, no draft save, no write to the reader's own view. + * Save's menu names it (「Calculations」) beside the other unsaved parts; + * Discard drops it; picking the view's own calculation again drops the column + * from the draft. A save keeps it: 「Save to this view」 on the reader's own + * view, 「Save as my view」 anywhere. + * + * So a view the reader cannot change in place (one a read-only package ships, + * objectstack#35933, or a shared view of a reader who is no admin) offers the + * menu too: the pick goes into the draft, and Save offers 「Save as my view」 + * alone. Nothing a pick does reaches the door that refused it + * (objectstack#36195: `PUT /meta/view/?mode=draft` answered + * `NOT_OVERRIDABLE` in English). + * + * The menu is offered on the columns a saved body carries: the columns the + * list draws (the view's own, or the defaults drawn into a view that declares + * none) and the ones the reader added. + * + * What runs: the real `ObjectView` on a stub data source. `ListView` is + * replaced by a stand-in that records the props it is handed and draws the + * condition row's end (Discard and Save), so the menu's presence is read as + * the `onColumnSummaryPick` the list receives (the grid draws the menu exactly + * when it has one, pinned in plugin-grid's `footerCalculationPicker-35702` + * tests). The package list is stubbed at `fetchSessionPackages`; every request + * the page sends through `fetch` is recorded. + */ + +import * as React from 'react'; +import '@testing-library/jest-dom/vitest'; +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: reader.admin, 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 })); + +/** Whether the reader is a workspace administrator. */ +const reader = vi.hoisted(() => ({ admin: true })); + +/** 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; + // The condition row's end: Discard and Save while the list holds a draft. + return
{props.conditionRowEnd}
; + }, +})); + +/** 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 { listDraftScope, readListDraft, resetListDraftStoreForTests } from './listDraftStore'; + +const OBJECT = 'showcase_task'; +const SHIPPED_PACKAGE = 'com.example.showcase'; +const CUSTOM_PACKAGE = 'com.example.showcase.custom'; + +/** A view the read-only code package ships, as `listViews()` serves it. */ +const SHIPPED = { + name: `${OBJECT}.in_progress`, object: OBJECT, label: 'In progress', type: 'grid', + columns: ['name', 'amount'], _packageId: SHIPPED_PACKAGE, +}; +/** A shared view the console saved: dotted the same way, in the customization package. */ +const CUSTOM = { + name: `${OBJECT}.team_tasks`, object: OBJECT, label: 'Team tasks', type: 'grid', + columns: ['name', 'amount'], _packageId: CUSTOM_PACKAGE, +}; +/** A stored view bound to no package. */ +const UNBOUND = { name: `${OBJECT}.unbound`, object: OBJECT, label: 'Unbound', type: 'grid', columns: ['name', 'amount'] }; +/** A stored view that declares no columns (the list draws the object's defaults). */ +const BARE = { name: `${OBJECT}.bare`, object: OBJECT, label: 'Bare', type: 'grid' }; +/** The reader's own view (`sys_personal_view`). */ +const PERSONAL = { + id: 'pv_mine', user_id: 'u1', object_name: OBJECT, label: 'My tasks', + config: { type: 'grid', columns: ['name', 'amount'], data: { provider: 'object', object: OBJECT } }, +}; + +/** The packages row for each id: the server's `writable` verdict. */ +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 (resource: string) => + resource === 'sys_personal_view' ? { data: [PERSONAL], total: 1 } : { data: [], total: 0 }), + findOne: vi.fn(async () => null), + create: vi.fn(async (_resource: string, data: Record) => ({ id: 'pv_new', ...data })), + update: vi.fn(async (_resource: string, _id: string, _patch: Record) => ({})), + delete: vi.fn(async () => ({})), + getObjectSchema: vi.fn(async () => ({ name: OBJECT, fields: {} })), + listViews: vi.fn(async () => [SHIPPED, CUSTOM, UNBOUND, BARE]), + updateView: vi.fn(async () => ({})), + }; + render( + + + + {}} + /> + } + /> + + + , + ); + return { dataSource }; +} + +const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 300))); + +/** Whether the list is handed the footer's calculation pick. */ +const offersMenu = () => typeof listProps.current?.onColumnSummaryPick === 'function'; +/** Pick a calculation through the list's door, as the grid's footer menu does. */ +const pick = (field: string, summary: string | null) => + act(async () => { + expect(await listProps.current!.onColumnSummaryPick(field, summary)).toBe(true); + }); +/** The calculation the list draws under `field`, as its schema's columns carry it. */ +const summaryOf = (field: string) => { + const columns = (listProps.current?.schema?.columns ?? []) as Array; + const column = columns.find((c) => (typeof c === 'string' ? c : c.field) === field); + return column && typeof column === 'object' ? column.summary : undefined; +}; +const storedSummaries = (config: any) => + Object.fromEntries( + ((config?.columns ?? []) as Array) + .filter((c): c is { field: string; summary?: unknown } => typeof c === 'object' && c.summary !== undefined) + .map((c) => [c.field, c.summary]), + ); +const openSave = async () => { + fireEvent.pointerDown(await screen.findByTestId('list-draft-save'), { button: 0, ctrlKey: false, pointerType: 'mouse' }); + return screen.findByTestId('list-draft-save-menu'); +}; + +/** Every request the page sends through `fetch` that is not a read. */ +const writes: string[] = []; +vi.stubGlobal('fetch', vi.fn(async (input: unknown, init?: { method?: string }) => { + const method = (init?.method ?? 'GET').toUpperCase(); + if (method !== 'GET') writes.push(`${method} ${String(input)}`); + return new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'content-type': 'application/json' } }); +})); + +beforeEach(() => { + listProps.current = null; + reader.admin = true; + writes.length = 0; + packageList.answer = () => Promise.resolve(PACKAGES); + localStorage.clear(); + resetListDraftStoreForTests(); +}); + +afterEach(() => { + cleanup(); +}); + +describe('objectstack#36194 — a footer pick is a part of the list\'s draft', () => { + it('a pick applies at once and writes nothing; Save names it; picking the view\'s own drops it', async () => { + const page = mount(CUSTOM.name); + await settle(); + await waitFor(() => expect(offersMenu()).toBe(true)); + expect(listProps.current?.columnSummaryPickFields).toEqual(['name', 'amount']); + + await pick('amount', 'sum'); + expect(summaryOf('amount')).toBe('sum'); + expect(screen.getByTestId('list-draft')).toBeInTheDocument(); + const menu = await openSave(); + expect(menu.querySelector('[data-testid="list-draft-parts"]')).toHaveTextContent('personalizedParts.summaries'); + expect(writes).toEqual([]); + expect(page.dataSource.update).not.toHaveBeenCalled(); + expect(page.dataSource.updateView).not.toHaveBeenCalled(); + + // None, over a column the view does not sum, is the view's own again. + await pick('amount', null); + expect(summaryOf('amount')).toBeUndefined(); + await waitFor(() => expect(screen.queryByTestId('list-draft')).toBeNull()); + expect(readListDraft(listDraftScope('u1', OBJECT, CUSTOM.name))).toEqual({}); + expect(writes).toEqual([]); + }); + + it('Discard takes the calculation off: the list is the view\'s again', async () => { + mount(CUSTOM.name); + await settle(); + await waitFor(() => expect(offersMenu()).toBe(true)); + await pick('amount', 'avg'); + fireEvent.click(await screen.findByTestId('list-draft-discard')); + await waitFor(() => expect(screen.queryByTestId('list-draft')).toBeNull()); + expect(summaryOf('amount')).toBeUndefined(); + expect(writes).toEqual([]); + }); + + it('the reader\'s own view: the pick writes nothing until 「Save to this view」, which stores it', async () => { + const page = mount(PERSONAL.id); + await settle(); + await waitFor(() => expect(offersMenu()).toBe(true)); + await pick('amount', 'max'); + expect(summaryOf('amount')).toBe('max'); + expect(page.dataSource.update).not.toHaveBeenCalled(); + + await openSave(); + fireEvent.click(await screen.findByTestId('list-draft-save-to-view')); + await waitFor(() => expect(page.dataSource.update).toHaveBeenCalledTimes(1)); + const [resource, id, patch] = page.dataSource.update.mock.calls[0]; + expect([resource, id]).toEqual(['sys_personal_view', PERSONAL.id]); + expect(storedSummaries(patch.config)).toEqual({ amount: 'max' }); + expect(writes).toEqual([]); + }); + + it('a view that declares no columns: the menu is on the columns the list draws, and 「Save as my view」 keeps them with the pick', async () => { + const page = mount(BARE.name); + await settle(); + await waitFor(() => expect(offersMenu()).toBe(true)); + const drawn = listProps.current?.columnSummaryPickFields as string[]; + expect(drawn).toContain('amount'); + await pick('amount', 'sum'); + await openSave(); + fireEvent.click(await screen.findByTestId('list-draft-save-as')); + fireEvent.click(await screen.findByTestId('personal-view-name-submit')); + await waitFor(() => expect(page.dataSource.create).toHaveBeenCalledTimes(1)); + const [, row] = page.dataSource.create.mock.calls[0]; + expect(storedSummaries(row.config)).toEqual({ amount: 'sum' }); + expect(writes).toEqual([]); + }); +}); + +describe('objectstack#36195 — a view the reader cannot change in place: the pick goes into the draft, Save offers 「Save as my view」 alone', () => { + it('a view a read-only package ships: the pick is drawn, nothing reaches the door, and 「Save as my view」 stores it', async () => { + const page = mount(SHIPPED.name); + await settle(); + await waitFor(() => expect(offersMenu()).toBe(true)); + // objectstack#35974 — the rename lands in the package's customization pair. + expect(typeof listProps.current?.onRenameView).toBe('function'); + + await pick('amount', 'count_unique'); + expect(summaryOf('amount')).toBe('count_unique'); + expect(writes).toEqual([]); + expect(page.dataSource.updateView).not.toHaveBeenCalled(); + + await openSave(); + expect(screen.queryByTestId('list-draft-save-to-view')).toBeNull(); + fireEvent.click(await screen.findByTestId('list-draft-save-as')); + fireEvent.click(await screen.findByTestId('personal-view-name-submit')); + await waitFor(() => expect(page.dataSource.create).toHaveBeenCalledTimes(1)); + const [resource, row] = page.dataSource.create.mock.calls[0]; + expect(resource).toBe('sys_personal_view'); + expect(storedSummaries(row.config)).toEqual({ amount: 'count_unique' }); + expect(writes).toEqual([]); + }); + + it('the pick does not wait for the package list: while it is unread, the pick is a draft all the same', async () => { + packageList.answer = () => new Promise(() => {}); + const page = mount(SHIPPED.name); + await settle(); + await waitFor(() => expect(offersMenu()).toBe(true)); + await pick('amount', 'sum'); + expect(summaryOf('amount')).toBe('sum'); + expect(writes).toEqual([]); + expect(page.dataSource.updateView).not.toHaveBeenCalled(); + }); + + it('a reader who is no admin on a shared view: the pick is a draft too, and Save offers 「Save as my view」 alone', async () => { + reader.admin = false; + mount(UNBOUND.name); + await settle(); + await waitFor(() => expect(offersMenu()).toBe(true)); + await pick('amount', 'sum'); + expect(summaryOf('amount')).toBe('sum'); + await openSave(); + expect(screen.queryByTestId('list-draft-save-to-view')).toBeNull(); + expect(screen.getByTestId('list-draft-save-as')).toBeInTheDocument(); + expect(writes).toEqual([]); + }); +}); diff --git a/ui/packages/app-shell/src/views/ObjectView.readOnlyPackageView-35933.test.tsx b/ui/packages/app-shell/src/views/ObjectView.readOnlyPackageView-35933.test.tsx deleted file mode 100644 index 973b4904547..00000000000 --- a/ui/packages/app-shell/src/views/ObjectView.readOnlyPackageView-35933.test.tsx +++ /dev/null @@ -1,223 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#35933 — a view a read-only package ships offers an admin no save - * of its own: no footer calculation menu (objectstack#35702). Its Rename in - * the list's options menu stays (objectstack#35974): the label is written into - * the package's customization pair. A shared view the console saved into the - * customization package, and the reader's own view, still offer the menu. - * - * A dotted view name cannot tell the two apart: every stored view is named - * `object.key`, the console's own saved views included. What tells them apart - * is the package the row was served under (`listViews()` carries the item's - * `_packageId`) and the server's `writable` verdict for that package, read from - * the session-held package list the Studio entries read (`fetchSessionPackages`). - * While that verdict is unknown the menu stays offered, as it was before: the - * server refuses the save and the pick is taken back. - * - * What runs: the real `ObjectView` on a stub data source. `ListView` is - * replaced by a stand-in that records the props it is handed, so the menu's - * presence is read as the `onColumnSummaryPick` the list receives (the grid - * draws the menu exactly when it has one, pinned in plugin-grid's - * `footerCalculationPicker-35702` tests). The package list is stubbed at - * `fetchSessionPackages`. - */ - -import * as React from 'react'; -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, cleanup, act, waitFor } 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 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 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'; - -const OBJECT = 'showcase_task'; -const SHIPPED_PACKAGE = 'com.example.showcase'; -const CUSTOM_PACKAGE = 'com.example.showcase.custom'; - -/** A view the read-only code package ships, as `listViews()` serves it. */ -const SHIPPED = { - name: `${OBJECT}.in_progress`, object: OBJECT, label: 'In progress', type: 'grid', - columns: ['name', 'amount'], _packageId: SHIPPED_PACKAGE, -}; -/** A shared view the console saved: dotted the same way, in the customization package. */ -const CUSTOM = { - name: `${OBJECT}.team_tasks`, object: OBJECT, label: 'Team tasks', type: 'grid', - columns: ['name', 'amount'], _packageId: CUSTOM_PACKAGE, -}; -/** A stored view bound to no package. */ -const UNBOUND = { name: `${OBJECT}.unbound`, object: OBJECT, label: 'Unbound', type: 'grid', columns: ['name', 'amount'] }; -/** The reader's own view (`sys_personal_view`). */ -const PERSONAL = { - id: 'pv_mine', user_id: 'u1', object_name: OBJECT, label: 'My tasks', - config: { type: 'grid', columns: ['name', 'amount'], data: { provider: 'object', object: OBJECT } }, -}; - -/** The packages row for each id: the server's `writable` verdict. */ -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 (resource: string) => - resource === 'sys_personal_view' ? { data: [PERSONAL], total: 1 } : { 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 () => [SHIPPED, CUSTOM, UNBOUND]), - updateView: vi.fn(async () => ({})), - }; - render( - - - - {}} - /> - } - /> - - - , - ); -} - -const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 300))); - -/** Whether the list is handed the footer's calculation pick. */ -const offersMenu = () => typeof listProps.current?.onColumnSummaryPick === 'function'; - -beforeEach(() => { - listProps.current = null; - packageList.answer = () => Promise.resolve(PACKAGES); - localStorage.clear(); -}); - -afterEach(() => { - cleanup(); -}); - -describe('objectstack#35933 — a read-only package\'s view offers no save of its own', () => { - it('a view a read-only package ships: no calculation menu; Rename stays (objectstack#35974)', async () => { - mount(SHIPPED.name); - await settle(); - await waitFor(() => expect(listProps.current).not.toBeNull()); - expect(offersMenu()).toBe(false); - // objectstack#35974 — the rename lands in the package's customization - // pair (`updateView`), so it is offered. - expect(typeof listProps.current?.onRenameView).toBe('function'); - }); - - it('a shared view saved into the customization package keeps the menu and Rename', async () => { - mount(CUSTOM.name); - await settle(); - await waitFor(() => expect(offersMenu()).toBe(true)); - expect(listProps.current?.columnSummaryPickFields).toEqual(['name', 'amount']); - expect(typeof listProps.current?.onRenameView).toBe('function'); - }); - - it('a stored view bound to no package keeps the menu', async () => { - mount(UNBOUND.name); - await settle(); - await waitFor(() => expect(offersMenu()).toBe(true)); - }); - - it('the reader\'s own view keeps the menu', async () => { - mount(PERSONAL.id); - await settle(); - await waitFor(() => expect(offersMenu()).toBe(true)); - }); - - it('while the package list is unread, the shipped view keeps the menu (the server still refuses)', async () => { - packageList.answer = () => new Promise(() => {}); - mount(SHIPPED.name); - await settle(); - await waitFor(() => expect(offersMenu()).toBe(true)); - }); - - it('a failed package-list read keeps the menu', async () => { - packageList.answer = () => Promise.reject(new Error('offline')); - mount(SHIPPED.name); - await settle(); - await waitFor(() => expect(offersMenu()).toBe(true)); - }); -}); diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index b4ce519a337..8b8dfff0b0a 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -9,9 +9,6 @@ * - ListView delegation for non-grid view types (kanban, calendar, chart, etc.) */ -import type { ColumnSummary } from '@objectstack/spec/ui'; -import type { ListColumn } from '@object-ui/types'; -import { columnsWithSummary, declaredColumnFields } from './columnSummaryWrite.js'; import { useMemo, useState, useCallback, useEffect, useRef, lazy, Suspense, type ReactNode } from 'react'; import { useParams, useSearchParams, useNavigate, useLocation, useHref, createSearchParams } from 'react-router-dom'; import { resolveAffordance, type FilterTokenScope, type SchemaLike } from '@object-ui/core'; @@ -60,10 +57,9 @@ import { ManagedUsersInviteLine } from './managedEnvironmentUsers.js'; import { importTargetFields } from './importTargetFields.js'; import { resolveViewId } from '../utils/resolveViewId.js'; import { usePhoneViewport } from '../hooks/usePhoneViewport.js'; -import { usePackageRefusesSaves } from '../hooks/useStudioDesignGate.js'; import { studioPackageId } from '../utils/appRoute.js'; import { LIST_PINNED_VIEW_PREFERENCE, objectPreferenceScope, useWorkspacePreference } from '../utils/workspacePreference.js'; -import { defaultListViewId, isSavedViewId, viewRowId } from '../utils/viewIdentity.js'; +import { defaultListViewId, viewRowId } from '../utils/viewIdentity.js'; import { useObjectActions } from '../hooks/useObjectActions.js'; import { useObjectTranslation, useObjectLabel } from '@object-ui/i18n'; import { usePermissions } from '@object-ui/permissions'; @@ -101,6 +97,7 @@ import { import { ObjectViewRecordOverlay } from './objectViewRecordOverlay.js'; import { useObjectViewListRenderer } from './objectViewListRenderer.js'; import { ListDraftActions } from './ListDraftActions.js'; +import { viewSaveRefusalText } from './viewSaveRefusal.js'; import { listDraftPreference, listDraftScope, useListDraft } from './listDraftStore.js'; import { useObjectViewViewCrud } from './objectViewViewCrud.js'; import { @@ -783,6 +780,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co url: { ...parseListStateParams(searchParams, acceptListField), filters: readPanelFilters() }, preference: draftPreferenceOf(activeView.id), panelFilters: viewPanelFilters, + summaries: listDraft.draft.summaries, }); if (!built.ok) { toast.error(t('form.saveError'), { description: t(FILTER_FOLD_REFUSAL_KEYS[built.reason]) }); @@ -798,7 +796,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co } 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), + description: viewSaveRefusalText(err, t), classNames: { description: 'whitespace-pre-line' }, }); } @@ -860,44 +858,6 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co activeViewId, baseView, }); - // objectstack#35702 — a footer pick saves the column's calculation and - // nothing else (L1 7048239634): the stored view's own columns are the - // base, so the reader's unsaved hides, order or added columns never ride - // along, and a column the view does not declare is not offered. Each - // resolves whether the pick was saved; on `false` the grid takes it back. - const personalViewRow = activeView ? personalViews.views.find((v) => v.id === activeView.id) : undefined; - // objectstack#35933 — the open saved shared view's own package (its row's - // served `_packageId`), and whether the server refuses saves into it: a - // view a read-only package ships is offered no save of its own. Read for - // an admin only, the one reader offered such a save; unknown offers it. - const activeSavedViewRow = activeView && isAdmin - ? savedViews.find((sv: any) => viewRowId(sv) === activeView.id) - : undefined; - const activeViewPackageRefusesSaves = usePackageRefusesSaves(studioPackageId(activeSavedViewRow)); - const handlePickPersonalViewSummary = async (field: string, summary: ColumnSummary | null): Promise => { - if (!personalViewRow) return false; - const columns = columnsWithSummary(personalViewRow.config.columns as ListColumn[] | string[] | undefined, field, summary); - if (!columns) return false; - try { - await personalViews.update(personalViewRow.id, { ...personalViewRow.config, columns }); - return true; - } catch (err) { - console.error('[ObjectView] Failed to save a footer calculation:', err); - toast.error(t('form.saveError'), { description: err instanceof Error ? err.message : String(err) }); - return false; - } - }; - const handlePickSharedViewSummary = async (field: string, summary: ColumnSummary | null): Promise => { - if (!activeView) return false; - const columns = columnsWithSummary(activeView.columns as ListColumn[] | string[] | undefined, field, summary); - if (!columns) return false; - const priorDraft = viewDraft; - const saved = await handleViewConfigSave({ ...activeView, columns }); - // The panel's save keeps a refused draft on screen (the panel stays - // dirty); a refused pick is taken back instead. - if (!saved) setViewDraft(priorDraft); - return saved; - }; // 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 @@ -971,6 +931,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co url: { ...parseListStateParams(searchParams, acceptListField), filters: readPanelFilters() }, preference: draftPreferenceOf(activeView.id), panelFilters: viewPanelFilters, + summaries: listDraft.draft.summaries, }, ); if (!built.ok) { @@ -986,7 +947,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co } 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), + description: viewSaveRefusalText(err, t), classNames: { description: 'whitespace-pre-line' }, }); return false; @@ -1112,6 +1073,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co url: { ...parseListStateParams(searchParams, acceptListField), filters: readPanelFilters() }, preference: draftPreferenceOf(activeView?.id), panelFilters: viewPanelFilters, + summaries: listDraft.draft.summaries, }), savePersonal: personalViews.save, openPersonal: openPersonalView, @@ -1229,31 +1191,12 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co : undefined, save: !isEnvironmentList && canUpdatePersonalView && listDraftParts.length > 0 ? () => { void handleSaveToPersonalView(); } : 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, - // by a reader who may edit it, as a draft through the view panel's - // save, which others see once published. - pickSummary: isEnvironmentList || !activeView - ? undefined - : activeIsPersonal - ? (canUpdatePersonalView && personalViewRow ? handlePickPersonalViewSummary : undefined) - // Only a view the metadata door stores (one the overlay - // read lists), never the fallback tab an object with no - // views is drawn with. Every stored view has a qualified, - // dotted name, the console's own saved views included - // (`object.key` in the custom package), so the name cannot - // tell a view a read-only package ships: its row's package - // does (objectstack#35933), and such a view is offered no - // menu. While that is unknown the menu stays; the door - // refuses that save by design (it goes to the custom - // package) and the refused pick is taken back, as the - // panel's save is. - : isAdmin && !activeViewPackageRefusesSaves && isSavedViewId(savedViews, String(activeView.id)) - ? handlePickSharedViewSummary - : undefined, - summaryPickFields: declaredColumnFields( - (activeIsPersonal ? personalViewRow?.config.columns : activeView?.columns) as ListColumn[] | string[] | undefined, - ), + // objectstack#36194 — the footer's calculation is a draft part on + // every list that holds a draft: it applies at once, writes + // nothing, and Save keeps it where the reader may save (the Save + // menu's own test; a view the reader cannot change in place offers + // 「Save as my view」 alone). + draftsSummaries: !isEnvironmentList && !!activeView, }, }); diff --git a/ui/packages/app-shell/src/views/__tests__/footerCalculationDraft-36194.test.ts b/ui/packages/app-shell/src/views/__tests__/footerCalculationDraft-36194.test.ts new file mode 100644 index 00000000000..bcaf67440ee --- /dev/null +++ b/ui/packages/app-shell/src/views/__tests__/footerCalculationDraft-36194.test.ts @@ -0,0 +1,100 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36194 + objectstack#36195 — the pure halves of the footer's + * calculations as a part of the list's draft, and of what a refused view save + * says: + * + * - `columnsWithSummaries` lays the draft's calculations over the columns the + * list draws and the body a save stores; `columnSummaryOf` reads a column's + * own calculation (the one a pick of it drops from the draft); + * - the draft store keeps the part, and an emptied part is no part; + * - `buildPersonalViewConfig` (「Save to this view」 on the reader's own view + * and 「Save as my view」) stores the calculations on the columns it keeps, + * in a body spec's closed `ListViewSchema` accepts; + * - `viewSaveRefusalText` says a package's view in the reader's words, never + * the door's English text. + */ + +import { beforeEach, describe, expect, it } from 'vitest'; +import { ListViewSchema } from '@objectstack/spec/ui'; +import { columnSummaryOf, columnsWithSummaries } from '../columnSummaryWrite'; +import { listDraftScope, patchListDraft, readListDraft, resetListDraftStoreForTests } from '../listDraftStore'; +import { buildPersonalViewConfig } from '../personalViews'; +import { viewSaveRefusalText } from '../viewSaveRefusal'; + +describe('columnsWithSummaries / columnSummaryOf (objectstack#36194)', () => { + it('lays each calculation on its column, the columns in the object form', () => { + expect(columnsWithSummaries(['name', 'amount', 'closed_at'], { amount: 'sum', closed_at: 'max' })).toEqual([ + { field: 'name' }, { field: 'amount', summary: 'sum' }, { field: 'closed_at', summary: 'max' }, + ]); + }); + it('None takes a column\'s own calculation off', () => { + expect(columnsWithSummaries([{ field: 'amount', summary: 'avg' }], { amount: null })).toEqual([{ field: 'amount' }]); + }); + it('a calculation on a field the columns do not hold is dropped; nothing to lay hands the same array back', () => { + const columns = ['name']; + expect(columnsWithSummaries(columns, { amount: 'sum' })).toBe(columns); + expect(columnsWithSummaries(columns, undefined)).toBe(columns); + expect(columnsWithSummaries(undefined, { amount: 'sum' })).toBeUndefined(); + }); + it('reads a column\'s own calculation in either spelling, else null', () => { + const columns = [{ field: 'a', summary: 'sum' as const }, { field: 'b', summary: { type: 'avg' as const } }, { field: 'c' }]; + expect(columnSummaryOf(columns, 'a')).toBe('sum'); + expect(columnSummaryOf(columns, 'b')).toBe('avg'); + expect(columnSummaryOf(columns, 'c')).toBeNull(); + expect(columnSummaryOf(['a'], 'a')).toBeNull(); + }); +}); + +describe('the draft store keeps the calculations (objectstack#36194)', () => { + beforeEach(() => resetListDraftStoreForTests()); + const scope = listDraftScope('u1', 'crm_deal', 'all'); + it('a pick is held; an emptied part is no part', () => { + patchListDraft(scope, { summaries: { amount: 'sum' } }); + expect(readListDraft(scope)).toEqual({ summaries: { amount: 'sum' } }); + patchListDraft(scope, { summaries: {} }); + expect(readListDraft(scope)).toEqual({}); + }); +}); + +describe('buildPersonalViewConfig stores the draft\'s calculations (objectstack#36194)', () => { + const VIEW = { id: 'all', type: 'grid', columns: ['name', 'amount', 'stage'], data: { provider: 'object', object: 'crm_deal' } }; + it('on the columns it keeps, the reader\'s added ones included, in a body spec accepts', () => { + const built = buildPersonalViewConfig('crm_deal', VIEW, { + url: {}, + preference: { addedFields: ['owner'], hiddenFields: ['stage'] }, + summaries: { amount: 'sum', owner: 'count_unique', stage: 'count' }, + }); + expect(built.ok).toBe(true); + if (!built.ok) return; + expect(built.config.columns).toEqual([ + { field: 'name' }, { field: 'amount', summary: 'sum' }, { field: 'owner', summary: 'count_unique' }, + ]); + expect(ListViewSchema.safeParse(built.config).success).toBe(true); + }); + it('with no calculation in the draft the columns are stored as before', () => { + const built = buildPersonalViewConfig('crm_deal', VIEW, { url: {} }); + expect(built.ok && built.config.columns).toEqual(['name', 'amount', 'stage']); + }); +}); + +describe('viewSaveRefusalText (objectstack#36195)', () => { + const t = (key: string) => `t:${key}`; + const refusal = (status: number, code?: string, message = "'view/crm_account.all_accounts' ships in 'app.objectstack.hotcrm': save it into …") => + Object.assign(new Error(message), { status, ...(code ? { code } : {}) }); + it('a view a package ships: the reader\'s sentence, never the door\'s text', () => { + expect(viewSaveRefusalText(refusal(403, 'NOT_OVERRIDABLE'), t)).toBe('t:console.objectView.saveRefused.packaged'); + }); + it('any other refusal keeps the door\'s own words, which name the reader\'s missing grant', () => { + expect(viewSaveRefusalText(refusal(403, 'PERMISSION_DENIED', 'Saving views requires the Manage Metadata permission'), t)) + .toBe('Saving views requires the Manage Metadata permission'); + }); + it('a refusal that lists field issues keeps the list', () => { + const err = Object.assign(new Error('1 issue'), { + status: 422, + issues: [{ path: 'columns.0.summary', message: 'Invalid enum value', userMessage: 'Pick a calculation this field offers' }], + }); + expect(viewSaveRefusalText(err, t)).toBe('• columns.0.summary — Pick a calculation this field offers'); + }); +}); diff --git a/ui/packages/app-shell/src/views/columnSummaryWrite.ts b/ui/packages/app-shell/src/views/columnSummaryWrite.ts index 346e243065b..e0e9aa13f3d 100644 --- a/ui/packages/app-shell/src/views/columnSummaryWrite.ts +++ b/ui/packages/app-shell/src/views/columnSummaryWrite.ts @@ -1,13 +1,15 @@ /** - * objectstack#35702 — a view's `columns` with one column's footer calculation - * set (`null` = None), as the list's footer menu saves it on the view. Only the - * calculation moves: the view's own columns are kept, in their order, each in - * the object form (`columns` is all names or all objects, never a mix, and only - * the object form carries `summary`). A column the view does not declare — a column the reader - * added for themselves, or any column of a view that declares none — is not - * the view's to change (L1 7048239634): the answer is `null` and nothing is - * saved, which is why the menu is offered on the declared columns only - * ({@link declaredColumnFields}). + * objectstack#35702 — `columns` with one column's footer calculation set + * (`null` = None). Only the calculation moves: the columns are kept, in their + * order, each in the object form (`columns` is all names or all objects, never + * a mix, and only the object form carries `summary`). A field that is not one + * of `columns` has no column to carry it: the answer is `null`. + * + * objectstack#36194 — a pick is a part of the list's DRAFT + * ({@link DraftColumnSummaries}), laid over the columns the list draws and over + * the body a save stores ({@link columnsWithSummaries}). The menu is offered on + * the columns that body carries ({@link declaredColumnFields} of the columns + * the list draws, the reader's added ones included). */ import type { ListColumn } from '@object-ui/types'; @@ -42,3 +44,43 @@ export function columnsWithSummary( return column; }); } + +/** + * objectstack#36194 — the footer calculations a list's DRAFT holds (column → + * calculation, `null` = None), as they are kept beside the draft's other parts. + */ +export type DraftColumnSummaries = Readonly>; + +/** The calculation a column entry declares, by type (`summary` is a type or `{ type, … }`), else `null`. */ +export function columnSummaryOf(authored: AuthoredColumns, field: string): ColumnSummary | null { + for (const entry of authored ?? []) { + if (typeof entry === 'string' || entry?.field !== field) continue; + const summary = (entry as { summary?: unknown }).summary; + if (typeof summary === 'string') return summary as ColumnSummary; + if (summary && typeof summary === 'object' && typeof (summary as { type?: unknown }).type === 'string') { + return (summary as { type: ColumnSummary }).type; + } + return null; + } + return null; +} + +/** + * objectstack#36194 — `columns` with the draft's calculations laid over them, + * each moved as {@link columnsWithSummary} moves one: the list draws them at + * once, and a save stores them in the body it builds. A calculation on a field + * that is not one of `columns` is dropped (the body has no column to carry + * it). With nothing to lay, `columns` comes back as it came, the same array. + */ +export function columnsWithSummaries( + columns: T, + summaries: DraftColumnSummaries | undefined, +): T | ListColumn[] { + if (!summaries || !columns) return columns; + let laid: AuthoredColumns | ListColumn[] = columns; + for (const [field, summary] of Object.entries(summaries)) { + const next = columnsWithSummary(laid, field, summary); + if (next) laid = next; + } + return laid as T | ListColumn[]; +} diff --git a/ui/packages/app-shell/src/views/listDraftStore.ts b/ui/packages/app-shell/src/views/listDraftStore.ts index a9439cf1e2d..dec491eed23 100644 --- a/ui/packages/app-shell/src/views/listDraftStore.ts +++ b/ui/packages/app-shell/src/views/listDraftStore.ts @@ -7,8 +7,9 @@ * (into the open view, or as a view of their own) or drops it with Discard. * * 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 + * search term, the columns shown (hidden ones, added ones), the column order, + * the footer's calculations (objectstack#36194) and (from PR 2) 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. * @@ -36,6 +37,7 @@ import { useCallback, useSyncExternalStore } from 'react'; import type { GroupingConfig } from '@objectstack/spec/ui'; +import type { DraftColumnSummaries } from './columnSummaryWrite.js'; import type { ListFilterGroupPreference, ListSortPreference, @@ -65,6 +67,12 @@ export interface ListDraft { * colours its rows. Written from PR 2 of objectstack#35955, as `viewType`. */ rowColor?: { field: string; colors?: Record } | null; + /** + * objectstack#36194 — the footer calculations the reader picked, by column + * (`null` = None over a column the view sums). Only the columns that differ + * from the view are held; picking the view's own again drops the column. + */ + summaries?: DraftColumnSummaries; } /** A patch: a part set to `undefined` is dropped back to the view's own. */ @@ -122,6 +130,9 @@ function normalizePart(key: string, value: unknown): unknown { const conditions = (value as { conditions?: unknown } | null | undefined)?.conditions; return Array.isArray(conditions) && conditions.length > 0 ? value : undefined; } + if (key === 'summaries') { + return value && typeof value === 'object' && Object.keys(value).length > 0 ? value : undefined; + } return value; } diff --git a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx index d7eff6f3479..4b7e6e523b5 100644 --- a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx +++ b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx @@ -12,12 +12,13 @@ import type { ColumnSummary } from '@objectstack/spec/ui'; import { useCallback, useLayoutEffect, useRef, useState, useSyncExternalStore, lazy, Suspense, type ReactNode } from 'react'; import { DENSITY_MODE_TO_ROW_HEIGHT, columnIdentity, normalizeListViewSchema, servedPackageId, type FilterTokenScope } from '@object-ui/core'; import { listDraftPreference, type useListDraft } from './listDraftStore.js'; +import { columnSummaryOf, columnsWithSummaries, declaredColumnFields } from './columnSummaryWrite.js'; import type { useObjectListPreferences, ListViewPreference, ListViewPreferencePatch } from '../context/ListPreferencesProvider.js'; const ObjectChart = lazy(() => import('@object-ui/plugin-charts').then((m) => ({ default: m.ObjectChart })), ); import { ListView, type ListToolbarTrailingState } from '@object-ui/plugin-list'; -import type { ListViewSchema, TreeViewConfig } from '@object-ui/types'; +import type { ListColumn, ListViewSchema, TreeViewConfig } from '@object-ui/types'; import type { FilterBuilderRowGroup } from '@object-ui/components'; import type { useAuth } from '@object-ui/auth'; import type { useActionTextLocalizer } from '@object-ui/react'; @@ -186,12 +187,11 @@ export function useObjectViewListRenderer({ save?: () => void; reset?: () => void; /** - * objectstack#35702 — save a footer calculation on the open view (wired - * only for a reader who may change it); resolves whether it was saved. + * objectstack#36194 — the footer's calculation picks go into the list's + * draft (`summaries`), on every column the saved body would carry: + * set where the list holds a draft. Nothing a pick does writes. */ - pickSummary?: (field: string, summary: ColumnSummary | null) => boolean | Promise; - /** objectstack#35702 — the columns the view declares: the only ones a pick may change. */ - summaryPickFields?: readonly string[]; + draftsSummaries?: boolean; }; }) { // objectstack#35551 — the host hands fresh closures every render; the list @@ -201,9 +201,7 @@ export function useObjectViewListRenderer({ const offersRename = !!listViewActions?.rename; const offersSave = !!listViewActions?.save; const offersReset = !!listViewActions?.reset; - const offersSummaryPick = !!listViewActions?.pickSummary; - // Keyed on content, never the array's identity (a fresh one every render). - const summaryPickKey = (listViewActions?.summaryPickFields ?? []).join('\n'); + const offersSummaryPick = !!listViewActions?.draftsSummaries; // 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(); @@ -553,6 +551,25 @@ export function useObjectViewListRenderer({ listSchema.columns, addedFieldsStored ? viewPref?.addedFields : undefined, ); + /** + * objectstack#36194 — the footer's calculations are part of the draft + * too: a pick applies at once (the columns the list draws carry it) + * and is written nowhere; Discard drops it, Save keeps it. The menu is + * offered on the columns a saved body carries (the columns the list + * draws, the reader's added ones included), the only columns the draft + * can carry a calculation on. A pick of the view's own calculation + * drops the column from the draft. + */ + const summaryColumns = columnsWithSummaries(listColumns.columns as ListColumn[] | string[] | undefined, listDraft.draft.summaries) as ListViewSchema['columns']; + const summaryPickFields = offersSummaryPick + ? declaredColumnFields(listColumns.columns as ListColumn[] | string[] | undefined) + : undefined; + const pickDraftSummary = (field: string, summary: ColumnSummary | null): boolean => { + const own = columnSummaryOf(listColumns.columns as ListColumn[] | string[] | undefined, field); + const { [field]: _replaced, ...rest } = listDraft.draft.summaries ?? {}; + listDraft.patch({ summaries: (summary ?? null) === own ? rest : { ...rest, [field]: summary ?? null } }); + return true; + }; const persistAddedFields = (added: string[]) => { listDraft.patch({ addedFields: added.length > 0 ? added : undefined }); }; @@ -638,7 +655,9 @@ export function useObjectViewListRenderer({ // new object documents of equal content: hold it like the blocks. // objectstack#30077 — plus the fields this user added (see // `withAddedListColumns`). - columns: holdBlock('columns', listColumns.columns), + // objectstack#36194 — and the footer calculations the draft holds, + // drawn at once (`summaryColumns`). + columns: holdBlock('columns', summaryColumns), // objectui#10035 — the refresh signal, in place of the remount the // key used to force. The spread above carries only the plugin // ObjectView's counter; this page's own counter (actions, import, @@ -1092,10 +1111,8 @@ export function useObjectViewListRenderer({ onRenameView={offersRename ? (label: string) => listViewActionsRef.current?.rename?.(label) ?? false : undefined} onSaveView={offersSave ? () => listViewActionsRef.current?.save?.() : undefined} onResetView={offersReset ? () => listViewActionsRef.current?.reset?.() : undefined} - onColumnSummaryPick={offersSummaryPick - ? (field: string, summary: ColumnSummary | null) => listViewActionsRef.current?.pickSummary?.(field, summary) ?? false - : undefined} - columnSummaryPickFields={offersSummaryPick ? summaryPickKey.split('\n').filter(Boolean) : undefined} + onColumnSummaryPick={summaryPickFields && summaryPickFields.length > 0 ? pickDraftSummary : undefined} + columnSummaryPickFields={summaryPickFields} className={className} onEdit={editHandler} // objectui#13089 — the view's Add button is the header New: @@ -1203,7 +1220,7 @@ export function useObjectViewListRenderer({ dataSource={ds} /> ); - }, [hasViewBarTrailing, trailStore, rowEndStore, activeView, activeViewDeclaresColumns, activeViewIsSaved, objectDef, objectName, refreshKey, createRecord, urlFilters, initialUfSelections, handleUserFilterSelectionsChange, writeListUrlState, listPage, user?.id, pageOffersCreate, listAddRecordOpensCreate, listIdentityKey, listPrefs.ready, listPrefs.preference, listPrefs.patchView, listDraft.draft, listDraft.patch, managedUsers, managedUserMarker, openInPanel, rowOpensRecord, handleListRowsChange, handleListTotalChange, hasPhoneTitle, leadStore, wideViewport, handleListPersonalizationChange, workspaceTimeZone, viewPanelFilters, offersRename, offersSave, offersReset, offersSummaryPick, summaryPickKey, previewDrafts, previewDataSource, unpublishedObjects]); + }, [hasViewBarTrailing, trailStore, rowEndStore, activeView, activeViewDeclaresColumns, activeViewIsSaved, objectDef, objectName, refreshKey, createRecord, urlFilters, initialUfSelections, handleUserFilterSelectionsChange, writeListUrlState, listPage, user?.id, pageOffersCreate, listAddRecordOpensCreate, listIdentityKey, listPrefs.ready, listPrefs.preference, listPrefs.patchView, listDraft.draft, listDraft.patch, managedUsers, managedUserMarker, openInPanel, rowOpensRecord, handleListRowsChange, handleListTotalChange, hasPhoneTitle, leadStore, wideViewport, handleListPersonalizationChange, workspaceTimeZone, viewPanelFilters, offersRename, offersSave, offersReset, offersSummaryPick, previewDrafts, previewDataSource, unpublishedObjects]); return { renderListView }; } diff --git a/ui/packages/app-shell/src/views/objectViewListUrlState.ts b/ui/packages/app-shell/src/views/objectViewListUrlState.ts index 4708e60e451..cbd935286ba 100644 --- a/ui/packages/app-shell/src/views/objectViewListUrlState.ts +++ b/ui/packages/app-shell/src/views/objectViewListUrlState.ts @@ -385,6 +385,11 @@ export function useObjectViewListUrlState({ if ((listDraft.columnOrder || listDraft.addedFields?.length) && !listDraftParts.includes('columns')) { listDraftParts.push('columns'); } + // objectstack#36194 — so are the footer's calculations: one part, however + // many columns it holds. + if (listDraft.summaries && Object.keys(listDraft.summaries).length > 0) { + listDraftParts.push('summaries'); + } /** * objectstack#35955 — Discard (objectstack#28950's "Reset to view" before diff --git a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx index bac5e656520..e1acdf8b3aa 100644 --- a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx +++ b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx @@ -11,6 +11,7 @@ import { useCallback, useEffect, useMemo, useRef, type Dispatch, type SetStateAction } from 'react'; import { useParams, type useNavigate } from 'react-router-dom'; import { formatMetadataError } from '@object-ui/data-objectstack'; +import { viewSaveRefusalText } from './viewSaveRefusal.js'; import { toast } from 'sonner'; import type { useObjectTranslation } from '@object-ui/i18n'; import type { useObjectListPreferences } from '../context/ListPreferencesProvider.js'; @@ -159,10 +160,12 @@ export function useObjectViewViewCrud({ return true; } catch (err) { console.error('[ViewConfigPanel] Failed to persist view config:', err); - // objectui#11583: a refused save is SAID, with the door's own - // message, as the Create View doors do (objectui#11578). + // objectui#11583: a refused save is SAID, as the Create View doors + // do (objectui#11578), with the door's own message; + // objectstack#36195: a package's view in the reader's words + // (`viewSaveRefusalText`). toast.error(t('form.saveError'), { - description: formatMetadataError(err), + description: viewSaveRefusalText(err, t), classNames: { description: 'whitespace-pre-line' }, }); return false; @@ -258,7 +261,7 @@ export function useObjectViewViewCrud({ // message (the field-anchored issues of a 422, or the refusal's // text), and reported to the dialog as unsaved so it stays open. toast.error(t('form.saveError'), { - description: formatMetadataError(err), + description: viewSaveRefusalText(err, t), classNames: { description: 'whitespace-pre-line' }, }); return false; @@ -330,7 +333,7 @@ export function useObjectViewViewCrud({ // message, through the channel objectui#11583 gave the view saves // and objectui#12398 gave Delete view. toast.error(t('objectViewActions.renameFailed'), { - description: formatMetadataError(err), + description: viewSaveRefusalText(err, t), classNames: { description: 'whitespace-pre-line' }, }); } @@ -390,7 +393,7 @@ export function useObjectViewViewCrud({ console.error('[ViewTabBar] Failed to pin view:', err); // objectui#11583: a refused pin is said, with the door's message. toast.error(t('form.saveError'), { - description: formatMetadataError(err), + description: viewSaveRefusalText(err, t), classNames: { description: 'whitespace-pre-line' }, }); } @@ -424,7 +427,7 @@ export function useObjectViewViewCrud({ console.error('[ViewTabBar] Failed to set default view:', err); // objectui#11583: said like its siblings, with the door's message. toast.error(t('form.saveError'), { - description: formatMetadataError(err), + description: viewSaveRefusalText(err, t), classNames: { description: 'whitespace-pre-line' }, }); } @@ -553,7 +556,7 @@ export function useCreateViewInPlace({ } 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), + description: viewSaveRefusalText(err, t), classNames: { description: 'whitespace-pre-line' }, }); return false; diff --git a/ui/packages/app-shell/src/views/personalViews.ts b/ui/packages/app-shell/src/views/personalViews.ts index 31f28e5901a..91c0305c22a 100644 --- a/ui/packages/app-shell/src/views/personalViews.ts +++ b/ui/packages/app-shell/src/views/personalViews.ts @@ -34,9 +34,10 @@ import { createAuthenticatedFetch } from '@object-ui/auth'; import type { FilterBuilderRowGroup } from '@object-ui/components'; import { builderRulesOfSpecFilter } from '@object-ui/core'; import type { usePermissions } from '@object-ui/permissions'; -import type { DataSource } from '@object-ui/types'; +import type { DataSource, ListColumn } from '@object-ui/types'; import { foldFilterGroupToSpecRules, type FilterFoldRefusal } from './viewFilterFold.js'; import { buildViewConfigSaveBody } from './objectViewTabs.js'; +import { columnsWithSummaries, type DraftColumnSummaries } from './columnSummaryWrite.js'; import type { ListSortRule, ListUrlState } from './userFilterUrlState.js'; import type { ListViewPreference } from '../context/ListPreferencesProvider.js'; @@ -171,6 +172,11 @@ export interface PersonalViewListState { * the view's conditions included, and is not laid over them a second time. */ panelFilters?: FilterBuilderRowGroup; + /** + * objectstack#36194 — the footer calculations the list's draft holds, laid + * over the saved columns ({@link columnsWithSummaries}). + */ + summaries?: DraftColumnSummaries; } /** The column a `columns` entry names: a bare name, or an entry's `field`. */ @@ -194,7 +200,8 @@ function columnName(column: unknown): string | undefined { * the view's own. * - **columns**: the view's and the ones the reader added, in the reader's * dragged order, without the columns they hid (so `hiddenFields` and - * `fieldOrder` are applied, not carried). **rowHeight**: the reader's density, else the view's. + * `fieldOrder` are applied, not carried), with the footer calculations the + * draft holds (objectstack#36194). **rowHeight**: the reader's density, else the view's. * * The body is narrowed to the keys spec's closed `ListViewSchema` declares and * bound to this object (`config.data.object`) by `buildViewConfigSaveBody`, @@ -241,6 +248,9 @@ export function buildPersonalViewConfig( .map(({ c }) => c); } columns = columns.filter((c) => !hidden.has(columnName(c) ?? '')); + // objectstack#36194 — and the footer calculations the reader picked, on + // the columns the body keeps. + columns = columnsWithSummaries(columns as Array, state.summaries); } const sort: ListSortRule[] | undefined = state.url.sort ?? view.sort; diff --git a/ui/packages/app-shell/src/views/viewSaveRefusal.ts b/ui/packages/app-shell/src/views/viewSaveRefusal.ts new file mode 100644 index 00000000000..7c88603f23b --- /dev/null +++ b/ui/packages/app-shell/src/views/viewSaveRefusal.ts @@ -0,0 +1,30 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36195 — what a list says when the server refuses to save a view + * an app package ships. + * + * That refusal, `NOT_OVERRIDABLE` (the metadata door's close on an item a + * package ships, `protocol-packaged-base-refusal.ts`), is written for a + * developer: in English, naming the package, the customization pair, the ADR + * and a command (`'view/…' ships in '…': save it into '….custom' …`). A reader + * saving a list gets their own sentence instead: the view comes with an app + * package and cannot be changed directly; it can be saved as their own view. + * The door's text goes to the console, where the caller already logs the + * error. + * + * Every other refusal is said as before (`formatMetadataError`): a list of + * field-anchored issues, else the door's message, which the view-write doors + * word for the person saving (objectui#11583, objectui#12417). + */ + +import { formatMetadataError } from '@object-ui/data-objectstack'; + +type Translate = (key: string) => string; + +/** The toast description for a refused view save. */ +export function viewSaveRefusalText(err: unknown, t: Translate): string { + const code = err && typeof err === 'object' ? (err as { code?: unknown }).code : undefined; + if (code === 'NOT_OVERRIDABLE') return t('console.objectView.saveRefused.packaged'); + return formatMetadataError(err); +} diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 58f4d20e37f..36166eb98ff 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -2994,11 +2994,15 @@ const ar = { grouping: "التجميع", columns: "ترتيب الأعمدة", hiddenFields: "الحقول المخفية", + summaries: "العمليات الحسابية", density: "الكثافة", layout: "التخطيط", rowColor: "لون الصف", inlineEdit: "التحرير المضمّن", }, + saveRefused: { + packaged: "هذا العرض يأتي مع حزمة تطبيق ولا يمكن تغييره مباشرة. يمكنك حفظه كعرض خاص بك.", + }, cannotDeleteMetaView: "هذا عرض مدمج معرَّف في الكود — لا يمكن حذفه.", expandToPage: "فتح كصفحة كاملة", openInSidePanel: "فتح في اللوحة الجانبية", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index ccf10ab9582..c5ad6043aa2 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -2706,11 +2706,15 @@ const de = { grouping: "Gruppierung", columns: "Spaltenanordnung", hiddenFields: "Ausgeblendete Felder", + summaries: "Berechnungen", density: "Dichte", layout: "Layout", rowColor: "Zeilenfarbe", inlineEdit: "Inline-Bearbeitung", }, + saveRefused: { + packaged: "Diese Ansicht gehört zu einem App-Paket und kann nicht direkt geändert werden. Sie können sie als eigene Ansicht speichern.", + }, cannotDeleteMetaView: "Diese Ansicht ist integriert und im Code definiert – sie kann nicht gelöscht werden.", expandToPage: "Als ganze Seite öffnen", openInSidePanel: "Im Seitenbereich öffnen", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index c1a53af99c0..c37e013426b 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -3303,11 +3303,15 @@ const en = { grouping: 'Grouping', columns: 'Column layout', hiddenFields: 'Hidden fields', + summaries: 'Calculations', density: 'Density', layout: 'Layout', rowColor: 'Row color', inlineEdit: 'Inline editing', }, + saveRefused: { + packaged: 'This view comes with an app package and can’t be changed directly. You can save it as your own view.', + }, cannotDeleteMetaView: 'This view is built in and defined in code — it cannot be deleted.', expandToPage: 'Open as full page', openInSidePanel: 'Open in side panel', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 7020c607946..0ed6f4d9891 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -2780,11 +2780,15 @@ const es = { grouping: "Agrupación", columns: "Disposición de columnas", hiddenFields: "Campos ocultos", + summaries: "Cálculos", density: "Densidad", layout: "Diseño", rowColor: "Color de fila", inlineEdit: "Edición en línea", }, + saveRefused: { + packaged: "Esta vista viene con un paquete de aplicación y no se puede cambiar directamente. Puedes guardarla como tu propia vista.", + }, cannotDeleteMetaView: "Esta vista está integrada y definida en el código: no se puede eliminar.", expandToPage: "Abrir como página completa", openInSidePanel: "Abrir en el panel lateral", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index a6c8de9becc..ba6414c678a 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -2776,11 +2776,15 @@ const fr = { grouping: "Regroupement", columns: "Disposition des colonnes", hiddenFields: "Champs masqués", + summaries: "Calculs", density: "Densité", layout: "Disposition", rowColor: "Couleur de ligne", inlineEdit: "Édition en ligne", }, + saveRefused: { + packaged: "Cette vue est fournie par un package d’application et ne peut pas être modifiée directement. Vous pouvez l’enregistrer comme votre propre vue.", + }, cannotDeleteMetaView: "Cette vue est intégrée et définie dans le code — elle ne peut pas être supprimée.", expandToPage: "Ouvrir en pleine page", openInSidePanel: "Ouvrir dans le panneau latéral", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 5198fe0fe10..61878ae6bc5 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -2708,11 +2708,15 @@ const ja = { grouping: "グループ", columns: "列の配置", hiddenFields: "非表示フィールド", + summaries: "集計", density: "密度", layout: "レイアウト", rowColor: "行の色", inlineEdit: "インライン編集", }, + saveRefused: { + packaged: "このビューはアプリパッケージに含まれているため、直接変更できません。自分のビューとして保存できます。", + }, cannotDeleteMetaView: "このビューはコードで定義された組み込みビューのため、削除できません。", expandToPage: "フルページで開く", openInSidePanel: "サイドパネルで開く", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 6e6e09d71a9..08a66668e35 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -2706,11 +2706,15 @@ const ko = { grouping: "그룹", columns: "열 배치", hiddenFields: "숨긴 필드", + summaries: "계산", density: "밀도", layout: "레이아웃", rowColor: "행 색상", inlineEdit: "인라인 편집", }, + saveRefused: { + packaged: "이 보기는 앱 패키지에 포함되어 있어 직접 변경할 수 없습니다. 내 보기로 저장할 수 있습니다.", + }, cannotDeleteMetaView: "이 보기는 코드에 정의된 기본 제공 보기이므로 삭제할 수 없습니다.", expandToPage: "전체 페이지로 열기", openInSidePanel: "사이드 패널에서 열기", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index a4ef5a2bbb2..665249a1419 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -2775,11 +2775,15 @@ const pt = { grouping: "Agrupamento", columns: "Disposição das colunas", hiddenFields: "Campos ocultos", + summaries: "Cálculos", density: "Densidade", layout: "Layout", rowColor: "Cor da linha", inlineEdit: "Edição em linha", }, + saveRefused: { + packaged: "Esta visualização vem de um pacote de aplicativo e não pode ser alterada diretamente. Você pode salvá-la como sua própria visualização.", + }, cannotDeleteMetaView: "Esta exibição é integrada e definida no código — não é possível excluí-la.", expandToPage: "Abrir como página inteira", openInSidePanel: "Abrir no painel lateral", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 5f3b652b17f..f8a59f7b44b 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -2856,11 +2856,15 @@ const ru = { grouping: "Группировка", columns: "Расположение столбцов", hiddenFields: "Скрытые поля", + summaries: "Вычисления", density: "Плотность", layout: "Макет", rowColor: "Цвет строк", inlineEdit: "Встроенное редактирование", }, + saveRefused: { + packaged: "Это представление входит в пакет приложения, и его нельзя изменить напрямую. Его можно сохранить как своё представление.", + }, cannotDeleteMetaView: "Это встроенное представление, определённое в коде, — удалить его нельзя.", expandToPage: "Открыть на всю страницу", openInSidePanel: "Открыть в боковой панели", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 5329fb456b3..45aa977d16a 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -2793,11 +2793,15 @@ const zh = { grouping: '分组', columns: '列布局', hiddenFields: '隐藏字段', + summaries: '统计', density: '密度', layout: '布局', rowColor: '行颜色', inlineEdit: '行内编辑', }, + saveRefused: { + packaged: '这个视图来自应用包,不能直接修改,可以另存为我的视图。', + }, cannotDeleteMetaView: '该视图为内置视图,由代码定义,无法删除。', expandToPage: '整页打开', openInSidePanel: '在侧边打开', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 41c49ce39d1..71f394a4d3d 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -2793,11 +2793,15 @@ const zhHant = { grouping: '分組', columns: '列布局', hiddenFields: '隱藏欄位', + summaries: '統計', density: '密度', layout: '佈局', rowColor: '行顏色', inlineEdit: '行內編輯', }, + saveRefused: { + packaged: '這個檢視來自應用包,不能直接修改,可以另存為我的檢視。', + }, cannotDeleteMetaView: '該檢視為內建檢視,由程式碼定義,無法刪除。', expandToPage: '整頁開啟', openInSidePanel: '在側邊開啟', diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index c77ab8cbaf4..dd85ad40cd2 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -269,17 +269,17 @@ export interface ObjectGridComponentProps extends ObjectGridExternalPaginationPr */ summaryRowLead?: (count: number) => React.ReactNode; /** - * [objectstack#35702] Wired only for a reader who may change the view: each - * footer cell becomes the menu that picks the column's calculation (`null` = - * None). The grid draws the pick at once; the host saves it on the view and - * hands it back as the column's `summary`. A host that answers `false` + * [objectstack#35702] Each footer cell becomes the menu that picks the + * column's calculation (`null` = None). The grid draws the pick at once; the + * host keeps it (on the view, or in a draft, objectstack#36194) and hands it + * back as the column's `summary`. A host that answers `false` * (or a promise of it, or one that rejects) did not save it, and the grid * takes the pick back. */ onColumnSummaryPick?: (field: string, summary: ColumnSummaryType | null) => void | boolean | Promise; /** * [objectstack#35702] The fields whose calculation `onColumnSummaryPick` can - * save (the columns the view itself declares); every other footer cell draws + * keep (the columns a saved view would carry); every other footer cell draws * its figure with no menu. Absent ⇒ every field column is offered. */ summaryPickFields?: readonly string[]; diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 65f8beee39e..1d2aaffcf00 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -397,17 +397,17 @@ export interface ListViewProps { onColumnStateChange?: (state: { order?: string[]; widths?: Record }) => void; /** * objectstack#35702 — the grid's footer calculation picked by the reader - * (`null` = None). Wired only for a reader who may change the open view; - * absent ⇒ the footer draws its figures and offers no menu. The host saves - * the pick as the column's `summary` on the view and resolves whether it - * did; on `false` the grid takes the pick back. A HOST prop, never a schema - * key. + * (`null` = None). Absent ⇒ the footer draws its figures and offers no + * menu. The host keeps the pick as the column's `summary` (on the view, or + * in an unsaved draft it hands back in `columns`, objectstack#36194) and + * resolves whether it did; on `false` the grid takes the pick back. A HOST + * prop, never a schema key. */ onColumnSummaryPick?: (field: string, summary: ColumnSummary | null) => void | boolean | Promise; /** - * objectstack#35702 — the fields whose calculation the host can save (the - * columns the open view itself declares); the menu is offered on those - * only. Absent ⇒ every field column. A HOST prop, never a schema key. + * objectstack#35702 — the fields whose calculation the host can keep (the + * columns a saved view would carry); the menu is offered on those only. + * Absent ⇒ every field column. A HOST prop, never a schema key. */ columnSummaryPickFields?: readonly string[]; /**