From 227a2fbb66b567a85cf42979518657310ff59b13 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 08:57:27 +0000 Subject: [PATCH 1/8] wip(console): only administrators share list views (#36371) Claude-Session: https://claude.ai/code/session_01QsR2jTPMb2q2wRssyREqhQ Co-authored-by: Claude --- ...-write-door-capability-enumeration.test.ts | 64 ++++ .../app-shell/src/hooks/useMetaItemRefusal.ts | 14 +- .../app-shell/src/views/ObjectView.tsx | 57 +++- .../src/views/objectViewSwitcherMenu.tsx | 38 ++- .../src/views/objectViewTitleSwitcher.tsx | 27 ++ .../src/views/objectViewViewSharing.ts | 279 ++++++++++++++++++ .../src/views/runtime-metadata-persistence.ts | 17 +- ui/packages/i18n/src/locales/ar.ts | 14 + ui/packages/i18n/src/locales/de.ts | 14 + ui/packages/i18n/src/locales/en.ts | 14 + ui/packages/i18n/src/locales/es.ts | 14 + ui/packages/i18n/src/locales/fr.ts | 14 + ui/packages/i18n/src/locales/ja.ts | 14 + ui/packages/i18n/src/locales/ko.ts | 14 + ui/packages/i18n/src/locales/pt-BR.ts | 14 + ui/packages/i18n/src/locales/ru.ts | 14 + ui/packages/i18n/src/locales/zh-Hans.ts | 14 + ui/packages/i18n/src/locales/zh-Hant.ts | 14 + 18 files changed, 641 insertions(+), 9 deletions(-) create mode 100644 ui/packages/app-shell/src/views/objectViewViewSharing.ts diff --git a/packages/rest/src/meta-write-door-capability-enumeration.test.ts b/packages/rest/src/meta-write-door-capability-enumeration.test.ts index ab4c3df008a..03d794d1b2e 100644 --- a/packages/rest/src/meta-write-door-capability-enumeration.test.ts +++ b/packages/rest/src/meta-write-door-capability-enumeration.test.ts @@ -68,6 +68,7 @@ import '@objectstack/objectql'; import { describe, it, expect, vi, beforeEach } from 'vitest'; import { ANONYMOUS_DENY_CODE, ANONYMOUS_DENY_STATUS } from '@objectstack/core'; import { RestServer } from './rest-server.js'; +import { securityDefaultPermissionSets } from '@objectstack/plugin-security'; /** * The unscoped mount base, and the `/meta` prefix on it. The `DOORS` table @@ -703,3 +704,66 @@ describe('#30675 — the data doors refuse on their own capability, not `manage_ }, ); }); + +/** + * [objectstack#36371] Only an administrator makes a list view everyone sees. + * A shared view is `view` metadata, so the door that shares one is this + * surface's save (the Console saves `?mode=draft` and publishes at once), the + * door that unshares one is the delete, and the publish promotes it. Driven + * with the systemPermissions the SHIPPED sets grant, not hand-written ones: a + * member (`member_default`), an organization administrator (that baseline + * plus `organization_admin`, which withholds `manage_metadata`) and the + * platform administrator (`admin_full_access`, the control). The Console asks + * the same capability before it offers Shared (`useCanAuthorMetadata`), so the + * organization administrator's refusal here is why that control is hidden. + */ +describe('#36371 — sharing a list view is an administrator\'s act', () => { + const grants = (...names: string[]): string[] => { + const held = new Set(); + for (const name of names) { + const set = securityDefaultPermissionSets.find((ps) => ps.name === name); + if (!set) throw new Error(`no shipped permission set named ${name}`); + for (const capability of set.systemPermissions ?? []) held.add(capability); + } + return [...held]; + }; + const VIEW = { type: 'view', name: 'account.team_pipeline' }; + const viewDoor = (protocolMethod: string): Door => { + const door = DOORS.find((d) => d.protocolMethod === protocolMethod)!; + return { + ...door, + params: { ...VIEW }, + ...(protocolMethod === 'saveMetaItem' + ? { body: { name: VIEW.name, object: 'account', viewKind: 'list', label: 'Team pipeline', config: { type: 'grid', data: { provider: 'object', object: 'account' } } } } + : {}), + }; + }; + const SHARE_DOORS = ['saveMetaItem', 'publishMetaItem', 'deleteMetaItem'].map(viewDoor); + + it.each([ + ['a member', ['member_default']], + ['an organization administrator', ['member_default', 'organization_admin']], + ] as const)('%s is refused each share door 403 FORBIDDEN, and nothing is written', async (_who, sets) => { + const systemPermissions = grants(...sets); + expect(systemPermissions).not.toContain('manage_metadata'); + for (const door of SHARE_DOORS) { + const stack = boot({ userId: 'u_member', systemPermissions }); + const out = await stack.knock(door); + expect(out.status, door.label).toBe(403); + expect(out.body, door.label).toMatchObject({ error: { code: 'FORBIDDEN' } }); + expect(stack.calls[door.protocolMethod], door.label).toBe(0); + } + }); + + it('the control: the platform administrator reaches each share door', async () => { + const systemPermissions = grants('admin_full_access'); + expect(systemPermissions).toContain('manage_metadata'); + for (const door of SHARE_DOORS) { + const stack = boot({ userId: 'u_admin', systemPermissions }); + const out = await stack.knock(door); + expect(out.status, door.label).not.toBe(403); + expect(out.status, door.label).not.toBe(401); + expect(stack.calls[door.protocolMethod], door.label).toBe(1); + } + }); +}); diff --git a/ui/packages/app-shell/src/hooks/useMetaItemRefusal.ts b/ui/packages/app-shell/src/hooks/useMetaItemRefusal.ts index 4fd32f3adb1..319d8dda1fd 100644 --- a/ui/packages/app-shell/src/hooks/useMetaItemRefusal.ts +++ b/ui/packages/app-shell/src/hooks/useMetaItemRefusal.ts @@ -29,6 +29,10 @@ * only, so it never answers for the next URL. * - `refusal` is set for `denied` alone. Every other verdict leaves the page's * missing-item face: the server said absence, or said nothing. + * - `absent` (objectstack#36371) is set for `not_found` alone: the server + * says the item is not there for anyone, so a page may say it is gone (a + * view unshared or deleted while a reader had it open) rather than fall + * back in silence. Unreachable and unknown answers say nothing. * * Nothing is cached across mounts: a verdict about the CALLER goes stale the * moment they are granted the capability. @@ -50,10 +54,13 @@ export interface MetaItemRefusalReading { readonly checking: boolean; /** The server refused this caller the item; `null` for every other answer. */ readonly refusal: MetaItemRefusal | null; + /** The server answered that no such item exists. */ + readonly absent: boolean; } -const NOT_REFUSED: MetaItemRefusalReading = Object.freeze({ checking: false, refusal: null }); -const CHECKING: MetaItemRefusalReading = Object.freeze({ checking: true, refusal: null }); +const NOT_REFUSED: MetaItemRefusalReading = Object.freeze({ checking: false, refusal: null, absent: false }); +const CHECKING: MetaItemRefusalReading = Object.freeze({ checking: true, refusal: null, absent: false }); +const ABSENT: MetaItemRefusalReading = Object.freeze({ checking: false, refusal: null, absent: true }); export function useMetaItemRefusal(type: 'dashboard' | 'view', name: string | null): MetaItemRefusalReading { const adapter = useAdapter(); @@ -79,6 +86,7 @@ export function useMetaItemRefusal(type: 'dashboard' | 'view', name: string | nu if (!asked) return NOT_REFUSED; if (!answer || answer.type !== type || answer.name !== asked) return CHECKING; + if (answer.access.verdict === 'not_found') return ABSENT; if (answer.access.verdict !== 'denied') return NOT_REFUSED; - return { checking: false, refusal: { message: answer.access.message } }; + return { checking: false, refusal: { message: answer.access.message }, absent: false }; } diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index 8e10960f6e7..95f93fe128f 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -100,7 +100,9 @@ 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 { useObjectViewViewCrud, useRuntimeCreateApp } from './objectViewViewCrud.js'; +import { mayShareViews, useViewSharing } from './objectViewViewSharing.js'; +import { useCanAuthorMetadata } from '../hooks/useCanAuthorMetadata.js'; import { PERSONAL_VIEW_OBJECT, buildInPlaceViewConfig, @@ -698,6 +700,17 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co ? (requestedViewId.includes('.') ? requestedViewId : `${objectDef.name}.${requestedViewId}`) : null; const viewAccess = useMetaItemRefusal('view', missedViewName); + // objectstack#36371 — a view the address names that the server says is + // gone (unshared or deleted while the reader had it open): the list opens + // its default view, and says why once per name. + const goneViewNoticed = useRef(null); + useEffect(() => { + if (!viewAccess.absent || !missedViewName || goneViewNoticed.current === missedViewName) return; + goneViewNoticed.current = missedViewName; + toast.info(t('view.switcher.viewGone', { + defaultValue: 'The view you opened is no longer available, so the list shows its default view.', + })); + }, [viewAccess.absent, missedViewName, t]); const activeViewId = resolvedViewId || pinnedViewId || defaultViewId || views[0]?.id; const baseView = views.find((v: any) => v.id === activeViewId) || views[0]; const activeView = viewDraft && viewDraft.id === baseView?.id @@ -1124,6 +1137,33 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co listSeedRef, }); + // objectstack#36371 — only an administrator holding the shared view's write + // capability shares views: creates one shared, makes one of their own + // shared, or unshares one (`./objectViewViewSharing.ts`). + const canAuthorMetadata = useCanAuthorMetadata(); + const canShareViews = mayShareViews(isAdmin, canAuthorMetadata); + const sharingApp = useRuntimeCreateApp(t); + const viewTabItemsRef = useRef>([]); + const viewSharing = useViewSharing({ + objectName: objectDef.name, + objectDef, + metadataClient, + dataSource, + app: sharingApp, + personalViews, + savedViews, + viewIds: views.map((v: any) => String(v.id)), + labelOf: (id) => String(viewTabItemsRef.current.find((item) => item.id === id)?.label ?? id), + activeViewId, + routeViewId: viewId, + navigate, + pinnedViewId, + setPinnedViewId: setPinnedViewChoice, + refresh: () => setRefreshKey((k) => k + 1), + confirmHandler, + t, + }); + // 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, refusingPackages } = useObjectViewTitleSwitcher({ @@ -1156,17 +1196,28 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co }), savePersonal: personalViews.save, openPersonal: openPersonalView, - createShared: handleViewCreate, + createShared: viewSharing.createShared, clearSourceListState, canCreatePersonal: canCreatePersonalView, - canCreateShared: isAdmin, + canCreateShared: canShareViews, hasUnsavedConditions: listDraftParts.some((part) => part === 'filters' || part === 'sort'), }, onRenamePersonalView: personalViewsReady && personalGrant('update') ? (id: string) => setPersonalViewDialog({ mode: 'rename', viewId: id }) : undefined, onDeletePersonalView: personalViewsReady ? (id: string) => { void handleDeletePersonalView(id); } : undefined, + onMakeSharedView: canShareViews && personalViewsReady + ? (id: string) => { void viewSharing.makeShared(id); } + : undefined, + // Unsharing makes the view one of the reader's own, so it needs their create. + onUnshareView: canShareViews && personalViewsReady && personalGrant('create') + ? (id: string) => { void viewSharing.unshare(id); } + : undefined, }); + // Read when an unshare asks for the view's name, after this render. + useEffect(() => { + viewTabItemsRef.current = viewTabItems; + }, [viewTabItems]); // 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 diff --git a/ui/packages/app-shell/src/views/objectViewSwitcherMenu.tsx b/ui/packages/app-shell/src/views/objectViewSwitcherMenu.tsx index 26e882f7dfe..c50ccf80e72 100644 --- a/ui/packages/app-shell/src/views/objectViewSwitcherMenu.tsx +++ b/ui/packages/app-shell/src/views/objectViewSwitcherMenu.tsx @@ -12,14 +12,16 @@ * * Each row offers on hover the reader's ☆ (sidebar Favorites) and 📌 (the * view this object's list opens by default), and on the reader's own views - * Rename and Delete. The trigger (type icon, name, count, caret) and the + * Rename and Delete. For a reader who may share views (objectstack#36371), + * the reader's own views add 「Make shared」 and a shared view saved here adds + * 「Unshare」 (`./objectViewViewSharing.ts`). The trigger (type icon, name, count, caret) and the * popover around this body are the switcher's (`./objectViewTitleSwitcher.tsx`). */ import { lazy, Suspense, useState, type ComponentType, type ReactNode } from 'react'; import { cn, Input } from '@object-ui/components'; import type { useObjectTranslation } from '@object-ui/i18n'; -import { Check, ListOrdered, Pencil, Pin, Plus, Star, Trash2 } from 'lucide-react'; +import { Check, ListOrdered, Lock, Pencil, Pin, Plus, Share2, Star, Trash2 } from 'lucide-react'; import type { ListViewFavorites } from '../layout/listViewFavorites.js'; import { VIEW_TYPE_ICONS } from './objectViewHelpers.js'; import type { CreateViewCardProps } from './CreateViewDialog.js'; @@ -58,6 +60,10 @@ export interface ObjectViewSwitcherMenuProps { onManageViews?: () => void; onRenamePersonalView?: (viewId: string) => void; onDeletePersonalView?: (viewId: string) => void; + /** objectstack#36371 — 「Make shared」 on the reader's own views. Absent ⇒ not offered. */ + onMakeSharedView?: (viewId: string) => void; + /** objectstack#36371 — 「Unshare」 on the shared views marked `unsharable`. Absent ⇒ not offered. */ + onUnshareView?: (viewId: string) => void; /** 「Add view」 and its card. Absent ⇒ `onAddView`, if any. */ create?: SwitcherCreateOptions; /** 「Add view」 for a host with no card to offer: the dropdown closes and this runs (the Create View dialog). */ @@ -106,6 +112,8 @@ export function ObjectViewSwitcherMenu({ onManageViews, onRenamePersonalView, onDeletePersonalView, + onMakeSharedView, + onUnshareView, create, onAddView, phone = false, @@ -162,6 +170,8 @@ export function ObjectViewSwitcherMenu({ : t('view.switcher.pin', { defaultValue: 'Pin: open this view by default' }); const renameLabel = t('view.rename', { defaultValue: 'Rename' }); const deleteLabel = t('view.deleteView', { defaultValue: 'Delete View' }); + const makeSharedLabel = t('view.switcher.makeShared', { defaultValue: 'Make shared' }); + const unshareLabel = t('view.switcher.unshare', { defaultValue: 'Unshare' }); const iconButton = 'flex h-7 w-7 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground max-sm:h-11 max-sm:w-11 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'; // Shown on hover or focus, and always while set; a touch screen has no // hover, so there they always show. @@ -235,6 +245,30 @@ export function ObjectViewSwitcherMenu({ )} + {view.personal && onMakeSharedView && ( + + )} + {!view.personal && view.unsharable && onUnshareView && ( + + )} {view.personal && onDeletePersonalView && ( {/* The dropdown's body (objectstack#35553): the views, grouped, and - 「Add view」, which turns it into the in-place create card. */} + 「Add view」, which turns it into the in-place create card. + w-80, not w-72 (objectstack#36371): a personal row's hidden + actions keep their width, and 「Make shared」 is a sixth + icon, so at w-72 a two-word name broke onto three lines. */} From 5bdea0f9117911cb9d551e59bb4b61460067a830 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 10:17:18 +0000 Subject: [PATCH 6/8] test(console): ledger Unshare's deleteView in the write-refusal census (#36371) The census counts every view write under app-shell views; Unshare's delete surfaces its refusal through toast.error with formatMetadataError and takes the My views copy back, pinned by objectViewViewSharing.test.tsx. Claude-Session: https://claude.ai/code/session_01QsR2jTPMb2q2wRssyREqhQ Co-authored-by: Claude --- .../app-shell/src/views/writeRefusalCensus-11583.test.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ui/packages/app-shell/src/views/writeRefusalCensus-11583.test.ts b/ui/packages/app-shell/src/views/writeRefusalCensus-11583.test.ts index 4fee778d117..627d3ff0ffd 100644 --- a/ui/packages/app-shell/src/views/writeRefusalCensus-11583.test.ts +++ b/ui/packages/app-shell/src/views/writeRefusalCensus-11583.test.ts @@ -107,6 +107,11 @@ const LEDGER: Row[] = [ kind: 'surfaces', pin: 'ObjectView.viewWriteRefusal-11583.test.tsx', reason: 'Delete: the translated `objectViewActions.deleteFailed` title, with the door\'s message as the description (objectui#12398).', }, + { + file: 'objectViewViewSharing.ts', symbol: 'unshare', callee: 'deleteView', calls: 1, + kind: 'surfaces', pin: 'objectViewViewSharing.test.tsx', + reason: 'Unshare (objectstack#36371): a refused delete, or one answered `deleted: false`, takes the My views copy back and toasts the translated `view.switcher.unshareFailed` title with the door\'s message.', + }, { file: 'objectViewViewCrud.tsx', symbol: 'handlePinView', callee: 'updateView', calls: 1, kind: 'surfaces', pin: 'ObjectView.viewWriteRefusal-11583.test.tsx', From 905e4231d3db5f2fcef08d0f27e09149e2b7ad74 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 10:43:08 +0000 Subject: [PATCH 7/8] refactor(console): drop Make shared and Unshare; keep the Shared gate, publish-at-once and the gone-view notice (#36409) #36371 closed as not planned: sharing or unsharing an existing view is not wanted now. Its three measured faults are #36409: Shared offered to an organization administrator the server refuses, a view created Shared left an unpublished draft, and a gone view dropped in silence. This keeps those fixes and removes the row actions, their keys, tests, docs and census row; the dropdown width and the de quote-pair pin go back to main. Claude-Session: https://claude.ai/code/session_01QsR2jTPMb2q2wRssyREqhQ Co-authored-by: Claude --- .changeset/only-admins-share-views.md | 9 - .../shared-view-create-for-metadata-admins.md | 9 + content/docs/ui/views.mdx | 7 +- ...-write-door-capability-enumeration.test.ts | 6 +- .../app-shell/src/hooks/useMetaItemRefusal.ts | 4 +- .../app-shell/src/views/ObjectView.tsx | 32 +-- .../src/views/objectViewSwitcherMenu.tsx | 38 +--- .../views/objectViewTitleSwitcher.test.tsx | 45 ----- .../src/views/objectViewTitleSwitcher.tsx | 34 +--- .../src/views/objectViewViewSharing.test.tsx | 139 ++----------- .../src/views/objectViewViewSharing.ts | 187 +----------------- .../src/views/runtime-metadata-persistence.ts | 4 +- .../views/writeRefusalCensus-11583.test.ts | 5 - .../__tests__/de-quote-pairing-3876.test.ts | 11 +- ui/packages/i18n/src/locales/ar.ts | 13 +- ui/packages/i18n/src/locales/de.ts | 13 +- ui/packages/i18n/src/locales/en.ts | 13 +- ui/packages/i18n/src/locales/es.ts | 13 +- ui/packages/i18n/src/locales/fr.ts | 13 +- ui/packages/i18n/src/locales/ja.ts | 13 +- ui/packages/i18n/src/locales/ko.ts | 13 +- ui/packages/i18n/src/locales/pt-BR.ts | 13 +- ui/packages/i18n/src/locales/ru.ts | 13 +- ui/packages/i18n/src/locales/zh-Hans.ts | 13 +- ui/packages/i18n/src/locales/zh-Hant.ts | 13 +- 25 files changed, 63 insertions(+), 610 deletions(-) delete mode 100644 .changeset/only-admins-share-views.md create mode 100644 .changeset/shared-view-create-for-metadata-admins.md diff --git a/.changeset/only-admins-share-views.md b/.changeset/only-admins-share-views.md deleted file mode 100644 index 03a61358bfc..00000000000 --- a/.changeset/only-admins-share-views.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -'@object-ui/app-shell': patch -'@object-ui/i18n': patch ---- - -Clause-②: yes (widening) -Metadata-protocol: none - -Only an administrator shares a list view, and a shared view is shared at once. The view dropdown offers Shared in Add view, 「Make shared」 on the reader's own views and 「Unshare」 on a shared view saved in the app only to an administrator whose session holds `manage_metadata`, the capability the shared view's write door asks; an organization administrator without it is no longer offered a Shared choice the server answers `403`. A view created shared, or made shared, is saved and published in one act, so everyone sees it on their next read instead of waiting behind a draft. 「Make shared」 publishes the reader's view under a free key and removes it from My views; 「Unshare」 moves a shared view into the administrator's My views and deletes the shared one, and takes the copy back when the server keeps the view. A view the object authors, a read-only package ships or a package view's customization is never offered 「Unshare」. A reader who opens a view the server says no longer exists is told so once, and the list shows its default view. New `@object-ui/i18n` keys under `view.switcher` carry the new labels and notices in every locale. diff --git a/.changeset/shared-view-create-for-metadata-admins.md b/.changeset/shared-view-create-for-metadata-admins.md new file mode 100644 index 00000000000..c9206775018 --- /dev/null +++ b/.changeset/shared-view-create-for-metadata-admins.md @@ -0,0 +1,9 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +Clause-②: yes (widening) +Metadata-protocol: none + +A shared list view is offered only to an administrator who may write one, and it is shared at once. Add view offers Shared only to an administrator whose session holds `manage_metadata`, the capability the shared view's write door asks; an organization administrator without it is no longer offered a Shared choice the server answers `403`. A view created Shared is saved and published in one act, so everyone sees it on their next read instead of waiting behind a draft; a refused save publishes nothing. A reader who opens a view the server says no longer exists is told so once, and the list shows its default view. Two new `@object-ui/i18n` keys under `view.switcher` carry the notices in every locale. diff --git a/content/docs/ui/views.mdx b/content/docs/ui/views.mdx index c0e6504df6b..3dbdd448a21 100644 --- a/content/docs/ui/views.mdx +++ b/content/docs/ui/views.mdx @@ -473,11 +473,8 @@ The split pane beside an open record keeps the same switcher. one: a user whose session holds `manage_metadata`, the capability the view's write door (`PUT /api/v1/meta/view/:name`) asks, so the server refuses everyone else whatever the Console shows. For that administrator **Add view** offers **Shared** beside **My view** - (**My view** stays the default), each of their own views offers **Make shared**, and a shared - view saved in the app offers **Unshare**, which moves it back into their **My views**. A - view your app authors, a read-only package ships, or a package view's customization has no - **Unshare**. A view created shared, or made shared, is published at once: there is no draft - to publish first. A user who has a view open when it is unshared or deleted is told so, and + (**My view** stays the default). A view created shared is published at once: there is no + draft to publish first. A user who opens a view that has since been deleted is told so, and the list shows its default view. ## Form View diff --git a/packages/rest/src/meta-write-door-capability-enumeration.test.ts b/packages/rest/src/meta-write-door-capability-enumeration.test.ts index 03d794d1b2e..ad542bfb511 100644 --- a/packages/rest/src/meta-write-door-capability-enumeration.test.ts +++ b/packages/rest/src/meta-write-door-capability-enumeration.test.ts @@ -706,10 +706,10 @@ describe('#30675 — the data doors refuse on their own capability, not `manage_ }); /** - * [objectstack#36371] Only an administrator makes a list view everyone sees. + * [objectstack#36409] Only an administrator makes a list view everyone sees. * A shared view is `view` metadata, so the door that shares one is this * surface's save (the Console saves `?mode=draft` and publishes at once), the - * door that unshares one is the delete, and the publish promotes it. Driven + * publish promotes it, and the delete removes it. Driven * with the systemPermissions the SHIPPED sets grant, not hand-written ones: a * member (`member_default`), an organization administrator (that baseline * plus `organization_admin`, which withholds `manage_metadata`) and the @@ -717,7 +717,7 @@ describe('#30675 — the data doors refuse on their own capability, not `manage_ * the same capability before it offers Shared (`useCanAuthorMetadata`), so the * organization administrator's refusal here is why that control is hidden. */ -describe('#36371 — sharing a list view is an administrator\'s act', () => { +describe('#36409 — sharing a list view is an administrator\'s act', () => { const grants = (...names: string[]): string[] => { const held = new Set(); for (const name of names) { diff --git a/ui/packages/app-shell/src/hooks/useMetaItemRefusal.ts b/ui/packages/app-shell/src/hooks/useMetaItemRefusal.ts index 319d8dda1fd..d4f65c74b50 100644 --- a/ui/packages/app-shell/src/hooks/useMetaItemRefusal.ts +++ b/ui/packages/app-shell/src/hooks/useMetaItemRefusal.ts @@ -29,9 +29,9 @@ * only, so it never answers for the next URL. * - `refusal` is set for `denied` alone. Every other verdict leaves the page's * missing-item face: the server said absence, or said nothing. - * - `absent` (objectstack#36371) is set for `not_found` alone: the server + * - `absent` (objectstack#36409) is set for `not_found` alone: the server * says the item is not there for anyone, so a page may say it is gone (a - * view unshared or deleted while a reader had it open) rather than fall + * view deleted since the reader's address named it) rather than fall * back in silence. Unreachable and unknown answers say nothing. * * Nothing is cached across mounts: a verdict about the CALLER goes stale the diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index 95f93fe128f..df534ba00e2 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -700,9 +700,9 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co ? (requestedViewId.includes('.') ? requestedViewId : `${objectDef.name}.${requestedViewId}`) : null; const viewAccess = useMetaItemRefusal('view', missedViewName); - // objectstack#36371 — a view the address names that the server says is - // gone (unshared or deleted while the reader had it open): the list opens - // its default view, and says why once per name. + // objectstack#36409 — a view the address names that the server says is + // gone (deleted, or never there): the list opens its default view, and + // says why once per name. const goneViewNoticed = useRef(null); useEffect(() => { if (!viewAccess.absent || !missedViewName || goneViewNoticed.current === missedViewName) return; @@ -1137,30 +1137,21 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co listSeedRef, }); - // objectstack#36371 — only an administrator holding the shared view's write - // capability shares views: creates one shared, makes one of their own - // shared, or unshares one (`./objectViewViewSharing.ts`). + // objectstack#36409 — only an administrator holding the shared view's write + // capability creates a shared view, and it is published at once + // (`./objectViewViewSharing.ts`). const canAuthorMetadata = useCanAuthorMetadata(); const canShareViews = mayShareViews(isAdmin, canAuthorMetadata); const sharingApp = useRuntimeCreateApp(t); - const viewTabItemsRef = useRef>([]); const viewSharing = useViewSharing({ objectName: objectDef.name, objectDef, metadataClient, dataSource, app: sharingApp, - personalViews, - savedViews, - viewIds: views.map((v: any) => String(v.id)), - labelOf: (id) => String(viewTabItemsRef.current.find((item) => item.id === id)?.label ?? id), - activeViewId, routeViewId: viewId, navigate, - pinnedViewId, - setPinnedViewId: setPinnedViewChoice, refresh: () => setRefreshKey((k) => k + 1), - confirmHandler, t, }); @@ -1206,18 +1197,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co ? (id: string) => setPersonalViewDialog({ mode: 'rename', viewId: id }) : undefined, onDeletePersonalView: personalViewsReady ? (id: string) => { void handleDeletePersonalView(id); } : undefined, - onMakeSharedView: canShareViews && personalViewsReady - ? (id: string) => { void viewSharing.makeShared(id); } - : undefined, - // Unsharing makes the view one of the reader's own, so it needs their create. - onUnshareView: canShareViews && personalViewsReady && personalGrant('create') - ? (id: string) => { void viewSharing.unshare(id); } - : undefined, }); - // Read when an unshare asks for the view's name, after this render. - useEffect(() => { - viewTabItemsRef.current = viewTabItems; - }, [viewTabItems]); // 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 diff --git a/ui/packages/app-shell/src/views/objectViewSwitcherMenu.tsx b/ui/packages/app-shell/src/views/objectViewSwitcherMenu.tsx index c50ccf80e72..26e882f7dfe 100644 --- a/ui/packages/app-shell/src/views/objectViewSwitcherMenu.tsx +++ b/ui/packages/app-shell/src/views/objectViewSwitcherMenu.tsx @@ -12,16 +12,14 @@ * * Each row offers on hover the reader's ☆ (sidebar Favorites) and 📌 (the * view this object's list opens by default), and on the reader's own views - * Rename and Delete. For a reader who may share views (objectstack#36371), - * the reader's own views add 「Make shared」 and a shared view saved here adds - * 「Unshare」 (`./objectViewViewSharing.ts`). The trigger (type icon, name, count, caret) and the + * Rename and Delete. The trigger (type icon, name, count, caret) and the * popover around this body are the switcher's (`./objectViewTitleSwitcher.tsx`). */ import { lazy, Suspense, useState, type ComponentType, type ReactNode } from 'react'; import { cn, Input } from '@object-ui/components'; import type { useObjectTranslation } from '@object-ui/i18n'; -import { Check, ListOrdered, Lock, Pencil, Pin, Plus, Share2, Star, Trash2 } from 'lucide-react'; +import { Check, ListOrdered, Pencil, Pin, Plus, Star, Trash2 } from 'lucide-react'; import type { ListViewFavorites } from '../layout/listViewFavorites.js'; import { VIEW_TYPE_ICONS } from './objectViewHelpers.js'; import type { CreateViewCardProps } from './CreateViewDialog.js'; @@ -60,10 +58,6 @@ export interface ObjectViewSwitcherMenuProps { onManageViews?: () => void; onRenamePersonalView?: (viewId: string) => void; onDeletePersonalView?: (viewId: string) => void; - /** objectstack#36371 — 「Make shared」 on the reader's own views. Absent ⇒ not offered. */ - onMakeSharedView?: (viewId: string) => void; - /** objectstack#36371 — 「Unshare」 on the shared views marked `unsharable`. Absent ⇒ not offered. */ - onUnshareView?: (viewId: string) => void; /** 「Add view」 and its card. Absent ⇒ `onAddView`, if any. */ create?: SwitcherCreateOptions; /** 「Add view」 for a host with no card to offer: the dropdown closes and this runs (the Create View dialog). */ @@ -112,8 +106,6 @@ export function ObjectViewSwitcherMenu({ onManageViews, onRenamePersonalView, onDeletePersonalView, - onMakeSharedView, - onUnshareView, create, onAddView, phone = false, @@ -170,8 +162,6 @@ export function ObjectViewSwitcherMenu({ : t('view.switcher.pin', { defaultValue: 'Pin: open this view by default' }); const renameLabel = t('view.rename', { defaultValue: 'Rename' }); const deleteLabel = t('view.deleteView', { defaultValue: 'Delete View' }); - const makeSharedLabel = t('view.switcher.makeShared', { defaultValue: 'Make shared' }); - const unshareLabel = t('view.switcher.unshare', { defaultValue: 'Unshare' }); const iconButton = 'flex h-7 w-7 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground max-sm:h-11 max-sm:w-11 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'; // Shown on hover or focus, and always while set; a touch screen has no // hover, so there they always show. @@ -245,30 +235,6 @@ export function ObjectViewSwitcherMenu({ )} - {view.personal && onMakeSharedView && ( - - )} - {!view.personal && view.unsharable && onUnshareView && ( - - )} {view.personal && onDeletePersonalView && ( {/* The dropdown's body (objectstack#35553): the views, grouped, and - 「Add view」, which turns it into the in-place create card. - w-80, not w-72 (objectstack#36371): a personal row's hidden - actions keep their width, and 「Make shared」 is a sixth - icon, so at w-72 a two-word name broke onto three lines. */} + 「Add view」, which turns it into the in-place create card. */} @@ -333,8 +319,6 @@ export function useObjectViewTitleSwitcher({ create, onRenamePersonalView, onDeletePersonalView, - onMakeSharedView, - onUnshareView, }: { views: ReturnType; savedViews: Parameters[0]['savedViews']; @@ -370,13 +354,6 @@ export function useObjectViewTitleSwitcher({ }; onRenamePersonalView?: (viewId: string) => void; onDeletePersonalView?: (viewId: string) => void; - /** - * objectstack#36371 — for a reader who may share views: 「Make shared」 on - * their own views, and 「Unshare」 on each shared view `isUnsharableView` - * admits, judged from the same item Manage views lists. - */ - onMakeSharedView?: (viewId: string) => void; - onUnshareView?: (viewId: string) => void; }) { const createInPlace = useCreateViewInPlace({ objectName: objectDef.name, @@ -464,19 +441,14 @@ export function useObjectViewTitleSwitcher({ const customized = saved?.overrides?.package === packageId; return { ...item, definitionReadonly: true, ...(customized ? { customized: true } : {}) }; }); - const manageItemOf = new Map(viewTabItems.map((item) => [item.id, item])); const switcherViews: TitleSwitcherView[] = viewItems.map((item) => { const personal = personalViewIds.has(item.id); - const manageItem = personal ? undefined : manageItemOf.get(item.id); - const unsharable = !!onUnshareView && !!manageItem - && isUnsharableView(manageItem, savedViews.find((sv: any) => viewRowId(sv) === item.id)); return { id: item.id, label: item.label, type: item.type, authored: !personal && !!item.readonly, ...(personal ? { personal: true } : {}), - ...(unsharable ? { unsharable: true } : {}), }; }); const viewIds = switcherViews.map((v) => v.id); @@ -518,8 +490,6 @@ export function useObjectViewTitleSwitcher({ create={createOptions} onRenamePersonalView={onRenamePersonalView} onDeletePersonalView={onDeletePersonalView} - onMakeSharedView={onMakeSharedView} - onUnshareView={onUnshareView} t={t} /> ) : null; diff --git a/ui/packages/app-shell/src/views/objectViewViewSharing.test.tsx b/ui/packages/app-shell/src/views/objectViewViewSharing.test.tsx index 5d4c5d318ee..41d1f5a771c 100644 --- a/ui/packages/app-shell/src/views/objectViewViewSharing.test.tsx +++ b/ui/packages/app-shell/src/views/objectViewViewSharing.test.tsx @@ -1,20 +1,15 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * objectstack#36371 — who may share a list's views, and the three acts that - * share or unshare one (`./objectViewViewSharing.ts`). + * objectstack#36409 — who may create a shared view from a list's view + * dropdown, and the act that creates one (`./objectViewViewSharing.ts`). * * WHAT IS PINNED. * - Who: an administrator whose session holds `manage_metadata`; an * administrator without it (an organization administrator) is not offered - * a control the server refuses. - * - Create, shared: saved and published in one act, never left as a draft. - * - Make shared: the reader's row becomes a published view under a key no - * served view holds, then the row is deleted and the pin follows it. - * - Unshare: the view becomes one of the reader's own, then is deleted; a - * delete the server refuses takes the copy back. - * - Which shared views may be unshared: one saved here, never a view the - * object authors, a read-only package ships or a package's customization. + * a Shared choice the server refuses. + * - Create, shared: saved and published in one act, never left as a draft; a + * refused save publishes nothing. */ import { describe, it, expect, vi, beforeEach } from 'vitest'; @@ -23,8 +18,7 @@ import { renderHook, act } from '@testing-library/react'; const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() })); vi.mock('sonner', () => ({ toast })); -import { freeViewKey, isUnsharableView, mayShareViews, useViewSharing } from './objectViewViewSharing'; -import type { PersonalView } from './personalViews'; +import { mayShareViews, useViewSharing } from './objectViewViewSharing'; const t = ((key: string, options?: { defaultValue?: string; name?: string }) => (options?.defaultValue ?? key).replace('{{name}}', options?.name ?? '')) as never; @@ -32,50 +26,33 @@ const t = ((key: string, options?: { defaultValue?: string; name?: string }) => const OBJECT = 'crm_lead'; const OBJECT_DEF = { name: OBJECT, fields: { name: { type: 'text' } } }; -function rig(over: { personal?: PersonalView[]; savedViews?: unknown[]; deleteView?: (...a: unknown[]) => Promise; pinned?: string | null; activeViewId?: string } = {}) { +function rig() { const metadataClient = { save: vi.fn(async () => ({})), publish: vi.fn(async () => ({})), reset: vi.fn(async () => ({})), }; - const dataSource = { deleteView: vi.fn(over.deleteView ?? (async () => ({ deleted: true }))) }; - const personalViews = { - views: over.personal ?? [], - save: vi.fn(async () => 'pv_copy'), - remove: vi.fn(async () => {}), - }; const navigate = vi.fn(); - const setPinnedViewId = vi.fn(); const refresh = vi.fn(); - const confirmHandler = vi.fn(async () => true); - const viewIds = ['all', `${OBJECT}.team`, ...(over.personal ?? []).map((v) => v.id)]; const { result } = renderHook(() => useViewSharing({ objectName: OBJECT, objectDef: OBJECT_DEF, metadataClient, - dataSource, + dataSource: {}, app: { packageId: null }, - personalViews, - savedViews: over.savedViews ?? [], - viewIds, - labelOf: (id) => (id === `${OBJECT}.team` ? 'Team' : id), - activeViewId: over.activeViewId, routeViewId: undefined, navigate, - pinnedViewId: over.pinned ?? null, - setPinnedViewId, refresh, - confirmHandler: confirmHandler as never, t, })); - return { result, metadataClient, dataSource, personalViews, navigate, setPinnedViewId, refresh, confirmHandler }; + return { result, metadataClient, navigate, refresh }; } beforeEach(() => { for (const fn of Object.values(toast)) fn.mockClear(); }); -describe('objectstack#36371 — who may share views', () => { +describe('objectstack#36409 — who may share views', () => { it('an administrator holding manage_metadata; neither half alone', () => { expect(mayShareViews(true, true)).toBe(true); expect(mayShareViews(true, false)).toBe(false); // an organization administrator @@ -84,26 +61,7 @@ describe('objectstack#36371 — who may share views', () => { }); }); -describe('objectstack#36371 — which shared views may be unshared', () => { - it('a saved, published view of the list, and no other', () => { - expect(isUnsharableView({}, { name: 'team' } as never)).toBe(true); - expect(isUnsharableView({ readonly: true }, undefined)).toBe(false); // authored by the object - expect(isUnsharableView({}, undefined)).toBe(false); // not a saved view - expect(isUnsharableView({ definitionReadonly: true }, {})).toBe(false); // a read-only package ships it - expect(isUnsharableView({ customized: true }, {})).toBe(false); // a package view's customization - expect(isUnsharableView({}, { _draft: true })).toBe(false); // an unpublished draft - }); -}); - -describe('objectstack#36371 — the key a view made shared is saved under', () => { - it('the key its name gives, numbered past every served view', () => { - expect(freeViewKey(OBJECT, 'Team', 'grid', ['all'])).toBe('team'); - expect(freeViewKey(OBJECT, 'Team', 'grid', [`${OBJECT}.team`])).toBe('team_2'); - expect(freeViewKey(OBJECT, 'Team', 'grid', ['team', `${OBJECT}.team_2`])).toBe('team_3'); - }); -}); - -describe('objectstack#36371 — Create, shared', () => { +describe('objectstack#36409 — Create, shared', () => { it('saves and publishes the new view in one act, and opens it', async () => { const r = rig(); let created = false; @@ -131,78 +89,3 @@ describe('objectstack#36371 — Create, shared', () => { expect(toast.error).toHaveBeenCalled(); }); }); - -describe('objectstack#36371 — Make shared', () => { - const MINE: PersonalView = { id: 'pv_1', label: 'Team', config: { type: 'kanban', columns: ['name'], kanban: { groupByField: 'name' } } }; - - it('publishes the row\'s body as a new view under a free key, then deletes the row and moves the pin', async () => { - const r = rig({ personal: [MINE], pinned: 'pv_1', activeViewId: 'pv_1' }); - await act(async () => { await r.result.current.makeShared('pv_1'); }); - expect(r.confirmHandler).toHaveBeenCalledTimes(1); - const [, name, body] = r.metadataClient.save.mock.calls[0] as unknown as [string, string, Record]; - // `team` is served already, so the next free key. - expect(name).toBe(`${OBJECT}.team_2`); - expect(body).toMatchObject({ name: `${OBJECT}.team_2`, label: 'Team', config: { type: 'kanban', kanban: { groupByField: 'name' }, data: { object: OBJECT } } }); - expect(r.metadataClient.publish).toHaveBeenCalledWith('view', `${OBJECT}.team_2`); - expect(r.personalViews.remove).toHaveBeenCalledWith('pv_1'); - expect(r.setPinnedViewId).toHaveBeenCalledWith(`${OBJECT}.team_2`); - expect(r.navigate).toHaveBeenCalledWith(`view/${OBJECT}.team_2`); - expect(toast.success).toHaveBeenCalled(); - }); - - it('a declined confirm writes nothing', async () => { - const r = rig({ personal: [MINE] }); - r.confirmHandler.mockResolvedValueOnce(false); - await act(async () => { await r.result.current.makeShared('pv_1'); }); - expect(r.metadataClient.save).not.toHaveBeenCalled(); - expect(r.personalViews.remove).not.toHaveBeenCalled(); - }); - - it('a refused publish keeps the reader\'s row: nothing changed', async () => { - const r = rig({ personal: [MINE] }); - r.metadataClient.publish.mockRejectedValueOnce(new Error('refused')); - await act(async () => { await r.result.current.makeShared('pv_1'); }); - expect(r.personalViews.remove).not.toHaveBeenCalled(); - expect(toast.error).toHaveBeenCalled(); - }); -}); - -describe('objectstack#36371 — Unshare', () => { - const SAVED = { id: `${OBJECT}.team`, name: `${OBJECT}.team`, label: 'Team', type: 'grid', columns: ['name'], filter: [['name', '=', 'x']] }; - - it('copies the view into the reader\'s own views, then deletes the shared view and opens the copy', async () => { - const r = rig({ savedViews: [SAVED], pinned: `${OBJECT}.team`, activeViewId: `${OBJECT}.team` }); - await act(async () => { await r.result.current.unshare(`${OBJECT}.team`); }); - expect(r.personalViews.save).toHaveBeenCalledTimes(1); - const [label, config] = r.personalViews.save.mock.calls[0] as unknown as [string, Record]; - expect(label).toBe('Team'); - expect(config).toMatchObject({ type: 'grid', columns: ['name'], filter: [['name', '=', 'x']], data: { object: OBJECT } }); - expect(r.dataSource.deleteView).toHaveBeenCalledWith(OBJECT, `${OBJECT}.team`); - expect(r.personalViews.remove).not.toHaveBeenCalled(); - expect(r.setPinnedViewId).toHaveBeenCalledWith('pv_copy'); - expect(r.navigate).toHaveBeenCalledWith('view/pv_copy'); - }); - - it('a delete the server refuses takes the copy back, and says so', async () => { - const r = rig({ savedViews: [SAVED], deleteView: async () => { throw new Error('Deleting metadata requires the `manage_metadata` capability.'); } }); - await act(async () => { await r.result.current.unshare(`${OBJECT}.team`); }); - expect(r.personalViews.remove).toHaveBeenCalledWith('pv_copy'); - expect(r.refresh).not.toHaveBeenCalled(); - expect(toast.error).toHaveBeenCalled(); - }); - - it('a delete that answers deleted: false is a refusal too', async () => { - const r = rig({ savedViews: [SAVED], deleteView: async () => ({ deleted: false }) }); - await act(async () => { await r.result.current.unshare(`${OBJECT}.team`); }); - expect(r.personalViews.remove).toHaveBeenCalledWith('pv_copy'); - expect(r.navigate).not.toHaveBeenCalled(); - }); - - it('a view that is not a saved view of the list is left alone', async () => { - const r = rig({ savedViews: [] }); - await act(async () => { await r.result.current.unshare('all'); }); - expect(r.confirmHandler).not.toHaveBeenCalled(); - expect(r.personalViews.save).not.toHaveBeenCalled(); - expect(r.dataSource.deleteView).not.toHaveBeenCalled(); - }); -}); diff --git a/ui/packages/app-shell/src/views/objectViewViewSharing.ts b/ui/packages/app-shell/src/views/objectViewViewSharing.ts index 2e5c3c843a0..622523aa10a 100644 --- a/ui/packages/app-shell/src/views/objectViewViewSharing.ts +++ b/ui/packages/app-shell/src/views/objectViewViewSharing.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * objectstack#36371 — who may share a list's views, and the three acts that - * share or unshare one from the view dropdown. + * objectstack#36409 — who may create a shared view from a list's view dropdown, + * and the act that creates one. * * The rule (the maintainer's): only an administrator makes a view everyone * sees. A shared view is `view` metadata, written through `PUT /meta/view/:name`, @@ -11,31 +11,22 @@ * * - **who** ({@link mayShareViews}): an administrator whose session holds the * capability that door asks. An organization administrator without it is not - * offered a control the server would answer `403`; + * offered a Shared choice the server would answer `403`; * - **Create, shared** ({@link UseViewSharing.createShared}), from the add-view * card: the new view is saved and published in one act - * (`saveAndPublishRuntimeMetadata`), so everyone sees it on their next read; - * - **Make shared** ({@link UseViewSharing.makeShared}), on one of the reader's - * own views: its stored body becomes a new shared view, published, and the - * reader's row is then deleted; - * - **Unshare** ({@link UseViewSharing.unshare}), on a shared view saved here - * (never a view a package ships, never a package view's customization): it - * becomes one of the reader's own views, then the shared view is deleted. A - * delete the server refuses takes the copy back, so nothing changes. + * (`saveAndPublishRuntimeMetadata`, the maintainer's 「保存即生效」), so + * everyone sees it on their next read; a refused save publishes nothing. * - * Each act says what it did, and a refusal is said with the door's own words. + * Sharing or unsharing an existing view is not offered (the maintainer: not + * now). */ import { useCallback } from 'react'; import { toast } from 'sonner'; -import { formatMetadataError } from '@object-ui/data-objectstack'; import type { useObjectTranslation } from '@object-ui/i18n'; -import type { useConsoleActionRuntime } from '../hooks/useConsoleActionRuntime.js'; -import { viewRowId } from '../utils/viewIdentity.js'; -import { buildAddViewSpec, buildViewConfigSaveBody } from './objectViewTabs.js'; -import { deriveViewKey, saveAndPublishRuntimeMetadata, viewEnvelope } from './runtime-metadata-persistence.js'; +import { buildAddViewSpec } from './objectViewTabs.js'; +import { saveAndPublishRuntimeMetadata, viewEnvelope } from './runtime-metadata-persistence.js'; import type { RuntimeCreateApp, RuntimePersistCtx } from './runtime-metadata-persistence.js'; -import type { PersonalView } from './personalViews.js'; import { viewSaveRefusalText } from './viewSaveRefusal.js'; type TFn = ReturnType['t']; @@ -50,49 +41,9 @@ export function mayShareViews(isAdmin: boolean, canAuthorMetadata: boolean): boo return isAdmin && canAuthorMetadata; } -/** - * The key a view made shared from one of the reader's own is saved under: the - * key its name gives (`deriveViewKey`), numbered past every view this list - * already serves, so the save never lands on another view's name (a publish - * there would replace that view). - */ -export function freeViewKey(objectName: string, label: string, type: string | undefined, taken: Iterable): string { - const used = new Set(); - for (const id of taken) { - if (typeof id !== 'string' || !id) continue; - used.add(id); - if (id.startsWith(`${objectName}.`)) used.add(id.slice(objectName.length + 1)); - } - const base = deriveViewKey({ label, type }); - if (!used.has(base)) return base; - for (let i = 2; i < 10_000; i++) { - const candidate = `${base}_${i}`; - if (!used.has(candidate)) return candidate; - } - return `${base}_${Date.now().toString(36)}`; -} - -/** - * May a shared view of this list be unshared? A view saved here: one the - * object's metadata does not author, that no read-only package ships - * (`definitionReadonly`), that is no package view's customization - * (`customized`) and that is not an unpublished draft. Judged from the same - * Manage views item that decides whether Delete is offered there. - */ -export function isUnsharableView( - item: { readonly?: boolean; definitionReadonly?: boolean; customized?: boolean }, - saved: { _draft?: unknown } | undefined, -): boolean { - return !!saved && !item.readonly && !item.definitionReadonly && !item.customized && saved._draft !== true; -} - export interface UseViewSharing { /** The add-view card's door for a shared view; resolves whether it was created. */ createShared: (config: Record) => Promise; - /** 「Make shared」 on one of the reader's own views. */ - makeShared: (personalViewId: string) => Promise; - /** 「Unshare」 on a shared view saved here ({@link isUnsharableView}). */ - unshare: (viewId: string) => Promise; } export function useViewSharing({ @@ -101,17 +52,9 @@ export function useViewSharing({ metadataClient, dataSource, app, - personalViews, - savedViews, - viewIds, - labelOf, - activeViewId, routeViewId, navigate, - pinnedViewId, - setPinnedViewId, refresh, - confirmHandler, t, }: { objectName: string; @@ -120,26 +63,11 @@ export function useViewSharing({ dataSource: any; /** The app the list is in, so a new shared view is saved into its package. */ app: RuntimeCreateApp; - personalViews: { - views: readonly PersonalView[]; - save: (label: string, config: Record) => Promise; - remove: (id: string) => Promise; - }; - savedViews: readonly unknown[]; - /** Every view id the list serves (shared and the reader's own). */ - viewIds: readonly string[]; - /** A view's name as the dropdown draws it. */ - labelOf: (viewId: string) => string; - activeViewId: string | undefined; /** The route's view segment, when the address names one. */ routeViewId: string | undefined; navigate: (to: string, options?: { relative?: 'path' }) => void; - /** The view the reader pinned for this list, resolved to its id among `viewIds`. */ - pinnedViewId: string | null; - setPinnedViewId: (viewId: string | null) => void; /** Read the saved views again. */ refresh: () => void; - confirmHandler: ReturnType['confirmHandler']; t: TFn; }): UseViewSharing { const openView = useCallback((id: string) => { @@ -180,100 +108,5 @@ export function useViewSharing({ } }, [metadataClient, objectDef, objectName, publishNew, refresh, openView, t]); - const makeShared = useCallback(async (personalViewId: string): Promise => { - const target = personalViews.views.find((v) => v.id === personalViewId); - if (!target || !metadataClient) return; - const confirmed = await confirmHandler( - t('view.switcher.makeSharedConfirm', { - name: target.label, - defaultValue: 'Everyone who can see this list will find “{{name}}” under Shared views. It leaves your My views.', - }), - { - title: t('view.switcher.makeSharedTitle', { defaultValue: 'Share this view with everyone?' }), - confirmText: t('view.switcher.makeShared', { defaultValue: 'Make shared' }), - cancelText: t('console.objectView.cancel'), - }, - ); - if (!confirmed) return; - const type = typeof target.config.type === 'string' ? target.config.type : 'grid'; - const key = freeViewKey(objectName, target.label, type, viewIds); - const env = viewEnvelope(objectName, { ...target.config, type }, { name: key, label: target.label }); - try { - if (!(await publishNew(env.name, env as unknown as Record))) return; - } catch (err) { - console.error('[ObjectView] Failed to share a view:', err); - toast.error(t('form.saveError'), { - description: viewSaveRefusalText(err, t), - classNames: { description: 'whitespace-pre-line' }, - }); - return; - } - // The shared view exists now: the reader's own copy goes, and with it - // their pin moves to the shared one. - try { - await personalViews.remove(personalViewId); - } catch (err) { - console.error('[ObjectView] A shared view kept its source in My views:', err); - toast.warning(t('view.switcher.makeSharedKeptCopy', { - defaultValue: 'The view is shared, but your own copy could not be removed from My views. You can delete it there.', - })); - } - if (pinnedViewId === personalViewId) setPinnedViewId(env.name); - refresh(); - if (personalViewId === activeViewId) openView(env.name); - toast.success(t('view.switcher.makeSharedDone', { name: target.label, defaultValue: '“{{name}}” is now shared' })); - }, [personalViews, metadataClient, confirmHandler, t, objectName, viewIds, publishNew, pinnedViewId, setPinnedViewId, refresh, activeViewId, openView]); - - const unshare = useCallback(async (viewId: string): Promise => { - const saved = savedViews.find((sv) => viewRowId(sv) === viewId) as Record | undefined; - if (!saved || typeof dataSource?.deleteView !== 'function') return; - const label = labelOf(viewId); - const confirmed = await confirmHandler( - t('view.switcher.unshareConfirm', { - name: label, - defaultValue: '“{{name}}” moves to your My views. Everyone else stops seeing it, and anyone who has it open goes back to the default view.', - }), - { - title: t('view.switcher.unshareTitle', { defaultValue: 'Stop sharing this view?' }), - confirmText: t('view.switcher.unshare', { defaultValue: 'Unshare' }), - cancelText: t('console.objectView.cancel'), - }, - ); - if (!confirmed) return; - const { config } = buildViewConfigSaveBody(objectName, { ...saved, id: viewId }); - let copyId: string; - try { - copyId = await personalViews.save(label, config as Record); - } catch (err) { - console.error('[ObjectView] Failed to copy a view into My views:', err); - toast.error(t('view.switcher.unshareFailed', { defaultValue: 'The view could not be unshared' }), { - description: viewSaveRefusalText(err, t), - classNames: { description: 'whitespace-pre-line' }, - }); - return; - } - try { - const receipt = await dataSource.deleteView(objectName, viewId); - if (receipt && receipt.deleted === false) throw new Error(t('view.switcher.unshareNotDeleted', { defaultValue: 'The server kept the shared view.' })); - } catch (err) { - // Nothing changed for anyone: the copy is taken back. - try { - await personalViews.remove(copyId); - } catch (removeErr) { - console.error('[ObjectView] The copy of a view that stayed shared is left in My views:', removeErr); - } - console.error('[ObjectView] Failed to unshare a view:', err); - toast.error(t('view.switcher.unshareFailed', { defaultValue: 'The view could not be unshared' }), { - description: formatMetadataError(err), - classNames: { description: 'whitespace-pre-line' }, - }); - return; - } - if (pinnedViewId === viewId) setPinnedViewId(copyId); - refresh(); - if (viewId === activeViewId) openView(copyId); - toast.success(t('view.switcher.unshareDone', { name: label, defaultValue: '“{{name}}” is in your My views now' })); - }, [savedViews, dataSource, labelOf, confirmHandler, t, objectName, personalViews, pinnedViewId, setPinnedViewId, refresh, activeViewId, openView]); - - return { createShared, makeShared, unshare }; + return { createShared }; } diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts index 48def4fb0e5..744b956cf71 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts @@ -531,8 +531,8 @@ export type SaveAndPublishOutcome = 'published' | 'pending-draft'; * it wrote is discarded (it was the only one, by the pin) and the refusal is * rethrown. Any other refusal is rethrown as it came. * - * objectstack#36371 — a NEW view shared at once (the view dropdown's create - * and its 「Make shared」) passes the app it was made in + * objectstack#36409 — a NEW view shared at once (the view dropdown's create) + * passes the app it was made in * ({@link RuntimePersistCtx.app}): its first write is saved into the app's * package as {@link createRuntimeMetadata} saves it. The publish names no * package (ADR-0146 D8 addresses the name's one holder). When no package can be diff --git a/ui/packages/app-shell/src/views/writeRefusalCensus-11583.test.ts b/ui/packages/app-shell/src/views/writeRefusalCensus-11583.test.ts index 627d3ff0ffd..4fee778d117 100644 --- a/ui/packages/app-shell/src/views/writeRefusalCensus-11583.test.ts +++ b/ui/packages/app-shell/src/views/writeRefusalCensus-11583.test.ts @@ -107,11 +107,6 @@ const LEDGER: Row[] = [ kind: 'surfaces', pin: 'ObjectView.viewWriteRefusal-11583.test.tsx', reason: 'Delete: the translated `objectViewActions.deleteFailed` title, with the door\'s message as the description (objectui#12398).', }, - { - file: 'objectViewViewSharing.ts', symbol: 'unshare', callee: 'deleteView', calls: 1, - kind: 'surfaces', pin: 'objectViewViewSharing.test.tsx', - reason: 'Unshare (objectstack#36371): a refused delete, or one answered `deleted: false`, takes the My views copy back and toasts the translated `view.switcher.unshareFailed` title with the door\'s message.', - }, { file: 'objectViewViewCrud.tsx', symbol: 'handlePinView', callee: 'updateView', calls: 1, kind: 'surfaces', pin: 'ObjectView.viewWriteRefusal-11583.test.tsx', diff --git a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts index e53b35578e2..40195cbad94 100644 --- a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts +++ b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts @@ -459,11 +459,7 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // `console.objectView.restoreFactoryConfirm` and `restoreFactoryDone`, the // factory-view restore's question and result naming the view („{{name}}“) // — two interpolated spans, view data. - // 127 once objectstack-ai/objectstack#36371 added the view switcher's - // `makeSharedConfirm`, `makeSharedDone`, `unshareConfirm` and - // `unshareDone`, each naming the view („{{name}}“) — four interpolated - // spans, view data. - expect(okSpans, 'correctly paired spans').toBe(127); + expect(okSpans, 'correctly paired spans').toBe(123); }); it('keeps the count identity that replaces the card’s count(„) === count(“)', () => { @@ -584,9 +580,8 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // `console.objectView.draft.saveToViewConfirm`, one more matched pair. // 123 / 123 / 0 after objectstack-ai/objectstack#36011 added // `console.objectView.restoreFactoryConfirm` and `restoreFactoryDone`, two - // more matched pairs. 127 / 127 / 0 after objectstack-ai/objectstack#36371 - // added four view-switcher sharing strings, four more matched pairs. - expect({ open, close, rdq }).toEqual({ open: 127, close: 127, rdq: 0 }); + // more matched pairs. + expect({ open, close, rdq }).toEqual({ open: 123, close: 123, rdq: 0 }); // The durable shape: every „ closed by a “, every surplus “ an English // opener answered by a ”. Survived translating the two English values. expect(close).toBe(open + rdq); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 9743d8b9ffc..6ff0abf8eb5 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1408,19 +1408,8 @@ const ar = { includeCurrent: 'تضمين عوامل التصفية والفرز الحالية', scopeShared: 'مشترك', scopeHint: 'العروض المشتركة يراها كل من يمكنه رؤية هذه القائمة', - // objectstack#36371 — sharing a view, and a view that is gone. - makeShared: 'جعله مشتركًا', - makeSharedTitle: 'مشاركة هذا العرض مع الجميع؟', - makeSharedConfirm: 'سيجد كل من يمكنه رؤية هذه القائمة «{{name}}» ضمن العروض المشتركة، ويخرج من عروضي.', - makeSharedDone: 'أصبح «{{name}}» مشتركًا', - makeSharedKeptCopy: 'تمت مشاركة العرض، لكن تعذّر حذف نسختك من عروضي. يمكنك حذفها من هناك.', + // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'توجد مسودة غير منشورة تستخدم اسم هذا العرض بالفعل، لذلك لم تتم المشاركة. غيّر اسم العرض وحاول مرة أخرى.', - unshare: 'إلغاء المشاركة', - unshareTitle: 'إيقاف مشاركة هذا العرض؟', - unshareConfirm: 'ينتقل «{{name}}» إلى عروضي. لن يراه الآخرون بعد الآن، ومن يفتحه يعود إلى العرض الافتراضي.', - unshareDone: 'أصبح «{{name}}» ضمن عروضي الآن', - unshareFailed: 'تعذّر إلغاء مشاركة العرض', - unshareNotDeleted: 'احتفظ الخادم بالعرض المشترك.', viewGone: 'العرض الذي فتحته لم يعد متاحًا، لذا تعرض القائمة العرض الافتراضي.', create: 'إنشاء', }, diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 1852ad15dd6..6b0c0eaacaf 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1271,19 +1271,8 @@ const de = { includeCurrent: 'Aktuelle Filter und Sortierung übernehmen', scopeShared: 'Geteilt', scopeHint: 'Geteilte Ansichten sieht jeder, der diese Liste sehen kann', - // objectstack#36371 — sharing a view, and a view that is gone. - makeShared: 'Teilen', - makeSharedTitle: 'Diese Ansicht mit allen teilen?', - makeSharedConfirm: 'Alle, die diese Liste sehen, finden „{{name}}“ unter Geteilte Ansichten. Sie verschwindet aus Meine Ansichten.', - makeSharedDone: '„{{name}}“ ist jetzt geteilt', - makeSharedKeptCopy: 'Die Ansicht ist geteilt, aber Ihre eigene Kopie konnte nicht aus Meine Ansichten entfernt werden. Sie können sie dort löschen.', + // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'Ein unveröffentlichter Entwurf verwendet bereits den Namen dieser Ansicht, daher wurde nichts geteilt. Geben Sie der Ansicht einen anderen Namen und versuchen Sie es erneut.', - unshare: 'Nicht mehr teilen', - unshareTitle: 'Diese Ansicht nicht mehr teilen?', - unshareConfirm: '„{{name}}“ wandert in Meine Ansichten. Alle anderen sehen sie nicht mehr, und wer sie geöffnet hat, kehrt zur Standardansicht zurück.', - unshareDone: '„{{name}}“ ist jetzt in Meine Ansichten', - unshareFailed: 'Die Ansicht konnte nicht mehr privat gemacht werden', - unshareNotDeleted: 'Der Server hat die geteilte Ansicht behalten.', viewGone: 'Die geöffnete Ansicht ist nicht mehr verfügbar, daher zeigt die Liste ihre Standardansicht.', create: 'Erstellen', }, diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 0ef5ac0cba8..2cdac20f635 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1572,19 +1572,8 @@ const en = { includeCurrent: 'Include the current filters and sort', scopeShared: 'Shared', scopeHint: 'Shared views are seen by everyone who can see this list', - // objectstack#36371 — sharing a view, and a view that is gone. - makeShared: 'Make shared', - makeSharedTitle: 'Share this view with everyone?', - makeSharedConfirm: 'Everyone who can see this list will find “{{name}}” under Shared views. It leaves your My views.', - makeSharedDone: '“{{name}}” is now shared', - makeSharedKeptCopy: 'The view is shared, but your own copy could not be removed from My views. You can delete it there.', + // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'An unpublished draft already uses this view’s name, so nothing was shared. Give the view another name and try again.', - unshare: 'Unshare', - unshareTitle: 'Stop sharing this view?', - unshareConfirm: '“{{name}}” moves to your My views. Everyone else stops seeing it, and anyone who has it open goes back to the default view.', - unshareDone: '“{{name}}” is in your My views now', - unshareFailed: 'The view could not be unshared', - unshareNotDeleted: 'The server kept the shared view.', viewGone: 'The view you opened is no longer available, so the list shows its default view.', create: 'Create', }, diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 31cd0b2c6f5..52945511bcd 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1308,19 +1308,8 @@ const es = { includeCurrent: 'Incluir los filtros y el orden actuales', scopeShared: 'Compartida', scopeHint: 'Las vistas compartidas las ve cualquiera que pueda ver esta lista', - // objectstack#36371 — sharing a view, and a view that is gone. - makeShared: 'Compartir', - makeSharedTitle: '¿Compartir esta vista con todos?', - makeSharedConfirm: 'Todos los que pueden ver esta lista encontrarán «{{name}}» en Vistas compartidas. Sale de Mis vistas.', - makeSharedDone: '«{{name}}» ahora está compartida', - makeSharedKeptCopy: 'La vista está compartida, pero no se pudo quitar tu copia de Mis vistas. Puedes eliminarla allí.', + // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'Un borrador sin publicar ya usa el nombre de esta vista, así que no se compartió nada. Ponle otro nombre a la vista e inténtalo de nuevo.', - unshare: 'Dejar de compartir', - unshareTitle: '¿Dejar de compartir esta vista?', - unshareConfirm: '«{{name}}» pasa a Mis vistas. Los demás dejan de verla y quien la tenga abierta vuelve a la vista predeterminada.', - unshareDone: '«{{name}}» está ahora en Mis vistas', - unshareFailed: 'No se pudo dejar de compartir la vista', - unshareNotDeleted: 'El servidor conservó la vista compartida.', viewGone: 'La vista que abriste ya no está disponible, así que la lista muestra su vista predeterminada.', create: 'Crear', }, diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index d78b3ecca62..e114fbe6522 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1303,19 +1303,8 @@ const fr = { includeCurrent: 'Inclure les filtres et le tri actuels', scopeShared: 'Partagée', scopeHint: 'Les vues partagées sont visibles par tous ceux qui voient cette liste', - // objectstack#36371 — sharing a view, and a view that is gone. - makeShared: 'Partager', - makeSharedTitle: 'Partager cette vue avec tout le monde ?', - makeSharedConfirm: 'Tous ceux qui voient cette liste trouveront « {{name}} » dans Vues partagées. Elle quitte Mes vues.', - makeSharedDone: '« {{name}} » est maintenant partagée', - makeSharedKeptCopy: 'La vue est partagée, mais votre copie n’a pas pu être retirée de Mes vues. Vous pouvez la supprimer là-bas.', + // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'Un brouillon non publié utilise déjà le nom de cette vue, donc rien n’a été partagé. Donnez un autre nom à la vue et réessayez.', - unshare: 'Ne plus partager', - unshareTitle: 'Ne plus partager cette vue ?', - unshareConfirm: '« {{name}} » passe dans Mes vues. Les autres ne la voient plus, et ceux qui l’ont ouverte reviennent à la vue par défaut.', - unshareDone: '« {{name}} » est maintenant dans Mes vues', - unshareFailed: 'Impossible de ne plus partager la vue', - unshareNotDeleted: 'Le serveur a conservé la vue partagée.', viewGone: 'La vue ouverte n’est plus disponible, la liste affiche donc sa vue par défaut.', create: 'Créer', }, diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 1024793918f..3c8167fa93f 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1271,19 +1271,8 @@ const ja = { includeCurrent: '現在のフィルターと並べ替えを含める', scopeShared: '共有', scopeHint: '共有ビューはこのリストを見られる全員に表示されます', - // objectstack#36371 — sharing a view, and a view that is gone. - makeShared: '共有する', - makeSharedTitle: 'このビューを全員と共有しますか?', - makeSharedConfirm: 'このリストを見られる全員が「共有ビュー」で「{{name}}」を見られるようになります。「マイビュー」からは外れます。', - makeSharedDone: '「{{name}}」を共有しました', - makeSharedKeptCopy: 'ビューは共有されましたが、「マイビュー」の自分のコピーを削除できませんでした。そこで削除できます。', + // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: '未公開の下書きがすでにこのビューの名前を使っているため、共有しませんでした。ビューの名前を変えてもう一度お試しください。', - unshare: '共有を解除', - unshareTitle: 'このビューの共有を解除しますか?', - unshareConfirm: '「{{name}}」は「マイビュー」に移ります。ほかの人には表示されなくなり、開いている人は既定のビューに戻ります。', - unshareDone: '「{{name}}」は「マイビュー」に移りました', - unshareFailed: 'ビューの共有を解除できませんでした', - unshareNotDeleted: 'サーバーは共有ビューを残しました。', viewGone: '開いたビューはもう存在しないため、リストは既定のビューを表示しています。', create: '作成', }, diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 27765be30de..3a651f85d0c 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1271,19 +1271,8 @@ const ko = { includeCurrent: '현재 필터와 정렬 포함', scopeShared: '공유', scopeHint: '공유 보기는 이 목록을 볼 수 있는 모든 사람에게 표시됩니다', - // objectstack#36371 — sharing a view, and a view that is gone. - makeShared: '공유하기', - makeSharedTitle: '이 보기를 모든 사람과 공유할까요?', - makeSharedConfirm: '이 목록을 볼 수 있는 모든 사람이 공유 보기에서 「{{name}}」을(를) 보게 됩니다. 내 보기에서는 빠집니다.', - makeSharedDone: '「{{name}}」을(를) 공유했습니다', - makeSharedKeptCopy: '보기는 공유되었지만 내 보기의 내 사본을 삭제하지 못했습니다. 그곳에서 삭제할 수 있습니다.', + // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: '게시되지 않은 초안이 이미 이 보기의 이름을 사용하고 있어 공유하지 않았습니다. 보기 이름을 바꾸고 다시 시도하세요.', - unshare: '공유 해제', - unshareTitle: '이 보기의 공유를 해제할까요?', - unshareConfirm: '「{{name}}」이(가) 내 보기로 옮겨집니다. 다른 사람에게는 더 이상 보이지 않으며, 열어 둔 사람은 기본 보기로 돌아갑니다.', - unshareDone: '「{{name}}」이(가) 이제 내 보기에 있습니다', - unshareFailed: '보기의 공유를 해제하지 못했습니다', - unshareNotDeleted: '서버가 공유 보기를 유지했습니다.', viewGone: '연 보기가 더 이상 없으므로 목록에 기본 보기가 표시됩니다.', create: '만들기', }, diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 3e4c6a82b36..1fea106541c 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1303,19 +1303,8 @@ const pt = { includeCurrent: 'Incluir os filtros e a ordenação atuais', scopeShared: 'Compartilhada', scopeHint: 'Visualizações compartilhadas são vistas por todos que podem ver esta lista', - // objectstack#36371 — sharing a view, and a view that is gone. - makeShared: 'Compartilhar', - makeSharedTitle: 'Compartilhar esta visualização com todos?', - makeSharedConfirm: 'Todos que podem ver esta lista encontrarão “{{name}}” em Visualizações compartilhadas. Ela sai de Minhas visualizações.', - makeSharedDone: '“{{name}}” agora está compartilhada', - makeSharedKeptCopy: 'A visualização está compartilhada, mas sua cópia não pôde ser removida de Minhas visualizações. Você pode excluí-la lá.', + // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'Um rascunho não publicado já usa o nome desta visualização, então nada foi compartilhado. Dê outro nome à visualização e tente novamente.', - unshare: 'Deixar de compartilhar', - unshareTitle: 'Deixar de compartilhar esta visualização?', - unshareConfirm: '“{{name}}” vai para Minhas visualizações. Os demais deixam de vê-la, e quem estiver com ela aberta volta à visualização padrão.', - unshareDone: '“{{name}}” agora está em Minhas visualizações', - unshareFailed: 'Não foi possível deixar de compartilhar a visualização', - unshareNotDeleted: 'O servidor manteve a visualização compartilhada.', viewGone: 'A visualização que você abriu não está mais disponível, então a lista mostra a visualização padrão.', create: 'Criar', }, diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 94fdccc5ac5..5aa2be19372 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1341,19 +1341,8 @@ const ru = { includeCurrent: 'Включить текущие фильтры и сортировку', scopeShared: 'Общее', scopeHint: 'Общие представления видны всем, кто видит этот список', - // objectstack#36371 — sharing a view, and a view that is gone. - makeShared: 'Сделать общим', - makeSharedTitle: 'Открыть это представление для всех?', - makeSharedConfirm: 'Все, кто видит этот список, найдут «{{name}}» в разделе «Общие представления». Из «Моих представлений» оно уйдёт.', - makeSharedDone: '«{{name}}» теперь общее', - makeSharedKeptCopy: 'Представление стало общим, но вашу копию не удалось удалить из «Моих представлений». Удалите её там.', + // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'Неопубликованный черновик уже использует имя этого представления, поэтому ничего не открыто для всех. Переименуйте представление и попробуйте снова.', - unshare: 'Закрыть доступ', - unshareTitle: 'Закрыть общий доступ к этому представлению?', - unshareConfirm: '«{{name}}» переходит в ваши «Мои представления». Остальные перестанут его видеть, а у тех, кто его открыл, откроется представление по умолчанию.', - unshareDone: '«{{name}}» теперь в ваших «Моих представлениях»', - unshareFailed: 'Не удалось закрыть общий доступ к представлению', - unshareNotDeleted: 'Сервер сохранил общее представление.', viewGone: 'Открытое представление больше недоступно, поэтому список показывает представление по умолчанию.', create: 'Создать', }, diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 62bd10a4bea..9805057a8e3 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1298,19 +1298,8 @@ const zh = { includeCurrent: '包含当前的筛选和排序', scopeShared: '共享', scopeHint: '共享视图对能看到此列表的所有人可见', - // objectstack#36371 — sharing a view, and a view that is gone. - makeShared: '设为共享', - makeSharedTitle: '把这个视图共享给所有人?', - makeSharedConfirm: '能看到此列表的所有人都会在「共享视图」里看到「{{name}}」。它会从你的「我的视图」中移走。', - makeSharedDone: '「{{name}}」已共享', - makeSharedKeptCopy: '视图已共享,但你自己的那份没能从「我的视图」中删除,可以在那里手动删除。', + // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: '一个尚未发布的草稿已经用了这个视图的名称,所以没有共享。请换个名称再试。', - unshare: '取消共享', - unshareTitle: '不再共享这个视图?', - unshareConfirm: '「{{name}}」会回到你的「我的视图」。其他人将看不到它,正开着它的人会回到默认视图。', - unshareDone: '「{{name}}」已回到你的「我的视图」', - unshareFailed: '无法取消共享', - unshareNotDeleted: '服务器保留了这个共享视图。', viewGone: '你打开的视图已不存在,列表显示的是默认视图。', create: '创建', }, diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 4822ae6be46..23dfd23d925 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1298,19 +1298,8 @@ const zhHant = { includeCurrent: '包含當前的篩選和排序', scopeShared: '共享', scopeHint: '共享檢視對能看到此列表的所有人可見', - // objectstack#36371 — sharing a view, and a view that is gone. - makeShared: '設為共享', - makeSharedTitle: '把這個檢視共享給所有人?', - makeSharedConfirm: '能看到此列表的所有人都會在「共享檢視」裡看到「{{name}}」。它會從你的「我的檢視」中移走。', - makeSharedDone: '「{{name}}」已共享', - makeSharedKeptCopy: '檢視已共享,但你自己的那份沒能從「我的檢視」中刪除,可以在那裡手動刪除。', + // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: '一個尚未釋出的草稿已經用了這個檢視的名稱,所以沒有共享。請換個名稱再試。', - unshare: '取消共享', - unshareTitle: '不再共享這個檢視?', - unshareConfirm: '「{{name}}」會回到你的「我的檢視」。其他人將看不到它,正開著它的人會回到預設檢視。', - unshareDone: '「{{name}}」已回到你的「我的檢視」', - unshareFailed: '無法取消共享', - unshareNotDeleted: '伺服器保留了這個共享檢視。', viewGone: '你開啟的檢視已不存在,列表顯示的是預設檢視。', create: '建立', }, From 6554451104d5da29e53ab3f6d93b77b3c4e035c1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 12:27:01 +0000 Subject: [PATCH 8/8] test(console): pin where a shared view is saved, and a name a pending draft holds (#36409) saveAndPublishRuntimeMetadata with an app: a writable app package is named on the save, an installed one gets the pair the ensure door returns, an unresolvable one none; publish and the refused-publish discard name no package (ADR-0146 D8); a dashboard ignores the app. createShared over a pending draft says shareNameTaken and publishes, refreshes and opens nothing. Claude-Session: https://claude.ai/code/session_01QsR2jTPMb2q2wRssyREqhQ Co-authored-by: Claude --- .../src/views/objectViewViewSharing.test.tsx | 18 +- ...stence.saveAndPublishIntoApp-36409.test.ts | 175 ++++++++++++++++++ 2 files changed, 192 insertions(+), 1 deletion(-) create mode 100644 ui/packages/app-shell/src/views/runtime-metadata-persistence.saveAndPublishIntoApp-36409.test.ts diff --git a/ui/packages/app-shell/src/views/objectViewViewSharing.test.tsx b/ui/packages/app-shell/src/views/objectViewViewSharing.test.tsx index 41d1f5a771c..fffca4dda79 100644 --- a/ui/packages/app-shell/src/views/objectViewViewSharing.test.tsx +++ b/ui/packages/app-shell/src/views/objectViewViewSharing.test.tsx @@ -9,7 +9,8 @@ * administrator without it (an organization administrator) is not offered * a Shared choice the server refuses. * - Create, shared: saved and published in one act, never left as a draft; a - * refused save publishes nothing. + * refused save publishes nothing, and a name a pending draft holds is said + * (`shareNameTaken`). */ import { describe, it, expect, vi, beforeEach } from 'vitest'; @@ -88,4 +89,19 @@ describe('objectstack#36409 — Create, shared', () => { expect(r.metadataClient.publish).not.toHaveBeenCalled(); expect(toast.error).toHaveBeenCalled(); }); + + it('a name an unpublished draft already holds: told so, reported unsaved, nothing published', async () => { + const r = rig(); + r.metadataClient.save.mockRejectedValueOnce(Object.assign(new Error('pending'), { status: 409, code: 'METADATA_CONFLICT' })); + let created = true; + await act(async () => { + created = await r.result.current.createShared({ type: 'grid', label: 'Hot leads', name: 'hot_leads' }); + }); + expect(created).toBe(false); + expect(r.metadataClient.publish).not.toHaveBeenCalled(); + expect(r.refresh).not.toHaveBeenCalled(); + expect(r.navigate).not.toHaveBeenCalled(); + const [, options] = toast.error.mock.calls[0] as unknown as [string, { description: string }]; + expect(options.description).toContain('An unpublished draft already uses this view’s name'); + }); }); diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.saveAndPublishIntoApp-36409.test.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.saveAndPublishIntoApp-36409.test.ts new file mode 100644 index 00000000000..e90539b4155 --- /dev/null +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.saveAndPublishIntoApp-36409.test.ts @@ -0,0 +1,175 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36409 — a view created Shared from the view dropdown is saved + * and published in one act (`saveAndPublishRuntimeMetadata`), and its first + * write lands in the app it was made in, exactly as `createRuntimeMetadata` + * saves a new view (objectstack#35624, ruling C): the app's own package when + * the server lists it writable, else the pair the ensure door names, else no + * package at all. Only the SAVE names a package: the publish, and the discard + * a refused publish runs, address the name's one holder (ADR-0146 D8). A type + * other than `view` ignores the app. + * + * A REAL `MetadataClient` writes, so each pin reads the request the server + * would receive; the two package doors answer through the page's `fetch`, + * with the bodies `createIntoApp-35624` measured on examples/app-crm. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { MetadataClient } from '@object-ui/data-objectstack'; +import { saveAndPublishRuntimeMetadata, viewEnvelope } from './runtime-metadata-persistence'; + +const json = (status: number, body: unknown) => + new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); + +function packageList(rows: Array<{ id: string; writable: boolean }>) { + return { + success: true, + data: { + packages: rows.map(({ id, writable }) => ({ + manifest: { id, name: id, version: '4.0.0', type: 'app', scope: 'project' }, + writable, + })), + total: rows.length, + hasMore: false, + }, + }; +} + +const ENSURED = { + success: true, + data: { + basePackageId: 'com.example.crm', + packageId: 'com.example.crm.custom', + namespace: 'crm_custom', + dependencyRange: '^4', + created: true, + writable: true, + }, +}; + +let pageCalls: string[] = []; +let writes: Array<{ method: string; url: URL }> = []; + +function stubPageFetch(rows: Array<{ id: string; writable: boolean }>) { + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + pageCalls.push(`${(init?.method ?? 'GET').toUpperCase()} ${url}`); + if (url === '/api/v1/packages') return json(200, packageList(rows)); + if (url.endsWith('/ensure-customization')) return json(201, ENSURED); + return json(404, { success: false, error: { code: 'RESOURCE_NOT_FOUND', message: url, httpStatus: 404 } }); + }), + ); +} + +/** A real client; `refusePublish` answers the publish door `400 VALIDATION_ERROR`. */ +function realClient(refusePublish = false): MetadataClient { + return new MetadataClient({ + baseUrl: 'http://localhost:3000', + fetch: (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(String(input)); + writes.push({ method: (init?.method ?? 'GET').toUpperCase(), url }); + if (refusePublish && url.pathname.endsWith('/publish')) { + return json(400, { success: false, error: { code: 'VALIDATION_ERROR', message: 'refused', httpStatus: 400 } }); + } + return json(200, { success: true, state: 'draft' }); + }) as unknown as typeof fetch, + }); +} + +const env = viewEnvelope('crm_account', { type: 'grid', columns: ['name'] }, { name: 'key_accounts', label: 'Key accounts' }); +const VIEW_PATH = '/api/v1/meta/view/crm_account.key_accounts'; + +/** Every write after the save: none of them may name a package. */ +const packagesNamedAfterSave = () => writes.slice(1).map((w) => w.url.searchParams.get('package')); + +beforeEach(() => { + pageCalls = []; + writes = []; +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe('saveAndPublishRuntimeMetadata saves a new shared view into the app it was made in (objectstack#36409)', () => { + it('a writable app package: the save names it; the publish names none, and no pair is asked for', async () => { + stubPageFetch([{ id: 'com.acme.helpdesk', writable: true }]); + + await expect( + saveAndPublishRuntimeMetadata('view', env.name, env, { + metadataClient: realClient(), + objectName: 'crm_account', + app: { packageId: 'com.acme.helpdesk' }, + }), + ).resolves.toBe('published'); + + expect(pageCalls).toEqual(['GET /api/v1/packages']); + expect(writes).toHaveLength(2); + expect(writes[0]!.url.pathname).toBe(VIEW_PATH); + expect(writes[0]!.url.searchParams.get('mode')).toBe('draft'); + expect(writes[0]!.url.searchParams.get('package')).toBe('com.acme.helpdesk'); + expect(writes[1]!.url.pathname).toBe(`${VIEW_PATH}/publish`); + expect(packagesNamedAfterSave()).toEqual([null]); + }); + + it('an installed (read-only) app package: the save names the pair the ensure door returns; the publish names none', async () => { + stubPageFetch([{ id: 'com.example.crm', writable: false }]); + + await saveAndPublishRuntimeMetadata('view', env.name, env, { + metadataClient: realClient(), + objectName: 'crm_account', + app: { packageId: 'com.example.crm' }, + }); + + expect(pageCalls).toEqual([ + 'GET /api/v1/packages', + 'POST /api/v1/packages/com.example.crm/ensure-customization', + ]); + expect(writes[0]!.url.searchParams.get('package')).toBe('com.example.crm.custom'); + expect(writes[1]!.url.pathname).toBe(`${VIEW_PATH}/publish`); + expect(packagesNamedAfterSave()).toEqual([null]); + }); + + it('an app whose package cannot be resolved (not listed), or no app: the save names none', async () => { + stubPageFetch([{ id: 'com.other.app', writable: true }]); + + await saveAndPublishRuntimeMetadata('view', env.name, env, { metadataClient: realClient(), app: { packageId: 'com.example.crm' } }); + await saveAndPublishRuntimeMetadata('view', env.name, env, { metadataClient: realClient(), app: { packageId: null } }); + await saveAndPublishRuntimeMetadata('view', env.name, env, { metadataClient: realClient() }); + + expect(pageCalls).toEqual(['GET /api/v1/packages']); + expect(writes.map((w) => w.url.searchParams.get('package'))).toEqual([null, null, null, null, null, null]); + }); + + it('a refused publish: the discard of the draft this call wrote names no package either', async () => { + stubPageFetch([{ id: 'com.example.crm', writable: false }]); + + await expect( + saveAndPublishRuntimeMetadata('view', env.name, env, { + metadataClient: realClient(true), + app: { packageId: 'com.example.crm' }, + }), + ).rejects.toBeTruthy(); + + expect(writes[0]!.url.searchParams.get('package')).toBe('com.example.crm.custom'); + expect(writes[1]!.url.pathname).toBe(`${VIEW_PATH}/publish`); + expect(writes.length).toBeGreaterThanOrEqual(3); // the discard + expect(packagesNamedAfterSave().every((p) => p === null)).toBe(true); + }); + + it('a type other than view ignores the app: no package door is asked and the save names none', async () => { + stubPageFetch([{ id: 'com.acme.helpdesk', writable: true }]); + + await saveAndPublishRuntimeMetadata('dashboard', 'ops_board', { name: 'ops_board' }, { + metadataClient: realClient(), + app: { packageId: 'com.acme.helpdesk' }, + }); + + expect(pageCalls).toEqual([]); + expect(writes.map((w) => w.url.searchParams.get('package'))).toEqual([null, null]); + }); +});