diff --git a/.changeset/35974-read-only-package-view-panel.md b/.changeset/35974-read-only-package-view-panel.md new file mode 100644 index 00000000000..35f61ce3aca --- /dev/null +++ b/.changeset/35974-read-only-package-view-panel.md @@ -0,0 +1,22 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/console': patch +'@object-ui/plugin-view': patch +'@object-ui/i18n': patch +--- + +fix(ui): a view a read-only package ships hides only Delete in Manage views and opens its view panel read-only + +Clause-②: yes (widening) +Metadata-protocol: none + +This applies to a list view that ships inside a read-only package (a code or installed package). The console no longer offers that view the two writes the server refuses: + +- Manage views hides Delete on its row. +- The row's configuration entry reads "View config". It opens the admin's view panel read-only: the configuration is shown read-only, no edit reaches the list, and there is nothing to save. The panel has no Save, no draft bar to publish or discard, and only Close. + +Rename, pin and set as default stay offered. They land in that package's customization (the console creates it on first use), so no lock icon is drawn on the row. The list's options menu offers Rename on such a view again. A shared view the console saved into the customization package, and the reader's own view, are unchanged. The toolbar's personal list changes keep saving to the reader's preferences. + +`@object-ui/plugin-view`: `ViewTabItem` gains an optional `definitionReadonly` field. When it is `true`, `ManageViewsDialog` hides Delete and labels the configuration entry "View config" (`view.showViewConfig`, a new key in every locale of `@object-ui/i18n`). Rename, pin, set as default and the configuration entry stay. `readonly` still wins when both are set. Without the field a row behaves as before. `ViewTabBar` does not read it. + +The read-only verdict is the one the footer calculation menu already uses. The console takes the package the view row was served under and reads the server's `writable` verdict for it from the package list it holds for the session. While that list is unread, or when the read fails or does not name the package, everything stays offered as before and the server's refusal still applies. The view panel reads the same answer that drew the Manage views row, so a row's "View config" never opens an editable panel. If the answer arrives after the admin has started editing, the panel turns read-only and discards the edit: the list's preview goes back to the stored view. diff --git a/ui/packages/app-shell/src/hooks/useStudioDesignGate.ts b/ui/packages/app-shell/src/hooks/useStudioDesignGate.ts index efcbf70cdb9..07103b53585 100644 --- a/ui/packages/app-shell/src/hooks/useStudioDesignGate.ts +++ b/ui/packages/app-shell/src/hooks/useStudioDesignGate.ts @@ -77,7 +77,7 @@ * @module */ -import { useEffect, useState } from 'react'; +import { useEffect, useMemo, useState } from 'react'; import { useAuth, useWorkspaceAdminStatus } from '@object-ui/auth'; import { useCanAuthorMetadata } from './useCanAuthorMetadata.js'; import { fetchSessionPackages, type PkgEntry } from '../views/studio-design/packages-io.js'; @@ -207,3 +207,57 @@ export function useStudioDesignGate(path: string | null | undefined): string | n export function usePackageRefusesSaves(packageId: string | null): boolean { return usePackagePosture(packageId) === 'view'; } + +const NO_REFUSING_PACKAGES: ReadonlySet = new Set(); + +/** + * objectstack#35974 — {@link usePackageRefusesSaves} for a list of packages + * at once, for a surface that draws one row per view (Manage views): the ids + * among `packageIds` the package list carries as read-only. The same + * `writable` verdict, the same session-held read (`fetchSessionPackages`: at + * most one `GET /api/v1/packages` per new package id per session, concurrent + * asks sharing it) and the same fail-open: an id still being read, an + * id whose read failed and an id the list leaves out are not in the answer, so + * that row keeps what it offered before this read. + * + * Keyed on the ids themselves, never on the array's identity: callers may hand + * a fresh array each render. Each id's answer is kept for the session as it + * lands, so a change to the list of ids (a refetch that brings a view of a new + * package) never takes back what is already known: a surface reading this + * while open, such as the view panel, cannot flip back to savable. + */ +export function usePackagesRefusingSaves(packageIds: readonly string[]): ReadonlySet { + const session = usePackageListSession(); + const key = JSON.stringify([...new Set(packageIds)].sort()); + const [answers, setAnswers] = useState<{ + session: string; + refuses: ReadonlyMap; + } | null>(null); + useEffect(() => { + const ids = JSON.parse(key) as string[]; + let cancelled = false; + for (const id of ids) { + fetchSessionPackages(session, id).then((list) => { + if (cancelled) return; + const refuses = packageStudioPosture(list, id) === 'view'; + setAnswers((prev) => { + const known = prev && prev.session === session ? prev.refuses : new Map(); + if (known.get(id) === refuses) return prev; + const next = new Map(known); + next.set(id, refuses); + return { session, refuses: next }; + }); + }, () => { + // A failed read answers nothing: the id keeps what it offered. + }); + } + return () => { + cancelled = true; + }; + }, [key, session]); + return useMemo(() => { + if (!answers || answers.session !== session) return NO_REFUSING_PACKAGES; + const refusing = (JSON.parse(key) as string[]).filter((id) => answers.refuses.get(id) === true); + return refusing.length === 0 ? NO_REFUSING_PACKAGES : new Set(refusing); + }, [answers, key, session]); +} 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 index caa7c0ac37b..973b4904547 100644 --- a/ui/packages/app-shell/src/views/ObjectView.readOnlyPackageView-35933.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.readOnlyPackageView-35933.test.tsx @@ -2,8 +2,9 @@ /** * objectstack#35933 — a view a read-only package ships offers an admin no save - * of its own: no footer calculation menu (objectstack#35702) and no Rename in - * the list's options menu. A shared view the console saved into the + * 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 @@ -176,12 +177,14 @@ afterEach(() => { }); 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, no Rename', async () => { + 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); - expect(listProps.current?.onRenameView).toBeUndefined(); + // 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 () => { diff --git a/ui/packages/app-shell/src/views/ObjectView.readOnlyPackageViewSaves-35974.test.tsx b/ui/packages/app-shell/src/views/ObjectView.readOnlyPackageViewSaves-35974.test.tsx new file mode 100644 index 00000000000..3923624e214 --- /dev/null +++ b/ui/packages/app-shell/src/views/ObjectView.readOnlyPackageViewSaves-35974.test.tsx @@ -0,0 +1,342 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#35974 (ruling record 7058654416) — on a list view a read-only + * package ships, Manage views hides only Delete and offers its configuration + * as "View config", which opens the panel read-only (no Save): the server + * refuses that view's delete and its panel save. Rename, pin and set as + * default stay: `updateView` writes them into the package's customization + * pair. A shared view the console saved into the customization package and + * the reader's own view are unchanged, and while the package's `writable` + * verdict is unknown (unread, failed read) everything stays offered as before. + * + * The verdict is objectstack#35933's: the package the row was served under + * (`listViews()` carries `_packageId`) and the session-held package list + * (`fetchSessionPackages`), stubbed here. The panel's read-only verdict is + * the very answer that drew the row (`usePackagesRefusingSaves`), so the two + * cannot disagree, and that answer is kept per package as it lands. + * + * What runs: the real `ObjectView` on a stub data source. `ListView` is a + * stand-in (the list itself is not under test). The real `ManageViewsDialog` + * renders, held open, so the row affordances are read from the DOM, and its + * "View config" entry is clicked through to the panel. The view panel is a + * stand-in recording the props it is handed: its own read-only face is pinned + * in `ViewConfigPanel.test.tsx`. + */ + +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' } }), + // Manage views and the view panel 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 })); + +vi.mock('@object-ui/plugin-list', async (importOriginal) => ({ + ...(await importOriginal()), + ListView: () => null, +})); + +// The real dialog, held open: the host opens it from the title switcher. +vi.mock('@object-ui/plugin-view', async (importOriginal) => { + const actual = await importOriginal(); + const Dialog = actual.ManageViewsDialog; + return { + ...actual, + ManageViewsDialog: (props: React.ComponentProps) => ( + {}} /> + ), + }; +}); + +/** The props the view panel was last handed, and every render's, in order. */ +const panelProps = vi.hoisted(() => ({ current: null as Record | null, renders: [] as Record[] })); +vi.mock('./ViewConfigPanel', () => ({ + ViewConfigPanel: (props: any) => { + panelProps.current = props; + panelProps.renders.push(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'; +import { usePackagesRefusingSaves } from '../hooks/useStudioDesignGate'; + +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, +}; +/** 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]), + updateView: vi.fn(async () => ({})), + }; + render( + + + + {}} + /> + } + /> + + + , + ); +} + +const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 300))); + +/** The row's own affordances (pin, set default star, lock) and its `…` menu's entries, read by opening it. */ +async function rowOffers(id: string) { + const row = { + pin: screen.queryByTestId(`manage-views-pin-${id}`) !== null, + setDefault: screen.queryByTestId(`manage-views-default-${id}`) !== null, + lock: screen.queryByTestId(`manage-views-readonly-${id}`) !== null, + }; + const trigger = screen.getByTestId(`manage-views-actions-${id}`); + fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false }); + fireEvent.click(trigger); + await waitFor(() => expect(screen.getByRole('menu')).toBeTruthy()); + const entries = ['rename', 'config', 'default', 'pin', 'delete'] + .filter((key) => screen.queryByTestId(`manage-views-action-${key}-${id}`) !== null); + const configLabel = screen.queryByTestId(`manage-views-action-config-${id}`)?.textContent?.trim() ?? null; + fireEvent.keyDown(screen.getByRole('menu'), { key: 'Escape' }); + await waitFor(() => expect(screen.queryByRole('menu')).toBeNull()); + return { ...row, entries, configLabel }; +} + +/** A row as every savable view is offered: everything, Delete included, "Edit view config". */ +const OFFERED = { + pin: true, setDefault: true, lock: false, + entries: ['rename', 'config', 'default', 'pin', 'delete'], configLabel: 'Edit view config', +}; +/** A factory row of a read-only package: everything but Delete, "View config", no lock. */ +const FACTORY_OFFERS = { + pin: true, setDefault: true, lock: false, + entries: ['rename', 'config', 'default', 'pin'], configLabel: 'View config', +}; + +/** Open a row's `…` and click its configuration entry. */ +async function clickConfig(id: string) { + const trigger = await waitFor(() => screen.getByTestId(`manage-views-actions-${id}`)); + fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false }); + fireEvent.click(trigger); + fireEvent.click(await waitFor(() => screen.getByTestId(`manage-views-action-config-${id}`))); +} + +beforeEach(() => { + panelProps.current = null; + panelProps.renders = []; + packageList.answer = () => Promise.resolve(PACKAGES); + localStorage.clear(); +}); + +afterEach(() => { + cleanup(); +}); + +describe('objectstack#35974 — a read-only package\'s view: no Delete, a read-only panel', () => { + it('Manage views: the shipped row offers everything but Delete and "View config"; the custom row is unchanged', async () => { + mount(CUSTOM.name); + await settle(); + await waitFor(() => expect(screen.getByTestId(`manage-views-row-${SHIPPED.name}`)).toBeTruthy()); + await waitFor(async () => expect(await rowOffers(SHIPPED.name)).toEqual(FACTORY_OFFERS)); + expect(await rowOffers(CUSTOM.name)).toEqual(OFFERED); + }); + + it('the shipped row\'s "View config" opens the panel on that view, read-only', async () => { + mount(CUSTOM.name); + await settle(); + await waitFor(async () => expect((await rowOffers(SHIPPED.name)).configLabel).toBe('View config')); + await clickConfig(SHIPPED.name); + await waitFor(() => expect(panelProps.current?.open).toBe(true)); + await waitFor(() => expect(panelProps.current?.activeView?.id).toBe(SHIPPED.name)); + await waitFor(() => expect(panelProps.current?.readOnly).toBe(true)); + expect(panelProps.current?.mode).toBe('edit'); + }); + + it('"View config" on a shipped row while another package\'s view is open: no render of the open panel is editable', async () => { + mount(CUSTOM.name); + await settle(); + await waitFor(async () => expect((await rowOffers(SHIPPED.name)).configLabel).toBe('View config')); + const before = panelProps.renders.length; + await clickConfig(SHIPPED.name); + await waitFor(() => expect(panelProps.current?.activeView?.id).toBe(SHIPPED.name)); + await waitFor(() => expect(panelProps.current?.open).toBe(true)); + const opened = panelProps.renders.slice(before).filter((props) => props.open); + expect(opened.length).toBeGreaterThan(0); + // The first render after the click already reads the row's own verdict: + // no switch-first answer for the newly open view is waited for. + expect(opened.map((props) => props.readOnly)).toEqual(opened.map(() => true)); + }); + + it('the custom row\'s "Edit view config" opens the panel savable', async () => { + mount(SHIPPED.name); + await settle(); + await clickConfig(CUSTOM.name); + await waitFor(() => expect(panelProps.current?.activeView?.id).toBe(CUSTOM.name)); + await waitFor(() => expect(panelProps.current?.open).toBe(true)); + expect(panelProps.current?.readOnly).toBe(false); + }); + + it('the panel opens on the shipped view read-only', async () => { + mount(SHIPPED.name); + await settle(); + await waitFor(() => expect(panelProps.current?.activeView?.id).toBe(SHIPPED.name)); + await waitFor(() => expect(panelProps.current?.readOnly).toBe(true)); + }); + + it('the panel on a shared view saved into the customization package is not read-only', async () => { + mount(CUSTOM.name); + await settle(); + await waitFor(() => expect(panelProps.current?.activeView?.id).toBe(CUSTOM.name)); + expect(panelProps.current?.readOnly).toBe(false); + }); + + it('on the reader\'s own view the panel is not read-only and Manage views is unchanged', async () => { + mount(PERSONAL.id); + await settle(); + await waitFor(() => expect(panelProps.current?.activeView?.id).toBe(PERSONAL.id)); + expect(panelProps.current?.readOnly).toBe(false); + // My views are no row of Manage views; the shared rows are judged as ever. + expect(screen.queryByTestId(`manage-views-row-${PERSONAL.id}`)).toBeNull(); + await waitFor(async () => expect(await rowOffers(SHIPPED.name)).toEqual(FACTORY_OFFERS)); + expect(await rowOffers(CUSTOM.name)).toEqual(OFFERED); + }); + + it('while the package list is unread, the shipped view keeps every offer (the server still refuses)', async () => { + packageList.answer = () => new Promise(() => {}); + mount(SHIPPED.name); + await settle(); + await waitFor(() => expect(screen.getByTestId(`manage-views-row-${SHIPPED.name}`)).toBeTruthy()); + expect(await rowOffers(SHIPPED.name)).toEqual(OFFERED); + expect(panelProps.current?.readOnly).toBe(false); + }); + + it('a failed package-list read keeps every offer', async () => { + packageList.answer = () => Promise.reject(new Error('offline')); + mount(SHIPPED.name); + await settle(); + await waitFor(() => expect(screen.getByTestId(`manage-views-row-${SHIPPED.name}`)).toBeTruthy()); + expect(await rowOffers(SHIPPED.name)).toEqual(OFFERED); + expect(panelProps.current?.readOnly).toBe(false); + }); +}); + +describe('objectstack#35974 — the verdict is kept per package as it lands', () => { + function Probe({ ids }: { ids: string[] }) { + const refusing = usePackagesRefusingSaves(ids); + return {[...refusing].sort().join(',')}; + } + + it('a new package id joining the list takes back none of what is known', async () => { + const pending: Array<(rows: any[]) => void> = []; + packageList.answer = () => Promise.resolve(PACKAGES); + const view = render(); + await waitFor(() => expect(screen.getByTestId('refusing').textContent).toBe(SHIPPED_PACKAGE)); + // A refetch brings a view of a package whose answer is still on the wire. + packageList.answer = () => new Promise((resolve) => { pending.push(resolve); }); + view.rerender(); + expect(screen.getByTestId('refusing').textContent).toBe(SHIPPED_PACKAGE); + await settle(); + expect(screen.getByTestId('refusing').textContent).toBe(SHIPPED_PACKAGE); + expect(pending.length).toBeGreaterThan(0); + const rows = [...PACKAGES, { id: 'com.example.other', name: 'Other', writable: false }]; + await act(async () => { pending.forEach((resolve) => resolve(rows)); }); + await waitFor(() => expect(screen.getByTestId('refusing').textContent).toBe(`com.example.other,${SHIPPED_PACKAGE}`)); + }); +}); diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index d5e44eb86c3..e5370a8c048 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -1021,7 +1021,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co // objectstack#27594: the list title is the view switcher, which replaced the // view tab strip; the view items `ManageViewsDialog` lists come with it. - const { viewTabItems, titleSwitcher } = useObjectViewTitleSwitcher({ + const { viewTabItems, titleSwitcher, refusingPackages } = useObjectViewTitleSwitcher({ views, savedViews, objectDef, @@ -1062,6 +1062,28 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co onDeletePersonalView: personalViewsReady ? (id: string) => { void handleDeletePersonalView(id); } : undefined, }); + // objectstack#35974 — the view panel is read-only on a view a read-only + // package ships, judged from the SAME answer that drew its Manage views + // row (`refusingPackages`), so the row's "View config" never opens an + // editable panel. The view it was opened for counts as well as the open + // one: a row of another view switches views in a transition, and the + // panel opens before the switch lands. + const [configTargetId, setConfigTargetId] = useState(null); + useEffect(() => { + if (!showViewConfigPanel) setConfigTargetId(null); + }, [showViewConfigPanel]); + const viewRefusesSaves = (id: string | null | undefined): boolean => { + if (!isAdmin || !id) return false; + const packageId = studioPackageId(savedViews.find((sv: any) => viewRowId(sv) === id)); + return packageId !== null && refusingPackages.has(packageId); + }; + const viewConfigPanelReadOnly = viewConfigPanelMode === 'edit' + && (viewRefusesSaves(activeView?.id) || viewRefusesSaves(configTargetId)); + const handleConfigViewFromRow = (id: string) => { + setConfigTargetId(id); + handleConfigView(id); + }; + // objectstack#35878 — the page bar's props, for the view bar's right end // (`viewBarTrailing` below). Filled on every render once the header chrome // is known; the end reads it when it draws, after this render. @@ -1135,7 +1157,9 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co listViewActions: { rename: activeView && activeIsPersonal && personalViewsReady && personalGrant('update') ? (label: string) => handleRenamePersonalView(String(activeView.id), label) - : activeView && isAdmin && !activeViewPackageRefusesSaves && savedViews.some((sv: any) => viewRowId(sv) === activeView.id) + // A read-only package's view is renamed too (objectstack#35974): + // `updateView` writes the label into its customization pair. + : activeView && isAdmin && savedViews.some((sv: any) => viewRowId(sv) === activeView.id) ? async (label: string) => { await handleRenameView(String(activeView.id), label); return true; } : undefined, save: !isEnvironmentList && canUpdatePersonalView && listPersonalizedParts.length > 0 ? () => { void handleSaveToPersonalView(); } : undefined, @@ -1401,7 +1425,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co onSetPinned={handlePinView} onReorder={handleReorderViews} onAddView={handleAddView} - onConfigView={handleConfigView} + onConfigView={handleConfigViewFromRow} /> )} @@ -1447,6 +1471,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co metadataClient={metadataClient} dataSource={dataSource} onAfterChange={handleDraftBarChange} + readOnly={viewConfigPanelReadOnly} /> diff --git a/ui/packages/app-shell/src/views/ViewConfigPanel.test.tsx b/ui/packages/app-shell/src/views/ViewConfigPanel.test.tsx index c97ab4385f0..52f034e219f 100644 --- a/ui/packages/app-shell/src/views/ViewConfigPanel.test.tsx +++ b/ui/packages/app-shell/src/views/ViewConfigPanel.test.tsx @@ -2,6 +2,11 @@ import { describe, it, expect, vi } from 'vitest'; import { render, screen, fireEvent } from '@testing-library/react'; +// The panel's source reaches dynamic `import('@objectstack/formula')` and +// `import('@objectstack/lint')`: pay their load at collection, never inside a +// case's clocked window (`check:test-source-alias`). +import '@objectstack/formula'; +import '@objectstack/lint'; /** * ViewConfigPanel discard/close behavior (objectui#2320). @@ -14,10 +19,12 @@ import { render, screen, fireEvent } from '@testing-library/react'; // Swap the heavy spec-driven inspector for a light stub that lets a test drive // `onPatch` — the seam ViewConfigPanel mirrors edits back to the host with. vi.mock('./metadata-admin/inspectors/ViewVariantInspector', () => ({ - ViewVariantInspector: ({ draft, onPatch }: any) => ( + ViewVariantInspector: ({ draft, onPatch, readOnly }: any) => ( - + {readOnly ? ( + + ) : ( + <> + + + + )} ); diff --git a/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx b/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx index 35b35b5071e..45cda91ba8e 100644 --- a/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx +++ b/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx @@ -44,6 +44,8 @@ import type { useObjectLabel, useObjectTranslation } from '@object-ui/i18n'; import { ChevronDown } from 'lucide-react'; import { viewRowId } from '../utils/viewIdentity.js'; import { useRecentItems } from '../hooks/useRecentItems.js'; +import { usePackagesRefusingSaves } from '../hooks/useStudioDesignGate.js'; +import { studioPackageId } from '../utils/appRoute.js'; import { useListViewFavorites, type ListViewFavorites } from '../layout/listViewFavorites.js'; import type { useMetaItemRefusal } from '../hooks/useMetaItemRefusal.js'; import type { useServedViewItems } from '../hooks/useServedViewItems.js'; @@ -354,9 +356,27 @@ export function useObjectViewTitleSwitcher({ } as ViewTabItem; }); + // objectstack#35974 — a saved view a read-only package ships: its + // definition is read-only in Manage views (`definitionReadonly`). The + // server refuses its delete and its panel save, so Delete is not offered + // and the panel opens read-only ("View config"); rename, pin and set as + // default stay, since `updateView` writes those into the package's + // customization pair. Judged by the package the row was served under and + // the session-held `writable` verdict objectstack#35933 reads. Unknown + // (unread, failed, unlisted) keeps the row as it was. Manage views only: + // the switcher's sections above still read `authored` from `isSystem`. + const refusingPackages = usePackagesRefusingSaves(isAdmin + ? savedViews.map((sv: any) => studioPackageId(sv)).filter((id: string | null): id is string => id !== null) + : []); // The reader's own views are switched to here but are no view the admin's // Manage views lists: they are each reader's data, not the object's views. - const viewTabItems = viewItems.filter((item) => !personalViewIds.has(item.id)); + const viewTabItems = viewItems + .filter((item) => !personalViewIds.has(item.id)) + .map((item) => { + if (item.readonly) return item; + const packageId = studioPackageId(savedViews.find((sv: any) => viewRowId(sv) === item.id)); + return packageId !== null && refusingPackages.has(packageId) ? { ...item, definitionReadonly: true } : item; + }); const switcherViews: TitleSwitcherView[] = viewItems.map((item) => { const personal = personalViewIds.has(item.id); return { @@ -410,5 +430,5 @@ export function useObjectViewTitleSwitcher({ /> ) : null; - return { viewTabItems, titleSwitcher, titleLabel }; + return { viewTabItems, titleSwitcher, titleLabel, refusingPackages }; } diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 67f10f44d8e..80ecf4857ea 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1364,6 +1364,7 @@ const ar = { }, view: { editViewConfig: "تعديل إعدادات العرض", + showViewConfig: "عرض إعدادات العرض", rename: "إعادة تسمية", duplicateView: "تكرار العرض", shareView: "مشاركة العرض", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index a13959f73f7..83a7dfcef95 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1227,6 +1227,7 @@ const de = { }, view: { editViewConfig: "Ansichtskonfiguration bearbeiten", + showViewConfig: "Ansichtskonfiguration anzeigen", rename: "Umbenennen", duplicateView: "Ansicht duplizieren", shareView: "Ansicht teilen", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 3062cd03f8e..c78d8c5e195 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1526,6 +1526,7 @@ const en = { }, view: { editViewConfig: 'Edit view config', + showViewConfig: 'View config', rename: 'Rename', duplicateView: 'Duplicate View', shareView: 'Share View', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index bf2e6d0d783..8a05009f2b9 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1264,6 +1264,7 @@ const es = { }, view: { editViewConfig: "Editar configuración de vista", + showViewConfig: "Ver configuración de vista", rename: "Renombrar", duplicateView: "Duplicar vista", shareView: "Compartir vista", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 63af255230c..ca4262a0fb4 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1259,6 +1259,7 @@ const fr = { }, view: { editViewConfig: "Modifier la configuration de la vue", + showViewConfig: "Voir la configuration de la vue", rename: "Renommer", duplicateView: "Dupliquer la vue", shareView: "Partager la vue", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index f6941796ba2..a284075a477 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1227,6 +1227,7 @@ const ja = { }, view: { editViewConfig: "ビュー設定を編集", + showViewConfig: "ビュー設定を表示", rename: "名前を変更", duplicateView: "ビューを複製", shareView: "ビューを共有", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 157e8f58610..75535ed507c 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1227,6 +1227,7 @@ const ko = { }, view: { editViewConfig: "보기 구성 편집", + showViewConfig: "보기 구성 보기", rename: "이름 변경", duplicateView: "뷰 복제", shareView: "뷰 공유", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index dce7132a73b..aef4684bdb0 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1259,6 +1259,7 @@ const pt = { }, view: { editViewConfig: "Editar configuração da vista", + showViewConfig: "Ver configuração da vista", rename: "Renomear", duplicateView: "Duplicar visualização", shareView: "Compartilhar visualização", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 31f6b3cbffd..41a20276c3f 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1297,6 +1297,7 @@ const ru = { }, view: { editViewConfig: "Изменить настройки представления", + showViewConfig: "Просмотреть настройки представления", rename: "Переименовать", duplicateView: "Дублировать представление", shareView: "Поделиться представлением", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 77c9064d816..bcd037400c3 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1254,6 +1254,7 @@ const zh = { }, view: { editViewConfig: '编辑视图配置', + showViewConfig: '查阅视图配置', rename: '重命名', duplicateView: '复制视图', shareView: '共享视图', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index e6c94d5da72..c11e64e4d34 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1254,6 +1254,7 @@ const zhHant = { }, view: { editViewConfig: '編輯檢視配置', + showViewConfig: '查閱檢視配置', rename: '重新命名', duplicateView: '複製檢視', shareView: '共享檢視', diff --git a/ui/packages/plugin-view/src/ManageViewsDialog.tsx b/ui/packages/plugin-view/src/ManageViewsDialog.tsx index 91f68f617d4..a7fcad6afc6 100644 --- a/ui/packages/plugin-view/src/ManageViewsDialog.tsx +++ b/ui/packages/plugin-view/src/ManageViewsDialog.tsx @@ -58,6 +58,7 @@ import { Check, X, Lock, + Eye, } from 'lucide-react'; import { cn } from '@object-ui/components'; import { useObjectTranslation } from '@object-ui/react'; @@ -170,6 +171,11 @@ const SortableRow: React.FC = ({ // default, pin, edit configuration, delete). Duplicate is preserved // because it produces a fresh override that *is* mutable. const isReadonly = !!view.readonly; + // A row whose definition is read-only but whose row state is not + // (`ViewTabItem.definitionReadonly`): no Delete, and its configuration is + // offered to look at. `readonly` wins without a check here: it already + // drops both entries this flag changes. + const definitionReadonly = !!view.definitionReadonly; /** * The overflow menu's entries, each resolved ONCE to the handler it will @@ -187,7 +193,7 @@ const SortableRow: React.FC = ({ const configAction = isReadonly ? undefined : onConfigView; const setDefaultAction = isReadonly || view.isDefault ? undefined : onSetDefault; const pinAction = isReadonly ? undefined : onSetPinned; - const deleteAction = isReadonly ? undefined : onDelete; + const deleteAction = isReadonly || definitionReadonly ? undefined : onDelete; const hasEntryAboveDelete = !!(renameAction || duplicateAction || configAction || setDefaultAction || pinAction); const hasMenuEntry = hasEntryAboveDelete || !!deleteAction; @@ -380,7 +386,9 @@ const SortableRow: React.FC = ({ data-testid={`manage-views-action-config-${view.id}`} onClick={() => configAction(view.id)} > - {vt('view.editViewConfig', 'Edit view config')} + {definitionReadonly + ? <> {vt('view.showViewConfig', 'View config')} + : <> {vt('view.editViewConfig', 'Edit view config')}} )} {setDefaultAction && ( diff --git a/ui/packages/plugin-view/src/ViewTabBar.tsx b/ui/packages/plugin-view/src/ViewTabBar.tsx index 0cc577ff5e6..4c7537fbfc1 100644 --- a/ui/packages/plugin-view/src/ViewTabBar.tsx +++ b/ui/packages/plugin-view/src/ViewTabBar.tsx @@ -196,6 +196,20 @@ export interface ViewTabItem { readonly?: boolean; /** Optional tooltip shown alongside the lock icon when `readonly` is true. */ readonlyReason?: string; + /** + * The view's DEFINITION is read-only while its row state is not: e.g. a + * view a read-only package ships, whose label, pin and default the host + * still writes (into that package's customization), but whose definition + * cannot be saved and which cannot be deleted. + * + * When `true`, `ManageViewsDialog` hides Delete and labels the + * configuration entry as viewing ("View config", not "Edit view config"): + * the host's `onConfigView` opens the configuration with nothing to save. + * Rename, pin and set as default stay offered, and no lock icon is drawn + * (the row is not read-only). `readonly` wins when both are set. Absent ⇒ + * the row behaves as before. `ViewTabBar` does not read it. + */ + definitionReadonly?: boolean; /** * The view's description, already resolved to the viewer's language and * already gated by the host on the view's `appearance.showDescription` diff --git a/ui/packages/plugin-view/src/__tests__/readonlyViewMenus-10209.test.tsx b/ui/packages/plugin-view/src/__tests__/readonlyViewMenus-10209.test.tsx index a0395f818e0..514adf868f1 100644 --- a/ui/packages/plugin-view/src/__tests__/readonlyViewMenus-10209.test.tsx +++ b/ui/packages/plugin-view/src/__tests__/readonlyViewMenus-10209.test.tsx @@ -25,7 +25,7 @@ import React from 'react'; import { describe, it, expect, vi, afterEach } from 'vitest'; -import { render, screen, cleanup, fireEvent, within } from '@testing-library/react'; +import { render, screen, cleanup, fireEvent, within, waitFor } from '@testing-library/react'; import '@testing-library/jest-dom'; import { ViewTabBar } from '../ViewTabBar'; import type { ViewTabItem } from '../ViewTabBar'; @@ -110,6 +110,52 @@ describe('ManageViewsDialog row menu (#10209)', () => { }); }); +describe('ManageViewsDialog `definitionReadonly` (objectstack#35974)', () => { + /** A factory view of a read-only package: its definition is read-only, its row state is not. */ + const FACTORY: ViewTabItem = { id: 'crm_lead.shipped', label: 'Shipped', type: 'grid', definitionReadonly: true }; + + it('a definition-read-only row hides only Delete: rename, pin, set default and "View config" stay', () => { + renderDialog([FACTORY]); + // No lock: the row is not read-only. + expect(screen.queryByTestId(`manage-views-readonly-${FACTORY.id}`)).toBeNull(); + expect(screen.getByTestId(`manage-views-pin-${FACTORY.id}`)).toBeInTheDocument(); + expect(screen.getByTestId(`manage-views-default-${FACTORY.id}`)).toBeInTheDocument(); + open(screen.getByTestId(`manage-views-actions-${FACTORY.id}`)); + expect(menuShape()).toEqual(['menuitem', 'menuitem', 'menuitem', 'menuitem']); + for (const key of ['rename', 'config', 'default', 'pin']) { + expect(screen.getByTestId(`manage-views-action-${key}-${FACTORY.id}`)).toBeInTheDocument(); + } + expect(screen.queryByTestId(`manage-views-action-delete-${FACTORY.id}`)).toBeNull(); + const config = screen.getByTestId(`manage-views-action-config-${FACTORY.id}`); + expect(config).toHaveTextContent('View config'); + expect(config).not.toHaveTextContent('Edit'); + }); + + it('its "View config" hands the view to the host\'s `onConfigView`', async () => { + const onConfigView = vi.fn(); + renderDialog([FACTORY], { onConfigView }); + open(screen.getByTestId(`manage-views-actions-${FACTORY.id}`)); + fireEvent.click(screen.getByTestId(`manage-views-action-config-${FACTORY.id}`)); + await waitFor(() => expect(onConfigView).toHaveBeenCalledWith(FACTORY.id)); + }); + + it('without the flag a row is as before: all six entries, "Edit view config", Delete under a separator', () => { + renderDialog([{ ...FACTORY, definitionReadonly: undefined }], { onDuplicate: vi.fn() }); + open(screen.getByTestId(`manage-views-actions-${FACTORY.id}`)); + expect(menuShape()).toEqual([ + 'menuitem', 'menuitem', 'menuitem', 'menuitem', 'menuitem', 'separator', 'menuitem', + ]); + expect(screen.getByTestId(`manage-views-action-config-${FACTORY.id}`)).toHaveTextContent('Edit view config'); + expect(screen.getByTestId(`manage-views-action-delete-${FACTORY.id}`)).toBeInTheDocument(); + }); + + it('`readonly` wins: a read-only row with the flag is as any read-only row (no `…`, lock drawn)', () => { + renderDialog([{ ...READONLY, definitionReadonly: true }]); + expect(screen.queryByTestId(`manage-views-actions-${READONLY.id}`)).toBeNull(); + expect(screen.getByTestId(`manage-views-readonly-${READONLY.id}`)).toBeInTheDocument(); + }); +}); + // --- ViewTabBar -------------------------------------------------------------- /** The console's admin prop set. */