diff --git a/.changeset/36900-studio-cmdk.md b/.changeset/36900-studio-cmdk.md new file mode 100644 index 00000000000..58e0cef1e26 --- /dev/null +++ b/.changeset/36900-studio-cmdk.md @@ -0,0 +1,18 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/console': patch +--- + +feat(studio): ⌘K on every Studio design page lists the package's whole menu and its items + +Clause-②: no +Metadata-protocol: none + +Studio redesign: an author switches between items with ×, ‹ › and ⌘K · #36900, part of #36890. + +- **⌘K / Ctrl+K opens the command palette on every Studio design page.** That covers a package's pages and its "All metadata" area, the organization's own flows, and the cross-package positions-and-permissions catalog. Until now only the Studio start page had a palette, and the cross-package catalog had lost the one it used to have. +- **On a package it lists the left menu, group by group**: Data, UI, Automation, Platform, Access, AI (数据、界面、自动化、平台、访问、AI), in the menu's order and under the menu's names. Each group holds the menu's own entries (each type's list, Organization flows, Default sharing, Diagnostics, Positions and permissions), then every item of the types it lists, the package's customizations included. Each item shows its type on the right; a customization is marked "Customization of" the package's name. The packages stay listed, so another package is one pick away. On a package the palette no longer lists every package's objects and flows: the package's own items replace them. The organization's flows and the cross-package catalog keep those lists and add their own menu entries. +- **A pick opens what the menu and the lists open**: an object, a flow or a permission set in its designer, any other item on its own page in "All metadata", exactly where its list row leads. A menu entry goes where the menu entry goes. +- **It never drops unsaved work silently.** A pick, like Studio's Back to app, asks first whenever the page holds unsaved edits, the "All metadata" item page's included. A pick of the page already open on another view (Default sharing, from the Access page) reopens that page on it; a pick of the page already shown just closes the palette. +- The query matches an item by its label, its name or its type, and a menu entry by its label, its type or its group. While the package's lists are still loading, an empty result says "Searching…". The item lists are read only once the palette opens. +- Pressing Escape to close a dialog over a full-screen item editor (the palette, for one) no longer also leaves full screen. diff --git a/ui/e2e/studio-left-menu-36899.spec.ts b/ui/e2e/studio-left-menu-36899.spec.ts index cc24a12b5ac..9ac183bfa73 100644 --- a/ui/e2e/studio-left-menu-36899.spec.ts +++ b/ui/e2e/studio-left-menu-36899.spec.ts @@ -40,7 +40,10 @@ function workspaceSources(): Plugin { name: 'studio-left-menu-workspace-src', enforce: 'pre', async resolveId(id, importer) { - if (id.endsWith('/useMetadata.js') && importer?.endsWith('StudioMenu.tsx')) return METADATA_STUB; + // objectstack#36900 — the menu's reads live in `studioMenuData.ts`, beside the menu. + if (id.endsWith('/useMetadata.js') && (importer?.endsWith('StudioMenu.tsx') || importer?.endsWith('studioMenuData.ts'))) { + return METADATA_STUB; + } const m = /^@object-ui\/([a-z0-9-]+)(?:\/(.+))?$/.exec(id); if (!m) return null; const [, pkg, sub] = m; diff --git a/ui/packages/app-shell/README.md b/ui/packages/app-shell/README.md index ddab6aa11e8..b24a2b4849e 100644 --- a/ui/packages/app-shell/README.md +++ b/ui/packages/app-shell/README.md @@ -1424,11 +1424,32 @@ record search. Its open state and the command that opens it are provided by `CommandPalette` has two scopes. Inside an app it takes `apps`, `activeApp`, `objects`, `onAppChange` and an optional `dataSource`, and searches that app. -`` takes no other prop: it is the palette of the -`/studio` landing, a frame outside every app, which the console mounts under its -own `CommandPaletteProvider`. It leaves out every app-scoped group and the -full-search command (their links start with `/apps/APP`), and lists the Studio's -packages, their objects and their flows, each opening its Studio page. The +`` is the palette of Studio, outside every app. +It leaves out every app-scoped group and the full-search command (their links +start with `/apps/APP`), and lists the Studio's packages, their objects and their +flows, each opening its Studio page. On the `/studio` landing the console mounts +it with no other prop, under its own `CommandPaletteProvider`. + +On a Studio design page, `StudioDesignSurface` mounts it itself, with an optional +`surface` prop (a `StudioPaletteSurface`; objectstack#36900). The surface mounts +its own `CommandPaletteProvider` unless a host above it already mounts one. + +- `renderGroups({ query, open, onLoadingChange })` returns the page's own groups: + `StudioPaletteGroups`, which draws the left menu's six groups (the menu's data + shared through `StudioMenuDataProvider`, read once per page). On a package each + group also holds every item of its types, read from the type's list as its + list page reads it. They are drawn above the packages and mounted only while + the palette is open. `open` closes the palette and opens a Studio address; + `onLoadingChange` keeps the empty result on "Searching…" while a list is read. +- `packageScope: true` (a package's page) drops every package's objects and + flows: the page's groups list that package's items instead. +- `open(to)` is the page's departure (`openStudioPaletteAddress`). It asks the + shell's unsaved-edits seam (`confirmUnsavedLeave`), so every registered editor + is asked about, the "All metadata" item page included, then navigates. A pick + of the page already open on another query re-enters it once the router shows + that query; a pick of the page already shown only closes the palette. + +The header's search trigger is drawn wherever a provider is mounted, so `AppHeader` with `variant="studio"` shows it there. Inside an app, on every route (`system/*` included) from the `lg` breakpoint up, `AppHeader` draws it as the diff --git a/ui/packages/app-shell/src/chrome/CommandPalette.tsx b/ui/packages/app-shell/src/chrome/CommandPalette.tsx index 3096d971246..f6ac95f3f48 100644 --- a/ui/packages/app-shell/src/chrome/CommandPalette.tsx +++ b/ui/packages/app-shell/src/chrome/CommandPalette.tsx @@ -15,7 +15,10 @@ * app. On `/studio` (`scope="studio"`), a frame outside every app, it has no * app-scoped group and no full-search command, whose links all start with * `/apps/APP`; it lists the Studio's packages, objects and flows instead, each - * opening its Studio page. + * opening its Studio page. On a Studio design page (objectstack#36900) the page + * hands the palette its own groups (`surface`): on a package, every type and + * item of that package by the left menu's groups, in place of every package's + * objects and flows. * * A failure inside the palette closes it and leaves the console mounted; the * next open draws a fresh palette (objectui#13387). @@ -123,6 +126,45 @@ interface AppCommandPaletteProps { */ interface StudioCommandPaletteProps { scope: 'studio'; + /** + * The Studio design page the palette is open on (objectstack#36900), which + * hands it that page's own groups; omitted on the `/studio` landing. + */ + surface?: StudioPaletteSurface; +} + +/** What a scope's own groups are handed while the palette is open (objectstack#36900). */ +export interface StudioPaletteGroupsProps { + /** The typed query, matched with `matchesPaletteQuery`. */ + query: string; + /** Closes the palette and opens a Studio address, through the page's {@link StudioPaletteSurface.open}. */ + open: (to: string) => void; + /** Whether a read the groups wait on is still in flight: the empty palette says "Searching…" meanwhile. */ + onLoadingChange: (loading: boolean) => void; +} + +/** + * A Studio design page's half of the palette (objectstack#36900): the page + * knows its scope, its unsaved work and how it re-enters itself, so it draws + * its own groups and opens what is picked. The palette stays free of the + * page's reads: they load with the page, never with the console. + */ +export interface StudioPaletteSurface { + /** + * Whether the page is one package's. Its groups then list that package's + * items, so the palette does not also list every package's objects and + * flows; the package-less scope and the cross-package leg keep them. + */ + packageScope: boolean; + /** The page's groups for the query, drawn above the packages; mounted only while the palette is open. */ + renderGroups: (props: StudioPaletteGroupsProps) => ReactNode; + /** + * Opens a Studio address the palette picked, after it closes: the page asks + * the shell's unsaved-edits seam (every editor that registered edits, not + * only the page's own), and re-enters itself when the address is the page + * already open on another query (`openStudioPaletteAddress`). + */ + open: (to: string) => void; } type CommandPaletteProps = AppCommandPaletteProps | StudioCommandPaletteProps; @@ -372,8 +414,15 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates // objectui#11863 — the Studio's packages, objects and flows, read only while // the palette is open in the `studio` scope, matched like the entries above. - const studio = useStudioPaletteEntries(open && inStudio); + // + // objectstack#36900 — on a design page the page draws its own groups, and + // on a package those list its items in place of every package's objects + // and flows. What the palette picks there opens through the page. + const surface = inStudio ? props.surface : undefined; + const studio = useStudioPaletteEntries(open && inStudio, !surface?.packageScope); const studioMatches = (entry: StudioPaletteEntry) => matches(entry.label, entry.name); + const openStudio = (to: string) => (surface ? runCommand(() => surface.open(to)) : leaveTo(to)); + const [surfaceLoading, setSurfaceLoading] = useState(false); const studioPackages = studio.packages.filter(studioMatches); const studioObjects = studio.objects.filter(studioMatches); const studioFlows = studio.flows.filter(studioMatches); @@ -585,7 +634,7 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates /> - {isSearching || studio.loading ? ( + {isSearching || studio.loading || surfaceLoading ? ( )} + {/* objectstack#36900 — a Studio design page's own groups, first. */} + {open && surface?.renderGroups({ query: inputValue, open: openStudio, onLoadingChange: setSurfaceLoading })} + {/* Studio (objectui#11863): packages, objects and flows, `studio` scope only */} {studioPackages.length > 0 && ( @@ -775,7 +827,7 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates kind="studio-package" entry={entry} Icon={Boxes} - onOpen={() => leaveTo(entry.href)} + onOpen={() => openStudio(entry.href)} /> ))} @@ -788,7 +840,7 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates kind="studio-object" entry={entry} Icon={Database} - onOpen={() => leaveTo(entry.href)} + onOpen={() => openStudio(entry.href)} /> ))} @@ -801,7 +853,7 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates kind="studio-flow" entry={entry} Icon={Workflow} - onOpen={() => leaveTo(entry.href)} + onOpen={() => openStudio(entry.href)} /> ))} @@ -1056,8 +1108,12 @@ const NO_STUDIO_ENTRIES: StudioPaletteEntries = { packages: [], objects: [], flo * cache list. Until the package list answers nothing is listed, so no entry * is drawn without its package. If that read fails, the packaged entries are * left out; the landing behind the palette shows the same read's error. + * + * `crossPackageItems` false (a package's design page, objectstack#36900) + * lists the packages alone: the page lists its own package's items, and the + * objects and flows of every package are neither read nor listed. */ -function useStudioPaletteEntries(enabled: boolean): StudioPaletteEntries { +function useStudioPaletteEntries(enabled: boolean, crossPackageItems = true): StudioPaletteEntries { const metadata = useMetadata(); const { t } = useObjectTranslation(); const [packages, setPackages] = useState(null); @@ -1082,9 +1138,10 @@ function useStudioPaletteEntries(enabled: boolean): StudioPaletteEntries { // Read only while open: each read starts that type's fetch when it has not // been loaded yet, and the provider re-renders this palette when it answers. - const objectItems: StudioServedItem[] = metadata.objects; - const flowItems: StudioServedItem[] = metadata.getItemsByType('flow'); + const objectItems: StudioServedItem[] = crossPackageItems ? metadata.objects : []; + const flowItems: StudioServedItem[] = crossPackageItems ? metadata.getItemsByType('flow') : []; const typeLoading = (type: string) => { + if (!crossPackageItems) return false; const status = metadata.getTypeStatus?.(type); return status === 'idle' || status === 'loading'; }; diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.detailTabs-36901.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.detailTabs-36901.test.tsx index 0e5dc2aa5b5..ed78c5daab3 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.detailTabs-36901.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.detailTabs-36901.test.tsx @@ -201,4 +201,28 @@ describe('carry-forward N2 — Esc reaches the non-Radix fullscreen first', () = expect(await screen.findByTestId('list-page')).toBeInTheDocument(); expect(where()).toBe('/studio/com.acme.app/metadata/canvas_36901?package=com.acme.app'); }); + + it('objectstack#36900 — an Esc a dialog above already took (the command palette closing) leaves the fullscreen and the page alone', async () => { + open('canvas_36901', '?package=com.acme.app'); + await screen.findByTestId('canvas-stub'); + fireEvent.click(screen.getByTitle(t('engine.edit.fullscreen', 'en-US'))); + expect(screen.getByTitle(t('engine.edit.exitFullscreen', 'en-US'))).toBeInTheDocument(); + + // A Radix layer takes its Escape in the capture phase and marks it handled. + const takenByDialog = (e: KeyboardEvent) => { + if (e.key === 'Escape') e.preventDefault(); + }; + document.addEventListener('keydown', takenByDialog, true); + try { + fireEvent.keyDown(document.body, { key: 'Escape' }); + } finally { + document.removeEventListener('keydown', takenByDialog, true); + } + expect(screen.getByTitle(t('engine.edit.exitFullscreen', 'en-US'))).toBeInTheDocument(); + expect(where()).toBe('/studio/com.acme.app/metadata/canvas_36901/w1?package=com.acme.app'); + + // CONTROL: the next Esc nobody took leaves the fullscreen. + fireEvent.keyDown(document.body, { key: 'Escape' }); + await waitFor(() => expect(screen.getByTitle(t('engine.edit.fullscreen', 'en-US'))).toBeInTheDocument()); + }); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.leaveGuard-13231.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.leaveGuard-13231.test.tsx index bfc7237bedb..20873e1fafc 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.leaveGuard-13231.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.leaveGuard-13231.test.tsx @@ -20,10 +20,13 @@ */ import '@testing-library/jest-dom/vitest'; +// The source under test reaches a dynamic import of this module: its first load is paid here, at collection, never inside a case's clock (`check:test-source-alias`). +import '@objectstack/lint'; import * as React from 'react'; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; -import { Link, MemoryRouter, Route, Routes } from 'react-router-dom'; +import { Link, MemoryRouter, Route, Routes, useLocation, useNavigate } from 'react-router-dom'; +import { CommandItem } from '@object-ui/components'; import { z } from 'zod'; import { ComponentRegistry } from '@object-ui/core'; import { DocSchema } from '@objectstack/spec/system'; @@ -89,6 +92,9 @@ import { registerDefaultMetadataSchemas } from './default-schemas'; import { registerBuiltinPreviews } from './previews'; import { t } from './i18n'; import { confirmUnsavedLeave } from '../../chrome/unsavedEdits'; +import { CommandPalette, type StudioPaletteSurface } from '../../chrome/CommandPalette'; +import { CommandPaletteProvider } from '../../context/CommandPaletteProvider'; +import { openStudioPaletteAddress } from '../studio-design/studioPaletteModel'; const DOC_JSON_SCHEMA = z.toJSONSchema(DocSchema as unknown as z.ZodType) as Record; client.current = new MetadataClient({ baseUrl: '', fetch: vi.fn(serve) as unknown as typeof fetch }); @@ -220,3 +226,82 @@ describe('MetadataResourceEditPage registers its unsaved draft with the shell se expect(confirmSpy).not.toHaveBeenCalled(); }); }); + +/** + * objectstack#36900 (L1 M1) — a Studio palette pick leaves this page the way + * the Studio surface opens it (`openStudioPaletteAddress`): through the seam, + * so the page's own registered draft is asked about, though the surface's own + * unsaved bit never saw it. The real page and the real palette; the surface's + * groups are one entry. + */ +describe('a Studio palette pick asks before it drops this page\'s unsaved draft (objectstack#36900)', () => { + function StudioPalette() { + const navigate = useNavigate(); + const { pathname, search } = useLocation(); + const surface: StudioPaletteSurface = { + packageScope: true, + renderGroups: ({ open }) => ( + open('/metadata/doc')}> + All docs + + ), + open: (to) => openStudioPaletteAddress(to, { pathname, search }, { navigate, reenter: () => true }), + }; + return ; + } + + // The studio palette reads the package list when it opens: an empty one. + beforeEach(() => { + vi.stubGlobal('fetch', vi.fn(async () => json(200, { data: [] }))); + }); + afterEach(() => { + vi.unstubAllGlobals(); + }); + + async function openGuideWithPalette() { + active.set('doc/guide', { name: 'guide', label: 'Guide', content: '# Live', group: 'reference' }); + render( + + + + + } /> + Docs list} /> + + + , + ); + expect(await source()).toHaveValue('# Live'); + await settle(); + } + + async function pickAllDocs() { + fireEvent.keyDown(document, { key: 'k', ctrlKey: true }); + const item = await screen.findByText('All docs'); + fireEvent.click(item); + await settle(); + } + + it("Cancel keeps the page and the draft; OK leaves", async () => { + await openGuideWithPalette(); + await editSource(); + + await pickAllDocs(); + expect(confirmSpy).toHaveBeenCalledTimes(1); + expect(confirmSpy).toHaveBeenCalledWith(QUESTION); + expect(screen.queryByText('Docs list')).toBeNull(); + expect(await source()).toHaveValue('# Live, edited'); + + confirmSpy.mockReturnValue(true); + await pickAllDocs(); + expect(confirmSpy).toHaveBeenCalledTimes(2); + expect(await screen.findByText('Docs list')).toBeTruthy(); + }); + + it('CONTROL: a clean page leaves at once, asking nothing', async () => { + await openGuideWithPalette(); + await pickAllDocs(); + expect(await screen.findByText('Docs list')).toBeTruthy(); + expect(confirmSpy).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx index 962ff6009a7..105156195ca 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx @@ -1717,11 +1717,13 @@ function MetadataResourceEditPageImpl({ document.body.style.overflow = prev; }; }, [isFullscreen]); - // Escape exits fullscreen. + // Escape exits fullscreen. objectstack#36900 — not an Escape a dialog over + // the page (the command palette, a confirm) already took to close itself: + // Radix's dismissable layer marks the one it acts on `defaultPrevented`. React.useEffect(() => { if (typeof window === 'undefined' || !isFullscreen) return; function onKey(e: KeyboardEvent) { - if (e.key === 'Escape') { + if (e.key === 'Escape' && !e.defaultPrevented) { e.preventDefault(); setIsFullscreen(false); } diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.metadataArea-28561.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.metadataArea-28561.test.tsx index de051a782c0..eea40c4c4b4 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.metadataArea-28561.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.metadataArea-28561.test.tsx @@ -18,6 +18,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; import { useMetadataAreaHost } from '../metadata-admin/metadataAreaHost'; +import { useRegisterUnsavedEdits } from '../../chrome/unsavedEdits'; const PACKAGE_ID = 'app.r34d'; const KERNEL_ID = 'com.objectstack.platform'; @@ -29,7 +30,7 @@ vi.mock('sonner', () => ({ })); const mockClient = { - list: vi.fn(async () => []), + list: vi.fn(async (_type?: string): Promise => []), listDrafts: vi.fn(async () => []), layered: vi.fn(async (_t: string, name: string) => ({ effective: { name } })), getDraft: vi.fn(async () => null), @@ -65,8 +66,13 @@ vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); +/** objectstack#36900 — the item page holds unsaved edits, registered with the shell's seam as `ResourceEditPage` does. */ +const itemPage = vi.hoisted(() => ({ dirty: false })); +const ITEM_QUESTION = 'Discard the edits on this item?'; + function PageStub({ page }: { page: string }) { const host = useMetadataAreaHost(); + useRegisterUnsavedEdits(page === 'item' && itemPage.dirty, ITEM_QUESTION); return
; } vi.mock('../metadata-admin/index.js', () => ({ @@ -109,6 +115,9 @@ import { StudioDesignSurface } from './StudioDesignSurface'; // The source under test reaches dynamic imports of `@objectstack/lint`; their first // load is paid here, at collection, never inside a case's clock (`check:test-source-alias`). import '@objectstack/lint'; +// objectstack#36900 — the surface mounts the command palette, which reaches the +// record preview's `lazy()` detail entry: its first load is paid here too. +import '@object-ui/plugin-detail'; const answer = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); @@ -274,3 +283,142 @@ describe('the area\'s form editor in the builder (objectstack#28569)', () => { expect(await screen.findByTestId('studio-changes-count')).toHaveTextContent('1'); }); }); + +/** + * objectstack#36900 — ⌘K on the builder's pages: the surface mounts the + * command palette with its own groups, on a package's pillars and area and on + * the cross-package leg, and a pick leaves through the surface. + */ +describe('⌘K on the builder (objectstack#36900)', () => { + const overlay = () => document.querySelector('[data-testid="overlay:command-palette"]'); + const paletteItem = (value: string) => document.querySelector(`[cmdk-item][data-value="${value}"]`); + + it("on a package's pillar, Ctrl+K opens the palette with the menu's entries, and a pick opens through the surface", async () => { + servePackages(); + renderAt(`/studio/${PACKAGE_ID}/data`); + await waitFor(() => menu().getByTestId('studio-menu-entry-type:flow')); + expect(overlay()).toBeNull(); + + fireEvent.keyDown(document, { key: 'k', ctrlKey: true }); + await waitFor(() => expect(overlay()).not.toBeNull()); + expect(where()).toBe(`/studio/${PACKAGE_ID}/data?palette=1`); + await waitFor(() => expect(paletteItem('studio-entry type:flow')).not.toBeNull()); + expect(paletteItem('studio-entry orgFlows')).not.toBeNull(); + + fireEvent.click(paletteItem('studio-entry type:flow')!); + expect((await areaPage()).page).toBe('list'); + expect(where()).toBe(`/studio/${PACKAGE_ID}/metadata/flow?package=${PACKAGE_ID}`); + expect(overlay()).toBeNull(); + expect(current()).toHaveAttribute('data-testid', 'studio-menu-entry-type:flow'); + }); + + it('on the cross-package leg, Ctrl+K opens the palette again, with the environment menu', async () => { + servePackages(); + renderAt('/studio/~all/metadata'); + await areaPage(); + + fireEvent.keyDown(document, { key: 'k', ctrlKey: true }); + await waitFor(() => expect(overlay()).not.toBeNull()); + await waitFor(() => expect(paletteItem('studio-entry environment')).not.toBeNull()); + expect(paletteItem('studio-entry diagnostics')).toBeNull(); + }); + + it('a package that is not there has no menu, and its palette lists the packages instead', async () => { + servePackages(); + renderAt(`/studio/${PHANTOM}/data?palette=1`); + expect(await screen.findByTestId('studio-package-not-found')).toBeInTheDocument(); + await waitFor(() => expect(document.querySelector('[cmdk-item][data-value^="studio-package Field Ops "]')).not.toBeNull()); + expect(document.querySelector('[cmdk-item][data-value^="studio-entry "]')).toBeNull(); + }); +}); + +/** + * objectstack#36900 (L1 M1, S5) — a pick from the palette leaves through the + * shell's unsaved-edits seam, so an editor below the surface that registers + * its own edits (the "All metadata" item page) is asked about too, and so is + * the header's Back to app; Default sharing picked on the Access pillar + * remounts the pillar on its own deep link. + */ +describe('⌘K and the header ask before they drop edits the item page holds (objectstack#36900)', () => { + const overlay = () => document.querySelector('[data-testid="overlay:command-palette"]'); + const paletteItem = (value: string) => document.querySelector(`[cmdk-item][data-value="${value}"]`); + const ITEM_URL = `/studio/${PACKAGE_ID}/metadata/agent/a1?package=${PACKAGE_ID}`; + let confirmSpy: ReturnType; + + beforeEach(() => { + itemPage.dirty = true; + confirmSpy = vi.fn(() => false); + vi.stubGlobal('confirm', confirmSpy); + }); + afterEach(() => { + itemPage.dirty = false; + }); + + async function pickFlowList() { + fireEvent.keyDown(document, { key: 'k', ctrlKey: true }); + await waitFor(() => expect(paletteItem('studio-entry type:flow')).not.toBeNull()); + fireEvent.click(paletteItem('studio-entry type:flow')!); + } + + it("a palette pick asks the item page's question: Cancel keeps the page, OK leaves", async () => { + servePackages(); + renderAt(ITEM_URL); + expect((await areaPage()).page).toBe('item'); + + await pickFlowList(); + expect(confirmSpy).toHaveBeenCalledTimes(1); + expect(confirmSpy).toHaveBeenCalledWith(ITEM_QUESTION); + await waitFor(() => expect(overlay()).toBeNull()); + expect(where()).toBe(ITEM_URL); + expect((await areaPage()).page).toBe('item'); + + confirmSpy.mockReturnValue(true); + await pickFlowList(); + expect(confirmSpy).toHaveBeenCalledTimes(2); + expect((await areaPage()).page).toBe('list'); + expect(where()).toBe(`/studio/${PACKAGE_ID}/metadata/flow?package=${PACKAGE_ID}`); + }); + + it("the header's Back to app asks the item page's question too: Cancel keeps the page", async () => { + servePackages(); + renderAt(ITEM_URL); + expect((await areaPage()).page).toBe('item'); + fireEvent.click(await screen.findByTestId('studio-back-to-app')); + expect(confirmSpy).toHaveBeenCalledWith(ITEM_QUESTION); + expect(where()).toBe(ITEM_URL); + }); + + it('CONTROL — a clean item page: the pick leaves at once and asks nothing', async () => { + itemPage.dirty = false; + servePackages(); + renderAt(ITEM_URL); + expect((await areaPage()).page).toBe('item'); + await pickFlowList(); + expect((await areaPage()).page).toBe('list'); + expect(confirmSpy).not.toHaveBeenCalled(); + }); + + it('Default sharing picked on the Access pillar remounts the pillar on its overview', async () => { + itemPage.dirty = false; + mockClient.list.mockImplementation(async (type?: string) => + type === 'permission' ? [{ name: 'sales_rep', label: 'Sales Rep', _packageId: PACKAGE_ID }] : [], + ); + try { + servePackages(); + renderAt(`/studio/${PACKAGE_ID}/access?surface=permission%3Asales_rep`); + await screen.findByTestId('access-rail-set-sales_rep'); + expect(screen.queryByTestId('owd-overview')).toBeNull(); + + fireEvent.keyDown(document, { key: 'k', ctrlKey: true }); + await waitFor(() => expect(paletteItem('studio-entry owd')).not.toBeNull()); + fireEvent.click(paletteItem('studio-entry owd')!); + + expect(await screen.findByTestId('owd-overview')).toBeInTheDocument(); + expect(where()).toBe(`/studio/${PACKAGE_ID}/access?surface=owd%3Aoverview`); + expect(overlay()).toBeNull(); + expect(confirmSpy).not.toHaveBeenCalled(); + } finally { + mockClient.list.mockImplementation(async () => []); + } + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx index 4051b0f6fa9..09a8f70dd38 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx @@ -69,7 +69,6 @@ import { type NewFlowTrigger, } from './AutomationsFlowRail.js'; import { - confirmDropUnsavedWork, CreateTakenNotice, findTakenIdentifier, type StudioBaseCustomization, @@ -133,7 +132,7 @@ import { studioOrgScopePath, } from './studioScope.js'; import { STUDIO_METADATA_AREA, isStudioAllPackagesScope } from './metadataArea.js'; -import { StudioMenu, StudioMenuProvider, StudioMenuTrigger } from './StudioMenu.js'; +import { StudioMenu, StudioMenuDataProvider, StudioMenuProvider, StudioMenuTrigger } from './StudioMenu.js'; import { StudioMetadataArea } from './StudioMetadataArea.js'; import { useMetadataRefreshNonce } from './useMetadataRefreshNonce.js'; import { @@ -142,7 +141,11 @@ import { import { SurfaceDeepLinkProvider } from './surfaceDeepLinkChannel.js'; import { buildAppSkeleton, type AppNavSeed } from './skeletons.js'; import { t, tFormat, useMetadataLocale } from '../metadata-admin/i18n.js'; -import { useRegisterUnsavedEdits } from '../../chrome/unsavedEdits.js'; +import { confirmUnsavedLeave, useRegisterUnsavedEdits } from '../../chrome/unsavedEdits.js'; +import { CommandPalette, type StudioPaletteSurface } from '../../chrome/CommandPalette.js'; +import { CommandPaletteProvider, useCommandPaletteProviderMounted } from '../../context/CommandPaletteProvider.js'; +import { StudioPaletteGroups } from './StudioPaletteGroups.js'; +import { openStudioPaletteAddress, studioSamePageSearch } from './studioPaletteModel.js'; import { CreateItemDialog } from './CreateItemDialog.js'; // objectui#11787 — the shared draft autosave, moved to its own module unchanged. import { @@ -470,10 +473,21 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re // unsaved work, and every guard below reads this one bit. objectstack#36511 // — so does an edit waiting for the top bar's Save. const unsavedPillarWork = pillarDirty || heldEdit !== null || saveBar.dirty; - const confirmLeavePillar = React.useCallback( - () => confirmDropUnsavedWork(unsavedPillarWork, locale), - [unsavedPillarWork, locale], - ); + // objectstack#36900 — every departure this surface starts asks the shell's + // unsaved-edits seam, not only this surface's own bit: the seam holds this + // surface's work (registered below with the same question) AND every editor + // below it that registers its own, the "All metadata" item page + // (`ResourceEditPage`) among them, whose edits this bit never sees. So the + // palette's picks, the header's Back to app, the retired-Interfaces notice + // and a request to open another pillar's surface all ask before they drop + // either kind of edit. `true`: nothing would be lost, or the author agreed. + const confirmLeavePillar = React.useCallback((): boolean => { + let agreed = false; + confirmUnsavedLeave(() => { + agreed = true; + }); + return agreed; + }, []); // Browser-native "leave site?" prompt on tab close / reload while a pillar // is dirty. The matrix editor installs its own (double registration is // harmless); the Interfaces nav editor has none, so this closes that gap. @@ -1221,22 +1235,67 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re // remount waits for the new query to be the router's: the router may apply // a navigation in a later render than the click's own state updates, and a // pillar remounted before it would capture the old deep link. + // objectstack#36900 — it waits for the query it was asked for, not for the + // next query change: the command palette closes itself (its `?palette=` + // goes) before the pick navigates, and that first change must not remount + // the pillar on the old deep link. const [pillarEntry, setPillarEntry] = React.useState(0); - const reentryPending = React.useRef(false); + const reentryPending = React.useRef(null); const currentSearch = useLocation().search; - const reenterPillar = React.useCallback((): boolean => { - if (!confirmLeavePillar()) return false; - reentryPending.current = true; - return true; - }, [confirmLeavePillar]); + const reenterPillar = React.useCallback( + (search: string): boolean => { + if (!confirmLeavePillar()) return false; + reentryPending.current = search; + return true; + }, + [confirmLeavePillar], + ); React.useLayoutEffect(() => { - if (!reentryPending.current) return; - reentryPending.current = false; + const expected = reentryPending.current; + if (expected === null || !studioSamePageSearch(currentSearch, expected)) return; + reentryPending.current = null; setPillarEntry((n) => n + 1); }, [currentSearch]); // objectstack#26708 — a package that is not there has no menu. const showMenu = !pkgMissing; + // objectstack#36900 — ⌘K on every design page (decision 7 of #36890: an + // author switches items by ×, by ‹ › and by ⌘K). The palette lists this + // scope's menu, and on a package its items (`StudioPaletteGroups`); a pick + // leaves the way a menu entry does: it asks about unsaved work, and an + // address that is the page already open on another query re-enters the + // page, which reads its deep link once, at mount. The palette's own + // `?palette=` is not part of the page's query. A package that is not there + // has no menu, so its palette is the landing's. + const currentPathname = useLocation().pathname; + const openFromPalette = React.useCallback( + (to: string) => + openStudioPaletteAddress( + to, + { pathname: currentPathname, search: currentSearch }, + { navigate: shellNavigate, reenter: reenterPillar }, + ), + [currentPathname, currentSearch, reenterPillar, shellNavigate], + ); + const paletteLabel = packageId !== null && pkgEntry?.id === packageId ? pkgEntry.name : undefined; + const paletteSurface = React.useMemo( + () => + showMenu + ? { + packageScope: packageId !== null, + renderGroups: (groupsProps) => ( + + ), + open: openFromPalette, + } + : undefined, + [showMenu, packageId, scopeSegment, paletteLabel, openFromPalette], + ); + // A host that already mounts a command palette above this surface keeps + // its own: a second provider would toggle the one `?palette=` twice per + // ⌘K, and a second palette would draw a second dialog. + const paletteHosted = useCommandPaletteProviderMounted(); + const publishButton = (