From c143cac1ecd47da715f8cd87281a23daac8eca36 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 01:03:10 +0000 Subject: [PATCH 1/9] fix(console): design mode menu save refuses a 404 read, pins its publish, and keeps own entries out of contributed groups WIP: implementation of objectstack#36538 items 1-4 and N10, N12-N16; tests follow. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzhpykmQZe1yMupC2CU --- .../app-shell/src/layout/DesignModeMenu.tsx | 124 +++++++++++++++--- .../src/layout/designModeMenuModel.ts | 74 +++++++++-- .../src/layout/designModeMenuSave.ts | 88 +++++++++++-- ui/packages/i18n/src/locales/en.ts | 3 + ui/packages/i18n/src/locales/zh-Hans.ts | 3 + 5 files changed, 257 insertions(+), 35 deletions(-) diff --git a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx index 42bcf898dd3..4dd5e61ac6a 100644 --- a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx +++ b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx @@ -15,7 +15,11 @@ * to a group, add an item before or after it, rename and icon, remove from * the menu. Removing takes the entry off the menu only; what it opened is * kept, and the picker offers it again. - * - An entry can be dragged to another place, in its group or another one. + * - An entry can be dragged to another place, in its group or another one, + * or moved from the keyboard: Space picks it up, the arrows move it, Space + * or Enter drops it and Escape puts it back. Enter on an entry not picked up + * opens its page (objectstack#36538, review N13). A drop outside the menu + * moves nothing (review N14). * * A name is changed only in the app's source language (objectstack#36363, * ruling (4)): the stored labels are the app's own, and a translation is @@ -31,6 +35,10 @@ * 「⋮」 says it is changed in that package, and it is not dragged. Adding an * item before or after it stays open; no other entry is moved past it (a * move up, a move down or a drop onto it), since its place is that package's. + * A group another package puts into the menu takes no own entry: it is not + * offered by 「Move to group」, is no drop target, and has no 「Add menu item」 + * (objectstack#36538, review N9), since the save could put such an entry + * nowhere but the end of the stored menu. * * In the picker's 「Dashboards」, the first row is 「New dashboard…」 * (objectstack#36364): it asks for a name, and on 「Create」 the dashboard is @@ -64,13 +72,17 @@ import { Link, useLocation, useNavigate } from 'react-router-dom'; import { toast } from 'sonner'; import { DndContext, + KeyboardCode, KeyboardSensor, PointerSensor, closestCenter, useDroppable, useSensor, useSensors, + type CollisionDetection, type DragEndEvent, + type DragStartEvent, + type KeyboardCodes, } from '@dnd-kit/core'; import { SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable'; import { CSS } from '@dnd-kit/utilities'; @@ -151,6 +163,7 @@ import { storedEntriesById, targetKeyFor, withEntryIds, + withOwnBeforeForeignRuns, type Menu, type MenuEntry, type MenuTargetKind, @@ -192,6 +205,32 @@ const parentOfEndZone = (id: string): string | null | undefined => { return rest === '' ? null : rest; }; +/** + * The keys of a keyboard move (objectstack#36538, review N13): Space picks an + * entry up, so Enter on an entry still opens its page, as on any link; Space + * or Enter drops it, Escape puts it back. + */ +export const MENU_KEYBOARD_CODES: KeyboardCodes = { + start: [KeyboardCode.Space], + cancel: [KeyboardCode.Esc], + end: [KeyboardCode.Space, KeyboardCode.Enter], +}; + +/** + * The editor's collision rule (objectstack#36538, review N14): a pointer + * released outside the box `area()` answers (the menu's own) is over nothing, + * so the drop moves nothing; inside it, and for a keyboard move (which has + * no pointer), the nearest entry's centre, as before. + */ +export function menuCollision(area: () => DOMRect | null | undefined): CollisionDetection { + return (args) => { + const at = args.pointerCoordinates; + const box = at ? area() : null; + if (at && box && (at.x < box.left || at.x > box.right || at.y < box.top || at.y > box.bottom)) return []; + return closestCenter(args); + }; +} + export interface DesignModeMenuProps { /** The app on screen: its name, its served `navigation` and its package. */ readonly app: { readonly name: string; readonly navigation?: unknown; readonly _packageId?: unknown }; @@ -211,7 +250,7 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso () => withEntryIds(inShownOrder(Array.isArray(app.navigation) ? (app.navigation as Menu) : [])), [app.navigation], ); - const menu = change.value ?? served; + const staged = change.value ?? served; const texts = React.useMemo( () => ({ @@ -227,6 +266,12 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso notWritable: t('designMode.menu.notWritable', { defaultValue: "This app's customization package cannot be written, so its menu cannot be saved.", }), + storedUnread: t('designMode.menu.storedUnread', { + defaultValue: "This app's saved menu could not be read, so nothing was saved.", + }), + publishedMoved: t('designMode.menu.publishedMoved', { + defaultValue: "Someone published this app's menu while you were saving, so nothing was saved. Save again to apply your changes over theirs.", + }), }), [t], ); @@ -260,6 +305,12 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso ); /** Whether the entry `id` is another package's (served, and not in the stored menu). */ const contributed = (id: string): boolean => !!storedById && !storedById.has(id) && !!entryOf(served, id); + // An own entry the editor put in or past another package's closing entries + // before the stored read told them apart is drawn where the save puts it: + // before them (objectstack#36538, review N10). + const menu = storedById ? withOwnBeforeForeignRuns(staged, served, contributed) : staged; + /** Whether the group `parentId` (the top level for `null`) is another package's: no own entry goes into it. */ + const foreignGroup = (parentId: string | null): boolean => parentId !== null && contributed(parentId); /** Whether the entry beside `id`, `by` places away in its group, is another package's. */ const besideContributed = (id: string, by: -1 | 1): boolean => { const place = placeOf(menu, id); @@ -293,8 +344,13 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso const sensors = useSensors( useSensor(PointerSensor, { activationConstraint: { distance: 5 } }), - useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }), + useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates, keyboardCodes: MENU_KEYBOARD_CODES }), ); + const menuArea = React.useRef(null); + const collision = React.useMemo(() => menuCollision(() => menuArea.current?.getBoundingClientRect()), []); + const keyboardHint = t('designMode.menu.keyboardHint', { + defaultValue: 'Drag an item to move it, or focus it and press Space, then the arrow keys. Enter opens it.', + }); const leafIds = React.useMemo(() => { const out: string[] = []; const walk = (entries: Menu) => { @@ -312,18 +368,33 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso // it is not a click, so it opens nothing. dnd-kit stops that click's // propagation in the document's capture phase but leaves its default (a full // navigation), so the default is cancelled before it, on the window. + // + // The window after a pointer drag starts at the RELEASE of the press that + // dragged, never at the drag's end: an Escape while the button is held ends + // the drag, and the release that follows, however late, is still no click + // (objectstack#36538, review N12). A keyboard move holds the links shut + // until it ends, whatever the pointer does meanwhile (review N16). const lastDragEnd = React.useRef(0); - const dragging = React.useRef(false); - const onDragStart = () => { - dragging.current = true; + /** A pointer press began a drag, and has not been released. */ + const pointerDrag = React.useRef(false); + /** A keyboard move is held. */ + const keyboardDrag = React.useRef(false); + /** A pointer button is down. */ + const pointerHeld = React.useRef(false); + const onDragStart = (event: DragStartEvent) => { + if (typeof KeyboardEvent !== 'undefined' && event.activatorEvent instanceof KeyboardEvent) keyboardDrag.current = true; + else pointerDrag.current = true; }; const endDrag = () => { - dragging.current = false; + keyboardDrag.current = false; + // Still held (an Escape mid-drag): the release stamps the window. + if (pointerHeld.current) return; + pointerDrag.current = false; lastDragEnd.current = Date.now(); }; React.useEffect(() => { const onClick = (event: MouseEvent) => { - const justDragged = dragging.current || Date.now() - lastDragEnd.current < 300; + const justDragged = keyboardDrag.current || pointerDrag.current || Date.now() - lastDragEnd.current < 300; if (justDragged && event.target instanceof Element && event.target.closest('[data-design-menu-link]')) event.preventDefault(); }; // The drag's end is stamped from the pointer itself too: dnd-kit reports a @@ -331,11 +402,13 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso // that would leave the flag set and every link of the editor shut. A new // press starts over. const onPress = () => { - dragging.current = false; + pointerHeld.current = true; + pointerDrag.current = false; }; const onRelease = () => { - if (!dragging.current) return; - dragging.current = false; + pointerHeld.current = false; + if (!pointerDrag.current) return; + pointerDrag.current = false; lastDragEnd.current = Date.now(); }; window.addEventListener('click', onClick, true); @@ -357,12 +430,12 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso if (!overId || overId === id) return; const endParent = parentOfEndZone(overId); if (endParent !== undefined) { - update(moveToOwnEnd(id, endParent)); + if (!foreignGroup(endParent)) update(moveToOwnEnd(id, endParent)); return; } const from = placeOf(menu, id); const to = placeOf(menu, overId); - if (!from || !to || contributed(overId)) return; + if (!from || !to || contributed(overId) || foreignGroup(to.parentId)) return; // `to.index` read after the entry leaves: below its old place in the same // group it lands after the entry dropped on, elsewhere before it. update(moveEntry(menu, id, to.parentId, to.index)); @@ -519,8 +592,9 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso canUp={canMoveBy(menu, id, -1) && !besideContributed(id, -1)} canDown={canMoveBy(menu, id, 1) && !besideContributed(id, 1)} groups={groups - .filter((g) => g.id !== place?.parentId) + .filter((g) => g.id !== place?.parentId && !contributed(g.id)) .map((g) => ({ id: g.id, label: labelOf(g.entry), depth: g.depth }))} + canAdd={!foreignGroup(place?.parentId ?? null)} atTopLevel={place?.parentId === null} onUp={() => update(moveBy(menu, id, -1))} onDown={() => update(moveBy(menu, id, 1))} @@ -560,6 +634,8 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso } }); if (addAt && addAt.parentId === parentId && addAt.index >= entries.length) rows.push(); + // Another package's group takes no own entry: no 「Add menu item」, no drop at its end. + if (foreignGroup(parentId)) return rows; rows.push( {t('designMode.menu.title', { defaultValue: 'Menu' })} +

+ {keyboardHint} +

- {renderEntries(menu, null, 0)} +
+ {renderEntries(menu, null, 0)} +
@@ -731,6 +816,7 @@ function EntryActions({ canUp, canDown, groups, + canAdd, atTopLevel, onUp, onDown, @@ -746,6 +832,8 @@ function EntryActions({ canUp: boolean; canDown: boolean; groups: Array<{ id: string; label: string; depth: number }>; + /** Whether an item may be added beside it: not in another package's group. */ + canAdd: boolean; atTopLevel: boolean; onUp: () => void; onDown: () => void; @@ -800,10 +888,10 @@ function EntryActions({ - + {t('designMode.menu.addBefore', { defaultValue: 'Add an item before' })} - + {t('designMode.menu.addAfter', { defaultValue: 'Add an item after' })} diff --git a/ui/packages/app-shell/src/layout/designModeMenuModel.ts b/ui/packages/app-shell/src/layout/designModeMenuModel.ts index b3f8791c807..c9d2d032e30 100644 --- a/ui/packages/app-shell/src/layout/designModeMenuModel.ts +++ b/ui/packages/app-shell/src/layout/designModeMenuModel.ts @@ -388,7 +388,11 @@ function locate(menu: Menu, keyOf: (entry: MenuEntry) => string | null): Map` of what the reader was * shown (`withEntryIds`), which a stored entry pruned from the reader can * already hold. A stored entry without an id is matched to an unmatched served - * entry by its group, type and target, in order. + * entry by its group, type and target, in order; an id-less entry is served + * with its stored keys (only an entry with an id is translated), so among + * such twins the one whose keys are its own is taken first ({@link servedAs}, + * objectstack#36538): a twin the reader was not shown (one with other + * `requiredPermissions`, say) never takes the shown one's key. */ interface StoredKeyer { (entry: MenuEntry): string | null; @@ -400,6 +404,19 @@ function sameThing(a: MenuEntry, b: MenuEntry): boolean { return a.type === b.type && targetKeyOf(a) === targetKeyOf(b); } +/** + * Whether the served entry `served` carries the own keys of the stored entry + * `stored`, its `id` (which the editor gives an entry without one) and its + * `children` (which the server prunes) left out (objectstack#36538). + */ +function servedAs(stored: MenuEntry, served: MenuEntry): boolean { + const { id: _a, ...a } = ownKeys(stored); + const { id: _b, ...b } = ownKeys(served); + const keys = new Set([...Object.keys(a), ...Object.keys(b)]); + for (const key of keys) if (JSON.stringify(a[key]) !== JSON.stringify(b[key])) return false; + return true; +} + function storedKeyer(served: Menu, stored: Menu): StoredKeyer { const servedAt = locate(served, idOf); const keys = new Map(); @@ -417,22 +434,26 @@ function storedKeyer(served: Menu, stored: Menu): StoredKeyer { }; byId(stored); const unclaimed = [...servedAt.entries()].filter(([id]) => !matched.has(id)); - const claim = (entry: MenuEntry, parentId: string | null): string | null => { - const at = unclaimed.findIndex(([, s]) => s.parentId === parentId && sameThing(s.entry, entry)); + const claim = (entry: MenuEntry, parentId: string | null, exact: boolean): string | null => { + const at = unclaimed.findIndex( + ([, s]) => s.parentId === parentId && sameThing(s.entry, entry) && (!exact || servedAs(entry, s.entry)), + ); if (at < 0) return null; const [[id]] = unclaimed.splice(at, 1); return id; }; // `undefined`: the group was never shown, so nothing in it can be claimed. + // Each level claims its twins carrying their own keys first, in order, and + // only then the rest, so a twin not shown never takes a shown one's key. const adopt = (entries: Menu, parentId: string | null | undefined) => { - for (const entry of entries) { - let key = keys.get(entry) ?? null; - if (!key && !idOf(entry) && parentId !== undefined) { - key = claim(entry, parentId); + for (const exact of [true, false]) { + for (const entry of entries) { + if (keys.has(entry) || idOf(entry) || parentId === undefined) continue; + const key = claim(entry, parentId, exact); if (key) keys.set(entry, key); } - if (isGroup(entry)) adopt(childrenOf(entry), key ?? undefined); } + for (const entry of entries) if (isGroup(entry)) adopt(childrenOf(entry), keys.get(entry) ?? undefined); }; adopt(stored, null); const keyOf = ((entry: MenuEntry) => keys.get(entry) ?? null) as StoredKeyer; @@ -495,6 +516,43 @@ function staysInOrder(served: Map, edited: Map return out; } +/** + * `menu` with each own entry that sits in or after the run of another + * package's entries closing its level in `served` put just before that run, + * at every depth (objectstack#36538, review N10). Those entries are appended + * when the app is served, so an own entry at or past them is stored, and + * served, before them; an entry the editor put there before it knew which + * entries are another package's is drawn where the save puts it. `foreign` + * tells another package's entry by its id. The answer is `menu` itself when + * no entry moves. + */ +export function withOwnBeforeForeignRuns(menu: Menu, served: Menu, foreign: (id: string) => boolean): Menu { + const isForeign = (entry: MenuEntry) => { + const id = idOf(entry); + return !!id && foreign(id); + }; + const walk = (entries: Menu, parentId: string | null): Menu => { + let next: Menu = entries.map((entry) => { + if (!isGroup(entry)) return entry; + const kids = childrenOf(entry); + const fixed = walk(kids, idOf(entry)); + return fixed === kids ? entry : { ...entry, children: fixed }; + }); + if (next.every((entry, i) => entry === entries[i])) next = entries; + const shown = siblingsAt(served, parentId) ?? []; + let start = shown.length; + while (start > 0 && isForeign(shown[start - 1])) start -= 1; + const run = new Set(shown.slice(start).map(idOf)); + const first = next.findIndex((entry) => run.has(idOf(entry))); + if (first < 0) return next; + const after = next.slice(first); + const own = after.filter((entry) => !isForeign(entry)); + if (own.length === 0) return next; + return [...next.slice(0, first), ...own, ...after.filter(isForeign)]; + }; + return walk(menu, null); +} + /** * The edits made to `served` (the tree the editor was seeded from, every * entry with an id) that turned it into `edited`, applied by entry id to diff --git a/ui/packages/app-shell/src/layout/designModeMenuSave.ts b/ui/packages/app-shell/src/layout/designModeMenuSave.ts index 9a9b8bc89fe..51b208b17eb 100644 --- a/ui/packages/app-shell/src/layout/designModeMenuSave.ts +++ b/ui/packages/app-shell/src/layout/designModeMenuSave.ts @@ -43,16 +43,29 @@ * wrote. A landed publish announces itself (`emitMetadataRefresh`), and the * console re-reads the app, its menu included. * + * The publish is pinned to the published row the save was composed from + * (objectstack#36538, the `/layers` read's `overlayVersion`, objectstack#36601): + * a publish somebody else lands between the read and this save's publish is + * refused `409`, the draft is discarded, and the bar says so, never written + * over. The pin is read at the address the publish writes (`publishPinAt`), + * before the body is read, so a publish in between pairs an old pin with a + * new body and is refused, the safe direction. + * + * A stored read that holds no app (the layered read answers a 404 as an + * empty view) refuses the save (objectstack#36538): nothing served is + * written, and the stored app's own keys are never dropped. + * * @module */ import { stripReadDecorations } from '@objectstack/spec/kernel'; import { emitMetadataRefresh } from '../assistant/assistantBus.js'; -import { isDraftVersionConflict } from '../views/metadata-admin/DraftConflictDialog.js'; +import { isDraftVersionConflict, publishedPinOf, type DraftPin } from '../views/metadata-admin/DraftConflictDialog.js'; import { overrideDraftBody } from '../views/studio-design/StudioCustomizeControls.js'; import { ensureCustomizationPackage, fetchListedPackageManifests, + listedCustomizationPairOf, listedPackageVersion, type EnsuredCustomizationPackage, type ListedPackageManifest, @@ -67,7 +80,7 @@ export interface AppMenuSaveDoors { readonly client: { layered: (type: string, name: string, options: { packageId?: string }) => Promise; save: (type: string, name: string, body: unknown, options: Record) => Promise; - publish: (type: string, name: string, options: { packageId?: string }) => Promise; + publish: (type: string, name: string, options: { packageId?: string; ifMatch?: string; ifNoneMatch?: '*' }) => Promise; reset: (type: string, name: string, options: Record) => Promise; }; } @@ -82,6 +95,17 @@ export interface AppMenuSaveTexts { readonly noVersion: string; /** The customization package the server answered is not writable. */ readonly notWritable: string; + /** + * The stored read holds no app (objectstack#36538): nothing is written. + * Absent, said with {@link notListed}. + */ + readonly storedUnread?: string; + /** + * The menu was published by somebody else between this save's read and its + * publish (objectstack#36538): nothing went live. Absent, the server's + * refusal is passed on as it came. + */ + readonly publishedMoved?: string; } /** A document as stored, less what a read adds and what belongs to its package. */ @@ -98,6 +122,30 @@ function storedApp(layers: unknown): Record { return documentOf(read.effective ?? read.code ?? {}); } +/** + * Whether a layered read holds a stored app at all ({@link storedApp} reads + * one): `MetadataClient.layered` answers a 404 as a view with every layer + * `null`, which holds none (objectstack#36538). + */ +export function holdsStoredApp(layers: unknown): boolean { + const read = (layers ?? {}) as { effective?: unknown; code?: unknown }; + return read.effective != null || read.code != null; +} + +/** + * The pin a publish at the address of the layered read `layers` is sent with + * (objectstack#36538): the read's `overlayVersion` (`publishedPinOf`), and + * `If-None-Match: *` for a read that holds no layer at all there (a 404, + * which the server answers when nothing of the item is stored at that + * address, so no published row is either). A read from a server that serves + * no `overlayVersion` pins nothing, as before. + */ +export function publishPinAt(layers: unknown): DraftPin | null { + const read = (layers ?? {}) as { effective?: unknown; code?: unknown; overlay?: unknown }; + if (read.effective == null && read.code == null && read.overlay == null) return { ifNoneMatch: '*' }; + return publishedPinOf(layers); +} + /** * The menu save once every check has passed: the package it writes to and * the app document it writes there. Nothing has been written yet, save the @@ -112,6 +160,12 @@ export interface PreparedAppMenuSave { */ readonly target: string; readonly body: Record; + /** + * The published row of the app at `target` the body was composed over + * (objectstack#36538), as the pin its publish is sent with; `null` or + * absent, the publish is not pinned. + */ + readonly publishPin?: DraftPin | null; } /** @@ -129,8 +183,14 @@ export async function prepareAppMenuSave( const manifests = await doors.listPackages(); const listed = manifests.get(packageId); if (!listed) throw new Error(texts.notListed); + // An installed app's menu is published in its customization package: the + // published row there is read first, before the body (objectstack#36538). + const listedPair = listed.writable ? null : listedCustomizationPairOf(manifests, packageId); + const pairPin = listedPair ? publishPinAt(await doors.client.layered('app', appName, { packageId: listedPair })) : null; // The app as stored, a customization of an installed app folded in. - const stored = storedApp(await doors.client.layered('app', appName, { packageId })); + const layers = await doors.client.layered('app', appName, { packageId }); + if (!holdsStoredApp(layers)) throw new Error(texts.storedUnread ?? texts.notListed); + const stored = storedApp(layers); const storedNav = Array.isArray(stored.navigation) ? (stored.navigation as Menu) : []; // The stored menu in its shown order, as the editor's is (`inShownOrder`), // so the edits land where the editor showed them; the result's order is @@ -139,23 +199,27 @@ export async function prepareAppMenuSave( const nextNav = withOrderRewritten(navPayloadOf(rebased as unknown[]) as Menu); let body: Record | null = { ...stored, name: appName, navigation: nextNav }; let target = packageId; + let publishPin = publishedPinOf(layers); if (!listed.writable) { body = overrideDraftBody(body, packageId, listedPackageVersion(manifests, packageId)); if (body === null) throw new Error(texts.noVersion); const pair = await doors.ensureCustomization(packageId); if (!pair.writable) throw new Error(texts.notWritable); target = pair.packageId; + // The pin read at the pair, when it is the pair answered; a pair this + // call created holds nothing yet; any other was not read, and is not pinned. + publishPin = pair.packageId === listedPair ? pairPin : pair.created ? { ifNoneMatch: '*' } : null; } - return { appName, target, body }; + return { appName, target, body, publishPin }; } /** Write and publish a prepared menu save ({@link prepareAppMenuSave}). */ export async function writeAppMenu( prepared: PreparedAppMenuSave, - texts: Pick, + texts: Pick, doors: Pick, ): Promise { - const { appName, target, body } = prepared; + const { appName, target, body, publishPin } = prepared; try { await doors.client.save('app', appName, body, { mode: 'draft', packageId: target, ifNoneMatch: '*' }); } catch (err) { @@ -163,7 +227,7 @@ export async function writeAppMenu( throw err; } try { - await doors.client.publish('app', appName, { packageId: target }); + await doors.client.publish('app', appName, { packageId: target, ...(publishPin ?? {}) }); } catch (err) { try { await doors.client.reset('app', appName, { state: 'draft', packageId: target }); @@ -171,6 +235,8 @@ export async function writeAppMenu( console.error('[design-mode] a refused publish left the menu draft pending:', discardErr); } emitMetadataRefresh(); + // A publish somebody landed since the read: nothing went live. + if (texts.publishedMoved && isDraftVersionConflict(err)) throw Object.assign(new Error(texts.publishedMoved), { cause: err }); throw err; } emitMetadataRefresh(); @@ -196,7 +262,9 @@ export function consoleAppMenuDoors(client: AppMenuSaveDoors['client']): AppMenu /** * The stored menu of the app `appName` of the package `packageId`: the - * navigation of its layered read (`storedApp`), `null` when the read fails. + * navigation of its layered read (`storedApp`), `null` when the read fails + * or holds no app (`holdsStoredApp`, objectstack#36538): an empty menu would + * read every served entry as another package's. * The editor compares an entry's shown label with it to tell a translated * label from the stored one (objectstack#36363, ruling (4)). */ @@ -206,7 +274,9 @@ export async function readStoredMenu( client: Pick, ): Promise { try { - const stored = storedApp(await client.layered('app', appName, packageId ? { packageId } : {})); + const layers = await client.layered('app', appName, packageId ? { packageId } : {}); + if (!holdsStoredApp(layers)) return null; + const stored = storedApp(layers); return Array.isArray(stored.navigation) ? (stored.navigation as Menu) : []; } catch { return null; diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index a948b5f5cc1..6580f3701d1 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -4370,6 +4370,9 @@ const en = { pendingDraft: 'This app has unpublished changes in Studio. Publish or discard them there, then save again.', noVersion: 'This app\'s package states no version, so its menu cannot be customized.', notWritable: 'This app\'s customization package cannot be written, so its menu cannot be saved.', + storedUnread: 'This app\'s saved menu could not be read, so nothing was saved.', + publishedMoved: 'Someone published this app\'s menu while you were saving, so nothing was saved. Save again to apply your changes over theirs.', + keyboardHint: 'Drag an item to move it, or focus it and press Space, then the arrow keys. Enter opens it.', newDashboard: 'New dashboard…', newDashboardTitle: 'New dashboard', newReport: 'New report…', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 79771f49d82..2938acb30b0 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -3764,6 +3764,9 @@ const zh = { pendingDraft: '这个应用在 Studio 里有未发布的改动。请先在那里发布或丢弃,再保存。', noVersion: '这个应用所在的包没有声明版本,菜单无法定制。', notWritable: '这个应用的定制包不可写,菜单无法保存。', + storedUnread: '无法读取这个应用已保存的菜单,所以没有保存任何内容。', + publishedMoved: '保存期间有人发布了这个应用的菜单,所以没有保存任何内容。再次保存即可把你的修改应用在他们的修改之上。', + keyboardHint: '拖动菜单项即可移动;也可以聚焦后按空格键,再用方向键移动。按回车键打开。', newDashboard: '新建仪表盘…', newDashboardTitle: '新建仪表盘', newReport: '新建报表…', From 348be32b2bc3c12e65aa3ed699af40fb916356c1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 01:16:26 +0000 Subject: [PATCH 2/9] test(console): pin objectstack#36538 items 1-4 and N10, N12-N16 with controls Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzhpykmQZe1yMupC2CU --- .../__tests__/DesignModeMenu-36363.test.tsx | 296 +++++++++++++++++- .../designModeMenuModel-36538.test.ts | 109 +++++++ .../designModeMenuSave-36538.test.ts | 183 +++++++++++ 3 files changed, 582 insertions(+), 6 deletions(-) create mode 100644 ui/packages/app-shell/src/layout/__tests__/designModeMenuModel-36538.test.ts create mode 100644 ui/packages/app-shell/src/layout/__tests__/designModeMenuSave-36538.test.ts 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 3bc5651c6f8..9b41df27937 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 @@ -33,6 +33,10 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({ const dragEnd = vi.hoisted(() => ({ current: null as null | ((event: unknown) => void) })); const dragStart = vi.hoisted(() => ({ current: null as null | ((event: unknown) => void) })); +/** objectstack#36538 — the editor's cancel handler, its collision rule, and every drag start dnd-kit itself reported. */ +const dragCancel = vi.hoisted(() => ({ current: null as null | ((event: unknown) => void) })); +const collisionRule = vi.hoisted(() => ({ current: null as null | ((args: unknown) => unknown[]) })); +const dragStarts = vi.hoisted(() => [] as unknown[]); vi.mock('@dnd-kit/core', async (importOriginal) => { const real = await importOriginal(); const { createElement } = await import('react'); @@ -41,7 +45,13 @@ vi.mock('@dnd-kit/core', async (importOriginal) => { DndContext: (props: React.ComponentProps) => { dragEnd.current = props.onDragEnd as never; dragStart.current = props.onDragStart as never; - return createElement(real.DndContext, props); + dragCancel.current = props.onDragCancel as never; + collisionRule.current = props.collisionDetection as never; + const onDragStart: typeof props.onDragStart = (event) => { + dragStarts.push(event); + props.onDragStart?.(event); + }; + return createElement(real.DndContext, { ...props, onDragStart }); }, }; }); @@ -68,20 +78,35 @@ const listed = vi.hoisted(() => ({ ], }) as Record>>); /** objectstack#36364 — names the server holds (`type/name`), and a refusal of the app's save. */ -const server = vi.hoisted(() => ({ held: new Set(), appSave: null as Error | null })); +const server = vi.hoisted(() => ({ held: new Set(), appSave: null as Error | null, appPublish: null as Error | null })); /** The app's menu as served (`null`: `NAVIGATION`). */ const servedNav = vi.hoisted(() => ({ current: null as unknown[] | null })); -/** The app's menu as stored (`null`: as served). */ -const storedNav = vi.hoisted(() => ({ current: null as unknown[] | null, failReads: 0 })); +/** + * The app's menu as stored (`null`: as served). objectstack#36538: `missing` + * answers every layered read as `MetadataClient.layered` answers a 404; + * `gate` holds the next read until it settles; `overlayVersion` is served + * when set. + */ +const storedNav = vi.hoisted(() => ({ + current: null as unknown[] | null, + failReads: 0, + missing: false, + gate: null as Promise | null, + overlayVersion: undefined as string | undefined, +})); const client = vi.hoisted(() => ({ list: async (type: string) => listed[type] ?? [], layered: async () => { + const gate = storedNav.gate; + storedNav.gate = null; + if (gate) await gate; if (storedNav.failReads > 0) { storedNav.failReads -= 1; throw new Error('layered read failed'); } + if (storedNav.missing) return { code: null, overlay: null, overlayScope: null, effective: null }; const code = { name: 'crm', label: 'CRM', navigation: storedNav.current ?? servedNav.current ?? NAVIGATION }; - return { code, effective: code }; + return { code, effective: code, ...(storedNav.overlayVersion ? { overlayVersion: storedNav.overlayVersion } : {}) }; }, get: async (type: string, name: string) => (server.held.has(`${type}/${name}`) ? { name } : null), save: async (...args: unknown[]) => { @@ -91,6 +116,7 @@ const client = vi.hoisted(() => ({ }, publish: async (...args: unknown[]) => { written.push(['publish', ...args]); + if (args[0] === 'app' && server.appPublish) throw server.appPublish; return {}; }, reset: async (...args: unknown[]) => { @@ -114,7 +140,8 @@ vi.mock('../../utils/getIcon', () => ({ getIcon: () => () => null })); import { DesignModeProvider, useDesignMode, useDesignModeController } from '../designMode'; import { DesignModeBar } from '../DesignModeBar'; -import DesignModeMenu from '../DesignModeMenu'; +import DesignModeMenu, { menuCollision } from '../DesignModeMenu'; +import { closestCenter, type CollisionDetection } from '@dnd-kit/core'; import { confirmUnsavedLeave } from '../../chrome/unsavedEdits'; import { __resetDefaultLocale } from '../designModeMenuSave'; import { newReportSlotFor } from '../designModeReportSlot'; @@ -214,8 +241,13 @@ beforeEach(() => { session.defaultLocale = 'en'; storedNav.current = null; storedNav.failReads = 0; + storedNav.missing = false; + storedNav.gate = null; + storedNav.overlayVersion = undefined; + dragStarts.length = 0; server.held.clear(); server.appSave = null; + server.appPublish = null; servedNav.current = null; __resetDefaultLocale(); vi.stubGlobal( @@ -1079,3 +1111,255 @@ describe('the design-mode menu in the sidebar order (objectstack#36591)', () => expect(sidebarOrder(saved)).toEqual(shown); }); }); + +describe('the design-mode menu save and drag, hardened (objectstack#36538)', () => { + /** Accounts is another package's entry, appended to Sales when the app is served. */ + const ACCOUNTS_FOREIGN = () => + NAVIGATION.map((e) => (e.id === 'sales' ? { ...e, children: (e.children ?? []).filter((c) => c.id !== 'accounts') } : e)); + /** A group another package puts into the menu, with its own entry. */ + const PARTNER = { id: 'partner', type: 'group', label: 'Partner', children: [{ id: 'partner_cases', type: 'object', objectName: 'crm_case', label: 'Cases' }] }; + + function startWhere() { + render( + + + + , + ); + fireEvent.click(screen.getByText('enter')); + } + const where = () => screen.getByTestId('where').textContent; + /** A press on `el`, released, then the click it ends with. */ + const press = (el: Element) => { + fireEvent.pointerDown(el, { button: 0, pointerType: 'mouse' }); + fireEvent.pointerUp(el, { button: 0, pointerType: 'mouse' }); + fireEvent.click(el); + }; + /** Opens 「⋮ → Move to group」 of the entry `id` and answers the groups it offers. */ + async function groupsOffered(id: string): Promise { + fireEvent.pointerDown(within(entry(id)).getByTestId('design-menu-actions'), { button: 0, pointerType: 'mouse' }); + await flush(); + fireEvent.keyDown(await screen.findByRole('menuitem', { name: 'Move to group' }), { key: 'ArrowRight' }); + await flush(); + return (await screen.findAllByRole('menuitem')).map((m) => m.textContent ?? ''); + } + /** A clock the editor's click window reads, moved by hand. */ + function clock() { + let now = 1_000_000; + const spy = vi.spyOn(Date, 'now').mockImplementation(() => now); + return { pass: (ms: number) => (now += ms), restore: () => spy.mockRestore() }; + } + + // Item 2 (review N8): the layered read answers a 404 as an empty view. + it('a stored read answering 404: 「Save」 writes nothing and the bar says so; on entry no entry reads as another package\'s', async () => { + storedNav.missing = true; + start(); + await flush(); + // CONTROL of the entry read: an empty stored menu would mark every entry another package's and shut 「Move up」. + fireEvent.pointerDown(within(entry('accounts')).getByTestId('design-menu-actions'), { button: 0, pointerType: 'mouse' }); + await flush(); + expect(screen.queryByTestId('design-menu-contributed')).toBeNull(); + fireEvent.click(await screen.findByRole('menuitem', { name: 'Move up' })); + await flush(); + fireEvent.click(screen.getByTestId('design-mode-save')); + await flush(); + await flush(); + expect(written).toEqual([]); + expect(toastError).toHaveBeenCalledTimes(1); + expect(String(toastError.mock.calls[0][0])).toContain("This app's saved menu could not be read"); + expect(screen.getByTestId('design-mode-bar')).toBeInTheDocument(); + }); + + // Item 4 (review N6): the publish is pinned, and a publish landed in between is said. + it("「Save」 pins the publish to the read's published row; a publish landed in between is refused, discarded and said", async () => { + storedNav.overlayVersion = 'v7'; + server.appPublish = Object.assign(new Error('conflict'), { status: 409, code: 'METADATA_CONFLICT' }); + start(); + await flush(); + await act_on('accounts', 'Move up'); + fireEvent.click(screen.getByTestId('design-mode-save')); + await flush(); + await flush(); + expect(written.map(([verb]) => verb)).toEqual(['save', 'publish', 'reset']); + expect(written[1]).toEqual(['publish', 'app', 'crm', { packageId: 'com.acme.crm', ifMatch: 'v7' }]); + expect(String(toastError.mock.calls[0][0])).toContain("Someone published this app's menu while you were saving"); + expect(screen.getByTestId('design-mode-bar')).toBeInTheDocument(); + }); + + // Item 3 (review N9): another package's group takes no own entry. + it("another package's group is not offered by 「Move to group」, has no 「Add menu item」, and takes no drop", async () => { + servedNav.current = [...NAVIGATION, PARTNER]; + storedNav.current = NAVIGATION; + start(); + await flush(); + const offered = await groupsOffered('leads'); + expect(offered).toContain('Insights'); // CONTROL: an own group is offered + expect(offered).not.toContain('Partner'); + fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' }); + await flush(); + expect(screen.getByTestId('design-menu-add-insights')).toBeInTheDocument(); // CONTROL + expect(screen.queryByTestId('design-menu-add-partner')).toBeNull(); + + act(() => dragEnd.current!({ active: { id: 'home' }, over: { id: 'design-menu-end:partner' } })); + expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', []], ['partner', ['partner_cases']]]); + act(() => dragEnd.current!({ active: { id: 'home' }, over: { id: 'design-menu-end:insights' } })); // CONTROL + expect(order()).toEqual([['sales', ['leads', 'accounts']], ['insights', ['home']], ['partner', ['partner_cases']]]); + }); + + it("「Add an item before / after」 is off on an entry of another package's group, and open on one of an own group", async () => { + servedNav.current = [...NAVIGATION, PARTNER]; + storedNav.current = NAVIGATION; + start(); + await flush(); + fireEvent.pointerDown(within(entry('partner_cases')).getByTestId('design-menu-actions'), { button: 0, pointerType: 'mouse' }); + await flush(); + for (const name of ['Add an item before', 'Add an item after']) { + expect(await screen.findByRole('menuitem', { name })).toHaveAttribute('aria-disabled', 'true'); + } + fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' }); + await flush(); + fireEvent.pointerDown(within(entry('accounts')).getByTestId('design-menu-actions'), { button: 0, pointerType: 'mouse' }); + await flush(); + expect(await screen.findByRole('menuitem', { name: 'Add an item after' })).not.toHaveAttribute('aria-disabled'); + }); + + // N10: an add made while the stored read is pending is drawn where it is saved, once the read lands. + it("an entry added at a group's end while the stored read is pending is drawn before another package's entries once it lands", async () => { + storedNav.current = ACCOUNTS_FOREIGN(); + let land!: () => void; + storedNav.gate = new Promise((resolve) => (land = resolve)); + start(); + await flush(); + fireEvent.click(screen.getByTestId('design-menu-add-sales')); + const picker = await screen.findByTestId('design-menu-picker'); + fireEvent.click(within(picker).getByRole('button', { name: 'Objects' })); + await flush(); + fireEvent.click(within(picker).getByRole('button', { name: 'Cases' })); + await flush(); + // CONTROL: still pending, nothing tells Accounts apart, the entry is drawn last. + expect(order()).toEqual(['home', ['sales', ['leads', 'accounts', 'nav_item_1']], ['insights', []]]); + await act(async () => land()); + await flush(); + expect(order()).toEqual(['home', ['sales', ['leads', 'nav_item_1', 'accounts']], ['insights', []]]); + fireEvent.click(screen.getByTestId('design-mode-save')); + await flush(); + await flush(); + const nav = (written[0][3] as { navigation: Array<{ id: string; children?: Array<{ id: string }> }> }).navigation; + expect(nav[1].children!.map((c) => c.id)).toEqual(['leads', 'nav_item_1']); + }); + + // N12: the window starts at the release of the press that dragged. + it('a pointer drag cancelled by Escape with the button held: the late release opens nothing; a plain click then opens', async () => { + const time = clock(); + try { + startWhere(); + await flush(); + const leads = linkOf('leads'); + fireEvent.pointerDown(leads, { button: 0, pointerType: 'mouse' }); + act(() => dragStart.current!({ active: { id: 'leads' }, activatorEvent: new MouseEvent('pointerdown') })); + act(() => dragCancel.current!({ active: { id: 'leads' } })); + time.pass(2_000); // the button held long past the old window + fireEvent.pointerUp(leads, { button: 0, pointerType: 'mouse' }); + fireEvent.click(leads); + expect(where()).toBe('/apps/crm'); + time.pass(1_000); + press(linkOf('home')); // CONTROL + expect(where()).not.toBe('/apps/crm'); + } finally { + time.restore(); + } + }); + + // N15: each clear of the drag flag has its own case. + it('a new press clears a drag whose end was never reported: its click opens the page', async () => { + startWhere(); + await flush(); + act(() => dragStart.current!({ active: { id: 'leads' } })); // started, no end, no pointer held + press(linkOf('home')); + expect(where()).not.toBe('/apps/crm'); + }); + + it('a window pointercancel clears a drag whose end was never reported: a later click opens the page', async () => { + const time = clock(); + try { + startWhere(); + await flush(); + act(() => dragStart.current!({ active: { id: 'leads' } })); + fireEvent.pointerCancel(window); + time.pass(1_000); + fireEvent.click(linkOf('home')); + expect(where()).not.toBe('/apps/crm'); + } finally { + time.restore(); + } + }); + + // N16: a keyboard move keeps the links shut whatever the pointer does. + it('a click during a held keyboard move opens nothing; once the move ends, a click opens', async () => { + const time = clock(); + try { + startWhere(); + await flush(); + act(() => dragStart.current!({ active: { id: 'leads' }, activatorEvent: new KeyboardEvent('keydown', { code: 'Space' }) })); + press(linkOf('home')); + expect(where()).toBe('/apps/crm'); + act(() => dragEnd.current!({ active: { id: 'leads' }, over: null })); + time.pass(1_000); + press(linkOf('home')); // CONTROL + expect(where()).not.toBe('/apps/crm'); + } finally { + time.restore(); + } + }); + + // N13: Space moves, Enter opens; the editor says so. + it('Space on an entry starts a keyboard move; Enter does not, and is left to open the link; the editor says which', async () => { + start(); + await flush(); + const leads = linkOf('leads'); + leads.focus(); + expect(fireEvent.keyDown(leads, { code: 'Enter', key: 'Enter' })).toBe(true); // not taken: the link opens + await flush(); + expect(dragStarts).toHaveLength(0); + expect(fireEvent.keyDown(leads, { code: 'Space', key: ' ' })).toBe(false); // taken by the move + await flush(); + expect(dragStarts).toHaveLength(1); + fireEvent.keyDown(leads, { code: 'Escape', key: 'Escape' }); + await flush(); + // The help the editor shows is the one a screen reader is given for an entry. + const hint = screen.getByTestId('design-menu-keyboard-hint').textContent; + expect(hint).toBeTruthy(); + expect(document.getElementById(linkOf('leads').getAttribute('aria-describedby') ?? '')?.textContent).toBe(hint); + }); + + // N14: a drop outside the menu moves nothing. + describe('the collision rule', () => { + const rect = { top: 0, left: 0, right: 100, bottom: 20, width: 100, height: 20 }; + const args = (pointer: { x: number; y: number } | null) => + ({ + active: { id: 'leads', data: { current: {} }, rect: { current: { initial: null, translated: null } } }, + collisionRect: rect, + droppableRects: new Map([['home', rect]]), + droppableContainers: [{ id: 'home', key: 'home', data: { current: {} }, disabled: false, node: { current: null }, rect: { current: rect } }], + pointerCoordinates: pointer, + }) as unknown as Parameters[0]; + const area = () => new DOMRect(0, 0, 200, 400); + + it('a pointer outside the menu is over nothing; inside it, and from the keyboard, the nearest entry', () => { + const rule = menuCollision(area); + expect(rule(args({ x: 900, y: 900 }))).toEqual([]); + expect(rule(args({ x: 50, y: 10 })).map((c) => c.id)).toEqual(['home']); + expect(rule(args(null)).map((c) => c.id)).toEqual(['home']); + expect(closestCenter(args({ x: 900, y: 900 })).map((c) => c.id)).toEqual(['home']); // CONTROL: the old rule moved it + }); + + it("is the editor's rule, and a drop it answers nothing for moves nothing", async () => { + start(); + await flush(); + // jsdom lays the menu out at no size, so any pointer off its origin is outside it. + expect(collisionRule.current!(args({ x: 900, y: 900 }))).toEqual([]); + act(() => dragEnd.current!({ active: { id: 'home' }, over: null })); + expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', []]]); + }); + }); +}); diff --git a/ui/packages/app-shell/src/layout/__tests__/designModeMenuModel-36538.test.ts b/ui/packages/app-shell/src/layout/__tests__/designModeMenuModel-36538.test.ts new file mode 100644 index 00000000000..199f40dabd3 --- /dev/null +++ b/ui/packages/app-shell/src/layout/__tests__/designModeMenuModel-36538.test.ts @@ -0,0 +1,109 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The design mode's menu model (objectstack#36538): id-less twins are matched + * to their own served copies (review N7), and an own entry put in or past + * another package's closing entries is drawn where the save puts it (N10). + */ + +import { describe, expect, it } from 'vitest'; +import { + rebaseMenuEdits, + removeEntry, + storedEntriesById, + withEntryIds, + withOwnBeforeForeignRuns, + type Menu, +} from '../designModeMenuModel'; + +const ids = (menu: Menu): unknown[] => menu.map((e) => (Array.isArray(e.children) ? [e.id ?? e.type, ids(e.children as Menu)] : e.id ?? e.type)); + +describe('id-less twins are matched to their own served copy (objectstack#36538, review N7)', () => { + // Two id-less entries of one group, the same type and target; the earlier + // one needs a permission this reader lacks, so the server prunes it. + const HIDDEN = { type: 'object', objectName: 'crm_lead', requiredPermissions: ['hr.admin'] }; + const SHOWN = { type: 'object', objectName: 'crm_lead' }; + const STORED: Menu = [{ id: 'sales', type: 'group', label: 'Sales', children: [HIDDEN, SHOWN] }]; + const SERVED = withEntryIds([{ id: 'sales', type: 'group', label: 'Sales', children: [SHOWN] }]); + + it('removing the shown twin removes it, and keeps the twin the reader was not shown', () => { + const shownId = String((SERVED[0].children as Menu)[0].id); + const rebased = rebaseMenuEdits(SERVED, removeEntry(SERVED, shownId), STORED); + expect(rebased[0].children).toEqual([HIDDEN]); + }); + + it('the stored entry behind the shown twin is the shown one', () => { + const shownId = String((SERVED[0].children as Menu)[0].id); + expect(storedEntriesById(SERVED, STORED).get(shownId)).toBe(SHOWN); + }); + + it('two separators, the earlier one pruned: removing the shown one keeps the pruned one', () => { + const pruned = { type: 'separator', requiredPermissions: ['hr.admin'] }; + const stored: Menu = [pruned, { id: 'leads', type: 'object', objectName: 'crm_lead' }, { type: 'separator' }]; + const served = withEntryIds([{ id: 'leads', type: 'object', objectName: 'crm_lead' }, { type: 'separator' }]); + const sepId = String(served[1].id); + expect(rebaseMenuEdits(served, removeEntry(served, sepId), stored)).toEqual([pruned, stored[1]]); + }); + + it('CONTROL: twins equal in every key are matched by their place: removing the second removes the second', () => { + const sep = () => ({ type: 'separator' }); + const stored: Menu = [sep(), { id: 'a', type: 'page', pageName: 'a' }, sep(), { id: 'b', type: 'page', pageName: 'b' }, sep()]; + const served = withEntryIds(stored.map((e) => ({ ...e }))); + const second = String(served[2].id); + const rebased = rebaseMenuEdits(served, removeEntry(served, second), stored); + expect(rebased).toHaveLength(4); + expect(rebased[0]).toBe(stored[0]); + expect(rebased[2]).toBe(stored[3]); + expect(rebased[3]).toBe(stored[4]); + }); + + it('CONTROL: an id-less entry whose served copy differs in a key is still matched by its type and target', () => { + const stored: Menu = [{ type: 'object', objectName: 'crm_lead', label: { en: 'Leads' } }]; + const served = withEntryIds([{ type: 'object', objectName: 'crm_lead', label: 'Leads' }]); + expect(storedEntriesById(served, stored).get(String(served[0].id))).toBe(stored[0]); + }); +}); + +describe("an own entry in or past another package's closing entries is drawn before them (objectstack#36538, review N10)", () => { + const SERVED: Menu = [ + { id: 'home', type: 'page', pageName: 'home' }, + { + id: 'sales', + type: 'group', + children: [ + { id: 'leads', type: 'object', objectName: 'crm_lead' }, + { id: 'partner_a', type: 'page', pageName: 'partner_a' }, + { id: 'partner_b', type: 'page', pageName: 'partner_b' }, + ], + }, + { id: 'partner_top', type: 'page', pageName: 'partner_top' }, + ]; + const foreign = (id: string) => id.startsWith('partner_'); + + it('an entry added after the run, or inside it, is put just before it; the run keeps its order', () => { + const added = { id: 'new', type: 'page', pageName: 'new' }; + const inside = { id: 'mid', type: 'page', pageName: 'mid' }; + const menu: Menu = [ + SERVED[0], + { ...SERVED[1], children: [...(SERVED[1].children as Menu).slice(0, 2), inside, (SERVED[1].children as Menu)[2], added] }, + SERVED[2], + { id: 'top_new', type: 'page', pageName: 'top_new' }, + ]; + expect(ids(withOwnBeforeForeignRuns(menu, SERVED, foreign))).toEqual([ + 'home', + ['sales', ['leads', 'mid', 'new', 'partner_a', 'partner_b']], + 'top_new', + 'partner_top', + ]); + }); + + it('CONTROL: a menu with no own entry past a run is the same menu', () => { + const menu: Menu = [SERVED[0], { ...SERVED[1] }, SERVED[2]]; + expect(withOwnBeforeForeignRuns(menu, SERVED, foreign)).toBe(menu); + }); + + it('CONTROL: with no entry another package\'s, nothing moves', () => { + const menu: Menu = [...SERVED, { id: 'top_new', type: 'page', pageName: 'top_new' }]; + expect(withOwnBeforeForeignRuns(menu, SERVED, () => false)).toBe(menu); + }); +}); diff --git a/ui/packages/app-shell/src/layout/__tests__/designModeMenuSave-36538.test.ts b/ui/packages/app-shell/src/layout/__tests__/designModeMenuSave-36538.test.ts new file mode 100644 index 00000000000..76a29c572cc --- /dev/null +++ b/ui/packages/app-shell/src/layout/__tests__/designModeMenuSave-36538.test.ts @@ -0,0 +1,183 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The design mode's menu save (objectstack#36538): a stored read that holds + * no app refuses the save (review N8), and the publish is pinned to the + * published row the save was composed over (review N6), read at the address + * the publish writes, before the body. + */ + +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const emitMetadataRefresh = vi.hoisted(() => vi.fn()); +vi.mock('../../assistant/assistantBus', async (importOriginal) => ({ + ...(await importOriginal>()), + emitMetadataRefresh, +})); + +import { readStoredMenu, saveAppMenu, type AppMenuSaveDoors, type AppMenuSaveTexts } from '../designModeMenuSave'; + +const TEXTS: AppMenuSaveTexts = { + notListed: 'not listed', + pendingDraft: 'pending draft', + noVersion: 'no version', + notWritable: 'not writable', + storedUnread: 'stored unread', + publishedMoved: 'published moved', +}; +const NAV = [{ id: 'leads', type: 'object', objectName: 'crm_lead' }]; +const INPUT = { appName: 'crm', packageId: 'com.acme.crm', served: [], navigation: NAV }; +/** What `MetadataClient.layered` answers for a 404. */ +const NOT_FOUND = { code: null, overlay: null, overlayScope: null, effective: null }; +const APP = { name: 'crm', label: 'CRM', navigation: [] }; + +type Layers = Record; + +function doors(opts: { + writable?: boolean; + /** The customization pair is listed. */ + pairListed?: boolean; + /** The ensure door created the pair. */ + created?: boolean; + /** The layered read at each package. */ + layers: Record; + publish?: () => Promise; +}) { + const calls: Array<[string, ...unknown[]]> = []; + const base = { id: 'com.acme.crm', name: 'CRM', writable: opts.writable ?? true, manifest: { version: '6.5.0' } }; + const pair = { id: 'com.acme.crm.custom', name: 'CRM custom', writable: true, manifest: { version: '0.0.1' } }; + const d: AppMenuSaveDoors = { + listPackages: async () => new Map([['com.acme.crm', base], ...(opts.pairListed ? [['com.acme.crm.custom', pair] as const] : [])]), + ensureCustomization: async (id) => { + calls.push(['ensure', id]); + return { basePackageId: id, packageId: `${id}.custom`, namespace: 'crm_custom', created: opts.created ?? false, writable: true }; + }, + client: { + layered: async (...args) => { + calls.push(['layered', ...args]); + return opts.layers[String(args[2].packageId)] ?? NOT_FOUND; + }, + save: async (...args) => { + calls.push(['save', ...args]); + return {}; + }, + publish: async (...args) => { + calls.push(['publish', ...args]); + return opts.publish ? opts.publish() : {}; + }, + reset: async (...args) => { + calls.push(['reset', ...args]); + return {}; + }, + }, + }; + return { d, calls }; +} + +const publishOf = (calls: Array<[string, ...unknown[]]>) => calls.find(([c]) => c === 'publish'); + +beforeEach(() => emitMetadataRefresh.mockReset()); + +describe('a stored read that holds no app refuses the save (objectstack#36538, review N8)', () => { + it('the layered read answers a 404: nothing is written, and the save says why', async () => { + const { d, calls } = doors({ layers: { 'com.acme.crm': NOT_FOUND } }); + await expect(saveAppMenu(INPUT, TEXTS, d)).rejects.toThrow(TEXTS.storedUnread); + expect(calls.map(([c]) => c)).toEqual(['layered']); + }); + + it('a caller that states no sentence for it is told the package sentence', async () => { + const { d } = doors({ layers: { 'com.acme.crm': NOT_FOUND } }); + const { storedUnread: _, ...texts } = TEXTS; + await expect(saveAppMenu(INPUT, texts, d)).rejects.toThrow(TEXTS.notListed); + }); + + it('CONTROL: a read that holds the app saves and publishes', async () => { + const { d, calls } = doors({ layers: { 'com.acme.crm': { code: APP, effective: APP } } }); + await saveAppMenu(INPUT, TEXTS, d); + expect(calls.map(([c]) => c)).toEqual(['layered', 'save', 'publish']); + }); + + it("the editor's stored menu is unknown (`null`) for a 404, never an empty menu; a stored app with no menu is an empty one", async () => { + const layered = vi.fn(async () => NOT_FOUND); + expect(await readStoredMenu('crm', 'com.acme.crm', { layered })).toBeNull(); + layered.mockResolvedValueOnce({ code: { name: 'crm', label: 'CRM' }, effective: null } as never); + expect(await readStoredMenu('crm', 'com.acme.crm', { layered })).toEqual([]); + }); +}); + +describe('the publish is pinned to the published row the save read (objectstack#36538, review N6)', () => { + it("a writable package: the read's overlayVersion is sent as If-Match", async () => { + const { d, calls } = doors({ layers: { 'com.acme.crm': { code: APP, effective: APP, overlayVersion: 'v3' } } }); + await saveAppMenu(INPUT, TEXTS, d); + expect(publishOf(calls)).toEqual(['publish', 'app', 'crm', { packageId: 'com.acme.crm', ifMatch: 'v3' }]); + }); + + it('no published row at that address (overlayVersion null): the publish is sent If-None-Match *', async () => { + const { d, calls } = doors({ layers: { 'com.acme.crm': { code: APP, effective: APP, overlayVersion: null } } }); + await saveAppMenu(INPUT, TEXTS, d); + expect(publishOf(calls)).toEqual(['publish', 'app', 'crm', { packageId: 'com.acme.crm', ifNoneMatch: '*' }]); + }); + + it('CONTROL: a server that serves no overlayVersion: the publish is not pinned, as before', async () => { + const { d, calls } = doors({ layers: { 'com.acme.crm': { code: APP, effective: APP } } }); + await saveAppMenu(INPUT, TEXTS, d); + expect(publishOf(calls)).toEqual(['publish', 'app', 'crm', { packageId: 'com.acme.crm' }]); + }); + + it('a publish landed since the read is refused 409: the draft is discarded, and the save says so', async () => { + const conflict = Object.assign(new Error('conflict'), { status: 409, code: 'METADATA_CONFLICT' }); + const { d, calls } = doors({ + layers: { 'com.acme.crm': { code: APP, effective: APP, overlayVersion: 'v3' } }, + publish: () => Promise.reject(conflict), + }); + const refusal = await saveAppMenu(INPUT, TEXTS, d).catch((e: unknown) => e); + expect(refusal).toBeInstanceOf(Error); + expect((refusal as Error).message).toBe(TEXTS.publishedMoved); + expect((refusal as Error).cause).toBe(conflict); + expect(calls.map(([c]) => c)).toEqual(['layered', 'save', 'publish', 'reset']); + expect(calls[3]).toEqual(['reset', 'app', 'crm', { state: 'draft', packageId: 'com.acme.crm' }]); + }); + + it('CONTROL: another refusal of the publish is passed on as it came', async () => { + const refused = Object.assign(new Error('Package is read-only'), { status: 403, code: 'PERMISSION_DENIED' }); + const { d } = doors({ layers: { 'com.acme.crm': { code: APP, effective: APP, overlayVersion: 'v3' } }, publish: () => Promise.reject(refused) }); + await expect(saveAppMenu(INPUT, TEXTS, d)).rejects.toBe(refused); + }); + + it("an installed app with a listed pair: the pair's published row is read first, and pins the publish there", async () => { + const { d, calls } = doors({ + writable: false, + pairListed: true, + layers: { + 'com.acme.crm.custom': { code: null, overlay: APP, effective: APP, overlayVersion: 'pair-9' }, + 'com.acme.crm': { code: APP, effective: APP, overlayVersion: 'base-1' }, + }, + }); + await saveAppMenu(INPUT, TEXTS, d); + expect(calls.filter(([c]) => c === 'layered').map((c) => (c[3] as { packageId: string }).packageId)).toEqual([ + 'com.acme.crm.custom', + 'com.acme.crm', + ]); + expect(publishOf(calls)).toEqual(['publish', 'app', 'crm', { packageId: 'com.acme.crm.custom', ifMatch: 'pair-9' }]); + }); + + it('a listed pair that holds nothing of the app (a 404 there): the publish is sent If-None-Match *', async () => { + const { d, calls } = doors({ + writable: false, + pairListed: true, + layers: { 'com.acme.crm': { code: APP, effective: APP, overlayVersion: null } }, + }); + await saveAppMenu(INPUT, TEXTS, d); + expect(publishOf(calls)).toEqual(['publish', 'app', 'crm', { packageId: 'com.acme.crm.custom', ifNoneMatch: '*' }]); + }); + + it('a pair the ensure door created holds nothing: If-None-Match *; one it found unlisted was not read: not pinned', async () => { + const created = doors({ writable: false, created: true, layers: { 'com.acme.crm': { code: APP, effective: APP, overlayVersion: null } } }); + await saveAppMenu(INPUT, TEXTS, created.d); + expect(publishOf(created.calls)).toEqual(['publish', 'app', 'crm', { packageId: 'com.acme.crm.custom', ifNoneMatch: '*' }]); + + const found = doors({ writable: false, created: false, layers: { 'com.acme.crm': { code: APP, effective: APP, overlayVersion: 'base-1' } } }); + await saveAppMenu(INPUT, TEXTS, found.d); + expect(publishOf(found.calls)).toEqual(['publish', 'app', 'crm', { packageId: 'com.acme.crm.custom' }]); + }); +}); From 44b1520a32e4013851ccbaf98d29f0f06a57d01b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 01:28:31 +0000 Subject: [PATCH 3/9] chore(changeset): design mode menu save hardening (objectstack#36538 follow-up) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzhpykmQZe1yMupC2CU --- .../36538-design-mode-menu-save-hardened.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 .changeset/36538-design-mode-menu-save-hardened.md diff --git a/.changeset/36538-design-mode-menu-save-hardened.md b/.changeset/36538-design-mode-menu-save-hardened.md new file mode 100644 index 00000000000..0d16b9c7b62 --- /dev/null +++ b/.changeset/36538-design-mode-menu-save-hardened.md @@ -0,0 +1,22 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +fix(console): the design mode's menu save refuses an unreadable stored app, pins its publish, and keeps own entries out of another package's group + +Clause-②: no +Metadata-protocol: none + +The menu editor of the console's design mode, and its 「Save」, are hardened in eight places: + +- Two id-less menu entries of one group with the same type and target (two separators, say) are matched to their own served copies: an entry the reader was not shown (other `requiredPermissions`) no longer takes the key of the one shown, so removing the shown entry removes it, not the hidden twin. Twins equal in every key are matched by their place. +- A stored read that holds no app (the layered read answers a 404 as an empty view) refuses the save, and the bar says why, instead of writing an app of the menu additions alone. On entry such a read no longer marks every entry as another package's. +- The publish is pinned to the published row the save was composed over (the `/layers` read's `overlayVersion`, sent as `If-Match`, or `If-None-Match: *` where no row is stored), read at the address the publish writes. A publish somebody lands in between is refused, the draft is discarded and the bar says so; saving again applies the edits over it. A server that serves no `overlayVersion` is published unpinned, as before. +- A group another package contributes is not offered by 「Move to group」, has no 「Add menu item」, takes no drop, and offers no 「Add an item before / after」 on its entries. +- An entry added at a group's end while the stored read is still pending is drawn before another package's entries once the read lands, where the save puts it. +- Space starts a keyboard move and Enter opens the entry's page; the editor's help line and its screen-reader instructions say so. +- A drop outside the menu moves nothing. +- The click that ends a pointer drag opens nothing however long the button was held after an Escape, and no click opens a link while a keyboard move is held. + +`AppMenuSaveTexts` gains two optional sentences, `storedUnread` and `publishedMoved`; a caller that states neither is told the package sentence for the first and the server's refusal for the second. Nothing to migrate. From 8895a52ee8308a1b2e75517da9a6e2b64232b84f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 01:52:56 +0000 Subject: [PATCH 4/9] refactor(console): keep the design mode menu module component-only; pin the wired collision rule Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzhpykmQZe1yMupC2CU --- .../app-shell/src/layout/DesignModeMenu.tsx | 31 +++++++++---------- .../__tests__/DesignModeMenu-36363.test.tsx | 18 +++++------ 2 files changed, 24 insertions(+), 25 deletions(-) diff --git a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx index 4dd5e61ac6a..9dc4020202a 100644 --- a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx +++ b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx @@ -210,25 +210,15 @@ const parentOfEndZone = (id: string): string | null | undefined => { * entry up, so Enter on an entry still opens its page, as on any link; Space * or Enter drops it, Escape puts it back. */ -export const MENU_KEYBOARD_CODES: KeyboardCodes = { +const MENU_KEYBOARD_CODES: KeyboardCodes = { start: [KeyboardCode.Space], cancel: [KeyboardCode.Esc], end: [KeyboardCode.Space, KeyboardCode.Enter], }; -/** - * The editor's collision rule (objectstack#36538, review N14): a pointer - * released outside the box `area()` answers (the menu's own) is over nothing, - * so the drop moves nothing; inside it, and for a keyboard move (which has - * no pointer), the nearest entry's centre, as before. - */ -export function menuCollision(area: () => DOMRect | null | undefined): CollisionDetection { - return (args) => { - const at = args.pointerCoordinates; - const box = at ? area() : null; - if (at && box && (at.x < box.left || at.x > box.right || at.y < box.top || at.y > box.bottom)) return []; - return closestCenter(args); - }; +/** Whether the point `at` lies outside the box `box`. */ +function outside(at: { x: number; y: number }, box: DOMRect): boolean { + return at.x < box.left || at.x > box.right || at.y < box.top || at.y > box.bottom; } export interface DesignModeMenuProps { @@ -346,8 +336,17 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso useSensor(PointerSensor, { activationConstraint: { distance: 5 } }), useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates, keyboardCodes: MENU_KEYBOARD_CODES }), ); + // The collision rule (objectstack#36538, review N14): a pointer released + // outside the menu's own box is over nothing, so the drop moves nothing; + // inside it, and for a keyboard move (which has no pointer), the nearest + // entry's centre, as before. const menuArea = React.useRef(null); - const collision = React.useMemo(() => menuCollision(() => menuArea.current?.getBoundingClientRect()), []); + const collision = React.useCallback((args) => { + const at = args.pointerCoordinates; + const box = at ? menuArea.current?.getBoundingClientRect() : null; + if (at && box && outside(at, box)) return []; + return closestCenter(args); + }, []); const keyboardHint = t('designMode.menu.keyboardHint', { defaultValue: 'Drag an item to move it, or focus it and press Space, then the arrow keys. Enter opens it.', }); @@ -677,7 +676,7 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso onDragCancel={endDrag} > -
+
{renderEntries(menu, null, 0)}
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 9b41df27937..a49c88d43c4 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 @@ -140,7 +140,7 @@ vi.mock('../../utils/getIcon', () => ({ getIcon: () => () => null })); import { DesignModeProvider, useDesignMode, useDesignModeController } from '../designMode'; import { DesignModeBar } from '../DesignModeBar'; -import DesignModeMenu, { menuCollision } from '../DesignModeMenu'; +import DesignModeMenu from '../DesignModeMenu'; import { closestCenter, type CollisionDetection } from '@dnd-kit/core'; import { confirmUnsavedLeave } from '../../chrome/unsavedEdits'; import { __resetDefaultLocale } from '../designModeMenuSave'; @@ -1343,21 +1343,21 @@ describe('the design-mode menu save and drag, hardened (objectstack#36538)', () droppableContainers: [{ id: 'home', key: 'home', data: { current: {} }, disabled: false, node: { current: null }, rect: { current: rect } }], pointerCoordinates: pointer, }) as unknown as Parameters[0]; - const area = () => new DOMRect(0, 0, 200, 400); - it('a pointer outside the menu is over nothing; inside it, and from the keyboard, the nearest entry', () => { - const rule = menuCollision(area); + it("the editor's rule: a pointer outside the menu is over nothing; inside it, and from the keyboard, the nearest entry", async () => { + start(); + await flush(); + vi.spyOn(screen.getByTestId('design-menu-area'), 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 200, 400)); + const rule = collisionRule.current!; expect(rule(args({ x: 900, y: 900 }))).toEqual([]); - expect(rule(args({ x: 50, y: 10 })).map((c) => c.id)).toEqual(['home']); - expect(rule(args(null)).map((c) => c.id)).toEqual(['home']); + expect((rule(args({ x: 50, y: 10 })) as Array<{ id: string }>).map((c) => c.id)).toEqual(['home']); + expect((rule(args(null)) as Array<{ id: string }>).map((c) => c.id)).toEqual(['home']); expect(closestCenter(args({ x: 900, y: 900 })).map((c) => c.id)).toEqual(['home']); // CONTROL: the old rule moved it }); - it("is the editor's rule, and a drop it answers nothing for moves nothing", async () => { + it('a drop the rule answers nothing for moves nothing', async () => { start(); await flush(); - // jsdom lays the menu out at no size, so any pointer off its origin is outside it. - expect(collisionRule.current!(args({ x: 900, y: 900 }))).toEqual([]); act(() => dragEnd.current!({ active: { id: 'home' }, over: null })); expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', []]]); }); From 1b45dda9552f753336ad89a34b56c3785d4e2711 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 02:09:31 +0000 Subject: [PATCH 5/9] fix(i18n): the design mode menu's new sentences in every locale pack (zh-Hant regenerated) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzhpykmQZe1yMupC2CU --- ui/packages/i18n/src/locales/ar.ts | 3 +++ ui/packages/i18n/src/locales/de.ts | 3 +++ ui/packages/i18n/src/locales/es.ts | 3 +++ ui/packages/i18n/src/locales/fr.ts | 3 +++ ui/packages/i18n/src/locales/ja.ts | 3 +++ ui/packages/i18n/src/locales/ko.ts | 3 +++ ui/packages/i18n/src/locales/pt-BR.ts | 3 +++ ui/packages/i18n/src/locales/ru.ts | 3 +++ ui/packages/i18n/src/locales/zh-Hant.ts | 3 +++ 9 files changed, 27 insertions(+) diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index c7b1e1467e0..27ee604a449 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -3944,6 +3944,9 @@ const ar = { pendingDraft: 'لهذا التطبيق تغييرات غير منشورة في Studio. انشرها أو تجاهلها هناك، ثم احفظ مرة أخرى.', noVersion: 'حزمة هذا التطبيق لا تذكر إصدارًا، لذا لا يمكن تخصيص قائمته.', notWritable: 'حزمة تخصيص هذا التطبيق غير قابلة للكتابة، لذا لا يمكن حفظ قائمته.', + storedUnread: 'تعذّرت قراءة القائمة المحفوظة لهذا التطبيق، لذا لم يُحفظ شيء.', + publishedMoved: 'نشر شخص آخر قائمة هذا التطبيق أثناء الحفظ، لذا لم يُحفظ شيء. احفظ مرة أخرى لتطبيق تغييراتك فوق تغييراته.', + keyboardHint: 'اسحب عنصرًا لنقله، أو ركّز عليه واضغط مفتاح المسافة ثم مفاتيح الأسهم. يفتحه مفتاح Enter.', newDashboard: 'لوحة معلومات جديدة…', newDashboardTitle: 'لوحة معلومات جديدة', newReport: 'تقرير جديد…', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index d461322c859..aef71d438c1 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -3621,6 +3621,9 @@ const de = { pendingDraft: 'Diese App hat unveröffentlichte Änderungen in Studio. Veröffentlichen oder verwerfen Sie sie dort und speichern Sie dann erneut.', noVersion: 'Das Paket dieser App nennt keine Version, daher kann ihr Menü nicht angepasst werden.', notWritable: 'Das Anpassungspaket dieser App ist nicht beschreibbar, daher kann ihr Menü nicht gespeichert werden.', + storedUnread: 'Das gespeicherte Menü dieser App konnte nicht gelesen werden, daher wurde nichts gespeichert.', + publishedMoved: 'Jemand hat das Menü dieser App während des Speicherns veröffentlicht, daher wurde nichts gespeichert. Speichern Sie erneut, um Ihre Änderungen darauf anzuwenden.', + keyboardHint: 'Ziehen Sie einen Eintrag, um ihn zu verschieben, oder fokussieren Sie ihn und drücken Sie die Leertaste, dann die Pfeiltasten. Die Eingabetaste öffnet ihn.', newDashboard: 'Neues Dashboard…', newDashboardTitle: 'Neues Dashboard', newReport: 'Neuer Bericht…', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 453f172b382..a7be04cd135 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -3703,6 +3703,9 @@ const es = { pendingDraft: 'Esta aplicación tiene cambios sin publicar en Studio. Publícalos o descártalos allí y vuelve a guardar.', noVersion: 'El paquete de esta aplicación no declara versión, así que su menú no se puede personalizar.', notWritable: 'El paquete de personalización de esta aplicación no se puede escribir, así que su menú no se puede guardar.', + storedUnread: 'No se pudo leer el menú guardado de esta aplicación, así que no se guardó nada.', + publishedMoved: 'Alguien publicó el menú de esta aplicación mientras guardabas, así que no se guardó nada. Vuelve a guardar para aplicar tus cambios sobre los suyos.', + keyboardHint: 'Arrastra un elemento para moverlo, o enfócalo y pulsa Espacio y luego las flechas. Intro lo abre.', newDashboard: 'Nuevo panel…', newDashboardTitle: 'Nuevo panel', newReport: 'Nuevo informe…', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index ddb3e55996f..e91702fd735 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -3699,6 +3699,9 @@ const fr = { pendingDraft: 'Cette application a des modifications non publiées dans Studio. Publiez-les ou annulez-les là-bas, puis enregistrez à nouveau.', noVersion: 'Le package de cette application ne déclare aucune version : son menu ne peut pas être personnalisé.', notWritable: 'Le package de personnalisation de cette application n’est pas modifiable : son menu ne peut pas être enregistré.', + storedUnread: 'Le menu enregistré de cette application n’a pas pu être lu : rien n’a été enregistré.', + publishedMoved: 'Quelqu’un a publié le menu de cette application pendant l’enregistrement : rien n’a été enregistré. Enregistrez de nouveau pour appliquer vos modifications par-dessus les siennes.', + keyboardHint: 'Faites glisser un élément pour le déplacer, ou placez le focus dessus et appuyez sur Espace, puis sur les flèches. Entrée l’ouvre.', newDashboard: 'Nouveau tableau de bord…', newDashboardTitle: 'Nouveau tableau de bord', newReport: 'Nouveau rapport…', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index ca02f6971dc..0b7d0ce487f 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -3623,6 +3623,9 @@ const ja = { pendingDraft: 'このアプリには Studio に未公開の変更があります。そちらで公開または破棄してから、もう一度保存してください。', noVersion: 'このアプリのパッケージにはバージョンがないため、メニューをカスタマイズできません。', notWritable: 'このアプリのカスタマイズパッケージに書き込めないため、メニューを保存できません。', + storedUnread: 'このアプリの保存済みメニューを読み取れなかったため、何も保存されませんでした。', + publishedMoved: '保存中に他のユーザーがこのアプリのメニューを公開したため、何も保存されませんでした。もう一度保存すると、その変更の上にあなたの変更が適用されます。', + keyboardHint: '項目をドラッグして移動するか、フォーカスしてスペースキーを押し、矢印キーで移動します。Enter キーで開きます。', newDashboard: '新しいダッシュボード…', newDashboardTitle: '新しいダッシュボード', newReport: '新規レポート…', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 0b53d3244f4..8c4c1ae9e1d 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -3621,6 +3621,9 @@ const ko = { pendingDraft: '이 앱에는 Studio에 게시되지 않은 변경 사항이 있습니다. 그곳에서 게시하거나 취소한 뒤 다시 저장하세요.', noVersion: '이 앱의 패키지에 버전이 없어 메뉴를 사용자 지정할 수 없습니다.', notWritable: '이 앱의 사용자 지정 패키지에 쓸 수 없어 메뉴를 저장할 수 없습니다.', + storedUnread: '이 앱의 저장된 메뉴를 읽을 수 없어 아무것도 저장하지 않았습니다.', + publishedMoved: '저장하는 동안 다른 사용자가 이 앱의 메뉴를 게시하여 아무것도 저장하지 않았습니다. 다시 저장하면 그 변경 위에 내 변경이 적용됩니다.', + keyboardHint: '항목을 끌어서 옮기거나, 포커스한 뒤 스페이스 키를 누르고 화살표 키로 옮기세요. Enter 키를 누르면 열립니다.', newDashboard: '새 대시보드…', newDashboardTitle: '새 대시보드', newReport: '새 보고서…', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 568f88e9671..6f878c394c7 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -3698,6 +3698,9 @@ const pt = { pendingDraft: 'Este aplicativo tem alterações não publicadas no Studio. Publique ou descarte-as lá e salve novamente.', noVersion: 'O pacote deste aplicativo não declara versão, então o menu não pode ser personalizado.', notWritable: 'O pacote de personalização deste aplicativo não pode ser gravado, então o menu não pode ser salvo.', + storedUnread: 'Não foi possível ler o menu salvo deste aplicativo, então nada foi salvo.', + publishedMoved: 'Alguém publicou o menu deste aplicativo enquanto você salvava, então nada foi salvo. Salve novamente para aplicar suas alterações sobre as dele.', + keyboardHint: 'Arraste um item para movê-lo, ou foque-o e pressione Espaço e depois as setas. Enter o abre.', newDashboard: 'Novo painel…', newDashboardTitle: 'Novo painel', newReport: 'Novo relatório…', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index be58532538d..21913f194b1 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -3790,6 +3790,9 @@ const ru = { pendingDraft: 'В Studio есть неопубликованные изменения этого приложения. Опубликуйте или отмените их там и сохраните снова.', noVersion: 'Пакет этого приложения не указывает версию, поэтому меню нельзя настроить.', notWritable: 'Пакет настроек этого приложения недоступен для записи, поэтому меню нельзя сохранить.', + storedUnread: 'Не удалось прочитать сохранённое меню этого приложения, поэтому ничего не сохранено.', + publishedMoved: 'Кто-то опубликовал меню этого приложения во время сохранения, поэтому ничего не сохранено. Сохраните ещё раз, чтобы применить свои изменения поверх его изменений.', + keyboardHint: 'Перетащите пункт, чтобы переместить его, или выделите его и нажмите Пробел, затем клавиши со стрелками. Enter открывает его.', newDashboard: 'Новая панель…', newDashboardTitle: 'Новая панель', newReport: 'Новый отчёт…', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index fa5950b9dee..6b3956dedff 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -3764,6 +3764,9 @@ const zhHant = { pendingDraft: '這個應用在 Studio 裡有未釋出的改動。請先在那裡釋出或丟棄,再儲存。', noVersion: '這個應用所在的包沒有宣告版本,選單無法定製。', notWritable: '這個應用的定製包不可寫,選單無法儲存。', + storedUnread: '無法讀取這個應用已儲存的選單,所以沒有儲存任何內容。', + publishedMoved: '儲存期間有人釋出了這個應用的選單,所以沒有儲存任何內容。再次儲存即可把你的修改應用在他們的修改之上。', + keyboardHint: '拖動選單項即可移動;也可以聚焦後按空格鍵,再用方向鍵移動。按回車鍵開啟。', newDashboard: '新建儀表盤…', newDashboardTitle: '新建儀表盤', newReport: '新建報表…', From 2f8683f3380746799c146b460eb74a1c5bbafe52 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 02:52:34 +0000 Subject: [PATCH 6/9] fix(app-shell): report editing is its own entry, mutually exclusive with design mode Design mode's Reports picker links existing reports only: the New report row, the report kind of the menu create, and the design-mode report slot are removed. The reports index offers New report, gated as the builder. The design mode's enter refuses, with a prompt, while a dashboard or report editor holds it out; those editors are not offered while the mode is on. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzhpykmQZe1yMupC2CU --- .../app-shell/src/layout/DesignModeMenu.tsx | 116 +----------- .../app-shell/src/layout/SidebarAppMenu.tsx | 5 + .../__tests__/DesignModeMenu-36363.test.tsx | 167 ++++------------- .../designModeMenuCreate-36364.test.ts | 58 +----- .../app-shell/src/layout/designMode.tsx | 63 ++++++- .../src/layout/designModeMenuCreate.ts | 58 ++---- .../src/layout/designModeReportSlot.ts | 83 --------- .../src/views/AppReportIndexView.tsx | 27 ++- .../src/views/DashboardInPageEditor.tsx | 14 +- .../ReportNewPage.menuSlot-36364.test.tsx | 171 ------------------ .../app-shell/src/views/ReportNewPage.tsx | 55 ++---- .../app-shell/src/views/ReportView.tsx | 12 +- .../__tests__/de-quote-pairing-3876.test.ts | 9 +- ui/packages/i18n/src/locales/ar.ts | 5 +- ui/packages/i18n/src/locales/de.ts | 5 +- ui/packages/i18n/src/locales/en.ts | 5 +- ui/packages/i18n/src/locales/es.ts | 5 +- ui/packages/i18n/src/locales/fr.ts | 5 +- ui/packages/i18n/src/locales/ja.ts | 5 +- ui/packages/i18n/src/locales/ko.ts | 5 +- ui/packages/i18n/src/locales/pt-BR.ts | 5 +- ui/packages/i18n/src/locales/ru.ts | 5 +- ui/packages/i18n/src/locales/zh-Hans.ts | 5 +- ui/packages/i18n/src/locales/zh-Hant.ts | 5 +- 24 files changed, 230 insertions(+), 663 deletions(-) delete mode 100644 ui/packages/app-shell/src/layout/designModeReportSlot.ts delete mode 100644 ui/packages/app-shell/src/views/ReportNewPage.menuSlot-36364.test.tsx diff --git a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx index 9dc4020202a..e4b6faf0563 100644 --- a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx +++ b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx @@ -46,10 +46,9 @@ * place, and the mode saves at once, every other staged change with it * (`saveAppMenuWithNewItem`); then the mode is left and the new dashboard * opens for editing (`dashboardEditArrival`). 「Cancel」 writes nothing. - * In 「Reports」 the first row is 「New report…」: a report needs a data source - * and a measure, so the place stays held and the report builder opens; its - * Save creates the report and saves the mode the same way - * (`designModeReportSlot`), and its Close drops the place, writing nothing. + * 「Reports」 lists only reports that exist (objectstack#36692, the + * 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. * * Every edit is staged with the mode (`useDesignModeChange`), under one key * for the app's menu: the mode's 「Save」 writes it (`saveAppMenu`), its @@ -68,7 +67,7 @@ */ import * as React from 'react'; -import { Link, useLocation, useNavigate } from 'react-router-dom'; +import { Link, useNavigate } from 'react-router-dom'; import { toast } from 'sonner'; import { DndContext, @@ -177,7 +176,6 @@ import { } from './designModeMenuSave.js'; import { freeItemName, isNewMenuItemKind, saveAppMenuWithNewItem, type NewMenuItemKind } from './designModeMenuCreate.js'; import { dashboardEditArrival } from './designModeArrival.js'; -import { offerNewReportSlot, withdrawNewReportSlot, type NewReportSlot } from './designModeReportSlot.js'; /** * The group label's icon-mode hiding, as the sidebar's own labels declare it @@ -494,83 +492,6 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso return true; }; - // objectstack#36364 (report half) — 「New report…」: a report cannot be - // made from a name (the spec wants `dataset` and `values`), so the place - // stays held and the report builder opens at `reports/new`. The builder - // saves through the slot offered here (`designModeReportSlot`): the report - // is created in the menu's package and its entry saved in the held place - // with every other staged change, in one act; nothing is written before. - // The builder's Close drops the place. Resolves `false` when nothing was - // saved (the mode has said why); the builder stays open for another try. - const [buildingReport, setBuildingReport] = React.useState(false); - const saveNewReport = async (name: string, label: string, body: Record): Promise => { - if (!addAt) return false; - // A report entry with no label shows its machine name (only an object, - // view or dashboard entry inherits its target's label), so the entry - // carries the name the reader gave the report. - const entry = { ...entryFor('report', name, newEntryId([...menu, ...(storedMenu ?? [])])), label }; - const itemTexts = { - ...texts, - itemPendingDraft: t('designMode.menu.newItemPendingDraft', { - defaultValue: 'A draft with this name is already pending. Try again.', - }), - itemLeft: t('designMode.menu.newReportLeft', { - defaultValue: 'The new report "{{name}}" could not be removed again; remove it in Studio.', - name: label, - }), - }; - const saved = await saveWith(insertEntry(menu, addAt.parentId, addAt.index, entry), (navigation) => - saveAppMenuWithNewItem( - { appName, packageId, served, navigation, item: { kind: 'report', name, label, body } }, - itemTexts, - consoleAppMenuDoors(client as never), - ), - ); - if (!saved) return false; - setAddAt(null); - setBuildingReport(false); - return true; - }; - // The builder's address the held place waits on. - const newReportPath = `${basePath}/reports/new`; - const saveNewReportRef = React.useRef(saveNewReport); - React.useLayoutEffect(() => { - saveNewReportRef.current = saveNewReport; - }); - React.useEffect(() => { - if (!buildingReport) return; - const slot: NewReportSlot = { - path: newReportPath, - save: (name, label, body) => saveNewReportRef.current(name, label, body), - cancel: () => { - setBuildingReport(false); - setAddAt(null); - }, - }; - offerNewReportSlot(slot); - // Withdrawn when the place is no longer held, and when the menu unmounts - // (the design mode ended): the builder then saves on its own, off the menu. - return () => withdrawNewReportSlot(slot); - }, [buildingReport, newReportPath]); - // Leaving the builder another way than its Save or Close (a menu link, the - // browser's Back) drops the place too, so no held row waits for a builder - // that is gone. Read once the builder has been reached. - const { pathname } = useLocation(); - const [reachedBuilder, setReachedBuilder] = React.useState(false); - const onBuilder = pathname === newReportPath || pathname.endsWith(newReportPath); - if (buildingReport && onBuilder && !reachedBuilder) setReachedBuilder(true); - if (!buildingReport && reachedBuilder) setReachedBuilder(false); - if (buildingReport && reachedBuilder && !onBuilder) { - setBuildingReport(false); - setReachedBuilder(false); - setAddAt(null); - } - const startNewReport = () => { - if (!addAt) return; - setBuildingReport(true); - navigate(newReportPath); - }; - const renderLeaf = (entry: MenuEntry, depth: number) => { const id = String(entry.id); const place = placeOf(menu, id); @@ -611,7 +532,7 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso const renderEntries = (entries: Menu, parentId: string | null, depth: number): React.ReactNode[] => { const rows: React.ReactNode[] = []; entries.forEach((entry, index) => { - if (addAt && addAt.parentId === parentId && addAt.index === index) rows.push(); + if (addAt && addAt.parentId === parentId && addAt.index === index) rows.push(); if (isGroup(entry)) { const gid = String(entry.id); rows.push( @@ -632,7 +553,7 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso rows.push(renderLeaf(entry, depth)); } }); - if (addAt && addAt.parentId === parentId && addAt.index >= entries.length) rows.push(); + if (addAt && addAt.parentId === parentId && addAt.index >= entries.length) rows.push(); // Another package's group takes no own entry: no 「Add menu item」, no drop at its end. if (foreignGroup(parentId)) return rows; rows.push( @@ -682,14 +603,13 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso - {addAt && !buildingReport && ( + {addAt && ( setAddAt(null)} onPick={(kind, name, link) => pick(entryFor(kind, name, newEntryId([...menu, ...(storedMenu ?? [])]), link))} onCreate={createItem} - onNewReport={startNewReport} language={language} /> )} @@ -779,14 +699,12 @@ function MenuLeaf({ ); } -function Placeholder({ depth, buildingReport }: { depth: number; buildingReport?: boolean }) { +function Placeholder({ depth }: { depth: number }) { const { t } = useObjectTranslation(); return (
  • - {buildingReport - ? t('designMode.menu.newReport', { defaultValue: 'New report…' }) - : t('designMode.menu.placeholder', { defaultValue: 'Choose a menu item…' })} + {t('designMode.menu.placeholder', { defaultValue: 'Choose a menu item…' })}
  • ); @@ -983,7 +901,6 @@ function MenuItemPicker({ onClose, onPick, onCreate, - onNewReport, language, }: { packageId: string; @@ -992,8 +909,6 @@ function MenuItemPicker({ 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. */ onCreate: (kind: NewMenuItemKind, label: string, taken: readonly string[]) => Promise; - /** Build a new report for the held place, in the report builder. */ - onNewReport: () => void; language: string; }) { const { t } = useObjectTranslation(); @@ -1118,19 +1033,6 @@ function MenuItemPicker({ )} - {kind === 'report' && ( -
  • - -
  • - )} {loading ? (
  • {t('designMode.menu.loading', { defaultValue: 'Loading…' })}
  • ) : offered.length === 0 ? ( diff --git a/ui/packages/app-shell/src/layout/SidebarAppMenu.tsx b/ui/packages/app-shell/src/layout/SidebarAppMenu.tsx index d33dc388b1e..ab346d49f42 100644 --- a/ui/packages/app-shell/src/layout/SidebarAppMenu.tsx +++ b/ui/packages/app-shell/src/layout/SidebarAppMenu.tsx @@ -74,6 +74,11 @@ export const APP_MENU_SEARCH_FROM = 8; * (objectstack#36363: its changes are saved as this environment's * customization), except where the customization door is walled off for this * caller. Not drawn where no shell holds the mode, nor while the mode is on. + * + * objectstack#36692 — while a dashboard's or a report's own editor is open + * it stays drawn, and choosing it refuses, saying to save or cancel those + * changes first: the mode's `enter` refuses while an editor holds it out + * (`useHoldDesignModeOut`), so the screen never shows two Save/Cancel sets. */ function useEnterDesignMode(apps: Parameters[0], activeAppName: string): (() => void) | null { const entry = useStudioEntryGate(appStudioDesignPath(matchAppBySegment(apps, activeAppName), true)); 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 a49c88d43c4..ca85bad444b 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, useNavigate } from 'react-router-dom'; +import { MemoryRouter, useLocation } from 'react-router-dom'; import { SidebarProvider } from '@object-ui/components'; import { NavigationRenderer } from '@object-ui/layout'; import type { NavigationItem } from '@object-ui/types'; @@ -144,7 +144,6 @@ import DesignModeMenu from '../DesignModeMenu'; import { closestCenter, type CollisionDetection } from '@dnd-kit/core'; import { confirmUnsavedLeave } from '../../chrome/unsavedEdits'; import { __resetDefaultLocale } from '../designModeMenuSave'; -import { newReportSlotFor } from '../designModeReportSlot'; const NAVIGATION = [ { id: 'home', type: 'report', reportName: 'pipeline', label: 'Home' }, @@ -819,135 +818,45 @@ async function openReports() { return picker; } -/** A link elsewhere in the app, as the sidebar would follow one. */ -function GoElsewhere() { - const navigate = useNavigate(); - return ( - - ); -} - -function startOnBuilderPath() { - render( - - - - - , - ); - fireEvent.click(screen.getByText('enter')); -} - -const REPORT_BODY = { - label: 'Payment analysis', - type: 'summary', - dataset: 'invoice_metrics', - values: ['invoice_count'], - chart: { type: 'metric', xAxis: '', yAxis: 'invoice_count' }, -}; - -describe('a new report from 「Add menu item」 (objectstack#36364, report half)', () => { - it('「Reports」 lists 「New report…」 first; it holds the place and opens the report builder, writing nothing', async () => { - startOnBuilderPath(); - const picker = await openReports(); - const rows = within(within(picker).getByTestId('design-menu-picker-rows')).getAllByRole('button').map((b) => b.textContent); - // The report the menu already opens (Home → pipeline) is not offered again. - expect(rows).toEqual(['New report…']); - fireEvent.click(within(picker).getByTestId('design-menu-picker-new-report')); - await flush(); - expect(screen.queryByTestId('design-menu-picker')).toBeNull(); - expect(screen.getByTestId('landing')).toHaveTextContent('/apps/crm/reports/new null'); - // The place stays held, saying what it waits for. - expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', ['…']]]); - expect(screen.getByTestId('design-menu-placeholder')).toHaveTextContent('New report…'); - expect(newReportSlotFor('/apps/crm/reports/new')).not.toBeNull(); - expect(newReportSlotFor('/apps/hr/reports/new')).toBeNull(); - expect(written).toEqual([]); - }); - - it('the builder\'s Save: the report, then the menu with its entry in the held place and every other staged edit; the mode is left', async () => { - startOnBuilderPath(); - await act_on('accounts', 'Move up'); // another staged edit, saved with it - const picker = await openReports(); - fireEvent.click(within(picker).getByTestId('design-menu-picker-new-report')); - await flush(); - const slot = newReportSlotFor('/apps/crm/reports/new')!; - let saved: boolean | undefined; - await act(async () => { - saved = await slot.save('payment_analysis', 'Payment analysis', { ...REPORT_BODY, name: 'payment_analysis' }); - }); - await flush(); - - expect(saved).toBe(true); - expect(written.map(([verb, type, name]) => `${verb} ${type} ${name}`)).toEqual([ - 'save report payment_analysis', - 'publish report payment_analysis', - 'save app crm', - 'publish app crm', - ]); - expect(written[0][3]).toEqual({ ...REPORT_BODY, name: 'payment_analysis' }); - expect(written[0][4]).toEqual({ mode: 'draft', ifNoneMatch: '*', packageId: 'com.acme.crm' }); - const navigation = (written[2][3] as { navigation: Array<{ id: string; children?: unknown[] }> }).navigation; - expect(navigation[1].children!.map((c) => (c as { id: string }).id)).toEqual(['accounts', 'leads']); - expect(navigation[2].children).toEqual([ - { id: 'nav_item_1', type: 'report', reportName: 'payment_analysis', label: 'Payment analysis' }, - ]); - expect(screen.queryByTestId('design-mode-bar')).toBeNull(); - expect(newReportSlotFor('/apps/crm/reports/new')).toBeNull(); - }); - - it('a refused menu removes the new report; the mode, the held place and the other staged edits stay', async () => { - server.appSave = new Error('the app was refused'); - startOnBuilderPath(); - await act_on('accounts', 'Move up'); - const picker = await openReports(); - fireEvent.click(within(picker).getByTestId('design-menu-picker-new-report')); - await flush(); - let saved: boolean | undefined; - await act(async () => { - saved = await newReportSlotFor('/apps/crm/reports/new')!.save('payment_analysis', 'Payment analysis', { ...REPORT_BODY, name: 'payment_analysis' }); - }); - await flush(); - - expect(saved).toBe(false); - expect(written.map(([verb, type, name, opt]) => `${verb} ${type} ${name} ${verb === 'reset' ? JSON.stringify(opt) : ''}`.trim())).toEqual([ - 'save report payment_analysis', - 'publish report payment_analysis', - 'save app crm', - 'reset report payment_analysis {"packageId":"com.acme.crm"}', - ]); - expect(toastError).toHaveBeenCalledWith('Some changes were not saved: the app was refused'); - expect(screen.getByTestId('design-mode-bar')).toBeInTheDocument(); - expect(order()).toEqual(['home', ['sales', ['accounts', 'leads']], ['insights', ['…']]]); - expect(newReportSlotFor('/apps/crm/reports/new')).not.toBeNull(); - }); - - it('the builder\'s Close drops the held place and writes nothing; the mode and its other edits stay', async () => { - startOnBuilderPath(); - await act_on('accounts', 'Move up'); - const picker = await openReports(); - fireEvent.click(within(picker).getByTestId('design-menu-picker-new-report')); - await flush(); - act(() => newReportSlotFor('/apps/crm/reports/new')!.cancel()); - await flush(); - expect(order()).toEqual(['home', ['sales', ['accounts', 'leads']], ['insights', []]]); - expect(newReportSlotFor('/apps/crm/reports/new')).toBeNull(); - expect(written).toEqual([]); - expect(screen.getByTestId('design-mode-save')).toBeEnabled(); +/** + * objectstack#36692 — the design mode stops hosting the report builder (the + * maintainer's 「照 Twenty 分开」): 「Reports」 only links reports that exist; + * a new report is made from the reports index, with its own Save. + */ +describe('「Reports」 links existing reports only (objectstack#36692)', () => { + it('lists the reports not in the menu yet, and no 「New report…」 row', async () => { + listed.report = [ + { name: 'pipeline', label: 'Pipeline' }, + { name: 'revenue_by_month', label: 'Revenue by month' }, + ]; + try { + start(); + const picker = await openReports(); + const rows = within(within(picker).getByTestId('design-menu-picker-rows')).getAllByRole('button').map((b) => b.textContent); + // The report the menu already opens (Home → pipeline) is not offered again. + expect(rows).toEqual(['Revenue by month']); + expect(within(picker).queryByTestId('design-menu-picker-new-report')).toBeNull(); + expect(within(picker).queryByText('New report…')).toBeNull(); + } finally { + listed.report = [{ name: 'pipeline', label: 'Pipeline' }]; + } }); - it('leaving the builder another way drops the held place too', async () => { - startOnBuilderPath(); - const picker = await openReports(); - fireEvent.click(within(picker).getByTestId('design-menu-picker-new-report')); - await flush(); - fireEvent.click(screen.getByText('go elsewhere')); - await flush(); - expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', []]]); - expect(newReportSlotFor('/apps/crm/reports/new')).toBeNull(); - expect(written).toEqual([]); + it('picking one links it in the held place, staged with the mode; nothing is written, nothing navigates', async () => { + listed.report = [{ name: 'revenue_by_month', label: 'Revenue by month' }]; + try { + startWithLanding(); + const picker = await openReports(); + fireEvent.click(within(picker).getByRole('button', { name: 'Revenue by month' })); + await flush(); + expect(screen.queryByTestId('design-menu-picker')).toBeNull(); + expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', ['nav_item_1']]]); + expect(written).toEqual([]); + expect(screen.getByTestId('landing')).toHaveTextContent('/apps/crm null'); + expect(screen.getByTestId('design-mode-save')).toBeEnabled(); + } finally { + listed.report = [{ name: 'pipeline', label: 'Pipeline' }]; + } }); }); diff --git a/ui/packages/app-shell/src/layout/__tests__/designModeMenuCreate-36364.test.ts b/ui/packages/app-shell/src/layout/__tests__/designModeMenuCreate-36364.test.ts index f46950b6c10..df94c44b7e3 100644 --- a/ui/packages/app-shell/src/layout/__tests__/designModeMenuCreate-36364.test.ts +++ b/ui/packages/app-shell/src/layout/__tests__/designModeMenuCreate-36364.test.ts @@ -24,7 +24,9 @@ import { loadHanRomanizer } from '../../views/metadata-admin/romanizeHan'; import { inShownOrder, insertEntry, withEntryIds, type Menu } from '../designModeMenuModel'; import type { AppMenuSaveDoors } from '../designModeMenuSave'; import { + NEW_MENU_ITEM_KINDS, freeItemName, + isNewMenuItemKind, newItemBody, saveAppMenuWithNewItem, uniqueItemName, @@ -223,56 +225,10 @@ describe('the new dashboard’s entry in a menu that carries `order` (objectstac }); }); -describe('a new report from the design mode (objectstack#36364, report half)', () => { - const REPORT_BODY = { - label: '回款分析', - type: 'summary', - dataset: 'invoice_metrics', - values: ['invoice_count'], - chart: { type: 'metric', xAxis: '', yAxis: 'invoice_count' }, - }; - const REPORT: NewMenuItem = { kind: 'report', name: 'hui_kuan_fen_xi', label: '回款分析', body: REPORT_BODY }; - const REPORT_ENTRY = { id: 'nav_item_1', type: 'report', reportName: 'hui_kuan_fen_xi' }; - const reportInput = { - ...input, - navigation: [{ id: 'insights', type: 'group', label: 'Insights', children: [REPORT_ENTRY] }] as Menu, - item: REPORT, - }; - - it('is created as the report builder made it, under the new name', () => { - expect(newItemBody(REPORT)).toEqual({ ...REPORT_BODY, name: 'hui_kuan_fen_xi' }); - }); - - it("is created and published in the menu's package, then the menu, in that order", async () => { - const { d, calls } = doors({ writable: false, version: '1.4.0' }); - await saveAppMenuWithNewItem(reportInput, TEXTS, d); - expect(calls.map(([verb, type]) => `${verb} ${type ?? ''}`.trim())).toEqual([ - 'ensure com.acme.crm', - 'save report', - 'publish report', - 'save app', - 'publish app', - ]); - expect(calls[1]).toEqual([ - 'save', - 'report', - 'hui_kuan_fen_xi', - { ...REPORT_BODY, name: 'hui_kuan_fen_xi' }, - { mode: 'draft', ifNoneMatch: '*', packageId: 'com.acme.crm.custom' }, - ]); - expect(calls[2]).toEqual(['publish', 'report', 'hui_kuan_fen_xi', { packageId: 'com.acme.crm.custom' }]); - }); - - it('a refused menu removes the report it was made for', async () => { - const refused = new Error('the app publish was refused'); - const { d, calls } = doors({ writable: true, refuse: ([verb, type]) => (verb === 'publish' && type === 'app' ? refused : null) }); - await expect(saveAppMenuWithNewItem(reportInput, TEXTS, d)).rejects.toBe(refused); - expect(calls.at(-1)).toEqual(['reset', 'report', 'hui_kuan_fen_xi', { packageId: 'com.acme.crm' }]); - }); - - it('where the menu cannot be saved, no report is created', async () => { - const { d, calls } = doors({ listed: false, writable: true }); - await expect(saveAppMenuWithNewItem(reportInput, TEXTS, d)).rejects.toThrow('not listed'); - expect(calls).toEqual([]); +describe('no report is created from the design mode (objectstack#36692)', () => { + it('a dashboard is the one kind made from a name; a report is made from the reports index', () => { + expect(NEW_MENU_ITEM_KINDS).toEqual(['dashboard']); + expect(isNewMenuItemKind('dashboard')).toBe(true); + expect(isNewMenuItemKind('report')).toBe(false); }); }); diff --git a/ui/packages/app-shell/src/layout/designMode.tsx b/ui/packages/app-shell/src/layout/designMode.tsx index 06051a33303..473cab2c738 100644 --- a/ui/packages/app-shell/src/layout/designMode.tsx +++ b/ui/packages/app-shell/src/layout/designMode.tsx @@ -44,6 +44,21 @@ * 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. * + * ## What the mode excludes + * + * A dashboard's and a report's own editors are not the mode's: each saves on + * its own, with its own 「Save」 in its page header (objectstack#36692, the + * maintainer's ruling to keep them two entries, as Twenty does). So the + * screen never shows two Save/Cancel sets, and no editor outlives a mode + * that has ended, the two exclude each other, both ways, through this one + * hold: + * + * - while the mode is on, those editors are not offered + * ({@link useDesignModeActive}); + * - while one of them is open it holds the mode out + * ({@link useHoldDesignModeOut}), and entering refuses, saying to save or + * cancel those changes first. + * * Who may enter is the header button's gate (`useAppStudioEntry`, a workspace * administrator holding `manage_metadata`), read where the button is drawn * (`ShellPageActions`). The app's package need not be writable: a read-only @@ -79,8 +94,11 @@ export interface DesignModeValue { 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; + /** + * Turn the mode on for the app on screen; `false`, and the reason said, + * while a dashboard or report editor holds the mode out. + */ + readonly enter: () => boolean; /** Drop every staged change and leave the mode. */ readonly cancel: () => void; /** Commit every staged change, then leave the mode; `false` when one failed. */ @@ -93,6 +111,8 @@ interface DesignModeStore extends DesignModeValue { readonly unstage: (key: string) => void; /** Save every staged change with `change` in `key`'s place; `false` when one failed. */ readonly saveWith: (key: string, change: DesignModeChange) => Promise; + /** Hold the mode out while an editor of its own is open; the answer lets go. */ + readonly holdOut: () => () => void; } const DesignModeContext = React.createContext(null); @@ -132,6 +152,8 @@ export function useDesignModeController({ const { t } = useObjectTranslation(); 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); // Another app: the mode and what it held were the previous app's. if (held.app !== null && held.app !== appName) setHeld(OFF); @@ -146,9 +168,28 @@ export function useDesignModeController({ heldRef.current = held; }); - const enter = React.useCallback(() => { + 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 })); - }, [appName]); + return true; + }, [appName, heldOut, t]); + + const holdOut = React.useCallback(() => { + setHeldOut((n) => n + 1); + let released = false; + return () => { + if (released) return; + released = true; + setHeldOut((n) => n - 1); + }; + }, []); const cancel = React.useCallback(() => { setHeld(OFF); @@ -229,8 +270,8 @@ export function useDesignModeController({ }, [dirty, leaveMessage, appBasePath]); return React.useMemo( - () => ({ active, dirty, saving, enter, cancel, save, changes, stage, unstage, saveWith }), - [active, dirty, saving, enter, cancel, save, changes, stage, unstage, saveWith], + () => ({ active, dirty, saving, enter, cancel, save, changes, stage, unstage, saveWith, holdOut }), + [active, dirty, saving, enter, cancel, save, changes, stage, unstage, saveWith, holdOut], ); } @@ -249,6 +290,16 @@ export function useDesignModeActive(): boolean { return React.useContext(DesignModeContext)?.active ?? false; } +/** + * 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 + * (objectstack#36692). Outside a shell that holds the mode, nothing. + */ +export function useHoldDesignModeOut(open: boolean): void { + const holdOut = React.useContext(DesignModeContext)?.holdOut; + React.useEffect(() => (open && holdOut ? holdOut() : undefined), [open, holdOut]); +} + /** * 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), diff --git a/ui/packages/app-shell/src/layout/designModeMenuCreate.ts b/ui/packages/app-shell/src/layout/designModeMenuCreate.ts index 6d02915e796..2f519b910b8 100644 --- a/ui/packages/app-shell/src/layout/designModeMenuCreate.ts +++ b/ui/packages/app-shell/src/layout/designModeMenuCreate.ts @@ -15,9 +15,8 @@ * * 1. every check of the menu save is made first, and nothing is written * before they pass; - * 2. the item is created and published in that package (a dashboard empty, - * `saveDashboardInPlace`; a report as the builder made it, - * `saveAndPublishInPackage`), so everyone the menu shows it to finds it, + * 2. the item is created, empty, and published in that package + * (`saveDashboardInPlace`), so everyone the menu shows it to finds it, * never a missing one; * 3. the menu is written and published (`writeAppMenu`), the new entry and * every other staged menu edit with it; @@ -25,12 +24,9 @@ * (the item's delete in its package), and the refusal is said. Should that * removal be refused too, the refusal says the item was left. * - * A dashboard is created from its name alone. A report is not: the spec - * refuses a report without `dataset` and `values`, so 「New report…」 opens - * the report builder instead (the seat's option A), and the report is - * created here, by the same steps, with the body the builder made, once the - * builder saves (`designModeReportSlot`). Cancelling the builder writes - * nothing. + * Only a dashboard is created here, from its name alone. A report is never + * made from the design mode (objectstack#36692): it is made from the reports + * index, with its own Save, and the menu then links it. * * @module */ @@ -38,7 +34,7 @@ import { emitMetadataRefresh } from '../assistant/assistantBus.js'; import { slugify } from '../views/metadata-admin/createDerive.js'; import { loadHanRomanizer, romanizeHan, romanizerPending } from '../views/metadata-admin/romanizeHan.js'; -import { saveAndPublishInPackage, saveDashboardInPlace } from '../views/runtime-metadata-persistence.js'; +import { saveDashboardInPlace } from '../views/runtime-metadata-persistence.js'; import type { Menu } from './designModeMenuModel.js'; import { prepareAppMenuSave, @@ -51,20 +47,16 @@ import { export const NEW_MENU_ITEM_KINDS = ['dashboard'] as const; export type NewMenuItemKind = (typeof NEW_MENU_ITEM_KINDS)[number]; -/** Every kind a menu entry can be created with: a report comes from the report builder. */ -export type CreatedMenuItemKind = NewMenuItemKind | 'report'; - export function isNewMenuItemKind(kind: string): kind is NewMenuItemKind { return (NEW_MENU_ITEM_KINDS as readonly string[]).includes(kind); } -/** - * The thing to create: its kind, its machine name and the name the reader - * gave it; a report also carries the body the report builder made. - */ -export type NewMenuItem = - | { readonly kind: NewMenuItemKind; readonly name: string; readonly label: string } - | { readonly kind: 'report'; readonly name: string; readonly label: string; readonly body: Record }; +/** The thing to create: its kind, its machine name and the name the reader gave it. */ +export interface NewMenuItem { + readonly kind: NewMenuItemKind; + readonly name: string; + readonly label: string; +} /** The sentences a refused create is said with, in the viewer's language. */ export interface NewMenuItemTexts extends AppMenuSaveTexts { @@ -121,14 +113,9 @@ export async function freeItemName( throw new Error(`No free ${kind} name was found for "${label}".`); } -/** The body a new `kind` is created with: an empty dashboard, or the report the builder made. */ +/** The body a new `kind` is created with: an empty dashboard. */ export function newItemBody(item: NewMenuItem): Record { - switch (item.kind) { - case 'dashboard': - return { name: item.name, label: item.label, widgets: [] }; - case 'report': - return { ...item.body, name: item.name }; - } + return { name: item.name, label: item.label, widgets: [] }; } /** @@ -143,17 +130,12 @@ export async function saveAppMenuWithNewItem( ): Promise { const { item } = input; const prepared = await prepareAppMenuSave(input, texts, doors); - const outcome = - item.kind === 'dashboard' - ? await saveDashboardInPlace( - item.name, - newItemBody(item), - { kind: 'package', packageId: prepared.target }, - { metadataClient: doors.client }, - ) - : await saveAndPublishInPackage(item.kind, item.name, newItemBody(item), prepared.target, { - metadataClient: doors.client, - }); + const outcome = await saveDashboardInPlace( + item.name, + newItemBody(item), + { kind: 'package', packageId: prepared.target }, + { metadataClient: doors.client }, + ); if (outcome === 'pending-draft') throw new Error(texts.itemPendingDraft); try { await writeAppMenu(prepared, texts, doors); diff --git a/ui/packages/app-shell/src/layout/designModeReportSlot.ts b/ui/packages/app-shell/src/layout/designModeReportSlot.ts deleted file mode 100644 index 3f8bc98e837..00000000000 --- a/ui/packages/app-shell/src/layout/designModeReportSlot.ts +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * The place a new report is being built for (objectstack#36364, report half). - * - * 「New report…」 in the design mode's 「Add menu item」 cannot create the - * report from a name: the spec refuses a report without `dataset` and - * `values`. So the menu holds the place (its dashed row stays), offers this - * slot, and opens the report builder at the app's `reports/new`. The builder - * fills it: its Save hands the report here, and the menu creates it in the - * menu's package and saves its entry in the held place with every other - * staged design change, in one act (`saveAppMenuWithNewItem`). Its Close - * cancels: the held place is dropped and nothing is written. - * - * The menu (in the sidebar) and the builder (in the page) are not in one - * tree that could pass a callback down, so the slot is held here, one at a - * time. The menu withdraws it when it unmounts, which is when the design mode - * ends, so the builder never saves into a mode that is gone: without a slot - * it is the plain new-report page. - * - * @module - */ - -import * as React from 'react'; - -/** What the builder's Save and Close do while a menu place waits for the report. */ -export interface NewReportSlot { - /** - * The builder's address the place waits on (`/reports/new`): - * the page there fills it. The address, not the app's name, because the - * console addresses an app by its route segment, which need not be its name. - */ - readonly path: string; - /** - * Create the report `name` with `body` (its `label` the one the builder - * shows) and save the menu with its entry. `false` when nothing was saved: - * the design mode has said why, and the builder stays open. - */ - readonly save: (name: string, label: string, body: Record) => Promise; - /** Drop the held place; nothing is written. */ - readonly cancel: () => void; -} - -let current: NewReportSlot | null = null; -const listeners = new Set<() => void>(); - -function emit(): void { - for (const listener of listeners) listener(); -} - -/** Offer `slot` to the builder, in place of any slot offered before. */ -export function offerNewReportSlot(slot: NewReportSlot): void { - current = slot; - emit(); -} - -/** Withdraw `slot`, if it is still the one offered. */ -export function withdrawNewReportSlot(slot: NewReportSlot): void { - if (current !== slot) return; - current = null; - emit(); -} - -/** Whether the page at `pathname` is the builder `slot` waits on (a router basename in front counts). */ -function isAt(slot: NewReportSlot, pathname: string | undefined): boolean { - return !!pathname && (pathname === slot.path || pathname.endsWith(slot.path)); -} - -/** The slot the page at `pathname` fills, or `null`. */ -export function newReportSlotFor(pathname: string | undefined): NewReportSlot | null { - return current && isAt(current, pathname) ? current : null; -} - -function subscribe(listener: () => void): () => void { - listeners.add(listener); - return () => listeners.delete(listener); -} - -/** The slot the page at `pathname` fills, read as it changes. */ -export function useNewReportSlot(pathname: string | undefined): NewReportSlot | null { - const slot = React.useSyncExternalStore(subscribe, () => current, () => null); - return slot && isAt(slot, pathname) ? slot : null; -} diff --git a/ui/packages/app-shell/src/views/AppReportIndexView.tsx b/ui/packages/app-shell/src/views/AppReportIndexView.tsx index abb11acd574..4ee901d5951 100644 --- a/ui/packages/app-shell/src/views/AppReportIndexView.tsx +++ b/ui/packages/app-shell/src/views/AppReportIndexView.tsx @@ -30,13 +30,23 @@ * list carries no creator. * * Which sections are collapsed is this visit's state only. + * + * ## 「New report」 (objectstack#36692) + * + * A report is made from its own entry: the header's 「New report」 opens the + * report builder at `reports/new`, whose own Save and Close are the screen's + * one Save/Cancel set. It is gated as the builder is (a workspace admin: a + * report is shared by every member), and not offered while the shell's + * design mode is on, which only links reports that exist. */ import { useId, useState, type ReactNode } from 'react'; import { Link, useParams } from 'react-router-dom'; -import { BarChart3, ChevronDown, ChevronRight, Loader2, Search } from 'lucide-react'; -import { Empty, EmptyTitle, EmptyDescription, Input, cn } from '@object-ui/components'; +import { BarChart3, ChevronDown, ChevronRight, Loader2, Plus, Search } from 'lucide-react'; +import { Button, Empty, EmptyTitle, EmptyDescription, Input, cn } from '@object-ui/components'; import { useDisplayLocale, useObjectTranslation } from '@object-ui/i18n'; +import { useWorkspaceAdminStatus } from '@object-ui/auth'; +import { useDesignModeActive } from '../layout/designMode.js'; import { useServedAppLabel } from '../hooks/useServedAppLabel.js'; import { PageHeader } from '../layout/PageHeader.js'; import { useMetadata } from '../providers/MetadataProvider.js'; @@ -94,6 +104,17 @@ export function AppReportIndexView() { const { apps: launcherApps } = useLauncherApps(metadataApps); const otherApps = useOtherAppsWithReports(launcherApps, app); const { appLabel } = useServedAppLabel(); + const { isAdmin, isResolved } = useWorkspaceAdminStatus(); + const designing = useDesignModeActive(); + const newReport = + isResolved && isAdmin && !designing && appName ? ( + + ) : undefined; if (loading) { return ( @@ -172,7 +193,7 @@ export function AppReportIndexView() {
    {/* objectstack#36111 — the console page header, as every list and dashboard draws it; the shell's top-right group sits at its right. */} - } /> + } actions={newReport} /> {entries.length === 0 ? (
    diff --git a/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx b/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx index 7133377da52..6e91e49edb6 100644 --- a/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx +++ b/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx @@ -22,6 +22,11 @@ * published): that draft is its saver's, and is never published on their * behalf. * + * The edit state and the shell's design mode exclude each other + * (objectstack#36692): while the mode is on the Edit button is not offered, + * and while the edit state is open (or opening) it holds the mode out, so + * entering the mode refuses. The screen shows one Save/Cancel set at a time. + * * Out of scope here: undo, a business user's own copy, a new dashboard, chart * drawing and drill-down. */ @@ -42,6 +47,7 @@ import { type SaveAndPublishOutcome, } from './runtime-metadata-persistence.js'; import { useStudioEntryGate } from '../hooks/useStudioDesignGate.js'; +import { useDesignModeActive, useHoldDesignModeOut } from '../layout/designMode.js'; import { DashboardWidgetInspector } from './metadata-admin/inspectors/DashboardWidgetInspector.js'; import { DashboardDefaultInspector } from './metadata-admin/inspectors/DashboardDefaultInspector.js'; import { AddWidgetPicker } from './metadata-admin/previews/AddWidgetPicker.js'; @@ -192,10 +198,14 @@ export function filtersSectionLabel(locale: SupportedLocale): string | null { * (`useStudioEntryGate`: a workspace admin who may author metadata, on a * package Studio lists, writable or not; never a kernel package). A * read-only package's dashboard is edited through its customization package. + * Not while the shell's design mode is on (objectstack#36692): the two are + * separate entries, never open together. */ export function useDashboardEditOffered(ownerPackageId: string | null | undefined): boolean { const path = ownerPackageId ? `/studio/${encodeURIComponent(ownerPackageId)}` : null; - return useStudioEntryGate(path) !== null; + const gated = useStudioEntryGate(path) !== null; + const designing = useDesignModeActive(); + return gated && !designing; } /** The page header's Edit button. */ @@ -405,6 +415,8 @@ export function useDashboardInPageEdit({ const [saving, setSaving] = React.useState(false); const [selection, setSelection] = React.useState(null); const [revealFilters, setRevealFilters] = React.useState(false); + // Open, or opening: the design mode is held out (objectstack#36692). + useHoldDesignModeOut(session !== null || opening); // Another dashboard on the same route drops the edit state. React.useEffect(() => { diff --git a/ui/packages/app-shell/src/views/ReportNewPage.menuSlot-36364.test.tsx b/ui/packages/app-shell/src/views/ReportNewPage.menuSlot-36364.test.tsx deleted file mode 100644 index 3bd3ddfb8f7..00000000000 --- a/ui/packages/app-shell/src/views/ReportNewPage.menuSlot-36364.test.tsx +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#36364 (report half) — the new-report builder page filling the - * design mode's held menu place: with a slot offered for the app, Save hands - * the report to it and writes nothing itself, Close cancels the place, and - * the page says that saving adds the report to the menu. With no slot the - * page saves on its own, as before. - * - * Real subjects: `ReportNewPage` and the slot store. The builder is a stub - * with a Save and a Close (the real one is `reportBuilder-36374`'s subject); - * the metadata client, the menu's slot and the save door are fakes. - */ - -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 } from '@testing-library/react'; -import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; - -const DRAFT = vi.hoisted(() => ({ - name: '', - label: 'Payment analysis', - type: 'summary', - dataset: 'invoice_metrics', - values: ['invoice_count'], - chart: { type: 'metric', xAxis: '', yAxis: 'invoice_count' }, -})); - -vi.mock('./ReportBuilderHost.js', () => ({ - ReportBuilderHost: (props: { - onSave: (draft: Record) => Promise; - onClose: () => void; - banner?: React.ReactNode; - }) => ( -
    - {props.banner} - - -
    - ), -})); - -const saveAndPublish = vi.hoisted(() => vi.fn(async () => 'published' as const)); -vi.mock('./runtime-metadata-persistence.js', async (importOriginal) => ({ - ...(await importOriginal>()), - saveAndPublishRuntimeMetadata: saveAndPublish, -})); - -const client = vi.hoisted(() => ({ get: vi.fn(async () => null) })); -vi.mock('./metadata-admin/useMetadata.js', () => ({ useMetadataClient: () => client })); - -const refresh = vi.hoisted(() => vi.fn(async () => {})); -vi.mock('../providers/MetadataProvider.js', () => ({ - useMetadata: () => ({ reports: [], loading: false, refresh }), -})); - -vi.mock('@object-ui/auth', async (importOriginal) => ({ - ...(await importOriginal>()), - useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), -})); - -import { ReportNewPage } from './ReportNewPage'; -import { offerNewReportSlot, withdrawNewReportSlot, type NewReportSlot } from '../layout/designModeReportSlot'; - -function Where() { - return {useLocation().pathname}; -} - -function mount(app = 'crm') { - render( - - - } /> - - - - , - ); -} - -const flush = () => - act(async () => { - await new Promise((r) => setTimeout(r, 0)); - }); - -let slot: NewReportSlot; -beforeEach(() => { - saveAndPublish.mockClear(); - client.get.mockClear(); - slot = { path: '/apps/crm/reports/new', save: vi.fn(async () => true), cancel: vi.fn() }; -}); -afterEach(() => { - withdrawNewReportSlot(slot); - cleanup(); -}); - -describe('the new-report page for a held menu place (objectstack#36364)', () => { - it('Save hands the report to the menu, which writes it; the page writes nothing itself', async () => { - offerNewReportSlot(slot); - mount(); - expect(screen.getByTestId('report-new-adds-to-menu')).toBeInTheDocument(); - fireEvent.click(screen.getByText('save')); - await flush(); - await flush(); - expect(slot.save).toHaveBeenCalledWith('payment_analysis', 'Payment analysis', { - ...DRAFT, - name: 'payment_analysis', - }); - expect(saveAndPublish).not.toHaveBeenCalled(); - expect(screen.getByTestId('where')).toHaveTextContent('/apps/crm/report/payment_analysis'); - }); - - it('a save the menu refuses keeps the builder open', async () => { - slot = { ...slot, save: vi.fn(async () => false) }; - offerNewReportSlot(slot); - mount(); - fireEvent.click(screen.getByText('save')); - await flush(); - await flush(); - expect(slot.save).toHaveBeenCalled(); - expect(screen.getByTestId('where')).toHaveTextContent('/apps/crm/reports/new'); - }); - - it('Close cancels the held place and goes back, writing nothing', async () => { - offerNewReportSlot(slot); - mount(); - fireEvent.click(screen.getByText('close')); - await flush(); - expect(slot.cancel).toHaveBeenCalled(); - expect(slot.save).not.toHaveBeenCalled(); - expect(saveAndPublish).not.toHaveBeenCalled(); - expect(screen.getByTestId('where')).toHaveTextContent('/apps/crm/object/crm_lead'); - }); - - it('an app addressed by a route segment other than its name finds its slot by the address', async () => { - // The console addresses the showcase app as `com.example.showcase` while - // its name is `showcase_app`: the place waits on the builder's address. - slot = { ...slot, path: '/apps/com.acme.crm/reports/new' }; - offerNewReportSlot(slot); - mount('com.acme.crm'); - expect(screen.getByTestId('report-new-adds-to-menu')).toBeInTheDocument(); - fireEvent.click(screen.getByText('save')); - await flush(); - await flush(); - expect(slot.save).toHaveBeenCalled(); - expect(saveAndPublish).not.toHaveBeenCalled(); - expect(screen.getByTestId('where')).toHaveTextContent('/apps/com.acme.crm/report/payment_analysis'); - }); - - it("another app's slot is not this page's: it saves on its own", async () => { - slot = { ...slot, path: '/apps/hr/reports/new' }; - offerNewReportSlot(slot); - mount(); - expect(screen.queryByTestId('report-new-adds-to-menu')).toBeNull(); - fireEvent.click(screen.getByText('save')); - await flush(); - await flush(); - expect(slot.save).not.toHaveBeenCalled(); - expect(saveAndPublish).toHaveBeenCalledWith( - 'report', - 'payment_analysis', - { ...DRAFT, name: 'payment_analysis' }, - expect.objectContaining({ metadataClient: client }), - ); - }); -}); diff --git a/ui/packages/app-shell/src/views/ReportNewPage.tsx b/ui/packages/app-shell/src/views/ReportNewPage.tsx index d7a28664b12..2f96de0253a 100644 --- a/ui/packages/app-shell/src/views/ReportNewPage.tsx +++ b/ui/packages/app-shell/src/views/ReportNewPage.tsx @@ -15,18 +15,17 @@ * romanised, as the Studio inspector derives it) and made unique against the * reports the console already knows, so a new report never writes over one. * - * Opened from the design mode's 「Add menu item → Reports → New report…」 - * (objectstack#36364), the page fills the menu's held place: a slot is - * offered for this app (`designModeReportSlot`), and Save hands the report to - * it, which creates the report in the menu's package and saves its menu entry - * with every other staged design change. Close cancels the place and writes - * nothing. + * Opened from the reports index's 「New report」 (objectstack#36692): a report + * is made from its own entry, never from the design mode, whose menu only + * links reports that exist. The builder's Save and Close in its own header + * are the screen's one Save/Cancel set: while the builder is open it holds + * the design mode out (`useHoldDesignModeOut`), so entering the mode refuses. * * @module */ import * as React from 'react'; -import { useLocation, useNavigate, useParams } from 'react-router-dom'; +import { useNavigate, useParams } from 'react-router-dom'; import { toast } from 'sonner'; import { Loader2 } from 'lucide-react'; import { Empty, EmptyDescription, EmptyTitle } from '@object-ui/components'; @@ -36,7 +35,7 @@ import { formatMetadataError } from '@object-ui/data-objectstack'; import type { DataSource } from '@object-ui/types'; import type { ReportDraft } from '@object-ui/plugin-report'; import { ReportBuilderHost } from './ReportBuilderHost.js'; -import { useNewReportSlot } from '../layout/designModeReportSlot.js'; +import { useHoldDesignModeOut } from '../layout/designMode.js'; import { saveAndPublishRuntimeMetadata } from './runtime-metadata-persistence.js'; import { useMetadataClient } from './metadata-admin/useMetadata.js'; import { useMetadata } from '../providers/MetadataProvider.js'; @@ -91,17 +90,13 @@ export function ReportNewPage({ dataSource }: { dataSource?: DataSource }) { const metadataClient = useMetadataClient(); const { reports, loading, refresh } = useMetadata(); const { isAdmin, isResolved } = useWorkspaceAdminStatus(); - /** The menu place this report fills, when the design mode opened the page for one. */ - const slot = useNewReportSlot(useLocation().pathname); + // The builder is open whenever this page draws it (objectstack#36692). + useHoldDesignModeOut(isResolved && isAdmin); const backToReports = React.useCallback(() => { - if (slot) { - // Back to the page the design mode was on; the held place is dropped. - slot.cancel(); - navigate(-1); - } else if (appName) navigate(`/apps/${appName}/reports`); + if (appName) navigate(`/apps/${appName}/reports`); else navigate(-1); - }, [navigate, appName, slot]); + }, [navigate, appName]); const handleSave = React.useCallback( async (draft: ReportDraft): Promise => { @@ -124,18 +119,13 @@ export function ReportNewPage({ dataSource }: { dataSource?: DataSource }) { return false; } const body = { ...draft, label, name }; - if (slot) { - // The design mode creates it with its menu entry, and says why when it cannot. - if (!(await slot.save(name, typed || String(label), body))) return false; - } else { - const outcome = await saveAndPublishRuntimeMetadata('report', name, body, { - metadataClient, - dataSource: dataSource as any, - }); - if (outcome === 'pending-draft') { - toast.error(t('form.saveError'), { description: t('report.builder.pendingDraft') }); - return false; - } + const outcome = await saveAndPublishRuntimeMetadata('report', name, body, { + metadataClient, + dataSource: dataSource as any, + }); + if (outcome === 'pending-draft') { + toast.error(t('form.saveError'), { description: t('report.builder.pendingDraft') }); + return false; } } catch (err) { toast.error(t('form.saveError'), { @@ -150,7 +140,7 @@ export function ReportNewPage({ dataSource }: { dataSource?: DataSource }) { }); return true; }, - [metadataClient, reports, language, dataSource, refresh, navigate, appName, t, slot], + [metadataClient, reports, language, dataSource, refresh, navigate, appName, t], ); if (loading || !isResolved) { @@ -178,13 +168,6 @@ export function ReportNewPage({ dataSource }: { dataSource?: DataSource }) { onSave={handleSave} onClose={backToReports} dataSource={dataSource} - banner={ - slot ? ( -

    - {t('report.builder.addsToMenu')} -

    - ) : undefined - } /> ); } diff --git a/ui/packages/app-shell/src/views/ReportView.tsx b/ui/packages/app-shell/src/views/ReportView.tsx index b3be4ed4865..d8bb685d949 100644 --- a/ui/packages/app-shell/src/views/ReportView.tsx +++ b/ui/packages/app-shell/src/views/ReportView.tsx @@ -14,6 +14,7 @@ import { ReportConfigPanel } from './ReportConfigPanel.js'; import { readReportBuilderArrival, withoutReportBuilderArrival } from './reportBuilderArrival.js'; import { Pencil, BarChart3, Loader2 } from 'lucide-react'; import { PageHeader } from '../layout/PageHeader.js'; +import { useDesignModeActive, useHoldDesignModeOut } from '../layout/designMode.js'; import { useObjectTranslation } from '@object-ui/i18n'; import { MetadataPanel, useMetadataInspector } from './MetadataInspector.js'; import { useMetadata } from '../providers/MetadataProvider.js'; @@ -118,6 +119,10 @@ export function ReportView({ dataSource }: { dataSource?: DataSource }) { // Editing a report mutates the SHARED definition, so it is an admin-only // quick-edit affordance (mirrors ObjectView's view-config gate). const { isAdmin } = useWorkspaceAdminStatus(); + // objectstack#36692 — the report's editors and the shell's design mode + // exclude each other: no Edit while the mode is on, and an open (or + // opening) editor holds the mode out (`useHoldDesignModeOut` below). + const designing = useDesignModeActive(); // objectstack#36374 — which editor is open: the report builder (it // replaces the page), or the inspector panel beside the report. const [editor, setEditor] = useState<'builder' | 'panel' | null>(null); @@ -334,6 +339,7 @@ export function ReportView({ dataSource }: { dataSource?: DataSource }) { // buffer is the untranslated source, so a close with no landed save draws // the served report again, which is the display copy for this locale. const [openingEditor, setOpeningEditor] = useState(false); + useHoldDesignModeOut(editor !== null || openingEditor); // The authored buffer as the builder opened on it, and the served text of // the report's name and description paired with the published layer — the // builder's name and description boxes read it, and the page draws the @@ -451,13 +457,13 @@ export function ReportView({ dataSource }: { dataSource?: DataSource }) { const navigate = useNavigate(); const arrivalReadRef = useRef(null); useEffect(() => { - if (!isAdmin || loading || !initialReport || !reportName) return; + if (!isAdmin || designing || loading || !initialReport || !reportName) return; if (!readReportBuilderArrival(location.state, reportName)) return; if (arrivalReadRef.current === location.key) return; arrivalReadRef.current = location.key; navigate(location.pathname + location.search, { replace: true, state: withoutReportBuilderArrival(location.state) }); void handleOpenBuilder(); - }, [isAdmin, loading, initialReport, reportName, location, navigate, handleOpenBuilder]); + }, [isAdmin, designing, loading, initialReport, reportName, location, navigate, handleOpenBuilder]); // Sync reportData when metadata finishes loading or reportName changes useEffect(() => { @@ -684,7 +690,7 @@ export function ReportView({ dataSource }: { dataSource?: DataSource }) { title={heading} subtitle={description || undefined} icon={} - actions={isAdmin ? ( + actions={isAdmin && !designing ? ( + ); + } + + async function mountMenu() { + render( + + + + + + , + ); + await act(() => new Promise((resolve) => setTimeout(resolve, 0))); + await act(() => new Promise((resolve) => setTimeout(resolve, 0))); + } + + const designLayout = () => menu().queryByTestId('sidebar-app-menu-design-layout'); + + beforeEach(() => { + apps = [CRM, SERVICE, SETUP]; + admin = true; + }); + + it('it stays drawn; choosing it says to save or cancel those changes first, and the mode stays off', async () => { + await mountMenu(); + fireEvent.click(screen.getByTestId('editor-toggle')); + expect(designLayout()).not.toBeNull(); + await act(async () => fireEvent.click(designLayout()!)); + expect(screen.getByTestId('mode')).toHaveTextContent('off'); + expect(toastError).toHaveBeenCalledTimes(1); + expect(toastError).toHaveBeenCalledWith('Save or cancel your dashboard or report changes before designing the layout.'); + }); + + it('control: the editor closed, choosing it enters the mode and says nothing', async () => { + await mountMenu(); + fireEvent.click(screen.getByTestId('editor-toggle')); + fireEvent.click(screen.getByTestId('editor-toggle')); + await act(async () => fireEvent.click(designLayout()!)); + expect(screen.getByTestId('mode')).toHaveTextContent('on'); + expect(toastError).not.toHaveBeenCalled(); + }); + + it('the prompt is in every built-in pack, and zh-Hans reads as the design mode is named', () => { + const packs = builtInLocales as unknown as Record; + for (const [locale, pack] of Object.entries(packs)) { + expect(pack.designMode.editorOpen, locale).toBeTruthy(); + } + expect(packs['zh-Hans'].designMode.editorOpen).toContain(packs['zh-Hans'].designMode.title); + }); +}); diff --git a/ui/packages/app-shell/src/layout/__tests__/designMode-36362.test.tsx b/ui/packages/app-shell/src/layout/__tests__/designMode-36362.test.tsx index bb4e415f6ab..93509936f1f 100644 --- a/ui/packages/app-shell/src/layout/__tests__/designMode-36362.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/designMode-36362.test.tsx @@ -43,8 +43,10 @@ import { DesignModeProvider, isPageOfApp, useDesignMode, + useDesignModeActive, useDesignModeChange, useDesignModeController, + useHoldDesignModeOut, } from '../designMode'; import { DesignModeBar } from '../DesignModeBar'; @@ -355,3 +357,101 @@ describe('staging a change and saving at once (objectstack#36364)', () => { expect(commit).not.toHaveBeenCalled(); }); }); + +/** + * objectstack#36692 — a dashboard's or a report's own editor and the mode + * exclude each other through one hold: an open editor holds the mode out, so + * `enter` refuses and says why; the mode on, `useDesignModeActive` is what an + * editor reads to not offer its Edit. + */ +describe('an editor of its own holds the mode out (objectstack#36692)', () => { + /** An editor that holds the mode out while it is open, and says whether it may be offered. */ + function Editor({ name }: { name: string }) { + const [open, setOpen] = React.useState(false); + useHoldDesignModeOut(open); + const offered = !useDesignModeActive(); + return ( +
    + {offered ? 'yes' : 'no'} + +
    + ); + } + + /** The door, with what `enter` answered. */ + function Door() { + const mode = useDesignMode(); + const [answer, setAnswer] = React.useState(''); + return ( + + ); + } + + const PROMPT = 'Save or cancel your dashboard or report changes before designing the layout.'; + + it('while an editor is open, entering refuses with the prompt and the mode stays off', () => { + render(); + fireEvent.click(screen.getByText('toggle dashboard')); + fireEvent.click(screen.getByText(/^door/)); + expect(screen.getByText(/^door/)).toHaveTextContent('door false'); + expect(bar()).toBeNull(); + expect(toastError).toHaveBeenCalledTimes(1); + expect(toastError).toHaveBeenCalledWith(PROMPT); + }); + + it('the hold is let go when the editor closes: entering works again', () => { + render(); + fireEvent.click(screen.getByText('toggle dashboard')); + fireEvent.click(screen.getByText('toggle dashboard')); + fireEvent.click(screen.getByText(/^door/)); + expect(screen.getByText(/^door/)).toHaveTextContent('door true'); + expect(bar()).not.toBeNull(); + expect(toastError).not.toHaveBeenCalled(); + }); + + it('two editors hold it out until both close', () => { + render(); + fireEvent.click(screen.getByText('toggle dashboard')); + fireEvent.click(screen.getByText('toggle report')); + fireEvent.click(screen.getByText('toggle dashboard')); + fireEvent.click(screen.getByText(/^door/)); + expect(bar()).toBeNull(); + fireEvent.click(screen.getByText('toggle report')); + fireEvent.click(screen.getByText(/^door/)); + expect(bar()).not.toBeNull(); + }); + + it('an editor unmounted while open lets go too', () => { + function Page() { + const [shown, setShown] = React.useState(true); + return ( + <> + {shown && } + + + ); + } + render(); + fireEvent.click(screen.getByText('toggle report')); + fireEvent.click(screen.getByText('leave page')); + fireEvent.click(screen.getByText(/^door/)); + expect(bar()).not.toBeNull(); + }); + + it('while the mode is on, an editor reads that it is not offered; outside a shell it always is', () => { + render(); + expect(screen.getByTestId('offered-dashboard')).toHaveTextContent('yes'); + fireEvent.click(screen.getByText(/^door/)); + expect(screen.getByTestId('offered-dashboard')).toHaveTextContent('no'); + fireEvent.click(screen.getByTestId('design-mode-cancel')); + expect(screen.getByTestId('offered-dashboard')).toHaveTextContent('yes'); + cleanup(); + render(); + fireEvent.click(screen.getByText('toggle bare')); + expect(screen.getByTestId('offered-bare')).toHaveTextContent('yes'); + }); +}); diff --git a/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx b/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx index 7138104ef47..20c2cd4624f 100644 --- a/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx +++ b/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx @@ -119,6 +119,8 @@ vi.mock('./metadata-admin/previews/AddWidgetPicker', () => ({ })); import { DashboardView } from './DashboardView'; +import { DesignModeProvider, useDesignModeController } from '../layout/designMode'; +import { DesignModeBar } from '../layout/DesignModeBar'; /** The served dashboard: translated for the session, with its read's decorations. */ const served = { @@ -398,3 +400,80 @@ describe('DashboardView with no cards yet (objectstack#36364)', () => { expect(screen.queryByTestId('dashboard-no-cards')).not.toBeInTheDocument(); }); }); + +/** + * objectstack#36692 — the dashboard's own edit state and the shell's design + * mode are two entries that exclude each other, both ways (the maintainer's + * 「照 Twenty 分开」): no Edit while the mode is on, and the mode's door + * refuses, saying why, while the edit state is open. So the screen never + * shows two Save/Cancel sets, and the bar's Cancel can never end the mode + * under a dashboard left in edit. + * + * Real subjects added: the shell's design-mode controller and its bar. + */ +describe('DashboardView and the design mode exclude each other (objectstack#36692)', () => { + function Shell({ children }: { children: React.ReactNode }) { + const mode = useDesignModeController({ appName: 'crm', appBasePath: '/apps/crm', enabled: true }); + return ( + + {mode.active && } + + {children} + + ); + } + + function mountInShell() { + meta.value = { + apps: [], + objects: [], + dashboards: [served], + reports: [], + pages: [], + loading: false, + error: null, + refresh: async () => {}, + invalidate: () => {}, + ensureType: async () => [], + getItem: vi.fn(async () => null), + getItemsByType: () => [], + getTypeStatus: () => 'ready', + }; + render( + }> + + + + , + ); + } + + it('while the mode is on, Edit is not offered; the mode left, it is again', async () => { + mountInShell(); + await screen.findByTestId('dashboard-edit'); + fireEvent.click(screen.getByTestId('enter-design-mode')); + expect(await screen.findByTestId('design-mode-bar')).toBeInTheDocument(); + expect(screen.queryByTestId('dashboard-edit')).not.toBeInTheDocument(); + fireEvent.click(screen.getByTestId('design-mode-cancel')); + expect(await screen.findByTestId('dashboard-edit')).toBeInTheDocument(); + }); + + it('while the edit state is open, entering the mode is refused with the prompt: one Save/Cancel set, and no bar Cancel to strand the edit', async () => { + mountInShell(); + await openEdit(); + fireEvent.click(screen.getByTestId('enter-design-mode')); + await act(async () => { await new Promise((r) => setTimeout(r, 0)); }); + expect(screen.queryByTestId('design-mode-bar')).not.toBeInTheDocument(); + expect(screen.queryByTestId('design-mode-cancel')).not.toBeInTheDocument(); + expect(toasts.error).toEqual([['Save or cancel your dashboard or report changes before designing the layout.']]); + expect(screen.getByTestId('dashboard-editing-badge')).toBeInTheDocument(); + expect(screen.getByTestId('dashboard-edit-save')).toBeInTheDocument(); + // The edit state closed, the door opens. + fireEvent.click(screen.getByTestId('dashboard-edit-discard')); + fireEvent.click(screen.getByTestId('enter-design-mode')); + expect(await screen.findByTestId('design-mode-bar')).toBeInTheDocument(); + expect(toasts.error).toHaveLength(1); + }); +}); diff --git a/ui/packages/app-shell/src/views/ReportNewPage-36692.test.tsx b/ui/packages/app-shell/src/views/ReportNewPage-36692.test.tsx new file mode 100644 index 00000000000..e66f238fc47 --- /dev/null +++ b/ui/packages/app-shell/src/views/ReportNewPage-36692.test.tsx @@ -0,0 +1,159 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36692 — the new-report builder page is reached from the reports + * index only, and saves on its own: the design mode no longer hands it a menu + * place (the maintainer's 「照 Twenty 分开」). + * + * - Save creates and publishes the report itself and lands on its page; the + * page says nothing about a menu; + * - Close goes back to the app's reports index; + * - while the builder is open it holds the design mode out, so entering the + * mode refuses with the prompt and the screen keeps one Save/Cancel set. + * + * Real subjects: `ReportNewPage` and the shell's design-mode controller. The + * builder is a stub with a Save and a Close (the real one is + * `reportBuilder-36374`'s subject); the metadata client and the save door are + * fakes. + */ + +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 } from '@testing-library/react'; +import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; + +const DRAFT = vi.hoisted(() => ({ + name: '', + label: 'Payment analysis', + type: 'summary', + dataset: 'invoice_metrics', + values: ['invoice_count'], + chart: { type: 'metric', xAxis: '', yAxis: 'invoice_count' }, +})); + +vi.mock('./ReportBuilderHost.js', () => ({ + ReportBuilderHost: (props: { + onSave: (draft: Record) => Promise; + onClose: () => void; + banner?: React.ReactNode; + }) => ( +
    + {props.banner} + + +
    + ), +})); + +const saveAndPublish = vi.hoisted(() => vi.fn(async () => 'published' as const)); +vi.mock('./runtime-metadata-persistence.js', async (importOriginal) => ({ + ...(await importOriginal>()), + saveAndPublishRuntimeMetadata: saveAndPublish, +})); + +const client = vi.hoisted(() => ({ get: vi.fn(async () => null) })); +vi.mock('./metadata-admin/useMetadata.js', () => ({ useMetadataClient: () => client })); + +const refresh = vi.hoisted(() => vi.fn(async () => {})); +vi.mock('../providers/MetadataProvider.js', () => ({ + useMetadata: () => ({ reports: [], loading: false, refresh }), +})); + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), +})); + +const toastError = vi.hoisted(() => vi.fn()); +vi.mock('sonner', async (importOriginal) => ({ + ...(await importOriginal>()), + toast: { error: toastError, success: vi.fn() }, +})); + +import { ReportNewPage } from './ReportNewPage'; +import { DesignModeProvider, useDesignModeController } from '../layout/designMode'; + +function Where() { + return {useLocation().pathname}; +} + +/** The shell's hold on the design mode, and its door. */ +function Shell({ children }: { children: React.ReactNode }) { + const mode = useDesignModeController({ appName: 'crm', appBasePath: '/apps/crm', enabled: true }); + return ( + + {mode.active ? 'on' : 'off'} + + {children} + + ); +} + +function mount() { + render( + + + + } /> + + + + + , + ); +} + +const flush = () => + act(async () => { + await new Promise((r) => setTimeout(r, 0)); + }); + +beforeEach(() => { + saveAndPublish.mockClear(); + client.get.mockClear(); + toastError.mockReset(); +}); +afterEach(() => { + cleanup(); +}); + +describe('the new-report page saves on its own (objectstack#36692)', () => { + it('Save creates and publishes the report and lands on its page; nothing speaks of a menu', async () => { + mount(); + expect(screen.queryByTestId('report-new-adds-to-menu')).toBeNull(); + fireEvent.click(screen.getByText('save')); + await flush(); + await flush(); + expect(saveAndPublish).toHaveBeenCalledWith( + 'report', + 'payment_analysis', + { ...DRAFT, name: 'payment_analysis' }, + expect.objectContaining({ metadataClient: client }), + ); + expect(screen.getByTestId('where')).toHaveTextContent('/apps/crm/report/payment_analysis'); + }); + + it('Close goes back to the reports index, writing nothing', async () => { + mount(); + fireEvent.click(screen.getByText('close')); + await flush(); + expect(saveAndPublish).not.toHaveBeenCalled(); + expect(screen.getByTestId('where').textContent).toBe('/apps/crm/reports'); + }); + + it('while the builder is open, entering the design mode refuses with the prompt', async () => { + mount(); + fireEvent.click(screen.getByText('enter design mode')); + await flush(); + expect(screen.getByTestId('mode')).toHaveTextContent('off'); + expect(toastError).toHaveBeenCalledWith('Save or cancel your dashboard or report changes before designing the layout.'); + expect(screen.getByTestId('builder')).toBeInTheDocument(); + }); +}); diff --git a/ui/packages/app-shell/src/views/ReportView.designModeExclusion-36692.test.tsx b/ui/packages/app-shell/src/views/ReportView.designModeExclusion-36692.test.tsx new file mode 100644 index 00000000000..de5653426c3 --- /dev/null +++ b/ui/packages/app-shell/src/views/ReportView.designModeExclusion-36692.test.tsx @@ -0,0 +1,207 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36692 — the report page's own editors (the report builder, and + * the inspector panel of a pre-dataset report) and the shell's design mode + * are two entries that exclude each other, both ways (the maintainer's + * 「照 Twenty 分开」): + * + * - while the mode is on, the report page's Edit is not offered; once the + * mode is left, it is again; + * - while an editor is open, entering the mode refuses, saying to save or + * cancel those changes first, so no bar and no second Save/Cancel set + * appear; the editor closed, the mode enters. + * + * The harness is `ReportView.saveRefusal-11583.test.tsx`'s (the real + * `ReportView`, `ReportBuilderHost` and `ReportConfigPanel`, the builder and + * the inspector reduced to their buttons), with the shell's real design-mode + * controller and its bar around the page. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, waitFor, fireEvent, act, cleanup } from '@testing-library/react'; +import { toast } from 'sonner'; +import { DesignModeProvider, useDesignModeController } from '../layout/designMode'; +import { DesignModeBar } from '../layout/DesignModeBar'; + +vi.mock('sonner', () => ({ + toast: Object.assign(vi.fn(), { + success: vi.fn(), error: vi.fn(), info: vi.fn(), + warning: vi.fn(), loading: vi.fn(), dismiss: vi.fn(), + }), +})); + +vi.mock('@object-ui/plugin-report', async (importOriginal) => ({ + ...(await importOriginal>()), + ReportRenderer: () => null, + // objectstack#36374 — the report builder, reduced to one edit and its + // buttons; the host around it (`ReportBuilderHost`) is the real one. + ReportBuilder: ({ report, onChange, onSave, onClose, banner }: any) => ( +
    + {banner} + + + +
    + ), +})); +// The builder host's catalog reads, answered empty: the stub draws no picker. +vi.mock('./metadata-admin/previews/useDatasetCatalog', () => ({ + useDatasetCatalog: () => ({ datasets: [], loading: false, error: null }), + useDatasetSemantics: () => ({ dimensions: [], measures: [], loading: false, error: null }), +})); +vi.mock('@object-ui/plugin-dashboard', async (importOriginal) => ({ + ...(await importOriginal>()), + DrillDownDrawer: () => null, +})); +// The panel's spec inspector, reduced to one edit: a new title. +vi.mock('./metadata-admin/inspectors/ReportDefaultInspector', () => ({ + ReportDefaultInspector: ({ onPatch, draft }: any) => ( + + ), +})); +vi.mock('./RuntimeDraftBar', () => ({ RuntimeDraftBar: () => null })); + +const meta = vi.hoisted(() => ({ value: null as any })); +vi.mock('../providers/MetadataProvider', () => ({ useMetadata: () => meta.value })); + +vi.mock('react-router-dom', () => ({ + useParams: () => ({ reportName: 'revenue_by_month' }), + useNavigate: () => vi.fn(), + useLocation: () => ({ pathname: '/reports/revenue_by_month', search: '' }), +})); + +vi.mock('./useOpenRecordList', () => ({ + useRecordListDrillNavigation: () => ({ openRecordList: vi.fn(), canOpenRecordList: () => true }), +})); +vi.mock('./MetadataInspector', () => ({ + MetadataPanel: () => null, + useMetadataInspector: () => ({ showDebug: false }), +})); +const client = vi.hoisted(() => ({ value: null as any })); +vi.mock('./metadata-admin/useMetadata', () => ({ useMetadataClient: () => client.value })); +vi.mock('../providers/AdapterProvider', () => ({ useAdapter: () => ({}) })); +vi.mock('../providers/ExpressionProvider', () => ({ useExpressionContext: () => ({ app: undefined }) })); +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + // The report editor is admin-only. + useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), +})); + +// `ReportView` reaches a dynamic `import('@objectstack/lint')` (through the panel's +// inspector): pay its load at collection, never inside a case's clocked window +// (`check:test-source-alias`). +import '@objectstack/lint'; +import { ReportView } from './ReportView'; + +const PROMPT = 'Save or cancel your dashboard or report changes before designing the layout.'; + +/** A dataset report opens in the builder; a pre-dataset one in the panel. */ +const DATASET_REPORT = { name: 'revenue_by_month', label: 'Revenue by Month', type: 'summary', dataset: 'ds_revenue', values: ['amount'] }; +const LEGACY_REPORT = { name: 'revenue_by_month', label: 'Revenue by Month', dataSource: { object: 'acct' } }; + +function Shell({ children }: { children: React.ReactNode }) { + const mode = useDesignModeController({ appName: 'crm', appBasePath: '/apps/crm', enabled: true }); + return ( + + {mode.active && } + + {children} + + ); +} + +function mountReport(report: Record) { + client.value = { + get: vi.fn(async () => null), + getDraft: vi.fn(async () => null), + layered: vi.fn(async () => ({ code: null, overlay: null, overlayScope: null, effective: report, draft: null })), + save: vi.fn(async () => ({})), + publish: vi.fn(async () => ({})), + }; + meta.value = { + apps: [], + objects: [{ name: 'acct', label: 'Account', fields: { industry: { label: 'Industry', type: 'text' } } }], + dashboards: [], + reports: [report], + pages: [], + loading: false, + error: null, + refresh: vi.fn(async () => {}), + invalidate: () => {}, + ensureType: async () => [], + getItem: vi.fn(async () => null), + getItemsByType: () => [], + getTypeStatus: () => 'ready', + }; + render( + + ({ data: [] })) } as any} /> + , + ); +} + +const flush = () => act(async () => { await new Promise((r) => setTimeout(r, 0)); }); + +beforeEach(() => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); +}); + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + vi.clearAllMocks(); +}); + +describe('the report page and the design mode exclude each other (objectstack#36692)', () => { + it('while the mode is on, Edit is not offered; the mode left, it is again', async () => { + mountReport(DATASET_REPORT); + await screen.findByTestId('report-edit-button'); + fireEvent.click(screen.getByTestId('enter-design-mode')); + expect(await screen.findByTestId('design-mode-bar')).toBeTruthy(); + expect(screen.queryByTestId('report-edit-button')).toBeNull(); + fireEvent.click(screen.getByTestId('design-mode-cancel')); + expect(await screen.findByTestId('report-edit-button')).toBeTruthy(); + }); + + it('while the builder is open, entering the mode is refused with the prompt; the builder closed, it enters', async () => { + mountReport(DATASET_REPORT); + fireEvent.click(await screen.findByTestId('report-edit-button')); + await screen.findByTestId('report-builder'); + fireEvent.click(screen.getByTestId('enter-design-mode')); + await flush(); + expect(screen.queryByTestId('design-mode-bar')).toBeNull(); + expect(toast.error).toHaveBeenCalledTimes(1); + expect(toast.error).toHaveBeenCalledWith(PROMPT); + expect(screen.getByTestId('report-builder')).toBeTruthy(); + + fireEvent.click(screen.getByTestId('report-builder-close')); + await waitFor(() => expect(screen.queryByTestId('report-builder')).toBeNull()); + fireEvent.click(screen.getByTestId('enter-design-mode')); + expect(await screen.findByTestId('design-mode-bar')).toBeTruthy(); + expect(toast.error).toHaveBeenCalledTimes(1); + }); + + it('the inspector panel holds the mode out too', async () => { + mountReport(LEGACY_REPORT); + fireEvent.click(await screen.findByTestId('report-edit-button')); + await screen.findByTestId('report-config-panel'); + fireEvent.click(screen.getByTestId('enter-design-mode')); + await flush(); + expect(screen.queryByTestId('design-mode-bar')).toBeNull(); + expect(toast.error).toHaveBeenCalledWith(PROMPT); + }); +}); diff --git a/ui/packages/app-shell/src/views/__tests__/AppReportIndex.newReport-36692.test.tsx b/ui/packages/app-shell/src/views/__tests__/AppReportIndex.newReport-36692.test.tsx new file mode 100644 index 00000000000..95a6ab1c57f --- /dev/null +++ b/ui/packages/app-shell/src/views/__tests__/AppReportIndex.newReport-36692.test.tsx @@ -0,0 +1,151 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36692 — a report is made from its own entry: the reports index + * offers 「New report」, which opens the report builder at `reports/new`. + * The design mode no longer hosts the builder (the maintainer's 「照 Twenty + * 分开」), so this is the one way to a new report. + * + * - a workspace admin sees 「New report」 in the index header, linking to the + * app's `reports/new`, also on an index with no report yet; + * - it is gated as the builder is: a member gets none; + * - it is not offered while the shell's design mode is on, and is again + * once the mode is left. + * + * The harness is `AppReportIndex.otherAppsAddress-29024.test.tsx`'s (the real + * `MetadataProvider`, `MePermissionsProvider`, `ExpressionProvider` and + * `I18nProvider` in `en`), with the admin status stubbed and the shell's real + * design-mode controller around the page. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { render, screen, cleanup, fireEvent } from '@testing-library/react'; +import { MemoryRouter, Route, Routes } from 'react-router-dom'; +import { createI18n, I18nProvider } from '@object-ui/i18n'; +import { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from '@object-ui/permissions'; + +const admin = vi.hoisted(() => ({ isAdmin: true, isResolved: true })); +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: { id: 'u_admin' }, activeOrganization: null }), + useWorkspaceAdminStatus: () => admin, +})); + +import { MetadataProvider } from '../../providers/MetadataProvider'; +import { ExpressionProvider } from '../../providers/ExpressionProvider'; +import { DesignModeProvider, useDesignModeController } from '../../layout/designMode'; +import { AppReportIndexView } from '../AppReportIndexView'; + +const CRM_APP = { name: 'crm', label: 'CRM', active: true, _packageId: 'com.example.crm', navigation: [] }; + +const REPORTS = [{ name: 'crm_win_rate', label: 'Win Rate', dataset: 'ds_accounts', _packageId: 'com.example.crm' }]; +const DATASETS = [{ name: 'ds_accounts', object: 'crm_account' }]; + +const ANSWER: MePermissionsAuthenticatedResponse = { + authenticated: true, + userId: 'u_admin', + tenantId: null, + positions: [], + hasAnyQueue: false, + objectsUsingQueues: [], + permissionSets: ['admin'], + systemPermissions: [], + objects: { crm_account: { allowRead: true } }, + fields: {}, +}; + +function adapterFor(reports: unknown[]) { + const items: Record = { app: [CRM_APP], report: reports, dataset: DATASETS }; + return { + clearCache: vi.fn(), + getObjectSchema: () => Promise.resolve(null), + getClient: () => ({ + meta: { + getItems: (type: string) => Promise.resolve({ type, items: items[type] ?? [] }), + getItem: () => Promise.resolve({ item: null }), + }, + }), + } as unknown as Parameters[0]['adapter']; +} + +/** The shell's hold on the design mode, with its door and its Cancel as plain buttons. */ +function Shell({ children }: { children: React.ReactNode }) { + const mode = useDesignModeController({ appName: 'crm', appBasePath: '/apps/crm', enabled: true }); + return ( + + + + {children} + + ); +} + +function renderIndex(reports: unknown[] = REPORTS) { + const fetcher = vi.fn(async () => ({ ok: true, status: 200, json: async () => ANSWER }) as unknown as Response); + render( + + + + + + + + } /> + builder

    } /> +
    +
    +
    +
    +
    +
    +
    , + ); +} + +beforeEach(() => { + cleanup(); + localStorage.clear(); + sessionStorage.clear(); + admin.isAdmin = true; + admin.isResolved = true; +}); + +describe('「New report」 on the reports index (objectstack#36692)', () => { + it('a workspace admin sees it in the header; it opens the report builder', async () => { + renderIndex(); + await screen.findByTestId('report-index-entry-crm_win_rate'); + const link = screen.getByTestId('report-index-new'); + expect(link).toHaveTextContent('New report'); + expect(link).toHaveAttribute('href', '/apps/crm/reports/new'); + fireEvent.click(link); + expect(await screen.findByTestId('builder-page')).toBeInTheDocument(); + }); + + it('an index with no report yet offers it too', async () => { + renderIndex([]); + await screen.findByText('No reports'); + expect(screen.getByTestId('report-index-new')).toHaveAttribute('href', '/apps/crm/reports/new'); + }); + + it('gated as the builder is: a member gets none', async () => { + admin.isAdmin = false; + renderIndex(); + await screen.findByTestId('report-index-entry-crm_win_rate'); + expect(screen.queryByTestId('report-index-new')).toBeNull(); + }); + + it('not offered while the design mode is on; offered again once it is left', async () => { + renderIndex(); + await screen.findByTestId('report-index-entry-crm_win_rate'); + fireEvent.click(screen.getByText('enter design mode')); + expect(screen.queryByTestId('report-index-new')).toBeNull(); + fireEvent.click(screen.getByText('leave design mode')); + expect(screen.getByTestId('report-index-new')).toBeInTheDocument(); + }); +}); From 22dee19f56d4bbefd1cd0e6d858460c95a9d122a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 03:02:49 +0000 Subject: [PATCH 8/9] chore: changeset for report editing as its own entry Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzhpykmQZe1yMupC2CU --- .changeset/36692-report-editing-own-entry.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 .changeset/36692-report-editing-own-entry.md diff --git a/.changeset/36692-report-editing-own-entry.md b/.changeset/36692-report-editing-own-entry.md new file mode 100644 index 00000000000..cdaa13640fd --- /dev/null +++ b/.changeset/36692-report-editing-own-entry.md @@ -0,0 +1,18 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +fix(console): report editing is its own entry, and report and dashboard editing exclude the design mode both ways + +Clause-②: no +Metadata-protocol: none + +The console's design mode no longer hosts the report builder, so the screen shows one Save/Cancel set at a time: + +- The design mode's 「Add menu item → Reports」 lists only reports that exist; its 「New report…」 row is gone, with the hand-off that let the builder save into the menu. A new report is made from the reports index, then linked from the design mode. +- The reports index offers 「New report」 in its header, opening the report builder. It is offered to workspace admins, as the builder is, and not while the design mode is on. +- While the design mode is on, a dashboard's and a report's own 「Edit」 are not offered. +- While a dashboard or report editor is open, 「Design layout」 refuses with a prompt to save or cancel those changes first, so the design mode's 「Cancel」 can no longer end the mode under an editor left open. + +The design mode's 「New dashboard…」 is unchanged. In `@object-ui/i18n`, `designMode.menu.newReport`, `designMode.menu.newReportLeft` and `report.builder.addsToMenu` are removed from every pack, and `designMode.editorOpen` and `console.reportIndex.newReport` are added. Nothing to migrate. From cccd01739c9bcfc6cb1c512133d63455c935cf9d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 05:27:13 +0000 Subject: [PATCH 9/9] fix(console): the new-report page draws no builder while the design mode is on Reached with the mode already on (the browser's Back to reports/new), the page drew the builder under the design-mode bar: two Save/Cancel sets, and the bar's Cancel ended the mode under the open builder. The page now draws a prompt in place of the builder while the mode is on, holds the mode out only while it draws the builder, and opens the builder once the mode is left. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzhpykmQZe1yMupC2CU --- .changeset/36692-report-editing-own-entry.md | 3 +- .../src/views/ReportNewPage-36692.test.tsx | 77 ++++++++++++++++++- .../app-shell/src/views/ReportNewPage.tsx | 21 ++++- ui/packages/i18n/src/locales/ar.ts | 2 + ui/packages/i18n/src/locales/de.ts | 2 + ui/packages/i18n/src/locales/en.ts | 2 + ui/packages/i18n/src/locales/es.ts | 2 + ui/packages/i18n/src/locales/fr.ts | 2 + ui/packages/i18n/src/locales/ja.ts | 2 + ui/packages/i18n/src/locales/ko.ts | 2 + ui/packages/i18n/src/locales/pt-BR.ts | 2 + ui/packages/i18n/src/locales/ru.ts | 2 + ui/packages/i18n/src/locales/zh-Hans.ts | 2 + ui/packages/i18n/src/locales/zh-Hant.ts | 2 + 14 files changed, 118 insertions(+), 5 deletions(-) diff --git a/.changeset/36692-report-editing-own-entry.md b/.changeset/36692-report-editing-own-entry.md index cdaa13640fd..8b9655b5900 100644 --- a/.changeset/36692-report-editing-own-entry.md +++ b/.changeset/36692-report-editing-own-entry.md @@ -14,5 +14,6 @@ The console's design mode no longer hosts the report builder, so the screen show - The reports index offers 「New report」 in its header, opening the report builder. It is offered to workspace admins, as the builder is, and not while the design mode is on. - While the design mode is on, a dashboard's and a report's own 「Edit」 are not offered. - While a dashboard or report editor is open, 「Design layout」 refuses with a prompt to save or cancel those changes first, so the design mode's 「Cancel」 can no longer end the mode under an editor left open. +- The report builder's own address reached with the design mode already on (the browser's Back) shows a prompt to finish designing the layout instead of the builder; the builder opens there once the mode is saved or cancelled. -The design mode's 「New dashboard…」 is unchanged. In `@object-ui/i18n`, `designMode.menu.newReport`, `designMode.menu.newReportLeft` and `report.builder.addsToMenu` are removed from every pack, and `designMode.editorOpen` and `console.reportIndex.newReport` are added. Nothing to migrate. +The design mode's 「New dashboard…」 is unchanged. In `@object-ui/i18n`, `designMode.menu.newReport`, `designMode.menu.newReportLeft` and `report.builder.addsToMenu` are removed from every pack, and `designMode.editorOpen`, `console.reportIndex.newReport`, `report.builder.designModeOnTitle` and `report.builder.designModeOn` are added. Nothing to migrate. diff --git a/ui/packages/app-shell/src/views/ReportNewPage-36692.test.tsx b/ui/packages/app-shell/src/views/ReportNewPage-36692.test.tsx index e66f238fc47..088e026c6e7 100644 --- a/ui/packages/app-shell/src/views/ReportNewPage-36692.test.tsx +++ b/ui/packages/app-shell/src/views/ReportNewPage-36692.test.tsx @@ -9,7 +9,10 @@ * page says nothing about a menu; * - Close goes back to the app's reports index; * - while the builder is open it holds the design mode out, so entering the - * mode refuses with the prompt and the screen keeps one Save/Cancel set. + * mode refuses with the prompt and the screen keeps one Save/Cancel set; + * - reached with the mode already on (the browser's Back), the page draws a + * prompt in place of the builder, and the builder opens once the mode is + * left. * * Real subjects: `ReportNewPage` and the shell's design-mode controller. The * builder is a stub with a Save and a Close (the real one is @@ -21,7 +24,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 } from '@testing-library/react'; -import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; +import { MemoryRouter, Route, Routes, useLocation, useNavigate } from 'react-router-dom'; const DRAFT = vi.hoisted(() => ({ name: '', @@ -91,6 +94,9 @@ function Shell({ children }: { children: React.ReactNode }) { + {children} ); @@ -110,6 +116,31 @@ function mount() { ); } +/** A link inside the app, standing in for the browser's Back to `reports/new`. */ +function GoNew() { + const navigate = useNavigate(); + return ( + + ); +} + +/** Starts on the reports index, where nothing holds the mode out. */ +function mountOnIndex() { + render( + + + + } /> + } /> + + + + , + ); +} + const flush = () => act(async () => { await new Promise((r) => setTimeout(r, 0)); @@ -157,3 +188,45 @@ describe('the new-report page saves on its own (objectstack#36692)', () => { expect(screen.getByTestId('builder')).toBeInTheDocument(); }); }); + +describe('reached with the design mode already on, the page draws no builder (objectstack#36692)', () => { + it('mode on, then reports/new mounts: no builder and no second Save, the prompt instead', async () => { + mountOnIndex(); + fireEvent.click(screen.getByText('enter design mode')); + await flush(); + expect(screen.getByTestId('mode')).toHaveTextContent('on'); + fireEvent.click(screen.getByText('go to new report')); + await flush(); + expect(screen.getByTestId('where').textContent).toBe('/apps/crm/reports/new'); + expect(screen.getByTestId('mode')).toHaveTextContent('on'); + expect(screen.queryByTestId('builder')).toBeNull(); + expect(screen.queryByText('save')).toBeNull(); + expect(screen.getByTestId('report-new-design-mode')).toBeInTheDocument(); + }); + + it('once the mode is left, the builder opens there and holds the mode out', async () => { + mountOnIndex(); + fireEvent.click(screen.getByText('enter design mode')); + await flush(); + fireEvent.click(screen.getByText('go to new report')); + await flush(); + fireEvent.click(screen.getByText('cancel design mode')); + await flush(); + expect(screen.getByTestId('mode')).toHaveTextContent('off'); + expect(screen.getByTestId('builder')).toBeInTheDocument(); + fireEvent.click(screen.getByText('enter design mode')); + await flush(); + expect(screen.getByTestId('mode')).toHaveTextContent('off'); + expect(screen.getByTestId('builder')).toBeInTheDocument(); + }); + + it('control: with the mode off, reports/new draws the builder and no prompt', async () => { + mountOnIndex(); + fireEvent.click(screen.getByText('go to new report')); + await flush(); + expect(screen.getByTestId('mode')).toHaveTextContent('off'); + expect(screen.getByTestId('builder')).toBeInTheDocument(); + expect(screen.getByText('save')).toBeInTheDocument(); + expect(screen.queryByTestId('report-new-design-mode')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/ReportNewPage.tsx b/ui/packages/app-shell/src/views/ReportNewPage.tsx index 2f96de0253a..f81d258a824 100644 --- a/ui/packages/app-shell/src/views/ReportNewPage.tsx +++ b/ui/packages/app-shell/src/views/ReportNewPage.tsx @@ -20,6 +20,10 @@ * links reports that exist. The builder's Save and Close in its own header * are the screen's one Save/Cancel set: while the builder is open it holds * the design mode out (`useHoldDesignModeOut`), so entering the mode refuses. + * The address can still be reached with the mode already on (the browser's + * Back from a page of the app the mode was entered on), so while the mode is + * on the page draws a prompt in place of the builder, and the builder opens + * once the mode is saved or cancelled. * * @module */ @@ -35,7 +39,7 @@ import { formatMetadataError } from '@object-ui/data-objectstack'; import type { DataSource } from '@object-ui/types'; import type { ReportDraft } from '@object-ui/plugin-report'; import { ReportBuilderHost } from './ReportBuilderHost.js'; -import { useHoldDesignModeOut } from '../layout/designMode.js'; +import { useDesignModeActive, useHoldDesignModeOut } from '../layout/designMode.js'; import { saveAndPublishRuntimeMetadata } from './runtime-metadata-persistence.js'; import { useMetadataClient } from './metadata-admin/useMetadata.js'; import { useMetadata } from '../providers/MetadataProvider.js'; @@ -90,8 +94,9 @@ export function ReportNewPage({ dataSource }: { dataSource?: DataSource }) { const metadataClient = useMetadataClient(); const { reports, loading, refresh } = useMetadata(); const { isAdmin, isResolved } = useWorkspaceAdminStatus(); + const designing = useDesignModeActive(); // The builder is open whenever this page draws it (objectstack#36692). - useHoldDesignModeOut(isResolved && isAdmin); + useHoldDesignModeOut(isResolved && isAdmin && !designing); const backToReports = React.useCallback(() => { if (appName) navigate(`/apps/${appName}/reports`); @@ -162,6 +167,18 @@ export function ReportNewPage({ dataSource }: { dataSource?: DataSource }) { ); } + // Never a second Save/Cancel set under the design mode's bar (objectstack#36692). + if (designing) { + return ( +
    + + {t('report.builder.designModeOnTitle')} + {t('report.builder.designModeOn')} + +
    + ); + } + return (