diff --git a/.changeset/36362-runtime-design-mode.md b/.changeset/36362-runtime-design-mode.md new file mode 100644 index 00000000000..931eca8913f --- /dev/null +++ b/.changeset/36362-runtime-design-mode.md @@ -0,0 +1,15 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(console): 「Edit app」 turns on a design mode in the running app instead of opening Studio + +Clause-②: yes (widening) +Metadata-protocol: none + +An administrator who may design the app (a workspace admin holding `manage_metadata`, on a writable package: the gate 「Edit app」 always had) now presses 「Edit app」 in the page header to turn on the app's design mode, in place. A bar across the top of the window says 「Design mode」 and offers 「Cancel」 and 「Save」, and nothing else. The mode stays on from page to page of the app and goes off when the app changes; it is never on a phone. While it is on, the sidebar shows the app's own menu without the person's Favorites. + +The mode is the extension point the next design-mode surfaces (menu editing, the page header's pinned actions) stage their changes through: 「Save」 writes every staged change and leaves the mode, 「Cancel」 drops them all. 「Save」 is off while nothing is staged. While a change is staged, closing or reloading the tab, a link out of the app and the app switcher ask first; a link to another page of the app does not. This release stages nothing yet. + +A read-only package's app keeps its 「Open APP in Studio」 entry unchanged. New `@object-ui/i18n` keys: `designMode.title`, `designMode.leaveUnsaved`, `designMode.saveFailed`. diff --git a/ui/packages/app-shell/src/chrome/unsavedEdits-13231.test.tsx b/ui/packages/app-shell/src/chrome/unsavedEdits-13231.test.tsx index cea9a5328b8..ccbd8438aeb 100644 --- a/ui/packages/app-shell/src/chrome/unsavedEdits-13231.test.tsx +++ b/ui/packages/app-shell/src/chrome/unsavedEdits-13231.test.tsx @@ -227,3 +227,59 @@ describe('useRegisterUnsavedEdits (objectui#13231)', () => { expect(confirmSpy).toHaveBeenCalledTimes(2); }); }); + +describe('a registration names the pages it keeps its edits on (objectstack#36362)', () => { + it('a link to a page it keeps asks nothing; a link to any other page asks its question', () => { + window.history.replaceState(null, '', '/_console/apps/crm/crm_lead'); + const inApp = document.createElement('a'); + inApp.href = '/_console/apps/crm/dashboard/sales'; + const outOfApp = document.createElement('a'); + outOfApp.href = '/_console/home'; + document.body.append(inApp, outOfApp); + const stop = (e: Event) => e.preventDefault(); + window.addEventListener('click', stop); + const release = registerUnsavedEdits(KEEP, { + keeps: (url) => url.pathname.startsWith('/_console/apps/crm/'), + }); + releases.push(release); + try { + inApp.click(); + expect(confirmSpy).not.toHaveBeenCalled(); + + outOfApp.click(); + expect(confirmSpy).toHaveBeenCalledTimes(1); + expect(confirmSpy).toHaveBeenCalledWith(KEEP); + } finally { + window.removeEventListener('click', stop); + inApp.remove(); + outOfApp.remove(); + } + }); + + it('a page another registration does not keep still asks that registration\'s question', () => { + window.history.replaceState(null, '', '/_console/apps/crm/crm_lead'); + const inApp = document.createElement('a'); + inApp.href = '/_console/apps/crm/dashboard/sales'; + document.body.append(inApp); + const stop = (e: Event) => e.preventDefault(); + window.addEventListener('click', stop); + releases.push(registerUnsavedEdits('page question')); + releases.push(registerUnsavedEdits(KEEP, { keeps: () => true })); + try { + inApp.click(); + expect(confirmSpy).toHaveBeenCalledWith('page question'); + } finally { + window.removeEventListener('click', stop); + inApp.remove(); + } + }); + + it('a tab close and a shell departure still ask, whatever the registration keeps', () => { + releases.push(registerUnsavedEdits(KEEP, { keeps: () => true })); + expect(unloadHeld()).toBe(true); + const go = vi.fn(); + confirmUnsavedLeave(go); + expect(confirmSpy).toHaveBeenCalledWith(KEEP); + expect(go).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/app-shell/src/chrome/unsavedEdits.ts b/ui/packages/app-shell/src/chrome/unsavedEdits.ts index d7d4ba07753..379444796a7 100644 --- a/ui/packages/app-shell/src/chrome/unsavedEdits.ts +++ b/ui/packages/app-shell/src/chrome/unsavedEdits.ts @@ -58,6 +58,18 @@ import { useEffect } from 'react'; interface Registration { /** The question asked before this page's edits are dropped, already translated. */ readonly message: string; + /** + * The in-app addresses a link may open without dropping these edits: a + * holder that outlives the page (the shell's design mode, which keeps its + * changes from page to page of one app) names the pages it keeps them on. + * Absent, every other page drops them. + */ + readonly keeps?: (url: URL) => boolean; +} + +/** How a registration is made: see {@link Registration.keeps}. */ +export interface UnsavedEditsOptions { + readonly keeps?: (url: URL) => boolean; } /** In registration order: the last one is the page shown most recently. */ @@ -71,35 +83,39 @@ const registrations = new Set(); */ let leaveConfirmed = false; -function latestMessage(): string | undefined { +/** The question of the most recent registration that `url` would drop, every one when no `url`. */ +function latestMessage(url?: URL): string | undefined { let message: string | undefined; - for (const registration of registrations) message = registration.message; + for (const registration of registrations) { + if (url && registration.keeps?.(url)) continue; + message = registration.message; + } return message; } /** - * Whether a click on the document would take the user to another page of this - * app. Mirrors what the router itself skips: a modified or non-primary click + * The page a click on the document would take the user to, in this app, or + * `null` when it stays. Mirrors what the router itself skips: a modified or non-primary click * (new tab / window), a link that opens elsewhere or downloads, a link to * another origin (the `beforeunload` prompt covers that one), and a link to the * page already shown — the view stays mounted and keeps its edits. */ -function leavesThisPage(e: MouseEvent): boolean { - if (e.defaultPrevented) return false; - if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return false; +function leavesThisPage(e: MouseEvent): URL | null { + if (e.defaultPrevented) return null; + if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return null; const target = e.target instanceof Element ? e.target : null; const anchor = target?.closest('a[href]') as HTMLAnchorElement | null; - if (!anchor) return false; - if (anchor.target && anchor.target !== '_self') return false; - if (anchor.hasAttribute('download')) return false; + if (!anchor) return null; + if (anchor.target && anchor.target !== '_self') return null; + if (anchor.hasAttribute('download')) return null; try { const url = new URL(anchor.href, window.location.href); - if (url.origin !== window.location.origin) return false; - if (url.pathname === window.location.pathname) return false; + if (url.origin !== window.location.origin) return null; + if (url.pathname === window.location.pathname) return null; + return url; } catch { - return false; + return null; } - return true; } function onBeforeUnload(e: BeforeUnloadEvent): void { @@ -110,8 +126,11 @@ function onBeforeUnload(e: BeforeUnloadEvent): void { } function onDocumentClick(e: MouseEvent): void { - const message = latestMessage(); - if (message === undefined || !leavesThisPage(e)) return; + if (registrations.size === 0) return; + const url = leavesThisPage(e); + if (!url) return; + const message = latestMessage(url); + if (message === undefined) return; if (window.confirm(message)) return; // Kept: the router never sees the click, so the URL and the edits stay. e.preventDefault(); @@ -133,8 +152,8 @@ function uninstall(): void { * any registration is held, every departure the seam sees asks `message` * first. Prefer {@link useRegisterUnsavedEdits} in a component. */ -export function registerUnsavedEdits(message: string): () => void { - const registration: Registration = { message }; +export function registerUnsavedEdits(message: string, options?: UnsavedEditsOptions): () => void { + const registration: Registration = { message, keeps: options?.keeps }; if (registrations.size === 0) install(); registrations.add(registration); let released = false; diff --git a/ui/packages/app-shell/src/layout/ConsoleLayout.tsx b/ui/packages/app-shell/src/layout/ConsoleLayout.tsx index 7730f9c5ae5..c6d92d5512a 100644 --- a/ui/packages/app-shell/src/layout/ConsoleLayout.tsx +++ b/ui/packages/app-shell/src/layout/ConsoleLayout.tsx @@ -35,6 +35,8 @@ import { ConnectionBanner } from './ConnectionBanner.js'; import { useGoHomeShortcut } from '../chrome/goHomeShortcut.js'; import { useHomePath } from '../hooks/useHomePath.js'; import { AppHeader } from './AppHeader.js'; +import { DesignModeProvider, useDesignModeController } from './designMode.js'; +import { DesignModeBar } from './DesignModeBar.js'; import { useResponsiveSidebar } from '../hooks/useResponsiveSidebar.js'; import { usePhoneNavDrawerHistory } from './usePhoneNavDrawerHistory.js'; import { usePhoneViewport } from '../hooks/usePhoneViewport.js'; @@ -200,6 +202,9 @@ export function ConsoleLayout({ }, [activeAppName, rememberApp]); const { apps: metadataApps } = useMetadata(); const appBasePath = `/apps/${appAddressSegment(metadataApps, activeApp) ?? activeAppName}`; + // objectstack#36362 — the app's design mode, held here so it stays on from + // page to page of the app; never on a phone, which has no 「Edit app」. + const designMode = useDesignModeController({ appName: activeAppName, appBasePath, enabled: !phone }); // objectstack#30043 — the page in view, handed to the dock as its // `context.surface` (cloud#1610's shape): the object of a list, the object // and record id of a record page, the dashboard, report or page. Read off the @@ -255,6 +260,7 @@ export function ConsoleLayout({ {/* objectstack#35883 — a page's own phone top row, drawn by the app bar. */} + + ) : ( + ) } // objectui#12463 — from `lg` up the inset is a flex column: the banners // box (`shrink-0`, below) keeps its height and the route slot (below) @@ -371,6 +384,7 @@ export function ConsoleLayout({ {/* Under `md` the drawer is a bottom sheet (no room for a rail on a phone). */} {chatDock.sheet} + diff --git a/ui/packages/app-shell/src/layout/DesignModeBar.tsx b/ui/packages/app-shell/src/layout/DesignModeBar.tsx new file mode 100644 index 00000000000..80f5418497d --- /dev/null +++ b/ui/packages/app-shell/src/layout/DesignModeBar.tsx @@ -0,0 +1,54 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The design mode's bar (objectstack#36362): 「Design mode」 at its left, + * 「Cancel」 and 「Save」 at its right, and nothing else (no app name, no + * explanation, no way to Studio). `ConsoleLayout` draws it in the app shell's + * top slot, across the whole window, while the mode is on (`designMode.tsx`). + */ + +import { PencilRuler } from 'lucide-react'; +import { Button } from '@object-ui/components'; +import { useObjectTranslation } from '@object-ui/i18n'; +import type { DesignModeValue } from './designMode.js'; + +export function DesignModeBar({ mode }: { mode: DesignModeValue }) { + const { t } = useObjectTranslation(); + const title = t('designMode.title', { defaultValue: 'Design mode' }); + return ( +
+
+ ); +} diff --git a/ui/packages/app-shell/src/layout/ShellPageActions.tsx b/ui/packages/app-shell/src/layout/ShellPageActions.tsx index 8454e9922dd..470f7f4582a 100644 --- a/ui/packages/app-shell/src/layout/ShellPageActions.tsx +++ b/ui/packages/app-shell/src/layout/ShellPageActions.tsx @@ -27,9 +27,12 @@ * test that mounts a page bare) the group is never drawn, and on a phone * neither: the phone has its own bar. * - * The parts are the top bar's own: 「Edit app」 reads the same gate and opens - * the same target as the top bar's pencil (`useAppStudioEntry`), the AI button - * IS `AssistantTopBarButton`, and the help menu IS `HelpMenu`. + * The parts are the top bar's own: 「Edit app」 reads the same gate as the top + * bar's pencil (`useAppStudioEntry`), the AI button IS `AssistantTopBarButton`, + * and the help menu IS `HelpMenu`. Where the shell holds the design mode + * (`designMode.tsx`, objectstack#36362), 「Edit app」 turns it on instead of + * opening Studio, and is not drawn while it is on; elsewhere it opens what the + * pencil opens. */ import * as React from 'react'; @@ -52,6 +55,7 @@ import { import { LocalizedSidebarTrigger } from './LocalizedSidebarTrigger.js'; import { AssistantTopBarButton } from './AssistantTopBarButton.js'; import { HelpMenu } from './HelpMenu.js'; +import { useDesignMode, type DesignModeValue } from './designMode.js'; /** * Counts the headers under a scope that place the expand button, so the @@ -204,8 +208,19 @@ export function useAppStudioEntry(enabled: boolean, activeAppName?: string): { * (the record's 「Edit」 carries the pencil), the words dropped below `lg` with * the tooltip keeping them. A read-only package's app gets the top bar's eye * and 「Open {app} in Studio」 (ADR-0146 D5) at the same place. + * + * objectstack#36362 — under a shell that holds the design mode, 「Edit app」 + * turns the mode on, in place, and opens no Studio. */ -function EditAppButton({ entry, appText }: { entry: StudioEntry; appText: string }) { +function EditAppButton({ + entry, + appText, + designMode, +}: { + entry: StudioEntry; + appText: string; + designMode: DesignModeValue | null; +}) { const { t } = useObjectTranslation(); if (entry.posture === 'view') { const viewText = t('topbar.openAppInStudio', { defaultValue: 'Open {{app}} in Studio', app: appText }); @@ -226,6 +241,23 @@ function EditAppButton({ entry, appText }: { entry: StudioEntry; appText: string ); } const label = t('topbar.editApp', { defaultValue: 'Edit app' }); + if (designMode) { + return ( + + ); + } return ( + + + ); + } + + it('the section (pinned entries and stored favorites) goes while the mode is on, and comes back after', async () => { + seed([ + RECORD_FAVORITE, + { id: 'nav:nav_accounts', label: 'nav_accounts', href: '', type: 'nav', navId: 'nav_accounts', pinned: true, favoritedAt: '2026-10-03T00:00:00.000Z' }, + ]); + metadataState = { + apps: [{ name: 'crm', label: 'CRM', active: true, _packageId: 'com.acme.crm', navigation: NAVIGATION }], + objects: [], + }; + render( + + + + + + + + + + , + ); + await tick(); + expect(favoriteLabels()).toEqual(['Accounts', 'Acme']); + + fireEvent.click(screen.getByText('enter design')); + expect(favoritesSection()).toBeNull(); + // The app's own entries stay, the pinned one included, in the menu. + expect(menuRows().map((row) => row.textContent)).toEqual(expect.arrayContaining([expect.stringContaining('Accounts')])); + + fireEvent.click(screen.getByText('leave design')); + expect(favoriteLabels()).toEqual(['Accounts', 'Acme']); + }); +}); diff --git a/ui/packages/app-shell/src/layout/__tests__/consoleTopBar.height-12639.test.ts b/ui/packages/app-shell/src/layout/__tests__/consoleTopBar.height-12639.test.ts index ad3dca8fe56..5bb13a68b3d 100644 --- a/ui/packages/app-shell/src/layout/__tests__/consoleTopBar.height-12639.test.ts +++ b/ui/packages/app-shell/src/layout/__tests__/consoleTopBar.height-12639.test.ts @@ -161,9 +161,10 @@ describe('the console top bar is one 48 px bar in every frame (objectui#12639)', ).toBe(`!top-${step} !h-[calc(100svh-${step / 4}rem)]`); // The sidebar's class leads with it below 768 px, where the phone keeps // its bar; from 768 px up an app draws no bar and the sidebar starts at - // the window's top (objectstack#36112). + // the window's top (objectstack#36112), unless the design mode's bar is + // drawn there (objectstack#36362). expect(code('packages/app-shell/src/layout/UnifiedSidebar.tsx')).toMatch( - /]*\bclassName=\{cn\(!rail\.desktop && CONSOLE_BELOW_TOP_BAR\b/, + /]*\bclassName=\{cn\(\(!rail\.desktop \|\| designMode\) && CONSOLE_BELOW_TOP_BAR\b/, ); }); @@ -199,7 +200,11 @@ describe('the console top bar is one 48 px bar in every frame (objectui#12639)', } if (bar === 'app-shell') { expect(code(file)).toMatch(/import\s*\{[^}]*\bAppShell\b[^}]*\}\s*from\s*'@object-ui\/layout'/); - expect(code(file)).toMatch(/ vi.fn()); +vi.mock('sonner', async (importOriginal) => ({ + ...(await importOriginal>()), + toast: { error: toastError, success: vi.fn() }, +})); + +vi.mock('@object-ui/i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useObjectTranslation: () => ({ + t: (k: string, o?: Record) => + String(o?.defaultValue ?? k).replace(/\{\{(\w+)\}\}/g, (_hole, name: string) => String(o?.[name] ?? '')), + language: 'en', + }), +})); + +import { + DesignModeProvider, + isPageOfApp, + useDesignMode, + useDesignModeChange, + useDesignModeController, +} from '../designMode'; +import { DesignModeBar } from '../DesignModeBar'; + +/** The shell's hold on the mode, with the bar drawn while it is on, and the probes below it. */ +function Shell({ app = 'crm', enabled = true, children }: { app?: string; enabled?: boolean; children?: React.ReactNode }) { + const mode = useDesignModeController({ appName: app, appBasePath: `/apps/${app}`, enabled }); + return ( + + {mode.active && } + {children} + + ); +} + +function EnterButton() { + const mode = useDesignMode(); + return ( + + ); +} + +/** A surface that stages one change under `name` when its button is pressed. */ +function Stager({ name, commit }: { name: string; commit: (value: string) => Promise }) { + const change = useDesignModeChange(name); + return ( +
+ {change.value ?? ''} + +
+ ); +} + +const bar = () => screen.queryByTestId('design-mode-bar'); +const save = () => screen.getByTestId('design-mode-save'); +const flush = () => act(async () => { await new Promise((r) => setTimeout(r, 0)); }); + +function stubConfirm() { + const spy = vi.fn((_message?: string): boolean => false); + vi.stubGlobal('confirm', spy); + return spy; +} + +beforeEach(() => { + toastError.mockReset(); +}); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +describe('the bar (objectstack#36362)', () => { + it('holds 「Design mode」, 「Cancel」 and 「Save」, and nothing else', () => { + render(); + expect(bar()).toBeNull(); + fireEvent.click(screen.getByText('enter')); + + const region = screen.getByRole('region', { name: 'Design mode' }); + expect(region).toHaveTextContent(/^Design modeCancelSave$/); + expect(within(region).getAllByRole('button').map((b) => b.textContent)).toEqual(['Cancel', 'Save']); + expect(within(region).queryAllByRole('link')).toEqual([]); + }); + + it('「Save」 is off while nothing is staged, on once something is', () => { + render( {}} />); + fireEvent.click(screen.getByText('enter')); + expect(save()).toBeDisabled(); + fireEvent.click(screen.getByText('stage menu')); + expect(save()).toBeEnabled(); + }); + + it('「Cancel」 leaves the mode', () => { + render(); + fireEvent.click(screen.getByText('enter')); + fireEvent.click(screen.getByTestId('design-mode-cancel')); + expect(bar()).toBeNull(); + }); +}); + +describe('saving and dropping what is staged (objectstack#36362)', () => { + it('「Save」 commits every staged change in the order first staged, then leaves the mode', async () => { + const order: string[] = []; + const commit = (value: string) => { + order.push(value); + return Promise.resolve(); + }; + render( + + + + + , + ); + fireEvent.click(screen.getByText('enter')); + fireEvent.click(screen.getByText('stage menu')); + fireEvent.click(screen.getByText('stage header')); + fireEvent.click(screen.getByText('stage menu')); + expect(screen.getByTestId('staged-menu')).toHaveTextContent('menu-value'); + + fireEvent.click(save()); + await flush(); + + expect(order).toEqual(['menu-value', 'header-value']); + expect(bar()).toBeNull(); + expect(screen.getByTestId('staged-menu')).toHaveTextContent(''); + expect(toastError).not.toHaveBeenCalled(); + }); + + it('a failed commit stops the save: the ones before it are saved, it and the later ones stay, the mode stays on and says why', async () => { + const header = vi.fn(async () => {}); + render( + + + {}} /> + { throw new Error('Package is read-only'); }} /> + + , + ); + fireEvent.click(screen.getByText('enter')); + fireEvent.click(screen.getByText('stage first')); + fireEvent.click(screen.getByText('stage menu')); + fireEvent.click(screen.getByText('stage header')); + + fireEvent.click(save()); + await flush(); + + expect(bar()).not.toBeNull(); + expect(screen.getByTestId('staged-first')).toHaveTextContent(''); + expect(screen.getByTestId('staged-menu')).toHaveTextContent('menu-value'); + expect(screen.getByTestId('staged-header')).toHaveTextContent('header-value'); + expect(header).not.toHaveBeenCalled(); + expect(toastError).toHaveBeenCalledWith('Some changes were not saved: Package is read-only'); + expect(save()).toBeEnabled(); + }); + + it('「Cancel」 drops every staged change and commits none', () => { + const commit = vi.fn(async () => {}); + render(); + fireEvent.click(screen.getByText('enter')); + fireEvent.click(screen.getByText('stage menu')); + fireEvent.click(screen.getByTestId('design-mode-cancel')); + + expect(bar()).toBeNull(); + expect(commit).not.toHaveBeenCalled(); + fireEvent.click(screen.getByText('enter')); + expect(screen.getByTestId('staged-menu')).toHaveTextContent(''); + expect(save()).toBeDisabled(); + }); + + it('outside the mode nothing can be staged', () => { + render( {}} />); + fireEvent.click(screen.getByText('stage menu')); + expect(screen.getByTestId('staged-menu')).toHaveTextContent(''); + }); +}); + +describe('where the mode holds (objectstack#36362)', () => { + it('another app turns it off and drops what it held', () => { + const view = render( {}} />); + fireEvent.click(screen.getByText('enter')); + fireEvent.click(screen.getByText('stage menu')); + view.rerender( {}} />); + expect(bar()).toBeNull(); + view.rerender( {}} />); + expect(bar()).toBeNull(); + expect(screen.getByTestId('staged-menu')).toHaveTextContent(''); + }); + + it('a phone turns it off and keeps what is staged until the window is wide again', () => { + const view = render( {}} />); + fireEvent.click(screen.getByText('enter')); + fireEvent.click(screen.getByText('stage menu')); + view.rerender( {}} />); + expect(bar()).toBeNull(); + view.rerender( {}} />); + expect(bar()).not.toBeNull(); + expect(screen.getByTestId('staged-menu')).toHaveTextContent('menu-value'); + }); +}); + +describe('leaving with something staged (objectstack#36362)', () => { + function unloadHeld(): boolean { + const unload = new Event('beforeunload', { cancelable: true }); + window.dispatchEvent(unload); + return unload.defaultPrevented; + } + + it('a tab close is held only while something is staged', () => { + render( {}} />); + fireEvent.click(screen.getByText('enter')); + expect(unloadHeld()).toBe(false); + fireEvent.click(screen.getByText('stage menu')); + expect(unloadHeld()).toBe(true); + fireEvent.click(screen.getByTestId('design-mode-cancel')); + expect(unloadHeld()).toBe(false); + }); + + it('a link to another page of the app asks nothing; a link out of it asks', () => { + const confirmSpy = stubConfirm(); + window.history.replaceState(null, '', '/_console/apps/crm/crm_lead'); + render( {}} />); + fireEvent.click(screen.getByText('enter')); + fireEvent.click(screen.getByText('stage menu')); + + const inApp = document.createElement('a'); + inApp.href = '/_console/apps/crm/dashboard/sales'; + const home = document.createElement('a'); + home.href = '/_console/home'; + document.body.append(inApp, home); + const stop = (e: Event) => e.preventDefault(); + window.addEventListener('click', stop); + try { + inApp.click(); + expect(confirmSpy).not.toHaveBeenCalled(); + home.click(); + expect(confirmSpy).toHaveBeenCalledWith('Leave design mode? Your unsaved changes will be lost.'); + } finally { + window.removeEventListener('click', stop); + inApp.remove(); + home.remove(); + } + }); +}); + +describe('isPageOfApp (objectstack#36362)', () => { + const at = (path: string) => new URL(path, 'http://localhost'); + it('reads the app prefix off the address on screen, basename included', () => { + expect(isPageOfApp(at('/_console/apps/crm/x'), '/apps/crm', '/_console/apps/crm/y')).toBe(true); + expect(isPageOfApp(at('/_console/apps/crm'), '/apps/crm', '/_console/apps/crm/y')).toBe(true); + expect(isPageOfApp(at('/_console/apps/crm_other/x'), '/apps/crm', '/_console/apps/crm/y')).toBe(false); + expect(isPageOfApp(at('/_console/apps/hr/x'), '/apps/crm', '/_console/apps/crm/y')).toBe(false); + expect(isPageOfApp(at('/apps/crm/x'), '/apps/crm', '/home')).toBe(true); + }); +}); diff --git a/ui/packages/app-shell/src/layout/designMode.tsx b/ui/packages/app-shell/src/layout/designMode.tsx new file mode 100644 index 00000000000..52e647e7724 --- /dev/null +++ b/ui/packages/app-shell/src/layout/designMode.tsx @@ -0,0 +1,253 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Design mode — the app shell's one place where an administrator changes the + * app's frame in the running app (objectstack#36362, epic objectstack#36359): + * entered from the page header's 「Edit app」, shown as a bar across the top + * of the window with 「Design mode」, 「Cancel」 and 「Save」 and nothing else + * (`DesignModeBar`). + * + * ## What the mode holds + * + * The mode is the shell's, not a page's: it is held by `ConsoleLayout` for the + * app it was entered in, so it stays on while the administrator moves from + * page to page of that app, and goes off when the app changes. It is never on + * a phone, which draws no 「Edit app」. + * + * It holds the changes made under it, and nothing else. Each change is staged + * under a key by the surface that makes it ({@link useDesignModeChange}): the + * menu editor, the page header's pinned actions. A staged change carries its + * own `commit`, the write that makes it real, so the mode needs to know + * nothing about what a change is: + * + * - 「Save」 commits every staged change, in the order they were first + * staged, then leaves the mode. A commit that fails stops the save there: + * the changes committed before it are saved, the failed one and every later + * one stay staged, the mode stays on, and the failure is said. + * - 「Cancel」 drops every staged change and leaves the mode. Nothing staged + * was written, so there is nothing to undo. + * - With nothing staged, 「Save」 is off. + * + * ## What leaving costs + * + * While a change is staged, leaving the app drops it, so the shell's + * unsaved-edits seam guards that departure (`chrome/unsavedEdits.ts`): a tab + * close or reload asks through the browser's own prompt, a link out of the + * app and the app switcher ask first. A link to another page of the same app + * does not ask: the mode, and what it holds, go along. + * + * Who may enter is the header button's gate (`useAppStudioEntry`, a workspace + * administrator holding `manage_metadata` on a writable package), read where + * the button is drawn. The mode has no address: no URL enters it. Each + * change's `commit` is a write the server judges again. + * + * @module + */ + +import * as React from 'react'; +import { toast } from 'sonner'; +import { useObjectTranslation } from '@object-ui/i18n'; +import { registerUnsavedEdits } from '../chrome/unsavedEdits.js'; + +/** One staged change: its value, and the write that makes it real. */ +export interface DesignModeChange { + readonly value: T; + readonly commit: (value: T) => Promise; +} + +type StagedChanges = ReadonlyMap>; + +const NO_CHANGES: StagedChanges = new Map(); + +/** The mode as the shell holds it, for the app it is on. */ +export interface DesignModeValue { + /** On, for the app on screen. */ + readonly active: boolean; + /** At least one change is staged. */ + readonly dirty: boolean; + /** A save is under way: the bar's buttons wait, and so should every editor. */ + readonly saving: boolean; + /** Turn the mode on for the app on screen. */ + readonly enter: () => void; + /** Drop every staged change and leave the mode. */ + readonly cancel: () => void; + /** Commit every staged change, then leave the mode; `false` when one failed. */ + readonly save: () => Promise; +} + +interface DesignModeStore extends DesignModeValue { + readonly changes: StagedChanges; + readonly stage: (key: string, change: DesignModeChange) => void; + readonly unstage: (key: string) => void; +} + +const DesignModeContext = React.createContext(null); + +interface HeldMode { + /** The app the mode was entered in; `null` while the mode is off. */ + readonly app: string | null; + readonly changes: StagedChanges; +} + +const OFF: HeldMode = { app: null, changes: NO_CHANGES }; + +/** + * Whether `url` is a page of the app at `appBasePath` (`/apps/SEGMENT`), read + * against the address on screen so a router basename in front of it counts. + */ +export function isPageOfApp(url: URL, appBasePath: string, currentPathname: string): boolean { + const at = currentPathname.indexOf(appBasePath); + const prefix = at >= 0 ? currentPathname.slice(0, at + appBasePath.length) : appBasePath; + return url.pathname === prefix || url.pathname.startsWith(`${prefix}/`); +} + +/** + * The mode for `appName`, held by the shell: hand its answer to + * {@link DesignModeProvider}. `enabled` is `false` where the mode is never on + * (a phone); the staged changes are kept, unseen, until it is `true` again. + */ +export function useDesignModeController({ + appName, + appBasePath, + enabled, +}: { + appName: string; + appBasePath: string; + enabled: boolean; +}): DesignModeStore { + const { t } = useObjectTranslation(); + const [held, setHeld] = React.useState(OFF); + const [saving, setSaving] = React.useState(false); + + // Another app: the mode and what it held were the previous app's. + if (held.app !== null && held.app !== appName) setHeld(OFF); + + const on = held.app !== null && held.app === appName; + const active = on && enabled; + const changes = on ? held.changes : NO_CHANGES; + const dirty = changes.size > 0; + + const heldRef = React.useRef(held); + React.useLayoutEffect(() => { + heldRef.current = held; + }); + + const enter = React.useCallback(() => { + setHeld((prev) => (prev.app === appName ? prev : { app: appName, changes: NO_CHANGES })); + }, [appName]); + + const cancel = React.useCallback(() => { + setHeld(OFF); + }, []); + + const stage = React.useCallback((key: string, change: DesignModeChange) => { + setHeld((prev) => { + if (prev.app === null) return prev; + const next = new Map(prev.changes); + next.set(key, change); + return { app: prev.app, changes: next }; + }); + }, []); + + const unstage = React.useCallback((key: string) => { + setHeld((prev) => { + if (prev.app === null || !prev.changes.has(key)) return prev; + const next = new Map(prev.changes); + next.delete(key); + return { app: prev.app, changes: next }; + }); + }, []); + + const savingRef = React.useRef(false); + const save = React.useCallback(async (): Promise => { + if (savingRef.current) return false; + const start = heldRef.current; + if (start.app === null) return false; + savingRef.current = true; + setSaving(true); + try { + for (const [key, change] of start.changes) { + try { + await change.commit(change.value); + } catch (error) { + toast.error( + t('designMode.saveFailed', { + defaultValue: 'Some changes were not saved: {{reason}}', + reason: error instanceof Error ? error.message : String(error), + }), + ); + return false; + } + // Saved: off the list, unless it was staged again while it was sent. + setHeld((prev) => { + if (prev.changes.get(key) !== change) return prev; + const next = new Map(prev.changes); + next.delete(key); + return { app: prev.app, changes: next }; + }); + } + setHeld((prev) => (prev.changes.size === 0 ? OFF : prev)); + return true; + } finally { + savingRef.current = false; + setSaving(false); + } + }, [t]); + + // Leaving the app drops what is staged; a page of the same app keeps it. + const leaveMessage = t('designMode.leaveUnsaved', { + defaultValue: 'Leave design mode? Your unsaved changes will be lost.', + }); + React.useEffect(() => { + if (!dirty) return undefined; + return registerUnsavedEdits(leaveMessage, { + keeps: (url) => isPageOfApp(url, appBasePath, window.location.pathname), + }); + }, [dirty, leaveMessage, appBasePath]); + + return React.useMemo( + () => ({ active, dirty, saving, enter, cancel, save, changes, stage, unstage }), + [active, dirty, saving, enter, cancel, save, changes, stage, unstage], + ); +} + +/** Hands the shell's mode to the pages and the chrome under it. */ +export function DesignModeProvider({ value, children }: { value: DesignModeStore; children: React.ReactNode }) { + return {children}; +} + +/** The mode, or `null` outside a shell that holds one (Home, Studio, a bare test mount). */ +export function useDesignMode(): DesignModeValue | null { + return React.useContext(DesignModeContext); +} + +/** Whether the mode is on for the app on screen; `false` outside a shell that holds one. */ +export function useDesignModeActive(): boolean { + return React.useContext(DesignModeContext)?.active ?? false; +} + +/** + * The extension point: a surface that changes something under the mode stages + * its change under `key` (one key per thing changed, such as the app's menu), + * and the mode saves or drops it with the rest. `value` is what is staged + * under `key`, `undefined` when nothing is: a surface draws from it, so its + * pending state survives a page change. Outside a shell that holds the mode, + * nothing is ever staged and `stage` does nothing. + */ +export function useDesignModeChange(key: string): { + readonly value: T | undefined; + readonly stage: (value: T, commit: (value: T) => Promise) => void; + readonly unstage: () => void; +} { + const store = React.useContext(DesignModeContext); + const staged = store?.changes.get(key) as DesignModeChange | undefined; + const storeStage = store?.stage; + const storeUnstage = store?.unstage; + const stage = React.useCallback( + (value: T, commit: (value: T) => Promise) => + storeStage?.(key, { value, commit: commit as (value: unknown) => Promise }), + [storeStage, key], + ); + const unstage = React.useCallback(() => storeUnstage?.(key), [storeUnstage, key]); + return { value: staged?.value, stage, unstage }; +} diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 960bb5b64d4..1dff39af414 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -3754,6 +3754,11 @@ const ar = { collapse: 'طي الشريط الجانبي', expand: 'توسيع الشريط الجانبي', }, + designMode: { + title: 'وضع التصميم', + leaveUnsaved: 'هل تريد مغادرة وضع التصميم؟ ستفقد التغييرات غير المحفوظة.', + saveFailed: 'لم يتم حفظ بعض التغييرات: {{reason}}', + }, topbar: { openAssistant: "فتح مساعد {{name}}", offline: "غير متصل", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 705e38b763d..7d12fd4c500 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -3439,6 +3439,11 @@ const de = { collapse: 'Seitenleiste einklappen', expand: 'Seitenleiste ausklappen', }, + designMode: { + title: 'Designmodus', + leaveUnsaved: 'Designmodus verlassen? Nicht gespeicherte Änderungen gehen verloren.', + saveFailed: 'Einige Änderungen wurden nicht gespeichert: {{reason}}', + }, topbar: { openAssistant: "Assistent {{name}} öffnen", offline: "Offline", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 8a43689a990..4dcb0872e14 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -4113,6 +4113,11 @@ const en = { collapse: 'Collapse sidebar', expand: 'Expand sidebar', }, + designMode: { + title: 'Design mode', + leaveUnsaved: 'Leave design mode? Your unsaved changes will be lost.', + saveFailed: 'Some changes were not saved: {{reason}}', + }, topbar: { aiAssistant: 'AI Assistant', designInStudio: 'Design in Studio', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index f24e9816f31..f1d0355e752 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -3519,6 +3519,11 @@ const es = { collapse: 'Contraer la barra lateral', expand: 'Expandir la barra lateral', }, + designMode: { + title: 'Modo de diseño', + leaveUnsaved: '¿Salir del modo de diseño? Se perderán los cambios no guardados.', + saveFailed: 'Algunos cambios no se guardaron: {{reason}}', + }, topbar: { openAssistant: "Abrir el asistente {{name}}", offline: "Sin conexión", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 868c80eb488..a8e514c8dcc 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -3515,6 +3515,11 @@ const fr = { collapse: 'Réduire la barre latérale', expand: 'Développer la barre latérale', }, + designMode: { + title: 'Mode conception', + leaveUnsaved: 'Quitter le mode conception ? Les modifications non enregistrées seront perdues.', + saveFailed: 'Certaines modifications n’ont pas été enregistrées : {{reason}}', + }, topbar: { openAssistant: "Ouvrir l'assistant {{name}}", offline: "Hors ligne", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index f5fefa091a6..e3e0a3c51f9 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -3441,6 +3441,11 @@ const ja = { collapse: 'サイドバーを折りたたむ', expand: 'サイドバーを展開', }, + designMode: { + title: 'デザインモード', + leaveUnsaved: 'デザインモードを終了しますか?保存されていない変更は失われます。', + saveFailed: '一部の変更が保存されませんでした:{{reason}}', + }, topbar: { openAssistant: "{{name}} アシスタントを開く", offline: "オフライン", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 5d3500174de..4dc1125e8ad 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -3439,6 +3439,11 @@ const ko = { collapse: '사이드바 접기', expand: '사이드바 펼치기', }, + designMode: { + title: '디자인 모드', + leaveUnsaved: '디자인 모드를 종료할까요? 저장하지 않은 변경 사항은 사라집니다.', + saveFailed: '일부 변경 사항이 저장되지 않았습니다: {{reason}}', + }, topbar: { openAssistant: "{{name}} 어시스턴트 열기", offline: "오프라인", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 53dc0b099f4..a518b528465 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -3514,6 +3514,11 @@ const pt = { collapse: 'Recolher a barra lateral', expand: 'Expandir a barra lateral', }, + designMode: { + title: 'Modo de design', + leaveUnsaved: 'Sair do modo de design? As alterações não salvas serão perdidas.', + saveFailed: 'Algumas alterações não foram salvas: {{reason}}', + }, topbar: { openAssistant: "Abrir o assistente {{name}}", offline: "Off-line", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 8f782fc7386..bf0f9d7e730 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -3604,6 +3604,11 @@ const ru = { collapse: 'Свернуть боковую панель', expand: 'Развернуть боковую панель', }, + designMode: { + title: 'Режим дизайна', + leaveUnsaved: 'Выйти из режима дизайна? Несохранённые изменения будут потеряны.', + saveFailed: 'Некоторые изменения не сохранены: {{reason}}', + }, topbar: { openAssistant: "Открыть ассистента {{name}}", offline: "Не в сети", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 677386b0bbd..34f9d5d2930 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -3520,6 +3520,11 @@ const zh = { collapse: '收起侧边栏', expand: '展开侧边栏', }, + designMode: { + title: '设计模式', + leaveUnsaved: '离开设计模式?未保存的改动将会丢失。', + saveFailed: '部分改动没有保存:{{reason}}', + }, topbar: { aiAssistant: 'AI 助手', designInStudio: '在 Studio 中设计', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 9e423c7f593..b700d84dcc7 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -3520,6 +3520,11 @@ const zhHant = { collapse: '收起側邊欄', expand: '展開側邊欄', }, + designMode: { + title: '設計模式', + leaveUnsaved: '離開設計模式?未儲存的改動將會丟失。', + saveFailed: '部分改動沒有儲存:{{reason}}', + }, topbar: { aiAssistant: 'AI 助手', designInStudio: '在 Studio 中設計',