From 6fbbdd9b30785084fcbb3251019939c4c4bd5f7d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 23:32:57 +0000 Subject: [PATCH] feat(studio): a dashboard list's New opens the app's design mode on its dashboards Studio's dashboard list New now opens the package's app (decision 6, the .custom pair leg included) with a one-time navigation-state arrival: ConsoleLayout reads it once, clears it from the history entry, and asks the design mode to enter with the Add menu item picker open on its dashboards. A refused entry does nothing more and says why; a phone does nothing. The dashboard created there opens for editing with ?studio= back to the list. The list offers no New at phone width, and none without a target app, saying why. The report New is unchanged. Claude-Session: https://claude.ai/code/session_01QSeKYoLfUxK6MRhuSp7nAt Co-authored-by: Claude --- .../36907-studio-new-dashboard-design-mode.md | 19 ++ .../app-shell/src/layout/ConsoleLayout.tsx | 5 + .../app-shell/src/layout/DesignModeMenu.tsx | 47 ++++- .../__tests__/DesignModeMenu-36363.test.tsx | 193 +++++++++++++++++- .../app-shell/src/layout/designMode.tsx | 126 +++++++++--- .../app-shell/src/layout/designModeArrival.ts | 47 +++++ .../src/layout/useDesignModeArrival.ts | 43 ++++ ...ResourceListPage.pairCreate-36897.test.tsx | 108 +++++++++- .../views/metadata-admin/ResourceListPage.tsx | 23 ++- .../StudioAreaAppOpen-36906.test.tsx | 138 ++++++++++++- .../views/studio-design/StudioAreaAppOpen.tsx | 162 ++++++++++++--- .../studio-design/StudioMetadataArea.tsx | 11 + .../src/views/studio-design/studioAppEdit.ts | 14 +- ui/packages/i18n/src/namespaces/studio/en.ts | 3 + ui/packages/i18n/src/namespaces/studio/zh.ts | 2 + 15 files changed, 856 insertions(+), 85 deletions(-) create mode 100644 .changeset/36907-studio-new-dashboard-design-mode.md create mode 100644 ui/packages/app-shell/src/layout/useDesignModeArrival.ts diff --git a/.changeset/36907-studio-new-dashboard-design-mode.md b/.changeset/36907-studio-new-dashboard-design-mode.md new file mode 100644 index 00000000000..2132757c83e --- /dev/null +++ b/.changeset/36907-studio-new-dashboard-design-mode.md @@ -0,0 +1,19 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(studio): New on a Studio dashboard list opens the app's design mode, ready to add a dashboard to its menu + +Clause-②: no +Metadata-protocol: none + +Studio redesign (epic #36890): a new dashboard is made where it hangs in an app's menu, never outside every menu. + +- **New on a Studio dashboard list** opens the package's app with Design layout already on and the 「Add menu item」 picker open on its Dashboards, 「New dashboard…」 first. The app is picked the same way as for opening a dashboard: the app you came from when it is one of the package's, otherwise the package's first app. For an installed app, what you save there goes to its customization package, as before. For a customization package (`.custom`) that has no app of its own, the base package's app opens. +- **After Create** the dashboard is in the menu where the picker put it, at the end of the menu's top level, and opens for editing, as a dashboard made in Design layout always has. Its × goes back to the Studio list you left. Closing the picker instead leaves you in Design layout, with nothing added. +- **When there is no New.** On a phone-width window the dashboard list offers no New: Design layout is never on there. A package with no app to open offers no New either, and the list says why. +- **Nothing enters Design layout by itself.** The way in is a one-time instruction carried by the click, never the address: a reload, a shared link or Back does not turn it on. If a dashboard's or a report's own editor is open at that moment, Design layout refuses with the usual message and nothing else happens. +- **The report list is unchanged:** its New still opens the app's New report page. +- **A note on an earlier entry,** customization packages' dashboards and reports opening in their base package's app: the app you came from also counts when it is not one of the base's apps, as long as its menu opens that dashboard or report. That is the same rule as for every package. +- New Studio string `engine.list.dashboardNewNoApp`, in English and Chinese. diff --git a/ui/packages/app-shell/src/layout/ConsoleLayout.tsx b/ui/packages/app-shell/src/layout/ConsoleLayout.tsx index 2ae1531489f..419d0563f33 100644 --- a/ui/packages/app-shell/src/layout/ConsoleLayout.tsx +++ b/ui/packages/app-shell/src/layout/ConsoleLayout.tsx @@ -39,6 +39,7 @@ import { useHomePath } from '../hooks/useHomePath.js'; import { AppHeader } from './AppHeader.js'; import { DesignModeProvider, useDesignModeController } from './designMode.js'; import { DesignModeBar } from './DesignModeBar.js'; +import { useDesignModeArrival } from './useDesignModeArrival.js'; import { useResponsiveSidebar } from '../hooks/useResponsiveSidebar.js'; import { usePhoneNavDrawerHistory } from './usePhoneNavDrawerHistory.js'; import { usePhoneViewport } from '../hooks/usePhoneViewport.js'; @@ -234,6 +235,10 @@ export function ConsoleLayout({ // 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 「Design layout」. const designMode = useDesignModeController({ appName: activeAppName, appBasePath, enabled: !phone }); + // objectstack#36907 — a Studio dashboard list's 「New」 arrives with the + // mode asked to enter and the 「Add menu item」 picker on its dashboards; + // read once and cleared, so Back or a reload enters nothing. + useDesignModeArrival(designMode, !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 diff --git a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx index 8297d0cae8f..9a802bc13ab 100644 --- a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx +++ b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx @@ -53,6 +53,13 @@ * maintainer's ruling to keep report editing its own entry, as Twenty does): * a new report is made from the reports index, then linked here. * + * The mode may arrive asking this menu to open first (objectstack#36907, a + * Studio dashboard list's 「New」, `useDesignModeOpening`): the picker then + * opens at once, on its 「Dashboards」, for an entry at the end of the top + * level, as that level's 「Add menu item」 would. A dashboard created from it + * opens with the Studio list it came from (`?studio=`), so its × goes back + * there; closing the picker drops that, and later adds are plain. + * * Every edit is staged with the mode (`useDesignModeChange`), under one key * for the app's menu: the mode's 「Save」 writes it (`saveAppMenu`), its * 「Cancel」 drops it. The menu drawn is the staged one, so it survives a page @@ -144,7 +151,7 @@ import { fetchListedPackageManifests, listedCustomizationPairOf, } from '../views/studio-design/packages-io.js'; -import { useDesignModeChange } from './designMode.js'; +import { useDesignModeChange, useDesignModeOpening } from './designMode.js'; import { MENU_TARGET_KINDS, canMoveBy, @@ -181,6 +188,7 @@ import { } from './designModeMenuSave.js'; import { freeItemName, isNewMenuItemKind, saveAppMenuWithNewItem, type NewMenuItemKind } from './designModeMenuCreate.js'; import { dashboardEditArrival } from './designModeArrival.js'; +import { withStudioReturn } from '../views/studio-design/studioAddress.js'; /** * The group label's icon-mode hiding, as the sidebar's own labels declare it @@ -452,10 +460,32 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso const startAdd = (at: AddAt) => { setAddAt({ parentId: at.parentId, index: Math.min(at.index, ownEndOf(menu, at.parentId)) }); }; + + // objectstack#36907 — what the mode arrived asking to open: the picker on + // its 「Dashboards」, at the end of the top level, taken once. `arrivedFrom` + // is the Studio list it came from, kept while that picker is open. + const arrivalOpening = useDesignModeOpening(); + const [pickerKind, setPickerKind] = React.useState(null); + const [arrivedFrom, setArrivedFrom] = React.useState(null); + const takeArrival = arrivalOpening.take; + React.useEffect(() => { + if (!arrivalOpening.opening) return; + const taken = takeArrival(); + if (!taken) return; + startAdd({ parentId: null, index: menu.length }); + setPickerKind(taken.column); + setArrivedFrom(taken.studioReturn); + // eslint-disable-next-line react-hooks/exhaustive-deps -- answered once per opening + }, [arrivalOpening.opening, takeArrival]); + const closePicker = () => { + setAddAt(null); + setPickerKind(null); + setArrivedFrom(null); + }; const pick = (entry: MenuEntry) => { if (!addAt) return; update(insertEntry(menu, addAt.parentId, addAt.index, entry)); - setAddAt(null); + closePicker(); }; // objectstack#36364 — a new dashboard, in the held place: created, put in @@ -498,8 +528,9 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso ), ); if (!saved) return false; - setAddAt(null); - navigate(resolveHref(entry as unknown as NavigationItem, basePath).href, { state: dashboardEditArrival(name) }); + const href = resolveHref(entry as unknown as NavigationItem, basePath).href; + closePicker(); + navigate(arrivedFrom ? withStudioReturn(href, arrivedFrom) : href, { state: dashboardEditArrival(name) }); return true; }; @@ -622,7 +653,8 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso setAddAt(null)} + initialKind={pickerKind} + onClose={closePicker} onPick={(kind, name, link) => pick(entryFor(kind, name, newEntryId([...menu, ...(storedMenu ?? [])]), link))} onCreate={createItem} language={language} @@ -915,6 +947,7 @@ function useTargetRows(packageId: string, language: string): { rows: TargetRow[] function MenuItemPicker({ packageId, inMenu, + initialKind = null, onClose, onPick, onCreate, @@ -922,6 +955,8 @@ function MenuItemPicker({ }: { packageId: string; inMenu: ReadonlySet; + /** The kind the picker opens on (objectstack#36907); `null`: the list of kinds. */ + initialKind?: MenuTargetKind | null; onClose: () => void; onPick: (kind: MenuTargetKind, name: string, link?: { label: string; url: string }) => void; /** Create a new `kind` named `label`; `taken` is every name of that kind the picker lists. */ @@ -930,7 +965,7 @@ function MenuItemPicker({ }) { const { t } = useObjectTranslation(); const { rows, loading } = useTargetRows(packageId, language); - const [kind, setKind] = React.useState(null); + const [kind, setKind] = React.useState(initialKind); const [query, setQuery] = React.useState(''); const [link, setLink] = React.useState({ label: '', url: '' }); /** The kind being named for creation (objectstack#36364), `null` while picking. */ diff --git a/ui/packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx b/ui/packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx index f8bda51a23e..8940249445e 100644 --- a/ui/packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx @@ -16,7 +16,7 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'; -import { MemoryRouter, useLocation } from 'react-router-dom'; +import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom'; import { SidebarProvider } from '@object-ui/components'; import { NavigationRenderer } from '@object-ui/layout'; import type { NavigationItem } from '@object-ui/types'; @@ -140,7 +140,9 @@ vi.mock('../../views/studio-design/packages-io', async (importOriginal) => ({ })); vi.mock('../../utils/getIcon', () => ({ getIcon: () => () => null })); -import { DesignModeProvider, useDesignMode, useDesignModeController } from '../designMode'; +import { DesignModeProvider, useDesignMode, useDesignModeController, useHoldDesignModeOut } from '../designMode'; +import { useDesignModeArrival } from '../useDesignModeArrival'; +import { designModeAddDashboardArrival } from '../designModeArrival'; import { DesignModeBar } from '../DesignModeBar'; import DesignModeMenu from '../DesignModeMenu'; import { closestCenter, type CollisionDetection } from '@dnd-kit/core'; @@ -1308,3 +1310,190 @@ describe('the design-mode menu save and drag, hardened (objectstack#36538)', () }); }); }); + +/* + * objectstack#36907 — a Studio dashboard list's 「New」 arrives in the app with + * `designModeAddDashboardArrival` in the navigation state. The shell + * (`useDesignModeArrival`, as `ConsoleLayout` calls it) reads it once, clears + * it from the history entry, and enters the mode with the picker open on its + * 「Dashboards」; where `enter` refuses, nothing more happens and the mode + * says why; on a phone, nothing at all. + */ +const STUDIO_LIST = '/studio/com.acme.crm/metadata/dashboard?package=com.acme.crm'; + +/** The shell's hold on the mode, as `ConsoleLayout` wires it, the arrival read included. */ +function ArrivalHarness({ enabled = true, editorOpen = false }: { enabled?: boolean; editorOpen?: boolean }) { + const mode = useDesignModeController({ appName: 'crm', appBasePath: '/apps/crm', enabled }); + useDesignModeArrival(mode, enabled); + return ( + + {mode.active && } + {editorOpen && } + + {mode.active && ( + (target.kind === 'object' ? OBJECT_LABELS[target.objectName] : undefined)} + /> + )} + + + + ); +} + +/** A dashboard's or a report's own editor, open: it holds the mode out (objectstack#36692). */ +function OpenEditor() { + useHoldDesignModeOut(true); + return null; +} + +/** The address and the navigation state on screen, as `JSON`. */ +function Here() { + const { pathname, search, state } = useLocation(); + return ; +} + +/** A second arrival into the app on screen: Studio's New, taken again. */ +function ArriveAgain() { + const navigate = useNavigate(); + return ( + + ); +} + +const here = () => { + const el = screen.getByTestId('here'); + return { at: el.getAttribute('data-at'), state: JSON.parse(el.getAttribute('data-state') ?? 'null') }; +}; + +function arrive(props: { enabled?: boolean; editorOpen?: boolean } = {}, entry: { pathname: string; state: unknown } = { + pathname: '/apps/crm', + state: designModeAddDashboardArrival(STUDIO_LIST), +}) { + return render( + + + + , + ); +} + +describe("the arrival from a Studio dashboard list's New (objectstack#36907)", () => { + it('enters the mode with the picker open on 「Dashboards」, 「New dashboard…」 first, for an entry at the end of the top level', async () => { + listed.dashboard = [{ name: 'revenue', label: 'Revenue' }]; + try { + arrive(); + await flush(); + expect(screen.getByTestId('design-mode-bar')).toBeInTheDocument(); + const picker = await screen.findByTestId('design-menu-picker'); + const rows = within(within(picker).getByTestId('design-menu-picker-rows')).getAllByRole('button').map((b) => b.textContent); + expect(rows).toEqual(['New dashboard…', 'Revenue']); + expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', []], '…']); + expect(toastError).not.toHaveBeenCalled(); + } finally { + listed.dashboard = []; + } + }); + + it('is read once: the history entry is cleared, so a reload of it, or Back to it, enters nothing', async () => { + arrive(); + await flush(); + expect(here()).toEqual({ at: '/apps/crm', state: null }); + expect(screen.getByTestId('design-mode-bar')).toBeInTheDocument(); + cleanup(); + + // The same entry, reloaded: what the history holds now carries no arrival. + arrive({}, { pathname: '/apps/crm', state: null }); + await flush(); + expect(screen.queryByTestId('design-mode-bar')).toBeNull(); + expect(screen.queryByTestId('design-menu-picker')).toBeNull(); + }); + + it('「Create」 in it: the dashboard hangs at the end of the top level and opens for editing, with × back to the Studio list', async () => { + arrive(); + await flush(); + const picker = await screen.findByTestId('design-menu-picker'); + fireEvent.click(within(picker).getByTestId('design-menu-picker-new-dashboard')); + const naming = await screen.findByTestId('design-menu-new-dashboard'); + fireEvent.change(within(naming).getByTestId('design-menu-new-name'), { target: { value: 'Payment analysis' } }); + fireEvent.click(within(naming).getByTestId('design-menu-new-create')); + await flush(); + await flush(); + await flush(); + + expect(written.map(([verb, type, name]) => `${verb} ${type} ${name}`)).toEqual([ + 'save dashboard payment_analysis', + 'publish dashboard payment_analysis', + 'save app crm', + 'publish app crm', + ]); + const navigation = (written[2][3] as { navigation: Array<{ id: string }> }).navigation; + expect(navigation.at(-1)).toEqual({ id: 'nav_item_1', type: 'dashboard', dashboardName: 'payment_analysis' }); + expect(screen.queryByTestId('design-mode-bar')).toBeNull(); + const landed = here(); + expect(landed.at!.split('?')[0]).toBe('/apps/crm/dashboard/payment_analysis'); + expect(new URLSearchParams(landed.at!.split('?')[1]).get('studio')).toBe(STUDIO_LIST); + expect(landed.state).toEqual({ designModeNewDashboard: 'payment_analysis' }); + }); + + it("closing that picker drops the Studio list: a dashboard made from another 「Add menu item」 opens without it", async () => { + arrive(); + await flush(); + fireEvent.keyDown(await screen.findByTestId('design-menu-picker'), { key: 'Escape' }); + await flush(); + expect(screen.queryByTestId('design-menu-picker')).toBeNull(); + const picker = await openDashboards(); + fireEvent.click(within(picker).getByTestId('design-menu-picker-new-dashboard')); + const naming = await screen.findByTestId('design-menu-new-dashboard'); + fireEvent.change(within(naming).getByTestId('design-menu-new-name'), { target: { value: 'Payment analysis' } }); + fireEvent.click(within(naming).getByTestId('design-menu-new-create')); + await flush(); + await flush(); + await flush(); + expect(here().at).toBe('/apps/crm/dashboard/payment_analysis'); + }); + + it('where an editor of its own holds the mode out, entering refuses and says why; the arrival does nothing more and is cleared', async () => { + render( + + + + , + ); + fireEvent.click(screen.getByText('arrive again')); + await flush(); + expect(toastError).toHaveBeenCalledWith('Save or cancel your dashboard or report changes before designing the layout.'); + expect(screen.queryByTestId('design-mode-bar')).toBeNull(); + expect(screen.queryByTestId('design-menu-picker')).toBeNull(); + expect(here()).toEqual({ at: '/apps/crm', state: null }); + expect(written).toEqual([]); + }); + + it('the same refusal when the editor opens in the very commit the arrival lands in', async () => { + arrive({ editorOpen: true }); + await flush(); + expect(toastError).toHaveBeenCalledWith('Save or cancel your dashboard or report changes before designing the layout.'); + expect(screen.queryByTestId('design-mode-bar')).toBeNull(); + expect(here()).toEqual({ at: '/apps/crm', state: null }); + }); + + it('on a phone the mode is never on: the arrival enters nothing, says nothing, and is cleared', async () => { + arrive({ enabled: false }); + await flush(); + expect(screen.queryByTestId('design-mode-bar')).toBeNull(); + expect(screen.queryByTestId('design-menu-picker')).toBeNull(); + expect(toastError).not.toHaveBeenCalled(); + expect(here()).toEqual({ at: '/apps/crm', state: null }); + }); + + it('CONTROL — the menu door enters the mode with no picker open', async () => { + start(); + await flush(); + expect(screen.getByTestId('design-mode-bar')).toBeInTheDocument(); + expect(screen.queryByTestId('design-menu-picker')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/layout/designMode.tsx b/ui/packages/app-shell/src/layout/designMode.tsx index 3ef4f48bc9f..3b1c6e15752 100644 --- a/ui/packages/app-shell/src/layout/designMode.tsx +++ b/ui/packages/app-shell/src/layout/designMode.tsx @@ -15,7 +15,9 @@ * page to page of that app, and goes off when the app changes. It is never on * a phone, which draws no 「Design layout」. * - * It holds the changes made under it, and nothing else. Each change is staged + * It holds the changes made under it, and nothing else but one thing: the + * surface an arrival asked to open first ({@link DesignModeOpening}, + * objectstack#36907), held until that surface takes it. 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 record page's tabs (its * tab row is their editor while the mode is on, objectstack#36737, as Twenty @@ -72,7 +74,11 @@ * (installed) package's app enters too, and what the mode saves goes to that * package's customization package, as Studio's edits do, except where the * customization door is walled off for the caller. The mode has no address: - * no URL enters it. Each + * no URL enters it. A Studio dashboard list's 「New」 enters it by a one-time + * arrival in the navigation state instead (`useDesignModeArrival`, + * objectstack#36907), which asks {@link DesignModeValue.enterOpening}: the + * same entry, refused the same way, with the 「Add menu item」 picker opened + * on its dashboards once the menu's editor is drawn. Each * change's `commit` is a write the server judges again. * * @module @@ -93,6 +99,17 @@ type StagedChanges = ReadonlyMap>; const NO_CHANGES: StagedChanges = new Map(); +/** + * What an arrival asks the mode to open first (objectstack#36907): the + * 「Add menu item」 picker, on its dashboards, at the end of the menu's top + * level. `studioReturn` is the Studio list the arrival came from, which the + * dashboard created there goes back to (`?studio=`), or `null`. + */ +export interface DesignModeOpening { + readonly column: 'dashboard'; + readonly studioReturn: string | null; +} + /** The mode as the shell holds it, for the app it is on. */ export interface DesignModeValue { /** On, for the app on screen. */ @@ -106,6 +123,12 @@ export interface DesignModeValue { * while a dashboard or report editor holds the mode out. */ readonly enter: () => boolean; + /** + * {@link DesignModeValue.enter}, then hold `opening` for the surface that + * opens it ({@link useDesignModeOpening}); `false`, nothing held and the + * reason said, where `enter` refuses. + */ + readonly enterOpening: (opening: DesignModeOpening) => boolean; /** Drop every staged change and leave the mode. */ readonly cancel: () => void; /** Commit every staged change, then leave the mode; `false` when one failed. */ @@ -114,6 +137,10 @@ export interface DesignModeValue { interface DesignModeStore extends DesignModeValue { readonly changes: StagedChanges; + /** What an arrival asked to open first, until that surface takes it. */ + readonly opening: DesignModeOpening | null; + /** Take {@link DesignModeStore.opening}: it is answered once. */ + readonly takeOpening: () => DesignModeOpening | null; readonly stage: (key: string, change: DesignModeChange) => void; readonly unstage: (key: string) => void; /** Save every staged change with `change` in `key`'s place; `false` when one failed. */ @@ -128,9 +155,11 @@ interface HeldMode { /** The app the mode was entered in; `null` while the mode is off. */ readonly app: string | null; readonly changes: StagedChanges; + /** What an arrival asked to open first, not yet taken. */ + readonly opening: DesignModeOpening | null; } -const OFF: HeldMode = { app: null, changes: NO_CHANGES }; +const OFF: HeldMode = { app: null, changes: NO_CHANGES, opening: null }; /** * Whether `url` is a page of the app at `appBasePath` (`/apps/SEGMENT`), read @@ -160,7 +189,10 @@ export function useDesignModeController({ const [held, setHeld] = React.useState(OFF); const [saving, setSaving] = React.useState(false); /** How many editors of their own hold the mode out. */ - const [heldOut, setHeldOut] = React.useState(0); + // Counted in a ref, not state: an editor that opens in the same commit as + // an arrival asks to enter (objectstack#36907) holds the mode out before + // that entry is judged. + const heldOut = React.useRef(0); // Another app: the mode and what it held were the previous app's. if (held.app !== null && held.app !== appName) setHeld(OFF); @@ -168,6 +200,7 @@ export function useDesignModeController({ const on = held.app !== null && held.app === appName; const active = on && enabled; const changes = on ? held.changes : NO_CHANGES; + const opening = active ? held.opening : null; const dirty = changes.size > 0; const heldRef = React.useRef(held); @@ -175,26 +208,43 @@ export function useDesignModeController({ heldRef.current = held; }); - const enter = React.useCallback((): boolean => { - if (heldOut > 0) { - toast.error( - t('designMode.editorOpen', { - defaultValue: 'Save or cancel your dashboard or report changes before designing the layout.', - }), - ); - return false; - } - setHeld((prev) => (prev.app === appName ? prev : { app: appName, changes: NO_CHANGES })); - return true; - }, [appName, heldOut, t]); + const enterWith = React.useCallback( + (asked: DesignModeOpening | null): boolean => { + if (heldOut.current > 0) { + toast.error( + t('designMode.editorOpen', { + defaultValue: 'Save or cancel your dashboard or report changes before designing the layout.', + }), + ); + return false; + } + setHeld((prev) => { + const entered = prev.app === appName ? prev : { app: appName, changes: NO_CHANGES, opening: null }; + return asked ? { ...entered, opening: asked } : entered; + }); + return true; + }, + [appName, t], + ); + // `enter` takes no argument: a button's click event is never an opening. + const enter = React.useCallback((): boolean => enterWith(null), [enterWith]); + const enterOpening = React.useCallback( + (asked: DesignModeOpening): boolean => enterWith(asked.column === 'dashboard' ? asked : null), + [enterWith], + ); + const takeOpening = React.useCallback((): DesignModeOpening | null => { + const taken = heldRef.current.opening; + if (taken) setHeld((prev) => (prev.opening ? { ...prev, opening: null } : prev)); + return taken; + }, []); const holdOut = React.useCallback(() => { - setHeldOut((n) => n + 1); + heldOut.current += 1; let released = false; return () => { if (released) return; released = true; - setHeldOut((n) => n - 1); + heldOut.current -= 1; }; }, []); @@ -207,7 +257,7 @@ export function useDesignModeController({ if (prev.app === null) return prev; const next = new Map(prev.changes); next.set(key, change); - return { app: prev.app, changes: next }; + return { ...prev, changes: next }; }); }, []); @@ -216,7 +266,7 @@ export function useDesignModeController({ 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 }; + return { ...prev, changes: next }; }); }, []); @@ -249,7 +299,7 @@ export function useDesignModeController({ if (now === undefined || (now !== change && now !== was)) return prev; const next = new Map(prev.changes); next.delete(key); - return { app: prev.app, changes: next }; + return { ...prev, changes: next }; }); } setHeld((prev) => (prev.changes.size === 0 ? OFF : prev)); @@ -277,8 +327,23 @@ export function useDesignModeController({ }, [dirty, leaveMessage, appBasePath]); return React.useMemo( - () => ({ active, dirty, saving, enter, cancel, save, changes, stage, unstage, saveWith, holdOut }), - [active, dirty, saving, enter, cancel, save, changes, stage, unstage, saveWith, holdOut], + () => ({ + active, + dirty, + saving, + enter, + enterOpening, + cancel, + save, + changes, + opening, + takeOpening, + stage, + unstage, + saveWith, + holdOut, + }), + [active, dirty, saving, enter, enterOpening, cancel, save, changes, opening, takeOpening, stage, unstage, saveWith, holdOut], ); } @@ -297,6 +362,21 @@ export function useDesignModeActive(): boolean { return React.useContext(DesignModeContext)?.active ?? false; } +/** + * What an arrival asked the mode to open first (objectstack#36907), for the + * surface that opens it: `opening` while it is held and the mode is on, + * `take` to answer it once. Outside a shell that holds the mode, nothing. + */ +export function useDesignModeOpening(): { + readonly opening: DesignModeOpening | null; + readonly take: () => DesignModeOpening | null; +} { + const store = React.useContext(DesignModeContext); + const takeOpening = store?.takeOpening; + const take = React.useCallback(() => takeOpening?.() ?? null, [takeOpening]); + return { opening: store?.opening ?? null, take }; +} + /** * The other half of the exclusion: a dashboard's or a report's own editor * holds the mode out while `open`, so entering it refuses and says why diff --git a/ui/packages/app-shell/src/layout/designModeArrival.ts b/ui/packages/app-shell/src/layout/designModeArrival.ts index 574f8d3b023..f61128dc9f2 100644 --- a/ui/packages/app-shell/src/layout/designModeArrival.ts +++ b/ui/packages/app-shell/src/layout/designModeArrival.ts @@ -6,6 +6,7 @@ * state, and the dashboard's page opens its edit state on arrival * (objectstack#36372), as its Edit button does. A dashboard opened from a * Studio list lands the same way (objectstack#36906, `StudioAreaAppOpen`). + * Below it, the arrival that enters the mode itself (objectstack#36907). * * Navigation state, not a URL parameter: it is a one-time instruction, not a * place anyone links to, so a shared or reloaded address never opens the edit @@ -38,3 +39,49 @@ export function withoutDashboardEditArrival(state: unknown): Record; return Object.keys(rest).length > 0 ? rest : null; } + +/* + * The arrival that ENTERS the mode (objectstack#36907): a Studio dashboard + * list's 「New」 opens its app with the mode on and the 「Add menu item」 + * picker open on its dashboards, so a dashboard is made where it hangs in a + * menu (objectstack#36364), never outside every menu (epic objectstack#36359). + * + * Navigation state, never a URL parameter: the mode has no address, so no + * link and no reload enters it. The app shell reads it once (`useDesignModeArrival`), + * asks the mode to enter, and clears it from the history entry, so Back or a + * reload enters nothing. A refused entry does nothing more: the mode says why. + */ + +/** The navigation-state key the entering arrival rides on. */ +export const DESIGN_MODE_ADD_DASHBOARD_ARRIVAL_STATE = 'designModeAddDashboard'; + +/** What the entering arrival carries: the Studio list it came from, or `null`. */ +export interface DesignModeAddDashboardArrival { + /** The Studio list the new dashboard's × goes back to (`?studio=`), or `null`. */ + readonly studioReturn: string | null; +} + +/** + * The navigation state that enters the mode on arrival and opens the + * 「Add menu item」 picker on its dashboards; `studioReturn` is the Studio list + * the dashboard created there goes back to. + */ +export function designModeAddDashboardArrival(studioReturn: string | null): Record { + return { [DESIGN_MODE_ADD_DASHBOARD_ARRIVAL_STATE]: { studioReturn } }; +} + +/** The entering arrival `state` carries, or `null`. */ +export function readDesignModeAddDashboardArrival(state: unknown): DesignModeAddDashboardArrival | null { + if (!state || typeof state !== 'object') return null; + const arrival = (state as Record)[DESIGN_MODE_ADD_DASHBOARD_ARRIVAL_STATE]; + if (!arrival || typeof arrival !== 'object') return null; + const studioReturn = (arrival as Record).studioReturn; + return { studioReturn: typeof studioReturn === 'string' && studioReturn ? studioReturn : null }; +} + +/** `state` without the entering arrival, for the replace that clears it once read. */ +export function withoutDesignModeAddDashboardArrival(state: unknown): Record | null { + if (!state || typeof state !== 'object') return null; + const { [DESIGN_MODE_ADD_DASHBOARD_ARRIVAL_STATE]: _arrival, ...rest } = state as Record; + return Object.keys(rest).length > 0 ? rest : null; +} diff --git a/ui/packages/app-shell/src/layout/useDesignModeArrival.ts b/ui/packages/app-shell/src/layout/useDesignModeArrival.ts new file mode 100644 index 00000000000..725492c027f --- /dev/null +++ b/ui/packages/app-shell/src/layout/useDesignModeArrival.ts @@ -0,0 +1,43 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The app shell's reader of the arrival that enters the design mode + * (objectstack#36907, `designModeAddDashboardArrival`): a Studio dashboard + * list's 「New」 opens the app with it in the navigation state. + * + * Read once per history entry, where it lands. The entry is replaced without + * it before anything else happens, so Back or a reload enters nothing: the + * mode has no address, and a history entry is not one either. Then: + * + * - on a phone, nothing more: the mode is never on there, and Studio offers + * that 「New」 on no phone; + * - elsewhere the mode is asked to enter with the 「Add menu item」 picker + * opened on its dashboards (`enterOpening`). Where `enter` refuses (a + * dashboard's or a report's own editor holds the mode out, + * objectstack#36692), the arrival does nothing more, and the mode says why, + * as it does for its own menu door. + * + * @module + */ + +import * as React from 'react'; +import { useLocation, useNavigate } from 'react-router-dom'; +import type { DesignModeValue } from './designMode.js'; +import { readDesignModeAddDashboardArrival, withoutDesignModeAddDashboardArrival } from './designModeArrival.js'; + +export function useDesignModeArrival(mode: DesignModeValue, enabled: boolean): void { + const location = useLocation(); + const navigate = useNavigate(); + const arrival = readDesignModeAddDashboardArrival(location.state); + const readRef = React.useRef(null); + React.useEffect(() => { + if (!arrival || readRef.current === location.key) return; + readRef.current = location.key; + navigate(`${location.pathname}${location.search}${location.hash}`, { + replace: true, + state: withoutDesignModeAddDashboardArrival(location.state), + }); + if (enabled) mode.enterOpening({ column: 'dashboard', studioReturn: arrival.studioReturn }); + // eslint-disable-next-line react-hooks/exhaustive-deps -- read once per history entry; `arrival` is a fresh object each render + }, [location.key, !!arrival]); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.pairCreate-36897.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.pairCreate-36897.test.tsx index ab4d10aa2fa..64ae8cda5be 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.pairCreate-36897.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.pairCreate-36897.test.tsx @@ -12,6 +12,11 @@ * for this caller) nothing is offered. * - Setup (no area) is unchanged — the control: its 「新建」 goes to the * item page's create and opens no dialog. + * + * objectstack#36907 — a dashboard list's 「新建」 in the area opens an app's + * design mode, so it is offered only where an app opens (decision 6, the + * pair leg included), never on a phone; with no app the list says why. The + * report list's 「新建」 is the control: it reads no app. */ // Paid at collection, not inside a case's clock (check:test-source-alias). @@ -19,21 +24,34 @@ import '@objectstack/lint'; import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; import '@objectstack/spec/identity'; import { MetadataAreaHostContext, type MetadataAreaHost } from './metadataAreaHost'; const BASE = 'hotcrm'; +/** objectstack#36907 — the published apps per package (unset: one app), and the app reads asked. */ +const APPS = { byPackage: new Map(), reads: [] as string[] }; const CLIENT = { - list: async (type: string) => - type === 'package' + list: async (type: string, options?: { packageId?: string }) => { + if (type === 'app') { + APPS.reads.push(options?.packageId ?? ''); + return APPS.byPackage.get(options?.packageId ?? '') ?? [{ name: 'crm_app_one', label: 'One app' }]; + } + return type === 'package' ? [{ manifest: { id: BASE, name: 'HotCRM', scope: 'installed' } }] - : [{ name: `crm_${type}_one`, label: `One ${type}`, _packageId: BASE }], + : [{ name: `crm_${type}_one`, label: `One ${type}`, _packageId: BASE }]; + }, }; const entry = (type: string, domain: string) => ({ type, label: type, domain, allowEnvironmentOverlay: false, allowRuntimeCreate: true }); -const ENTRIES = [entry('object', 'data'), entry('flow', 'automation'), entry('email_template', 'system')]; +const ENTRIES = [ + entry('object', 'data'), + entry('flow', 'automation'), + entry('email_template', 'system'), + entry('dashboard', 'ui'), + entry('report', 'ui'), +]; vi.mock('./useMetadata', async (importOriginal) => ({ ...(await importOriginal>()), @@ -74,13 +92,17 @@ const fetchMock = vi.fn(async (url: string) => { return json(404, { success: false }); }); +const DESKTOP_WIDTH = window.innerWidth; beforeEach(() => { fetchMock.mockClear(); vi.stubGlobal('fetch', fetchMock); + APPS.byPackage = new Map(); + APPS.reads = []; }); afterEach(() => { cleanup(); vi.unstubAllGlobals(); + Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: DESKTOP_WIDTH }); }); const READ_ONLY_BASE: MetadataAreaHost = { packageId: BASE, readOnly: true, basePath: `/studio/${BASE}/metadata`, pairCreate: true }; @@ -144,3 +166,79 @@ describe('the list offers 「新建」 on a read-only base, into its pair (objec expect(screen.queryByTestId('create-object-owd')).toBeNull(); }); }); + +describe("a dashboard list's 「新建」 in the area opens an app's design mode (objectstack#36907)", () => { + const WRITABLE: MetadataAreaHost = { packageId: BASE, readOnly: false, basePath: `/studio/${BASE}/metadata` }; + const PAIR = `${BASE}.custom`; + const reason = () => screen.queryByTestId('metadata-list-create-unavailable'); + // The header's 新建 (an empty list draws a second one in its empty state). + const newButton = () => screen.queryByTestId('metadata-list-create'); + + it("offered where an app opens: it goes to the area's create, which opens the app's design mode", async () => { + mount(WRITABLE, 'dashboard'); + await screen.findByTestId('metadata-row-crm_dashboard_one'); + await waitFor(() => expect(newButton()).not.toBeNull()); + expect(reason()).toBeNull(); + expect(APPS.reads).toEqual([BASE]); + fireEvent.click(newButton()!); + await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent(`/studio/${BASE}/metadata/dashboard/new?package=${BASE}`)); + }); + + it('with no app to open, no 新建, and the list says why', async () => { + APPS.byPackage.set(BASE, []); + mount(WRITABLE, 'dashboard'); + await screen.findByTestId('metadata-row-crm_dashboard_one'); + expect(await screen.findByTestId('metadata-list-create-unavailable')).toHaveTextContent( + t('engine.list.dashboardNewNoApp', 'en-US'), + ); + expect(newButton()).toBeNull(); + }); + + it('on a phone, no 新建 and no app read: the design mode is never on there', async () => { + Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 390 }); + mount(WRITABLE, 'dashboard'); + // A phone draws the list as cards: wait for the list's reads to settle. + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 50)); + }); + expect(screen.getByTestId('location')).toHaveTextContent(`/studio/${BASE}/metadata/dashboard?package=${BASE}`); + expect(newButton()).toBeNull(); + expect(reason()).toBeNull(); + expect(APPS.reads).toEqual([]); + }); + + it("a read-only base: offered by its own app; behind the customization wall nothing is offered, and no app is read", async () => { + mount(READ_ONLY_BASE, 'dashboard'); + await screen.findByTestId('metadata-row-crm_dashboard_one'); + await waitFor(() => expect(newButton()).not.toBeNull()); + cleanup(); + APPS.reads = []; + mount(NO_PAIR_CREATE, 'dashboard'); + await screen.findByTestId('metadata-row-crm_dashboard_one'); + expect(newButton()).toBeNull(); + expect(reason()).toBeNull(); + expect(APPS.reads).toEqual([]); + }); + + it("the pair leg: a pair publishing no app is offered by its base's app, one read more", async () => { + APPS.byPackage.set(PAIR, []); + mount({ packageId: PAIR, readOnly: false, basePath: `/studio/${PAIR}/metadata` }, 'dashboard'); + await waitFor(() => expect(newButton()).not.toBeNull()); + expect(APPS.reads).toEqual([PAIR, BASE]); + cleanup(); + APPS.reads = []; + APPS.byPackage.set(BASE, []); + mount({ packageId: PAIR, readOnly: false, basePath: `/studio/${PAIR}/metadata` }, 'dashboard'); + expect(await screen.findByTestId('metadata-list-create-unavailable')).toBeInTheDocument(); + expect(newButton()).toBeNull(); + }); + + it('CONTROL — the report list: 新建 offered with no app, and no app read', async () => { + APPS.byPackage.set(BASE, []); + mount(WRITABLE, 'report'); + await screen.findByTestId('metadata-row-crm_report_one'); + expect(newButton()).not.toBeNull(); + expect(reason()).toBeNull(); + expect(APPS.reads).toEqual([]); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx index 16a49bb3885..8ce9ce9f01b 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx @@ -103,6 +103,7 @@ import { SharingRuleCloneDialog, type SharingRuleCloneDialogProps } from './Shar import { PermissionSetCloneDialog } from './PermissionSetCloneDialog.js'; import { permissionSetCloneNoticeText } from './permission-set-clone.js'; import { newSimilarOutcome } from '../studio-design/permissionNewSimilar.js'; +import { useStudioDashboardNew } from '../studio-design/StudioAreaAppOpen.js'; import { postureHasOrgWall, useTenancyPosture } from '../../hooks/useTenancyPosture.js'; import { applyListState, @@ -823,8 +824,16 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string const typeWritable = !!(entry?.allowEnvironmentOverlay || entry?.allowRuntimeCreate); // A declaration-only catalog is never authored here: its items are created // on the authored object's page. - const canCreate = + const canCreateHere = typeWritable && !walled && (!envScope || canAuthor) && !authoredObject && (!host?.readOnly || createInPair); + // objectstack#36907 — in the Studio area a dashboard's New opens an app's + // design mode (its 「Add menu item」 picker, so the dashboard hangs in a + // menu): offered only where an app opens, never on a phone, and with no app + // the list says why instead. + const dashboardNew = useStudioDashboardNew( + canCreateHere && type === 'dashboard' && host?.packageId ? host.packageId : null, + ); + const canCreate = canCreateHere && (dashboardNew === 'off' || dashboardNew === 'offered'); // The wall is the gate to NAME only where the type would otherwise admit a // write: a type with no runtime write channel is read-only for the operator // too, and its page says nothing about the wall. @@ -849,7 +858,7 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string `${routeLocation.pathname}?${search}`, !loading && filtered.length > 0, ); - const createButton = canCreate && ( + const createButton = (canCreate && ( - ); + )) || (dashboardNew === 'no-app' && ( + + {t('engine.list.dashboardNewNoApp', locale)} + + )); // Declarative type-level actions (GAP-1) scoped to the list toolbar. // Per-row (`list_item`) actions are not surfaced here yet — they need the // row's recordId from the grid. @@ -1463,7 +1476,9 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string config.emptyStateHint ?? (canCreate ? tFormat('engine.list.createHint', locale, { type: typeLabel }) - : t('engine.list.readOnlyHint', locale))} + : dashboardNew === 'no-app' + ? t('engine.list.dashboardNewNoApp', locale) + : t('engine.list.readOnlyHint', locale))} {scopedItems.length === 0 && canCreate && (
diff --git a/ui/packages/app-shell/src/views/studio-design/StudioAreaAppOpen-36906.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioAreaAppOpen-36906.test.tsx index 2575181b2b0..d3cc5e102d1 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioAreaAppOpen-36906.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioAreaAppOpen-36906.test.tsx @@ -4,6 +4,8 @@ * objectstack#36906 — a dashboard or a report opened from a Studio list opens * in its app's edit state; the report list's New opens the app's new-report * page; with no app, the generic item page (or the area's own create). + * objectstack#36907 — the dashboard list's New opens the app in its design + * mode, the 「Add menu item」 picker on its dashboards. * * Through the real `StudioMetadataArea` and its routes, with the metadata * pages stubbed to their names and the metadata client answering the @@ -14,11 +16,15 @@ * - the Studio address is replaced, so Back from the app page skips it; * - which opens keep the generic item page (a tab, the draft review, no app, * the cross-package leg, any other type, an item with no published version); - * - a read-only base: its own rows open in its app, a pair row keeps the - * generic page, and its report New opens the app page only where the pair - * door is open; - * - a dashboard made by the area's own create opens in its app, and Back - * from there lands on the list, not on an empty create page. + * - a read-only base: its own rows open in its app, a pair row opens in the + * base's app (objectstack#37237: the pair publishes no app of its own), + * and its report New opens the app page only where the pair door is open; + * - a dashboard made by the area's own create (on a phone, where the + * dashboard New has no design mode to open) opens in its app, and Back + * from there lands on the list, not on an empty create page; + * - the dashboard New (objectstack#36907): the app's root with the arrival + * that enters the design mode, decision 6 and the pair leg picking the + * app; no app or a phone, the area's own create; the report New unchanged. */ import '@testing-library/jest-dom/vitest'; @@ -118,8 +124,13 @@ beforeEach(() => { afterEach(() => { cleanup(); resetAppReturnPageForTests(); + Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: DESKTOP_WIDTH }); }); +/** jsdom's window width, a desktop's; a phone is under 768 px (`usePhoneViewport`). */ +const DESKTOP_WIDTH = window.innerWidth; +const phoneWidth = () => Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 390 }); + /** The app page the area hands over to: its address, its landing and how it was reached; and the browser's Back. */ function AppPage() { const { pathname, search, state } = useLocation(); @@ -244,14 +255,10 @@ describe("the report list's New opens the app's new-report page (objectstack#369 expect(studioOf(opened.at)).toBe(`/studio/${PKG}/metadata/report?package=${PKG}`); }); - it('with no app to open, the area creates as before; a dashboard New is not this card', async () => { + it('with no app to open, the area creates as before', async () => { apps.byPackage.set(PKG, []); mount(`/studio/${PKG}/metadata/report/new?package=${PKG}`); expect((await screen.findByTestId('area-page')).getAttribute('data-page')).toBe('create'); - cleanup(); - apps.byPackage.set(PKG, [{ name: 'crm_app' }]); - mount(`/studio/${PKG}/metadata/dashboard/new?package=${PKG}`); - expect((await screen.findByTestId('area-page')).getAttribute('data-page')).toBe('create'); }); }); @@ -274,7 +281,9 @@ describe('an item with no published version keeps the generic item page (objects expect(screen.queryByTestId('app-page')).toBeNull(); }); - it("a dashboard made by the area's create opens in its app, and Back from there lands on the list", async () => { + it("a dashboard made by the area's create (a phone's) opens in its app, and Back from there lands on the list", async () => { + // objectstack#36907 — elsewhere a dashboard's New opens the app's design mode. + phoneWidth(); const list = `/studio/${PKG}/metadata/dashboard?package=${PKG}`; mount(`/studio/${PKG}/metadata/dashboard/new?package=${PKG}`, [list]); fireEvent.click(await screen.findByText('save the new item')); @@ -416,3 +425,110 @@ describe("a customization pair's dashboard or report opens in its base's app (ob expect(apps.listCalls).toEqual([['app', { packageId: PAIR }]]); }); }); + +describe("the dashboard list's New opens the app's design mode on its dashboards (objectstack#36907)", () => { + const LIST = `/studio/${PKG}/metadata/dashboard?package=${PKG}`; + const entersDesignMode = (studioReturn: string) => ({ designModeAddDashboard: { studioReturn } }); + + it("opens the app's root with the arrival that enters the mode; the address carries no mode, and Back lands on the list", async () => { + mount(`/studio/${PKG}/metadata/dashboard/new?package=${PKG}&q=ops`, [LIST]); + const opened = await appPage(); + // One app in the package: its address is the package id (ADR-0048 option A). + expect(opened.at).toBe(`/apps/${PKG}`); + expect(opened.state).toEqual(entersDesignMode(`${LIST}&q=ops`)); + expect(opened.how).toBe('REPLACE'); + expect(apps.listCalls).toEqual([['app', { packageId: PKG }]]); + expect(itemReads.calls).toEqual([]); + fireEvent.click(screen.getByText('back')); + expect((await screen.findByTestId('area-page')).getAttribute('data-page')).toBe('list'); + }); + + it('the app is picked by decision 6: the remembered app among the package apps, else the first', async () => { + apps.byPackage.set(PKG, [{ name: 'sales' }, { name: 'service' }]); + rememberAppReturnPage({ path: '/apps/service/home', app: 'service', label: 'Service' }); + mount(`/studio/${PKG}/metadata/dashboard/new?package=${PKG}`); + expect((await appPage()).at).toBe('/apps/service'); + cleanup(); + resetAppReturnPageForTests(); + mount(`/studio/${PKG}/metadata/dashboard/new?package=${PKG}`); + expect((await appPage()).at).toBe('/apps/sales'); + }); + + it("with no app to open, the area's own create; on a phone too, with no app read", async () => { + apps.byPackage.set(PKG, []); + mount(`/studio/${PKG}/metadata/dashboard/new?package=${PKG}`); + expect((await screen.findByTestId('area-page')).getAttribute('data-page')).toBe('create'); + expect(screen.queryByTestId('app-page')).toBeNull(); + cleanup(); + apps.byPackage.set(PKG, [{ name: 'crm_app' }]); + apps.listCalls = []; + phoneWidth(); + mount(`/studio/${PKG}/metadata/dashboard/new?package=${PKG}`); + expect((await screen.findByTestId('area-page')).getAttribute('data-page')).toBe('create'); + expect(apps.listCalls).toEqual([]); + }); + + describe('a read-only base and its pair', () => { + const BASE = 'com.example.hr'; + const PAIR = `${BASE}.custom`; + const customizationOf = (walled: boolean) => + ({ base: BASE, baseLabel: 'HR', basedOn: null, walled, pairId: null, ensure: async () => PAIR, ensurePackage: vi.fn() }) as any; + + beforeEach(() => { + listed.value.set(BASE, { id: BASE, name: 'HR', writable: false, manifest: {} }); + listed.value.set(PAIR, { id: PAIR, name: 'HR (customizations)', writable: true, manifest: {} }); + apps.byPackage.set(BASE, [{ name: 'hr_app', label: 'HR' }]); + }); + + function mountBase(url: string, customization: unknown) { + return render( + + + } /> + } /> + + , + ); + } + + it("a base's New opens the base's app (what the mode saves goes to the pair); walled, it goes back to the list", async () => { + mountBase(`/studio/${BASE}/metadata/dashboard/new?package=${BASE}`, customizationOf(false)); + const opened = await appPage(); + expect(opened.at).toBe(`/apps/${BASE}`); + expect(opened.state).toEqual(entersDesignMode(`/studio/${BASE}/metadata/dashboard?package=${BASE}`)); + cleanup(); + apps.listCalls = []; + mountBase(`/studio/${BASE}/metadata/dashboard/new?package=${BASE}`, customizationOf(true)); + expect((await screen.findByTestId('area-page')).getAttribute('data-page')).toBe('list'); + expect(apps.listCalls).toEqual([]); + }); + + it("the pair leg: a pair's New, the pair publishing no app, opens its base's app, one read more", async () => { + mount(`/studio/${PAIR}/metadata/dashboard/new?package=${PAIR}`); + const opened = await appPage(); + expect(opened.at).toBe(`/apps/${BASE}`); + expect(opened.state).toEqual(entersDesignMode(`/studio/${PAIR}/metadata/dashboard?package=${PAIR}`)); + expect(apps.listCalls).toEqual([ + ['app', { packageId: PAIR }], + ['app', { packageId: BASE }], + ]); + }); + + it("the pair leg picks among the base's apps by decision 6; a base with no app, the area's own create", async () => { + apps.byPackage.set(BASE, [{ name: 'hr_people' }, { name: 'hr_reports' }]); + rememberAppReturnPage({ path: '/apps/hr_reports/home', app: 'hr_reports', label: 'HR Reports' }); + mount(`/studio/${PAIR}/metadata/dashboard/new?package=${PAIR}`); + expect((await appPage()).at).toBe('/apps/hr_reports'); + cleanup(); + apps.byPackage.set(BASE, []); + mount(`/studio/${PAIR}/metadata/dashboard/new?package=${PAIR}`); + expect((await screen.findByTestId('area-page')).getAttribute('data-page')).toBe('create'); + }); + + it("CONTROL — a pair's report New keeps the area's own create: the pair leg is the dashboard New's alone", async () => { + mount(`/studio/${PAIR}/metadata/report/new?package=${PAIR}`); + expect((await screen.findByTestId('area-page')).getAttribute('data-page')).toBe('create'); + expect(apps.listCalls).toEqual([['app', { packageId: PAIR }]]); + }); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioAreaAppOpen.tsx b/ui/packages/app-shell/src/views/studio-design/StudioAreaAppOpen.tsx index e440f262c51..6e6aef9a2fe 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioAreaAppOpen.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioAreaAppOpen.tsx @@ -2,9 +2,12 @@ /** * A dashboard or a report opened from a Studio list opens in the app's own - * edit state (objectstack#36906, epic #36890), and a report's New opens the - * app's new-report page (decision 13). This component is the one step between - * the two places: + * edit state (objectstack#36906, epic #36890), a report's New opens the + * app's new-report page (decision 13), and a dashboard's New opens the app in + * its design mode, the 「Add menu item」 picker open on its dashboards + * (objectstack#36907, the maintainer's 「新建跳到设计模式加菜单」: a dashboard + * is made where it hangs in a menu, objectstack#36359). This component is the + * one step between the two places: * * 1. It reads the open package's published apps and, when the author came * from an app outside the package, that app's menu. A dashboard or a @@ -12,16 +15,26 @@ * of its own reads its base's apps instead, one read more: the pair has * no surface of its own (ADR-0146 D3), and the base's app is the one that * shows the pair's items. - * 2. It picks the app (decision 6, `studioAppEditSegment`), by the same rule - * over the base's apps on the pair leg. + * A dashboard's New of such a pair takes the same leg; a report's New + * does not (it keeps the area's own create there). + * 2. It picks the app (decision 6, `studioAppEditSegment`; for a New, + * `studioAppCreateSegment`), by the same rule over the base's apps on the + * pair leg. * 3. It replaces the Studio address with the app's. A dashboard or a report * carries its arrival in the navigation state, so the page opens the * dashboard's edit state or the report's builder as its Edit does, and * the address carries the Studio list (`?studio=`, decision 15), so the - * page's × goes back to the list, after a reload too. + * page's × goes back to the list, after a reload too. A dashboard's New + * opens the app's root with the arrival that enters the design mode + * (`designModeAddDashboardArrival`), which carries the list instead: the + * dashboard created there opens with it in its address + * (`DesignModeMenu`). The mode has no address, so neither has the list + * before then. * * With no app to open in, it renders `fallback`: the generic item page, or - * the area's own create (decision 3). So does an item with no published + * the area's own create (decision 3). So does a dashboard's New on a phone, + * where the design mode is never on; the list offers no such New there, nor + * with no app ({@link useStudioDashboardNew}). So does an item with no published * version (a draft only, such as an AI draft or a create whose publish was * refused): the app page reads the published world, so it would answer * 「not found」, and the generic item page is the one that opens the draft. @@ -36,8 +49,9 @@ import * as React from 'react'; import { Navigate, useLocation } from 'react-router-dom'; -import { readAppReturnPage } from '../../utils/appReturnPage.js'; -import { dashboardEditArrival } from '../../layout/designModeArrival.js'; +import { readAppReturnPage, type AppReturnPage } from '../../utils/appReturnPage.js'; +import { usePhoneViewport } from '../../hooks/usePhoneViewport.js'; +import { dashboardEditArrival, designModeAddDashboardArrival } from '../../layout/designModeArrival.js'; import { reportBuilderArrival } from '../reportBuilderArrival.js'; import { useMetadataClient } from '../metadata-admin/useMetadata.js'; import { ITEM_ONLY_PARAMS, detailListHref } from '../metadata-admin/ResourceDetailHeader.js'; @@ -46,6 +60,7 @@ import { t, useMetadataLocale } from '../metadata-admin/i18n.js'; import { withStudioReturn } from './studioAddress.js'; import { customizationPairBaseOf } from './StudioRailCustomizations.js'; import { + appHomePath, appItemPath, appNewReportPath, isStudioAppEditType, @@ -56,10 +71,93 @@ import { type StudioAppTarget, } from './studioAppEdit.js'; -/** What opens in the app: an item's page, or the new-report page. */ -export type StudioAreaAppTarget = { kind: 'item'; type: StudioAppEditType; name: string } | { kind: 'new-report' }; +/** + * What opens in the app: an item's page, the new-report page, or the app in + * its design mode with the 「Add menu item」 picker on its dashboards. + */ +export type StudioAreaAppTarget = + | { kind: 'item'; type: StudioAppEditType; name: string } + | { kind: 'new-report' } + | { kind: 'new-dashboard' }; + +type Answer = { to: string; state: Record | null } | 'fallback'; + +type MetadataClientLike = ReturnType; + +/** + * The published apps that an item, or a New, of `packageId` opens in, and + * the package they are of: the package's own, or, on the pair leg + * (`pairLeg`), for a customization pair (`.custom`) with no published + * app of its own, its base's, one read more. A failed read is no app. + */ +export async function readStudioTargetApps( + client: MetadataClientLike, + packageId: string, + pairLeg: boolean, + cancelled: () => boolean = () => false, +): Promise<{ appPackageId: string; apps: StudioAppTarget[] }> { + const readApps = async (scope: string): Promise => { + try { + const listed = (await client.list('app', { packageId: scope })) as Array>; + return (listed || []) + .filter((a) => typeof a?.name === 'string' && a.name) + .map((a) => ({ name: String(a.name), label: (a.label ?? a.name) as StudioAppTarget['label'] })); + } catch { + return []; + } + }; + const apps = await readApps(packageId); + const pairBase = pairLeg && apps.length === 0 ? customizationPairBaseOf(packageId) : null; + if (pairBase === null || cancelled()) return { appPackageId: packageId, apps }; + return { appPackageId: pairBase, apps: await readApps(pairBase) }; +} -type Answer = { to: string; state: Record | null } | 'fallback'; +/** The app segment a dashboard's New opens in (decision 6, the pair leg too), or `null`. */ +async function readNewDashboardSegment( + client: MetadataClientLike, + packageId: string, + remembered: AppReturnPage | null, + cancelled: () => boolean = () => false, +): Promise { + const { appPackageId, apps } = await readStudioTargetApps(client, packageId, true, cancelled); + return studioAppCreateSegment({ packageId: appPackageId, apps, remembered }); +} + +/** + * Whether a Studio dashboard list offers its 「New」 (objectstack#36907): the + * New opens an app's design mode, so it is offered only where one opens. + * + * - `'off'`: not asked (`packageId` is `null`: not a dashboard list of a + * package, or one that offers no create at all); + * - `'pending'`: the package's apps are being read; no New yet; + * - `'phone'`: a phone, where the design mode is never on; no New; + * - `'no-app'`: no app to open (decision 6 picks none, the pair leg + * included); no New, and the list says why; + * - `'offered'`: the New is offered, and opens the app `StudioAreaAppOpen` + * picks by the same reads. + */ +export type StudioDashboardNew = 'off' | 'pending' | 'phone' | 'no-app' | 'offered'; + +export function useStudioDashboardNew(packageId: string | null): StudioDashboardNew { + const client = useMetadataClient(); + const phone = usePhoneViewport(); + const [read, setRead] = React.useState<{ packageId: string; segment: string | null } | null>(null); + const asked = packageId !== null && !phone; + React.useEffect(() => { + if (!asked || packageId === null) return undefined; + let cancelled = false; + void readNewDashboardSegment(client, packageId, readAppReturnPage(), () => cancelled).then((segment) => { + if (!cancelled) setRead({ packageId, segment }); + }); + return () => { + cancelled = true; + }; + }, [asked, packageId, client]); + if (packageId === null) return 'off'; + if (phone) return 'phone'; + if (!read || read.packageId !== packageId) return 'pending'; + return read.segment ? 'offered' : 'no-app'; +} export function StudioAreaAppOpen({ packageId, @@ -74,6 +172,7 @@ export function StudioAreaAppOpen({ }): React.ReactElement { const client = useMetadataClient(); const locale = useMetadataLocale(); + const phone = usePhoneViewport(); const { pathname, search } = useLocation(); // Read once per open, as the back link reads it: nothing in Studio is an app page. const [remembered] = React.useState(readAppReturnPage); @@ -85,6 +184,24 @@ export function StudioAreaAppOpen({ let cancelled = false; const type: StudioAppEditType = target.kind === 'item' ? target.type : 'report'; const name = target.kind === 'item' ? target.name : ''; + const opened = openedAt.current; + const list = detailListHref(opened.pathname, new URLSearchParams(opened.search)); + // objectstack#36907 — a dashboard's New: the app's root, with the + // design mode entered and its picker open on its dashboards. Never on a + // phone, where the mode is never on. + if (target.kind === 'new-dashboard') { + if (phone) { + setAnswer('fallback'); + return undefined; + } + void readNewDashboardSegment(client, packageId, remembered, () => cancelled).then((segment) => { + if (cancelled) return; + setAnswer(segment ? { to: appHomePath(segment), state: designModeAddDashboardArrival(list) } : 'fallback'); + }); + return () => { + cancelled = true; + }; + } void (async () => { // An item the app cannot show (no published version, or the read // failed) keeps the generic item page. @@ -101,26 +218,9 @@ export function StudioAreaAppOpen({ return; } } - const readApps = async (scope: string): Promise => { - try { - const listed = (await client.list('app', { packageId: scope })) as Array>; - return (listed || []) - .filter((a) => typeof a?.name === 'string' && a.name) - .map((a) => ({ name: String(a.name), label: (a.label ?? a.name) as StudioAppTarget['label'] })); - } catch { - return []; - } - }; // The package whose apps the item opens in: the open package, or, for // an item of a pair with no app of its own, the pair's base. - let appPackageId = packageId; - let apps = await readApps(packageId); - const pairBase = target.kind === 'item' && apps.length === 0 ? customizationPairBaseOf(packageId) : null; - if (pairBase !== null) { - if (cancelled) return; - appPackageId = pairBase; - apps = await readApps(pairBase); - } + const { appPackageId, apps } = await readStudioTargetApps(client, packageId, target.kind === 'item', () => cancelled); // The remembered app's own menu counts only for an item, and only when // the app is not one of the package's: the package's own apps win first. let rememberedMenu: unknown; @@ -141,8 +241,6 @@ export function StudioAreaAppOpen({ setAnswer('fallback'); return; } - const opened = openedAt.current; - const list = detailListHref(opened.pathname, new URLSearchParams(opened.search)); if (target.kind === 'item') { setAnswer({ to: withStudioReturn(appItemPath(segment, type, name), list), diff --git a/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx b/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx index 997eb4d8106..7205f34fe4a 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx @@ -323,6 +323,17 @@ function AreaCreate({ customization }: { customization: StudioBaseCustomization } /> ); } + // objectstack#36907 — a dashboard is made in its app's design mode, in the + // 「Add menu item」 picker, so it hangs in a menu (objectstack#36359): the + // app opens with the mode entered and the picker on its dashboards. What + // the mode saves goes to the package, or a read-only base's pair. With no + // app to open, or on a phone, the area's own create, as for a report; the + // list offers no New in either case (`useStudioDashboardNew`). + if (type === 'dashboard' && host?.packageId && (!host.readOnly || host.pairCreate)) { + return ( + } /> + ); + } return ; } diff --git a/ui/packages/app-shell/src/views/studio-design/studioAppEdit.ts b/ui/packages/app-shell/src/views/studio-design/studioAppEdit.ts index dabc1008cb5..b682c36a12d 100644 --- a/ui/packages/app-shell/src/views/studio-design/studioAppEdit.ts +++ b/ui/packages/app-shell/src/views/studio-design/studioAppEdit.ts @@ -110,8 +110,9 @@ export function studioAppEditSegment({ } /** - * The app segment that a new report opens in (decision 13), or `null` when - * there is none. A new report has no menu entry yet, so this is + * The app segment that a new report opens in (decision 13), or a new + * dashboard (objectstack#36907, in the app's design mode), or `null` when + * there is none. A new item has no menu entry yet, so this is * {@link studioAppEditSegment} without the menu half of rule 1. */ export function studioAppCreateSegment({ @@ -143,6 +144,15 @@ export function appItemPath(segment: string, type: StudioAppEditType, name: stri return `/apps/${encodeURIComponent(segment)}/${type}/${encodeURIComponent(name)}`; } +/** + * The app's root, `/apps/`, where a new dashboard is made + * (objectstack#36907): the app opens its landing, with the design mode + * entered by the arrival the address never carries (`designModeAddDashboardArrival`). + */ +export function appHomePath(segment: string): string { + return `/apps/${encodeURIComponent(segment)}`; +} + /** The app's new-report page, `/apps//reports/new` (decision 13). */ export function appNewReportPath(segment: string): string { return `/apps/${encodeURIComponent(segment)}/reports/new`; diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 1b5e9a52bf8..1e33237a83d 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -4087,6 +4087,9 @@ const STUDIO_EN: Record = { 'engine.list.emptyType': 'No {type} items registered', 'engine.list.emptyQuery': 'No matches for "{query}"', 'engine.list.createHint': 'Click "New" above to create the first {type}.', + // objectstack#36907 — a Studio dashboard list's New opens an app's design mode. + 'engine.list.dashboardNewNoApp': + 'A new dashboard is made in an app\'s design mode, so that it hangs in a menu. This package has no app to make it in.', 'engine.list.readOnlyHint': 'This type is read-only — instances are defined by code artifacts in packages.', // objectui#7611 — the environment scope (Setup catalog). See `catalog-scope.ts`. diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index ca132b30608..ff28c738b27 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -3623,6 +3623,8 @@ const STUDIO_ZH: Record = { 'engine.list.emptyType': '暂无 {type} 条目', 'engine.list.emptyQuery': '没有匹配 "{query}" 的结果', 'engine.list.createHint': '点击上方"新建"创建第一个 {type}。', + // objectstack#36907 — a Studio dashboard list's New opens an app's design mode. + 'engine.list.dashboardNewNoApp': '新仪表盘在应用的设计模式中创建,这样它会挂在菜单上。这个包没有可以创建它的应用。', 'engine.list.readOnlyHint': '此类型为只读 — 实例由包内的代码工件定义。', 'engine.catalog.col.active': '启用', 'engine.catalog.status.all': '全部',