From 2b531cd23293a3700fd7058720947fe07a126657 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 00:32:59 +0000 Subject: [PATCH 1/6] feat(app-shell): create a dashboard from the design mode's Add menu item The picker's Dashboards list starts with New dashboard...: a name, then the dashboard is created empty in the package the menu is saved to, its entry takes the held place, every staged change is saved with it, and the new dashboard opens in its edit state. A refused menu save removes the dashboard again; cancel writes nothing. Claude-Session: https://claude.ai/code/session_01ADHkmPiTdmLxHXBjakSvJy Co-authored-by: Claude --- .../app-shell/src/layout/DesignModeMenu.tsx | 171 +++++++++++++++++- .../app-shell/src/layout/designMode.tsx | 44 ++++- .../app-shell/src/layout/designModeArrival.ts | 39 ++++ .../src/layout/designModeMenuCreate.ts | 155 ++++++++++++++++ .../src/layout/designModeMenuSave.ts | 50 ++++- .../app-shell/src/views/DashboardView.tsx | 22 ++- ui/packages/i18n/src/locales/ar.ts | 7 + ui/packages/i18n/src/locales/de.ts | 7 + ui/packages/i18n/src/locales/en.ts | 7 + ui/packages/i18n/src/locales/es.ts | 7 + ui/packages/i18n/src/locales/fr.ts | 7 + ui/packages/i18n/src/locales/ja.ts | 7 + ui/packages/i18n/src/locales/ko.ts | 7 + ui/packages/i18n/src/locales/pt-BR.ts | 7 + ui/packages/i18n/src/locales/ru.ts | 7 + ui/packages/i18n/src/locales/zh-Hans.ts | 7 + ui/packages/i18n/src/locales/zh-Hant.ts | 7 + 17 files changed, 543 insertions(+), 15 deletions(-) create mode 100644 ui/packages/app-shell/src/layout/designModeArrival.ts create mode 100644 ui/packages/app-shell/src/layout/designModeMenuCreate.ts diff --git a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx index 10afd48377f..4d92ae35175 100644 --- a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx +++ b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx @@ -32,6 +32,13 @@ * 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. * + * In the picker's 「Dashboards」, the first row is 「New dashboard…」 + * (objectstack#36364): it asks for a name, and on 「Create」 the dashboard is + * created, empty, where the menu is saved, its entry takes the dashed row's + * 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. + * * Every edit is staged with the mode (`useDesignModeChange`), under one key * for the app's menu: the mode's 「Save」 writes it (`saveAppMenu`), its * 「Cancel」 drops it. The menu drawn is the staged one, so it survives a page @@ -45,7 +52,8 @@ */ import * as React from 'react'; -import { Link } from 'react-router-dom'; +import { Link, useNavigate } from 'react-router-dom'; +import { toast } from 'sonner'; import { DndContext, KeyboardSensor, @@ -145,6 +153,8 @@ import { readStoredMenu, saveAppMenu, } from './designModeMenuSave.js'; +import { freeItemName, isNewMenuItemKind, saveAppMenuWithNewItem, type NewMenuItemKind } from './designModeMenuCreate.js'; +import { dashboardEditArrival } from './designModeArrival.js'; /** * The group label's icon-mode hiding, as the sidebar's own labels declare it @@ -355,6 +365,51 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso setAddAt(null); }; + // objectstack#36364 — a new dashboard, in the held place: created, put in + // the menu and saved with every other staged change in one act, then opened + // for editing. Resolves `false` when nothing was saved (the mode has said + // why); the held place and the picker stay, for another try or a cancel. + const navigate = useNavigate(); + const saveWith = change.saveWith; + const createItem = async (kind: NewMenuItemKind, label: string, taken: readonly string[]): Promise => { + if (!addAt) return false; + let name: string; + try { + name = await freeItemName(kind, label, taken, client as never); + } catch (err) { + toast.error( + t('designMode.saveFailed', { + defaultValue: 'Some changes were not saved: {{reason}}', + reason: err instanceof Error ? err.message : String(err), + }), + ); + return false; + } + const entry = entryFor(kind, name, newEntryId([...menu, ...(storedMenu ?? [])])); + const item = { kind, name, label }; + const itemTexts = { + ...texts, + itemPendingDraft: t('designMode.menu.newItemPendingDraft', { + defaultValue: 'A draft with this name is already pending. Try again.', + }), + itemLeft: t('designMode.menu.newItemLeft', { + defaultValue: 'The new dashboard "{{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 }, + itemTexts, + consoleAppMenuDoors(client as never), + ), + ); + if (!saved) return false; + setAddAt(null); + navigate(resolveHref(entry as unknown as NavigationItem, basePath).href, { state: dashboardEditArrival(name) }); + return true; + }; + const renderLeaf = (entry: MenuEntry, depth: number) => { const id = String(entry.id); const place = placeOf(menu, id); @@ -460,6 +515,7 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso inMenu={menuTargets(menu)} onClose={() => setAddAt(null)} onPick={(kind, name, link) => pick(entryFor(kind, name, newEntryId([...menu, ...(storedMenu ?? [])]), link))} + onCreate={createItem} language={language} /> )} @@ -747,12 +803,15 @@ function MenuItemPicker({ inMenu, onClose, onPick, + onCreate, language, }: { packageId: string; inMenu: ReadonlySet; onClose: () => void; onPick: (kind: MenuTargetKind, name: string, link?: { label: string; url: string }) => void; + /** Create a new `kind` named `label`; `taken` is every name of that kind the picker lists. */ + onCreate: (kind: NewMenuItemKind, label: string, taken: readonly string[]) => Promise; language: string; }) { const { t } = useObjectTranslation(); @@ -760,6 +819,23 @@ function MenuItemPicker({ const [kind, setKind] = React.useState(null); const [query, setQuery] = React.useState(''); const [link, setLink] = React.useState({ label: '', url: '' }); + /** The kind being named for creation (objectstack#36364), `null` while picking. */ + const [naming, setNaming] = React.useState(null); + if (naming !== null) { + return ( + + onCreate(naming, label, rows.filter((row) => row.kind === naming).map((row) => row.name)) + } + /> + ); + } + // Each key written whole, so the i18n call-site gate sees every one. + const newTexts: Record = { + dashboard: t('designMode.menu.newDashboard', { defaultValue: 'New dashboard…' }), + }; // Each key written whole, so the i18n call-site gate sees every one. const kindTexts: Record = { object: t('designMode.menu.kind.object', { defaultValue: 'Objects' }), @@ -847,6 +923,19 @@ function MenuItemPicker({ ) : (
    + {kind !== null && isNewMenuItemKind(kind) && ( +
  • + +
  • + )} {loading ? (
  • {t('designMode.menu.loading', { defaultValue: 'Loading…' })}
  • ) : offered.length === 0 ? ( @@ -878,6 +967,86 @@ function MenuItemPicker({ ); } +/** + * The name step of 「New dashboard…」 (objectstack#36364): a name, and + * 「Create」 or 「Cancel」. 「Cancel」 (and closing the dialog) writes nothing; + * 「Create」 waits on `onCreate`, and stays open with the name when it fails. + */ +function NewItemDialog({ + kind, + onCancel, + onCreate, +}: { + kind: NewMenuItemKind; + onCancel: () => void; + onCreate: (label: string) => Promise; +}) { + const { t } = useObjectTranslation(); + const [label, setLabel] = React.useState(''); + const [busy, setBusy] = React.useState(false); + const busyRef = React.useRef(false); + // Each key written whole, so the i18n call-site gate sees every one. + const titles: Record = { + dashboard: t('designMode.menu.newDashboardTitle', { defaultValue: 'New dashboard' }), + }; + const submit = async () => { + const name = label.trim(); + if (!name || busyRef.current) return; + busyRef.current = true; + setBusy(true); + try { + await onCreate(name); + } finally { + busyRef.current = false; + setBusy(false); + } + }; + return ( + !open && !busyRef.current && onCancel()}> + + + {titles[kind]} + +
    { + e.preventDefault(); + void submit(); + }} + > +
    + + setLabel(e.target.value)} + aria-describedby="design-menu-new-hint" + data-testid="design-menu-new-name" + /> +

    + {t('designMode.menu.newItemSavesAll', { + defaultValue: 'Creating it saves your other design changes too, then opens it for editing.', + })} +

    +
    + + + + +
    +
    +
    + ); +} + function RenameDialog({ label, icon, diff --git a/ui/packages/app-shell/src/layout/designMode.tsx b/ui/packages/app-shell/src/layout/designMode.tsx index 67099e4e49e..1d6e25b66b6 100644 --- a/ui/packages/app-shell/src/layout/designMode.tsx +++ b/ui/packages/app-shell/src/layout/designMode.tsx @@ -27,6 +27,13 @@ * - 「Cancel」 drops every staged change and leaves the mode. Nothing staged * was written, so there is nothing to undo. * - With nothing staged, 「Save」 is off. + * - A surface may also stage a change and save at once (`saveWith`): the + * change is committed with the rest, in the place its key holds, as if it + * had been staged and 「Save」 pressed. It is never staged on its own: when + * the save fails, what was staged under its key before stays staged and + * the change is gone, so a change that writes more than its key's value + * (the menu entry of a dashboard created for it, objectstack#36364) is + * never left staged for a later 「Save」 to half-write. * * ## What leaving costs * @@ -83,6 +90,8 @@ interface DesignModeStore extends DesignModeValue { readonly changes: StagedChanges; readonly stage: (key: string, change: DesignModeChange) => void; readonly unstage: (key: string) => void; + /** Save every staged change with `change` in `key`'s place; `false` when one failed. */ + readonly saveWith: (key: string, change: DesignModeChange) => Promise; } const DesignModeContext = React.createContext(null); @@ -163,14 +172,15 @@ export function useDesignModeController({ }, []); const savingRef = React.useRef(false); - const save = React.useCallback(async (): Promise => { + const commitAll = React.useCallback(async (extra?: { key: string; change: DesignModeChange }): Promise => { if (savingRef.current) return false; const start = heldRef.current; if (start.app === null) return false; + const changes = extra ? new Map(start.changes).set(extra.key, extra.change) : start.changes; savingRef.current = true; setSaving(true); try { - for (const [key, change] of start.changes) { + for (const [key, change] of changes) { try { await change.commit(change.value); } catch (error) { @@ -183,8 +193,11 @@ export function useDesignModeController({ return false; } // Saved: off the list, unless it was staged again while it was sent. + // A change saved with `saveWith` supersedes what its key held. + const was = start.changes.get(key); setHeld((prev) => { - if (prev.changes.get(key) !== change) return prev; + const now = prev.changes.get(key); + if (now === undefined || (now !== change && now !== was)) return prev; const next = new Map(prev.changes); next.delete(key); return { app: prev.app, changes: next }; @@ -197,6 +210,11 @@ export function useDesignModeController({ setSaving(false); } }, [t]); + const save = React.useCallback(() => commitAll(), [commitAll]); + const saveWith = React.useCallback( + (key: string, change: DesignModeChange) => commitAll({ key, change }), + [commitAll], + ); // Leaving the app drops what is staged; a page of the same app keeps it. const leaveMessage = t('designMode.leaveUnsaved', { @@ -210,8 +228,8 @@ export function useDesignModeController({ }, [dirty, leaveMessage, appBasePath]); return React.useMemo( - () => ({ active, dirty, saving, enter, cancel, save, changes, stage, unstage }), - [active, dirty, saving, enter, cancel, save, changes, stage, unstage], + () => ({ active, dirty, saving, enter, cancel, save, changes, stage, unstage, saveWith }), + [active, dirty, saving, enter, cancel, save, changes, stage, unstage, saveWith], ); } @@ -235,13 +253,17 @@ export function useDesignModeActive(): boolean { * its change under `key` (one key per thing changed, such as the app's menu), * and the mode saves or drops it with the rest. `value` is what is staged * under `key`, `undefined` when nothing is: a surface draws from it, so its - * pending state survives a page change. Outside a shell that holds the mode, - * nothing is ever staged and `stage` does nothing. + * pending state survives a page change. `saveWith` saves every staged change + * with `value` in `key`'s place, and leaves the mode when all were saved + * (`false` when one failed; outside a shell that holds the mode, `false` and + * nothing written). Outside a shell that holds the mode, nothing is ever + * staged and `stage` does nothing. */ export function useDesignModeChange(key: string): { readonly value: T | undefined; readonly stage: (value: T, commit: (value: T) => Promise) => void; readonly unstage: () => void; + readonly saveWith: (value: T, commit: (value: T) => Promise) => Promise; } { const store = React.useContext(DesignModeContext); const staged = store?.changes.get(key) as DesignModeChange | undefined; @@ -253,5 +275,11 @@ export function useDesignModeChange(key: string): { [storeStage, key], ); const unstage = React.useCallback(() => storeUnstage?.(key), [storeUnstage, key]); - return { value: staged?.value, stage, unstage }; + const storeSaveWith = store?.saveWith; + const saveWith = React.useCallback( + async (value: T, commit: (value: T) => Promise) => + storeSaveWith ? storeSaveWith(key, { value, commit: commit as (value: unknown) => Promise }) : false, + [storeSaveWith, key], + ); + return { value: staged?.value, stage, unstage, saveWith }; } diff --git a/ui/packages/app-shell/src/layout/designModeArrival.ts b/ui/packages/app-shell/src/layout/designModeArrival.ts new file mode 100644 index 00000000000..421fd0f915c --- /dev/null +++ b/ui/packages/app-shell/src/layout/designModeArrival.ts @@ -0,0 +1,39 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The landing of a dashboard the design mode just created (objectstack#36364): + * the design mode navigates to the new dashboard with this in the navigation + * state, and the dashboard's page opens its edit state on arrival + * (objectstack#36372), as its Edit button does. + * + * Navigation state, not a URL parameter: it is a one-time instruction, not a + * place anyone links to, so a shared or reloaded address never opens the edit + * state by itself. The page clears it once read. + * + * @module + */ + +/** The navigation-state key the landing rides on. */ +export const DASHBOARD_EDIT_ARRIVAL_STATE = 'designModeNewDashboard'; + +/** The navigation state that opens the dashboard `name` for editing on arrival. */ +export function dashboardEditArrival(name: string): Record { + return { [DASHBOARD_EDIT_ARRIVAL_STATE]: name }; +} + +/** + * Whether `state` asks the page of the dashboard `name` to open its edit + * state: only a landing that names THIS dashboard, so a history entry of + * another dashboard opens nothing. + */ +export function readDashboardEditArrival(state: unknown, name: string | null | undefined): boolean { + if (!name || !state || typeof state !== 'object') return false; + return (state as Record)[DASHBOARD_EDIT_ARRIVAL_STATE] === name; +} + +/** `state` without the landing, for the replace that clears it once read. */ +export function withoutDashboardEditArrival(state: unknown): Record | null { + if (!state || typeof state !== 'object') return null; + const { [DASHBOARD_EDIT_ARRIVAL_STATE]: _landing, ...rest } = state as Record; + return Object.keys(rest).length > 0 ? rest : null; +} diff --git a/ui/packages/app-shell/src/layout/designModeMenuCreate.ts b/ui/packages/app-shell/src/layout/designModeMenuCreate.ts new file mode 100644 index 00000000000..061b1aaa25a --- /dev/null +++ b/ui/packages/app-shell/src/layout/designModeMenuCreate.ts @@ -0,0 +1,155 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A new dashboard made from the design mode's 「Add menu item」 + * (objectstack#36364): named in the picker, created where the menu is + * saved, and put in the menu in the place the editor held for it. + * + * Where it is saved is the menu's own package (`prepareAppMenuSave`): the + * app's package when the server lists it writable, else its customization + * package (ADR-0146 D2, the maintainer's 「定制都进 .custom」; objectstack#35624 + * ruling C). Where no such package can be had the menu cannot be saved + * either, so nothing is created: there is no package-less fallback here. + * + * The order is what keeps a refused save from leaving anything behind: + * + * 1. every check of the menu save is made first, and nothing is written + * before they pass; + * 2. the dashboard is created and published (`saveDashboardInPlace`), empty, + * so everyone the menu shows it to finds an empty dashboard, never a + * missing one; + * 3. the menu is written and published (`writeAppMenu`), the new entry and + * every other staged menu edit with it; + * 4. when the menu is refused, the dashboard made in step 2 is removed again + * (the item's delete in its package), and the refusal is said. Should that + * removal be refused too, the refusal says the dashboard was left. + * + * Only a dashboard is offered. A report cannot be created from a name alone: + * the spec refuses a report without `dataset` and `values`, so an empty + * report is not a report anyone could publish. + * + * @module + */ + +import { emitMetadataRefresh } from '../assistant/assistantBus.js'; +import { slugify } from '../views/metadata-admin/createDerive.js'; +import { romanizeHan } from '../views/metadata-admin/romanizeHan.js'; +import { saveDashboardInPlace } from '../views/runtime-metadata-persistence.js'; +import type { Menu } from './designModeMenu.js'; +import { + prepareAppMenuSave, + writeAppMenu, + type AppMenuSaveDoors, + type AppMenuSaveTexts, +} from './designModeMenuSave.js'; + +/** The kinds of thing the picker creates. */ +export const NEW_MENU_ITEM_KINDS = ['dashboard'] as const; +export type NewMenuItemKind = (typeof NEW_MENU_ITEM_KINDS)[number]; + +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. */ +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 { + /** A draft is already pending under the new item's name. */ + readonly itemPendingDraft: string; + /** The menu was refused and the item created for it could not be removed; `{{name}}` is its name. */ + readonly itemLeft: string; +} + +/** The longest machine name the generator writes, before a numeric suffix. */ +const NAME_MAX = 48; + +/** + * A machine name for a new `kind` named `label`: the name's snake_case form + * (a Chinese name through its pinyin, `romanizeHan`), else the kind, made + * unique against `taken` with a `_2`, `_3`, … suffix. + */ +export function uniqueItemName(kind: NewMenuItemKind, label: string, taken: Iterable): string { + const used = new Set(taken); + let base = slugify(romanizeHan(label)).slice(0, NAME_MAX).replace(/_+$/g, ''); + if (!/^[a-z_][a-z0-9_]*$/.test(base)) base = kind; + if (!used.has(base)) return base; + for (let i = 2; i < 10_000; i += 1) { + const candidate = `${base}_${i}`; + if (!used.has(candidate)) return candidate; + } + return `${base}_${Date.now().toString(36)}`; +} + +/** How many names {@link freeItemName} asks the server about before it gives up. */ +const NAME_TRIES = 20; + +/** + * A machine name for a new `kind` named `label` that no item of that kind + * holds, in any package: each candidate ({@link uniqueItemName}, `taken` + * left out) is read by name, and a name the read finds is passed over. A + * read that fails is thrown: a name that could not be checked is not used, + * since saving over an existing item would publish over it. + */ +export async function freeItemName( + kind: NewMenuItemKind, + label: string, + taken: Iterable, + client: { get: (type: string, name: string) => Promise }, +): Promise { + const used = new Set(taken); + for (let i = 0; i < NAME_TRIES; i += 1) { + const candidate = uniqueItemName(kind, label, used); + if ((await client.get(kind, candidate)) == null) return candidate; + used.add(candidate); + } + throw new Error(`No free ${kind} name was found for "${label}".`); +} + +/** The body a new, empty `kind` is created with. */ +export function newItemBody(item: NewMenuItem): Record { + switch (item.kind) { + case 'dashboard': + return { name: item.name, label: item.label, widgets: [] }; + } +} + +/** + * Create `item`, then save the menu edits that turned `served` into + * `navigation` (the new item's entry among them), in that order and in the + * same package; when the menu is refused, the item is removed again. + */ +export async function saveAppMenuWithNewItem( + input: { appName: string; packageId: string; served: Menu; navigation: Menu; item: NewMenuItem }, + texts: NewMenuItemTexts, + doors: AppMenuSaveDoors, +): Promise { + const { item } = input; + const prepared = await prepareAppMenuSave(input, texts, doors); + 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); + } catch (err) { + try { + await doors.client.reset(item.kind, item.name, { packageId: prepared.target }); + } catch (removeErr) { + console.error(`[design-mode] the ${item.kind} "${item.name}" created for a refused menu was left:`, removeErr); + const reason = err instanceof Error ? err.message : String(err); + throw Object.assign(new Error(`${reason} ${texts.itemLeft}`), { cause: err }); + } finally { + emitMetadataRefresh(); + } + throw err; + } +} diff --git a/ui/packages/app-shell/src/layout/designModeMenuSave.ts b/ui/packages/app-shell/src/layout/designModeMenuSave.ts index 1a67c611f5a..357b89961d6 100644 --- a/ui/packages/app-shell/src/layout/designModeMenuSave.ts +++ b/ui/packages/app-shell/src/layout/designModeMenuSave.ts @@ -92,15 +92,32 @@ function storedApp(layers: unknown): Record { } /** - * Save the menu edits that turned `served` (the menu the editor was seeded - * from) into `navigation`, as the menu of the app `appName` of the package - * `packageId`, and publish it. + * 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 + * customization package the ensure door creates on first use. */ -export async function saveAppMenu( +export interface PreparedAppMenuSave { + readonly appName: string; + /** + * The package the menu is written to: the app's own when the server lists + * it writable, else its customization package. A thing created in design + * mode for the menu to open is saved here too (objectstack#36364). + */ + readonly target: string; + readonly body: Record; +} + +/** + * Every check of a save of the menu edits that turned `served` (the menu the + * editor was seeded from) into `navigation`, as the menu of the app `appName` + * of the package `packageId`, and its body. Throws, in the viewer's language, + * where the menu cannot be saved; nothing is written then. + */ +export async function prepareAppMenuSave( input: { appName: string; packageId: string; served: Menu; navigation: Menu }, texts: AppMenuSaveTexts, doors: AppMenuSaveDoors, -): Promise { +): Promise { const { appName, packageId, served, navigation } = input; const manifests = await doors.listPackages(); const listed = manifests.get(packageId); @@ -118,6 +135,16 @@ export async function saveAppMenu( if (!pair.writable) throw new Error(texts.notWritable); target = pair.packageId; } + return { appName, target, body }; +} + +/** Write and publish a prepared menu save ({@link prepareAppMenuSave}). */ +export async function writeAppMenu( + prepared: PreparedAppMenuSave, + texts: Pick, + doors: Pick, +): Promise { + const { appName, target, body } = prepared; try { await doors.client.save('app', appName, body, { mode: 'draft', packageId: target, ifNoneMatch: '*' }); } catch (err) { @@ -138,6 +165,19 @@ export async function saveAppMenu( emitMetadataRefresh(); } +/** + * Save the menu edits that turned `served` (the menu the editor was seeded + * from) into `navigation`, as the menu of the app `appName` of the package + * `packageId`, and publish it. + */ +export async function saveAppMenu( + input: { appName: string; packageId: string; served: Menu; navigation: Menu }, + texts: AppMenuSaveTexts, + doors: AppMenuSaveDoors, +): Promise { + await writeAppMenu(await prepareAppMenuSave(input, texts, doors), texts, doors); +} + /** The console's doors, around `client` (`useMetadataClient()`). */ export function consoleAppMenuDoors(client: AppMenuSaveDoors['client']): AppMenuSaveDoors { return { listPackages: fetchListedPackageManifests, ensureCustomization: ensureCustomizationPackage, client }; diff --git a/ui/packages/app-shell/src/views/DashboardView.tsx b/ui/packages/app-shell/src/views/DashboardView.tsx index 692315c07d1..b2796b1f449 100644 --- a/ui/packages/app-shell/src/views/DashboardView.tsx +++ b/ui/packages/app-shell/src/views/DashboardView.tsx @@ -12,7 +12,7 @@ */ import { useState, useEffect, useMemo, useRef, type ComponentProps } from 'react'; -import { useParams } from 'react-router-dom'; +import { useLocation, useNavigate, useParams } from 'react-router-dom'; import { DashboardRenderer } from '@object-ui/plugin-dashboard'; import { DrillNavigationProvider, notifyDataChanged } from '@object-ui/react'; import { useRecordListDrillNavigation } from './useOpenRecordList.js'; @@ -51,6 +51,7 @@ import { } from './DashboardInPageEditor.js'; import { useInSetupApp } from '../console/setupApp.js'; import { useCustomizeDoorWalled } from './studio-design/StudioCustomizeControls.js'; +import { readDashboardEditArrival, withoutDashboardEditArrival } from '../layout/designModeArrival.js'; /** * One refresh of this dashboard's data: the `onRefresh` handed to @@ -296,6 +297,25 @@ export function DashboardView({ dataSource }: { dataSource?: any }) { } }; + // objectstack#36364 — a dashboard the design mode just created arrives with + // its page asked to open the edit state, once the Edit button is offered; + // the landing is cleared as it is read, so Back or a reload opens nothing. + const location = useLocation(); + const navigate = useNavigate(); + const arrivedToEdit = readDashboardEditArrival(location.state, dashboardName); + const landedRef = useRef(null); + useEffect(() => { + if (!arrivedToEdit || !dashboard || !editOffered || editing) return; + if (landedRef.current === location.key) return; + landedRef.current = location.key; + navigate(`${location.pathname}${location.search}${location.hash}`, { + replace: true, + state: withoutDashboardEditArrival(location.state), + }); + void startEdit(); + // eslint-disable-next-line react-hooks/exhaustive-deps -- runs once per landing; `startEdit` is a fresh closure each render + }, [arrivedToEdit, dashboard, editOffered, editing, location.key]); + const previewSchema = useMemo(() => { if (!dashboard || !unregistered) return dashboard; const widgets = (dashboard as any).widgets; diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index ac43f404220..98b70ea77c2 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -3881,6 +3881,13 @@ const ar = { pendingDraft: 'لهذا التطبيق تغييرات غير منشورة في Studio. انشرها أو تجاهلها هناك، ثم احفظ مرة أخرى.', noVersion: 'حزمة هذا التطبيق لا تذكر إصدارًا، لذا لا يمكن تخصيص قائمته.', notWritable: 'حزمة تخصيص هذا التطبيق غير قابلة للكتابة، لذا لا يمكن حفظ قائمته.', + newDashboard: 'لوحة معلومات جديدة…', + newDashboardTitle: 'لوحة معلومات جديدة', + newItemSavesAll: 'يؤدي إنشاؤها إلى حفظ تغييرات التصميم الأخرى أيضًا، ثم تُفتح للتحرير.', + create: 'إنشاء', + creating: 'جارٍ الإنشاء…', + newItemPendingDraft: 'توجد مسودة غير منشورة بهذا الاسم بالفعل. حاول مرة أخرى.', + newItemLeft: 'تعذّرت إزالة لوحة المعلومات الجديدة "{{name}}"؛ أزلها في Studio.', }, }, topbar: { diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 8084ec8f42f..70bea0a8c3b 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -3558,6 +3558,13 @@ 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.', + newDashboard: 'Neues Dashboard…', + newDashboardTitle: 'Neues Dashboard', + newItemSavesAll: 'Beim Erstellen werden auch Ihre anderen Designänderungen gespeichert; danach wird es zum Bearbeiten geöffnet.', + create: 'Erstellen', + creating: 'Wird erstellt…', + newItemPendingDraft: 'Unter diesem Namen liegt bereits ein unveröffentlichter Entwurf. Versuchen Sie es erneut.', + newItemLeft: 'Das neue Dashboard „{{name}}“ konnte nicht wieder entfernt werden; entfernen Sie es in Studio.', }, }, topbar: { diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 3684e31dafe..0c56cab8060 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -4239,6 +4239,13 @@ 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.', + newDashboard: 'New dashboard…', + newDashboardTitle: 'New dashboard', + newItemSavesAll: 'Creating it saves your other design changes too, then opens it for editing.', + create: 'Create', + creating: 'Creating…', + newItemPendingDraft: 'A draft with this name is already pending. Try again.', + newItemLeft: 'The new dashboard "{{name}}" could not be removed again; remove it in Studio.', }, }, topbar: { diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 10d50139536..721d74e4276 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -3640,6 +3640,13 @@ 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.', + newDashboard: 'Nuevo panel…', + newDashboardTitle: 'Nuevo panel', + newItemSavesAll: 'Al crearlo también se guardan tus otros cambios de diseño y luego se abre para editarlo.', + create: 'Crear', + creating: 'Creando…', + newItemPendingDraft: 'Ya hay un borrador pendiente con este nombre. Inténtalo de nuevo.', + newItemLeft: 'No se pudo eliminar el nuevo panel "{{name}}"; elimínalo en Studio.', }, }, topbar: { diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 6a9fb41ee93..d491d65d7ca 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -3636,6 +3636,13 @@ 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é.', + newDashboard: 'Nouveau tableau de bord…', + newDashboardTitle: 'Nouveau tableau de bord', + newItemSavesAll: 'Le créer enregistre aussi vos autres modifications de design, puis l’ouvre en modification.', + create: 'Créer', + creating: 'Création…', + newItemPendingDraft: 'Un brouillon portant ce nom est déjà en attente. Réessayez.', + newItemLeft: 'Le nouveau tableau de bord « {{name}} » n’a pas pu être supprimé ; supprimez-le dans Studio.', }, }, topbar: { diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 61180baad15..8ceb75c236c 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -3560,6 +3560,13 @@ const ja = { pendingDraft: 'このアプリには Studio に未公開の変更があります。そちらで公開または破棄してから、もう一度保存してください。', noVersion: 'このアプリのパッケージにはバージョンがないため、メニューをカスタマイズできません。', notWritable: 'このアプリのカスタマイズパッケージに書き込めないため、メニューを保存できません。', + newDashboard: '新しいダッシュボード…', + newDashboardTitle: '新しいダッシュボード', + newItemSavesAll: '作成すると、デザインモードの他の変更も保存され、編集用に開きます。', + create: '作成', + creating: '作成中…', + newItemPendingDraft: 'この名前の未公開の下書きがすでにあります。もう一度お試しください。', + newItemLeft: '新しいダッシュボード「{{name}}」を削除できませんでした。Studio で削除してください。', }, }, topbar: { diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 5c13dde9655..59c958abe22 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -3558,6 +3558,13 @@ const ko = { pendingDraft: '이 앱에는 Studio에 게시되지 않은 변경 사항이 있습니다. 그곳에서 게시하거나 취소한 뒤 다시 저장하세요.', noVersion: '이 앱의 패키지에 버전이 없어 메뉴를 사용자 지정할 수 없습니다.', notWritable: '이 앱의 사용자 지정 패키지에 쓸 수 없어 메뉴를 저장할 수 없습니다.', + newDashboard: '새 대시보드…', + newDashboardTitle: '새 대시보드', + newItemSavesAll: '만들면 디자인 모드의 다른 변경 사항도 함께 저장되고 편집할 수 있게 열립니다.', + create: '만들기', + creating: '만드는 중…', + newItemPendingDraft: '이 이름으로 게시되지 않은 초안이 이미 있습니다. 다시 시도하세요.', + newItemLeft: '새 대시보드 "{{name}}"을(를) 삭제하지 못했습니다. Studio에서 삭제하세요.', }, }, topbar: { diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 0391db19ef5..6b02717d390 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -3635,6 +3635,13 @@ 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.', + newDashboard: 'Novo painel…', + newDashboardTitle: 'Novo painel', + newItemSavesAll: 'Ao criá-lo, suas outras alterações de design também são salvas e ele é aberto para edição.', + create: 'Criar', + creating: 'Criando…', + newItemPendingDraft: 'Já existe um rascunho pendente com este nome. Tente novamente.', + newItemLeft: 'Não foi possível remover o novo painel "{{name}}"; remova-o no Studio.', }, }, topbar: { diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 3b814bcf631..e652765333d 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -3727,6 +3727,13 @@ const ru = { pendingDraft: 'В Studio есть неопубликованные изменения этого приложения. Опубликуйте или отмените их там и сохраните снова.', noVersion: 'Пакет этого приложения не указывает версию, поэтому меню нельзя настроить.', notWritable: 'Пакет настроек этого приложения недоступен для записи, поэтому меню нельзя сохранить.', + newDashboard: 'Новая панель…', + newDashboardTitle: 'Новая панель', + newItemSavesAll: 'При создании сохраняются и другие изменения режима дизайна, затем панель открывается для редактирования.', + create: 'Создать', + creating: 'Создание…', + newItemPendingDraft: 'Под этим именем уже есть неопубликованный черновик. Повторите попытку.', + newItemLeft: 'Не удалось удалить новую панель «{{name}}»; удалите её в Studio.', }, }, topbar: { diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 4c4e8822b9e..992c15ce192 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -3639,6 +3639,13 @@ const zh = { pendingDraft: '这个应用在 Studio 里有未发布的改动。请先在那里发布或丢弃,再保存。', noVersion: '这个应用所在的包没有声明版本,菜单无法定制。', notWritable: '这个应用的定制包不可写,菜单无法保存。', + newDashboard: '新建仪表盘…', + newDashboardTitle: '新建仪表盘', + newItemSavesAll: '创建时会一并保存设计模式里的其他改动,然后打开它进行编辑。', + create: '创建', + creating: '正在创建…', + newItemPendingDraft: '这个名称下已有一份未发布的草稿,请再试一次。', + newItemLeft: '新建的仪表盘「{{name}}」没能删除,请在 Studio 里删除它。', }, }, topbar: { diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index a064abb5cca..1ab049a5af4 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -3639,6 +3639,13 @@ const zhHant = { pendingDraft: '這個應用在 Studio 裡有未釋出的改動。請先在那裡釋出或丟棄,再儲存。', noVersion: '這個應用所在的包沒有宣告版本,選單無法定製。', notWritable: '這個應用的定製包不可寫,選單無法儲存。', + newDashboard: '新建儀表盤…', + newDashboardTitle: '新建儀表盤', + newItemSavesAll: '建立時會一併儲存設計模式裡的其他變更,然後開啟它進行編輯。', + create: '建立', + creating: '正在建立…', + newItemPendingDraft: '這個名稱下已有一份未發佈的草稿,請再試一次。', + newItemLeft: '新建的儀表盤「{{name}}」沒能刪除,請在 Studio 裡刪除它。', }, }, topbar: { From 4f66359b996f64dbad6ef652c20fecec5a0276d3 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 00:36:33 +0000 Subject: [PATCH 2/6] test(app-shell): pin the design mode's new dashboard, its save-at-once and its landing Claude-Session: https://claude.ai/code/session_01ADHkmPiTdmLxHXBjakSvJy Co-authored-by: Claude --- .../__tests__/DesignModeMenu-36363.test.tsx | 125 ++++++++++- .../__tests__/designMode-36362.test.tsx | 72 +++++++ .../designModeMenuCreate-36364.test.ts | 202 ++++++++++++++++++ .../src/layout/designModeMenuCreate.ts | 6 +- .../DashboardView.inPageEdit-36372.test.tsx | 39 +++- 5 files changed, 439 insertions(+), 5 deletions(-) create mode 100644 ui/packages/app-shell/src/layout/__tests__/designModeMenuCreate-36364.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 56ddeb7ce41..67110831967 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 @@ -65,6 +65,8 @@ const listed = vi.hoisted(() => ({ { name: 'crm_lead_record', label: 'Lead record', type: 'record' }, ], }) 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 })); /** The app's menu as stored (`null`: as served). */ const storedNav = vi.hoisted(() => ({ current: null as unknown[] | null, failReads: 0 })); const client = vi.hoisted(() => ({ @@ -77,15 +79,20 @@ const client = vi.hoisted(() => ({ const code = { name: 'crm', label: 'CRM', navigation: storedNav.current ?? NAVIGATION }; return { code, effective: code }; }, + get: async (type: string, name: string) => (server.held.has(`${type}/${name}`) ? { name } : null), save: async (...args: unknown[]) => { written.push(['save', ...args]); + if (args[0] === 'app' && server.appSave) throw server.appSave; return {}; }, publish: async (...args: unknown[]) => { written.push(['publish', ...args]); return {}; }, - reset: async () => ({}), + reset: async (...args: unknown[]) => { + written.push(['reset', ...args]); + return {}; + }, })); vi.mock('../../views/metadata-admin/useMetadata', async (importOriginal) => ({ ...(await importOriginal>()), @@ -202,6 +209,8 @@ beforeEach(() => { session.defaultLocale = 'en'; storedNav.current = null; storedNav.failReads = 0; + server.held.clear(); + server.appSave = null; __resetDefaultLocale(); vi.stubGlobal( 'fetch', @@ -648,3 +657,117 @@ describe('the menu under the design mode (objectstack#36363)', () => { expect(switchedTo).toEqual(['hr']); }); }); + +/** objectstack#36364 — where the page went, and the navigation state it went with. */ +function Landing() { + const location = useLocation(); + return {`${location.pathname} ${JSON.stringify(location.state)}`}; +} + +function startWithLanding() { + render( + + + + , + ); + fireEvent.click(screen.getByText('enter')); +} + +/** 「Add menu item」 under Insights, then 「Dashboards」: the picker's dashboard list. */ +async function openDashboards() { + fireEvent.click(screen.getByTestId('design-menu-add-insights')); + const picker = await screen.findByTestId('design-menu-picker'); + fireEvent.click(within(picker).getByRole('button', { name: 'Dashboards' })); + await flush(); + return picker; +} + +describe('a new dashboard from 「Add menu item」 (objectstack#36364)', () => { + it('「Dashboards」 lists 「New dashboard…」 first, above the dashboards not in the menu yet', async () => { + listed.dashboard = [{ name: 'revenue', label: 'Revenue' }]; + try { + start(); + const picker = await openDashboards(); + const rows = within(within(picker).getByTestId('design-menu-picker-rows')).getAllByRole('button').map((b) => b.textContent); + expect(rows).toEqual(['New dashboard…', 'Revenue']); + // Another kind has no such row. + fireEvent.click(within(picker).getByRole('button', { name: 'Dashboards' })); + fireEvent.click(within(picker).getByRole('button', { name: 'Reports' })); + await flush(); + expect(within(picker).queryByText('New dashboard…')).toBeNull(); + } finally { + listed.dashboard = []; + } + }); + + it('「Cancel」 at the name writes nothing and leaves nothing in the menu', async () => { + start(); + const picker = await openDashboards(); + fireEvent.click(within(picker).getByTestId('design-menu-picker-new-dashboard')); + const naming = await screen.findByTestId('design-menu-new-dashboard'); + fireEvent.change(within(naming).getByTestId('design-menu-new-name'), { target: { value: 'Payment analysis' } }); + fireEvent.click(within(naming).getByTestId('design-menu-new-cancel')); + await flush(); + expect(screen.queryByTestId('design-menu-new-dashboard')).toBeNull(); + expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', []]]); + expect(written).toEqual([]); + expect(screen.getByTestId('design-mode-save')).toBeDisabled(); + }); + + it('「Create」: the dashboard, then the menu with its entry in the held place and every other staged edit; the mode is left and the dashboard opens for editing', async () => { + server.held.add('dashboard/payment_analysis'); // a dashboard of another app holds the plain name + startWithLanding(); + await act_on('accounts', 'Move up'); // another staged edit, saved with it + const picker = await openDashboards(); + fireEvent.click(within(picker).getByTestId('design-menu-picker-new-dashboard')); + const naming = await screen.findByTestId('design-menu-new-dashboard'); + fireEvent.change(within(naming).getByTestId('design-menu-new-name'), { target: { value: 'Payment analysis' } }); + expect(written).toEqual([]); + fireEvent.click(within(naming).getByTestId('design-menu-new-create')); + await flush(); + await flush(); + await flush(); + + expect(written.map(([verb, type, name]) => `${verb} ${type} ${name}`)).toEqual([ + 'save dashboard payment_analysis_2', + 'publish dashboard payment_analysis_2', + 'save app crm', + 'publish app crm', + ]); + expect(written[0][3]).toEqual({ name: 'payment_analysis_2', label: 'Payment analysis', widgets: [] }); + 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: 'dashboard', dashboardName: 'payment_analysis_2' }]); + expect(screen.queryByTestId('design-mode-bar')).toBeNull(); + expect(screen.getByTestId('landing')).toHaveTextContent( + '/apps/crm/dashboard/payment_analysis_2 {"designModeNewDashboard":"payment_analysis_2"}', + ); + }); + + it('a refused menu removes the new dashboard; the mode, the held place and the other staged edits stay', async () => { + server.appSave = new Error('the app was refused'); + startWithLanding(); + await act_on('accounts', 'Move up'); + const picker = await openDashboards(); + fireEvent.click(within(picker).getByTestId('design-menu-picker-new-dashboard')); + const naming = await screen.findByTestId('design-menu-new-dashboard'); + fireEvent.change(within(naming).getByTestId('design-menu-new-name'), { target: { value: 'Payment analysis' } }); + fireEvent.click(within(naming).getByTestId('design-menu-new-create')); + await flush(); + await flush(); + await flush(); + + expect(written.map(([verb, type, name, opt]) => `${verb} ${type} ${name} ${JSON.stringify(opt)}`)).toEqual([ + 'save dashboard payment_analysis {"name":"payment_analysis","label":"Payment analysis","widgets":[]}', + 'publish dashboard payment_analysis {"packageId":"com.acme.crm"}', + expect.stringMatching(/^save app crm /), + 'reset dashboard 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(screen.getByTestId('design-menu-new-dashboard')).toBeInTheDocument(); + expect(order()).toEqual(['home', ['sales', ['accounts', 'leads']], ['insights', ['…']]]); + expect(screen.getByTestId('landing')).toHaveTextContent('/apps/crm null'); + }); +}); 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 ab506a01986..5f5a7fca2b8 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 @@ -283,3 +283,75 @@ describe('isPageOfApp (objectstack#36362)', () => { expect(isPageOfApp(at('/apps/crm/x'), '/apps/crm', '/home')).toBe(true); }); }); + +/** objectstack#36364 — a surface that stages `value` under `name` and saves at once. */ +function SaverWith({ name, value, commit }: { name: string; value: string; commit: (value: string) => Promise }) { + const change = useDesignModeChange(name); + const [result, setResult] = React.useState(''); + return ( +
    + + {result} +
    + ); +} + +describe('staging a change and saving at once (objectstack#36364)', () => { + it('commits every staged change with the new one in its key’s place, in the order first staged, then leaves the mode', async () => { + const order: string[] = []; + const commit = (value: string) => { + order.push(value); + return Promise.resolve(); + }; + render( + + + + + + , + ); + fireEvent.click(screen.getByText('enter')); + fireEvent.click(screen.getByText('stage menu')); + fireEvent.click(screen.getByText('stage header')); + fireEvent.click(screen.getByText('save menu with menu-with-dashboard')); + await flush(); + expect(order).toEqual(['menu-with-dashboard', 'header-value']); + expect(screen.getByTestId('saved-with-menu')).toHaveTextContent('true'); + expect(bar()).toBeNull(); + }); + + it('a failed commit of the new change leaves what its key held before staged, and the new change gone', async () => { + const order: string[] = []; + render( + + + void order.push(value)} /> + Promise.reject(new Error('menu refused'))} /> + , + ); + fireEvent.click(screen.getByText('enter')); + fireEvent.click(screen.getByText('stage menu')); + fireEvent.click(screen.getByText('save menu with menu-with-dashboard')); + await flush(); + expect(screen.getByTestId('saved-with-menu')).toHaveTextContent('false'); + expect(toastError).toHaveBeenCalledWith('Some changes were not saved: menu refused'); + expect(bar()).not.toBeNull(); + expect(screen.getByTestId('staged-menu')).toHaveTextContent('menu-value'); + // 「Save」 now commits what was staged before, never the refused change. + fireEvent.click(save()); + await flush(); + expect(order).toEqual(['menu-value']); + }); + + it('outside a shell that holds the mode, nothing is written', async () => { + const commit = vi.fn(async () => {}); + render(); + fireEvent.click(screen.getByText('save menu with x')); + await flush(); + expect(screen.getByTestId('saved-with-menu')).toHaveTextContent('false'); + expect(commit).not.toHaveBeenCalled(); + }); +}); 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 new file mode 100644 index 00000000000..287ef803c07 --- /dev/null +++ b/ui/packages/app-shell/src/layout/__tests__/designModeMenuCreate-36364.test.ts @@ -0,0 +1,202 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A new dashboard made from the design mode's 「Add menu item」 + * (objectstack#36364): created, empty, in the package the menu is saved to, + * before the menu that opens it; refused, with nothing written, where the + * menu cannot be saved; removed again when the menu is refused. + * + * Real subjects: `saveAppMenuWithNewItem` over the real `prepareAppMenuSave`, + * `writeAppMenu` and `saveDashboardInPlace`; `freeItemName` and + * `uniqueItemName` over the real pinyin dictionary. The package doors and the + * metadata client are fakes that record every call. + */ + +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +const emitMetadataRefresh = vi.hoisted(() => vi.fn()); +vi.mock('../../assistant/assistantBus', async (importOriginal) => ({ + ...(await importOriginal>()), + emitMetadataRefresh, +})); + +import { loadHanRomanizer } from '../../views/metadata-admin/romanizeHan'; +import type { Menu } from '../designModeMenu'; +import type { AppMenuSaveDoors } from '../designModeMenuSave'; +import { + freeItemName, + newItemBody, + saveAppMenuWithNewItem, + uniqueItemName, + type NewMenuItem, +} from '../designModeMenuCreate'; + +const TEXTS = { + notListed: 'not listed', + pendingDraft: 'pending draft', + noVersion: 'no version', + notWritable: 'not writable', + itemPendingDraft: 'item pending draft', + itemLeft: 'item left', +}; +const ITEM: NewMenuItem = { kind: 'dashboard', name: 'hui_kuan_fen_xi', label: '回款分析' }; +const ENTRY = { id: 'nav_item_1', type: 'dashboard', dashboardName: 'hui_kuan_fen_xi' }; +const NAVIGATION: Menu = [{ id: 'insights', type: 'group', label: 'Insights', children: [ENTRY] }]; +const SERVED: Menu = [{ id: 'insights', type: 'group', label: 'Insights', children: [] }]; + +type Call = [string, ...unknown[]]; + +function doors(opts: { + listed?: boolean; + writable: boolean; + version?: string; + pairWritable?: boolean; + ensure?: () => Promise; + refuse?: (call: Call) => unknown; +}) { + const calls: Call[] = []; + const record = async (call: Call) => { + calls.push(call); + const refusal = opts.refuse?.(call); + if (refusal) throw refusal; + return {}; + }; + const d: AppMenuSaveDoors = { + listPackages: async () => + new Map( + opts.listed === false + ? [] + : [['com.acme.crm', { id: 'com.acme.crm', name: 'CRM', writable: opts.writable, manifest: opts.version ? { version: opts.version } : {} }]], + ), + ensureCustomization: async (base) => { + calls.push(['ensure', base]); + if (opts.ensure) return opts.ensure(); + return { basePackageId: base, packageId: `${base}.custom`, namespace: 'crm_custom', created: true, writable: opts.pairWritable ?? true }; + }, + client: { + layered: async () => { + const code = { name: 'crm', label: 'CRM', navigation: SERVED }; + return { code, effective: code }; + }, + save: (...args) => record(['save', ...args]), + publish: (...args) => record(['publish', ...args]), + reset: (...args) => record(['reset', ...args]), + }, + }; + return { d, calls }; +} + +const input = { appName: 'crm', packageId: 'com.acme.crm', served: SERVED, navigation: NAVIGATION, item: ITEM }; +const body = newItemBody(ITEM); + +beforeAll(async () => { + await loadHanRomanizer(); +}); +beforeEach(() => emitMetadataRefresh.mockReset()); + +describe('a new dashboard from the design mode (objectstack#36364)', () => { + it('is created empty: a name, the label and no cards', () => { + expect(body).toEqual({ name: 'hui_kuan_fen_xi', label: '回款分析', widgets: [] }); + }); + + it("a writable app: the dashboard is created and published in the app's package, then the menu, in that order", async () => { + const { d, calls } = doors({ writable: true }); + await saveAppMenuWithNewItem(input, TEXTS, d); + expect(calls.map(([verb, type]) => `${verb} ${type}`)).toEqual(['save dashboard', 'publish dashboard', 'save app', 'publish app']); + expect(calls[0]).toEqual(['save', 'dashboard', 'hui_kuan_fen_xi', body, { mode: 'draft', ifNoneMatch: '*', packageId: 'com.acme.crm' }]); + expect(calls[1]).toEqual(['publish', 'dashboard', 'hui_kuan_fen_xi', { packageId: 'com.acme.crm' }]); + expect((calls[2][3] as { navigation: Menu }).navigation).toEqual(NAVIGATION); + expect(calls[2][4]).toEqual({ mode: 'draft', packageId: 'com.acme.crm', ifNoneMatch: '*' }); + }); + + it("an installed app: both go to its customization package, the pair asked of the ensure door before anything is written", async () => { + const { d, calls } = doors({ writable: false, version: '1.4.0' }); + await saveAppMenuWithNewItem(input, TEXTS, d); + expect(calls.map(([verb, type]) => `${verb} ${type ?? ''}`.trim())).toEqual([ + 'ensure com.acme.crm', + 'save dashboard', + 'publish dashboard', + 'save app', + 'publish app', + ]); + // A new dashboard declares no override: it is the pair's own, not a customization of the base's. + expect(calls[1]).toEqual(['save', 'dashboard', 'hui_kuan_fen_xi', body, { mode: 'draft', ifNoneMatch: '*', packageId: 'com.acme.crm.custom' }]); + expect(calls[2]).toEqual(['publish', 'dashboard', 'hui_kuan_fen_xi', { packageId: 'com.acme.crm.custom' }]); + expect(calls[3][4]).toEqual({ mode: 'draft', packageId: 'com.acme.crm.custom', ifNoneMatch: '*' }); + }); + + it.each([ + ['the app’s package is not listed', { listed: false, writable: true }, 'not listed'], + ['the installed app states no version', { writable: false }, 'no version'], + ['the customization package is not writable', { writable: false, version: '1.4.0', pairWritable: false }, 'not writable'], + ['the ensure door refuses', { writable: false, version: '1.4.0', ensure: async () => Promise.reject(new Error('403 walled')) }, '403 walled'], + ])('where the menu cannot be saved (%s), nothing is created', async (_case, opts, message) => { + const { d, calls } = doors(opts); + await expect(saveAppMenuWithNewItem(input, TEXTS, d)).rejects.toThrow(message); + expect(calls.filter(([verb]) => verb !== 'ensure')).toEqual([]); + }); + + it('a refused menu removes the dashboard it was made for, and the refusal is the menu’s', async () => { + const refused = Object.assign(new Error('the app publish was refused'), { status: 422 }); + const { d, calls } = doors({ writable: true, refuse: ([verb, type]) => (verb === 'publish' && type === 'app' ? refused : null) }); + await expect(saveAppMenuWithNewItem(input, TEXTS, d)).rejects.toBe(refused); + expect(calls.map(([verb, type, , opt]) => `${verb} ${type} ${JSON.stringify(opt ?? null)}`)).toEqual([ + 'save dashboard {"name":"hui_kuan_fen_xi","label":"回款分析","widgets":[]}', + 'publish dashboard {"packageId":"com.acme.crm"}', + 'save app {"name":"crm","label":"CRM","navigation":[{"id":"insights","type":"group","label":"Insights","children":[{"id":"nav_item_1","type":"dashboard","dashboardName":"hui_kuan_fen_xi"}]}]}', + 'publish app {"packageId":"com.acme.crm"}', + // The menu's own draft, discarded (`writeAppMenu`). + 'reset app {"state":"draft","packageId":"com.acme.crm"}', + // The dashboard itself, removed from its package: not only its draft. + 'reset dashboard {"packageId":"com.acme.crm"}', + ]); + expect(emitMetadataRefresh).toHaveBeenCalled(); + }); + + it('a refused menu whose dashboard cannot be removed says the dashboard was left', async () => { + const { d } = doors({ + writable: true, + refuse: ([verb, type, , opt]) => + (verb === 'save' && type === 'app') || (verb === 'reset' && type === 'dashboard' && !(opt as { state?: string })?.state) + ? new Error(`${verb} ${type} refused`) + : null, + }); + const err = vi.spyOn(console, 'error').mockImplementation(() => {}); + await expect(saveAppMenuWithNewItem(input, TEXTS, d)).rejects.toThrow('save app refused item left'); + err.mockRestore(); + }); + + it('a draft already pending under the new name is refused before the menu is written', async () => { + const conflict = Object.assign(new Error('conflict'), { status: 409, code: 'METADATA_CONFLICT' }); + const { d, calls } = doors({ writable: true, refuse: ([verb, type]) => (verb === 'save' && type === 'dashboard' ? conflict : null) }); + await expect(saveAppMenuWithNewItem(input, TEXTS, d)).rejects.toThrow('item pending draft'); + expect(calls.map(([verb, type]) => `${verb} ${type}`)).toEqual(['save dashboard']); + }); +}); + +describe('the new dashboard’s machine name (objectstack#36364)', () => { + it('reads as its name: a Chinese name through its pinyin, else the kind', () => { + // Word breaks follow the runtime's segmenter; the syllables are the pinyin's. + expect(uniqueItemName('dashboard', '回款分析', [])).toMatch(/^hui_?kuan_?fen_?xi$/); + expect(uniqueItemName('dashboard', 'Payment analysis', [])).toBe('payment_analysis'); + expect(uniqueItemName('dashboard', '!!!', [])).toBe('dashboard'); + expect(uniqueItemName('dashboard', 'Payment analysis', ['payment_analysis', 'payment_analysis_2'])).toBe('payment_analysis_3'); + }); + + it('is a name no dashboard holds in any package, asked of the server', async () => { + const held = new Set(['dashboard/payment_analysis']); + const get = vi.fn(async (type: string, name: string) => (held.has(`${type}/${name}`) ? { name } : null)); + expect(await freeItemName('dashboard', 'Payment analysis', [], { get })).toBe('payment_analysis_2'); + expect(get.mock.calls).toEqual([ + ['dashboard', 'payment_analysis'], + ['dashboard', 'payment_analysis_2'], + ]); + }); + + it('a name that cannot be checked is not used', async () => { + const get = vi.fn(async () => { + throw new Error('read failed'); + }); + await expect(freeItemName('dashboard', 'Payment analysis', [], { get })).rejects.toThrow('read failed'); + }); +}); diff --git a/ui/packages/app-shell/src/layout/designModeMenuCreate.ts b/ui/packages/app-shell/src/layout/designModeMenuCreate.ts index 061b1aaa25a..fa79d214a3c 100644 --- a/ui/packages/app-shell/src/layout/designModeMenuCreate.ts +++ b/ui/packages/app-shell/src/layout/designModeMenuCreate.ts @@ -33,7 +33,7 @@ import { emitMetadataRefresh } from '../assistant/assistantBus.js'; import { slugify } from '../views/metadata-admin/createDerive.js'; -import { romanizeHan } from '../views/metadata-admin/romanizeHan.js'; +import { loadHanRomanizer, romanizeHan, romanizerPending } from '../views/metadata-admin/romanizeHan.js'; import { saveDashboardInPlace } from '../views/runtime-metadata-persistence.js'; import type { Menu } from './designModeMenu.js'; import { @@ -94,7 +94,8 @@ const NAME_TRIES = 20; * holds, in any package: each candidate ({@link uniqueItemName}, `taken` * left out) is read by name, and a name the read finds is passed over. A * read that fails is thrown: a name that could not be checked is not used, - * since saving over an existing item would publish over it. + * since saving over an existing item would publish over it. A Chinese name + * waits for the pinyin dictionary first, so its machine name reads as it. */ export async function freeItemName( kind: NewMenuItemKind, @@ -102,6 +103,7 @@ export async function freeItemName( taken: Iterable, client: { get: (type: string, name: string) => Promise }, ): Promise { + if (romanizerPending(label)) await loadHanRomanizer(); const used = new Set(taken); for (let i = 0; i < NAME_TRIES; i += 1) { const candidate = uniqueItemName(kind, label, used); 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 a89eec415bc..fa01dea2670 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 @@ -50,13 +50,15 @@ const packages = vi.hoisted(() => ({ ensure: null as null | ((base: string) => Promise<{ packageId: string; writable: boolean }>), ensured: [] as string[], })); +/** objectstack#36364 — the navigation state the page is reached with, and its replaces. */ +const route = vi.hoisted(() => ({ state: null as unknown, navigate: null as null | ((...a: unknown[]) => void) })); const toasts = vi.hoisted(() => ({ success: [] as unknown[], error: [] as unknown[] })); vi.mock('../providers/MetadataProvider', () => ({ useMetadata: () => meta.value })); vi.mock('react-router-dom', () => ({ useParams: () => ({ dashboardName: 'ops_board' }), - useNavigate: () => vi.fn(), - useLocation: () => ({ pathname: '/apps/crm/dashboard/ops_board', search: '' }), + useNavigate: () => route.navigate ?? (() => {}), + useLocation: () => ({ pathname: '/apps/crm/dashboard/ops_board', search: '', hash: '', key: 'landing', state: route.state }), })); vi.mock('./useOpenRecordList', () => ({ useRecordListDrillNavigation: () => ({ openRecordList: vi.fn(), canOpenRecordList: () => true }), @@ -181,6 +183,8 @@ beforeEach(() => { packages.ensured = []; toasts.success = []; toasts.error = []; + route.state = null; + route.navigate = null; }); afterEach(() => { @@ -343,3 +347,34 @@ describe('DashboardView in-page edit (objectstack#36372)', () => { expect(client.value.publish).not.toHaveBeenCalled(); }); }); + +describe('DashboardView arrival from the design mode (objectstack#36364)', () => { + it('a dashboard the design mode just created opens its edit state on arrival, and the landing is cleared', async () => { + const navigate = vi.fn(); + route.navigate = navigate; + route.state = { designModeNewDashboard: 'ops_board' }; + mount(); + expect(await screen.findByTestId('dashboard-editing-badge')).toBeInTheDocument(); + expect(client.value.layered).toHaveBeenCalledTimes(1); + expect(navigate).toHaveBeenCalledWith('/apps/crm/dashboard/ops_board', { replace: true, state: null }); + }); + + it("a landing that names another dashboard opens nothing", async () => { + route.state = { designModeNewDashboard: 'another_board' }; + mount(); + await screen.findByTestId('dashboard-edit'); + await act(async () => { await new Promise((r) => setTimeout(r, 0)); }); + expect(screen.queryByTestId('dashboard-editing-badge')).not.toBeInTheDocument(); + expect(client.value.layered).not.toHaveBeenCalled(); + }); + + it('without the Edit button (the Studio gate keeps the principal out), the landing opens nothing', async () => { + gate.entry = null; + route.state = { designModeNewDashboard: 'ops_board' }; + mount(); + await screen.findAllByText('Total (served)'); + await act(async () => { await new Promise((r) => setTimeout(r, 0)); }); + expect(screen.queryByTestId('dashboard-editing-badge')).not.toBeInTheDocument(); + expect(client.value.layered).not.toHaveBeenCalled(); + }); +}); From 45eaa741df9629f42905cf66ba201de065377e3b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 00:37:27 +0000 Subject: [PATCH 3/6] chore(changeset): the design mode's new dashboard Claude-Session: https://claude.ai/code/session_01ADHkmPiTdmLxHXBjakSvJy Co-authored-by: Claude --- .changeset/36364-design-mode-new-dashboard.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 .changeset/36364-design-mode-new-dashboard.md diff --git a/.changeset/36364-design-mode-new-dashboard.md b/.changeset/36364-design-mode-new-dashboard.md new file mode 100644 index 00000000000..e0390c4e303 --- /dev/null +++ b/.changeset/36364-design-mode-new-dashboard.md @@ -0,0 +1,11 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(console): a new dashboard is created from the design mode's 「Add menu item」 and opens for editing + +Clause-②: yes (widening) +Metadata-protocol: none + +In the design mode's 「Add menu item」 picker, the 「Dashboards」 list now starts with 「New dashboard…」, above the existing dashboards that are not in the menu yet. It asks for a name only. 「Create」 creates the dashboard, empty, in the package the menu is saved to (the app's package when it is writable, else its customization package), publishes it, puts its entry in the place the editor held for it, and saves the menu with every other change staged in the mode; the mode is then left and the new dashboard opens in its page's edit state. Members see the empty dashboard, not an error. 「Cancel」 writes nothing and leaves nothing in the menu. Where the menu cannot be saved (the app's package is not listed, an installed app states no version, or its customization package cannot be had or written) nothing is created. When the menu save is refused after the dashboard was created, the dashboard is removed again, the mode stays on and the reason is said. The machine name is generated from the name (a Chinese name through its pinyin), unused by any dashboard. A report cannot be created this way yet: a report needs a dataset and measures before it can be published. New `@object-ui/i18n` keys under `designMode.menu`. From 4175a0c7a18bc70c5eb5bdd127af595302ee438c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 00:52:08 +0000 Subject: [PATCH 4/6] feat(app-shell): a dashboard with no cards says so Claude-Session: https://claude.ai/code/session_01ADHkmPiTdmLxHXBjakSvJy Co-authored-by: Claude --- .changeset/36364-design-mode-new-dashboard.md | 2 +- .../DashboardView.inPageEdit-36372.test.tsx | 20 +++++++++++++++++++ .../app-shell/src/views/DashboardView.tsx | 12 +++++++++++ ui/packages/i18n/src/locales/ar.ts | 4 ++++ ui/packages/i18n/src/locales/de.ts | 4 ++++ ui/packages/i18n/src/locales/en.ts | 4 ++++ ui/packages/i18n/src/locales/es.ts | 4 ++++ ui/packages/i18n/src/locales/fr.ts | 4 ++++ ui/packages/i18n/src/locales/ja.ts | 4 ++++ ui/packages/i18n/src/locales/ko.ts | 4 ++++ ui/packages/i18n/src/locales/pt-BR.ts | 4 ++++ ui/packages/i18n/src/locales/ru.ts | 4 ++++ ui/packages/i18n/src/locales/zh-Hans.ts | 4 ++++ ui/packages/i18n/src/locales/zh-Hant.ts | 4 ++++ 14 files changed, 77 insertions(+), 1 deletion(-) diff --git a/.changeset/36364-design-mode-new-dashboard.md b/.changeset/36364-design-mode-new-dashboard.md index e0390c4e303..8b70beaa528 100644 --- a/.changeset/36364-design-mode-new-dashboard.md +++ b/.changeset/36364-design-mode-new-dashboard.md @@ -8,4 +8,4 @@ feat(console): a new dashboard is created from the design mode's 「Add menu ite Clause-②: yes (widening) Metadata-protocol: none -In the design mode's 「Add menu item」 picker, the 「Dashboards」 list now starts with 「New dashboard…」, above the existing dashboards that are not in the menu yet. It asks for a name only. 「Create」 creates the dashboard, empty, in the package the menu is saved to (the app's package when it is writable, else its customization package), publishes it, puts its entry in the place the editor held for it, and saves the menu with every other change staged in the mode; the mode is then left and the new dashboard opens in its page's edit state. Members see the empty dashboard, not an error. 「Cancel」 writes nothing and leaves nothing in the menu. Where the menu cannot be saved (the app's package is not listed, an installed app states no version, or its customization package cannot be had or written) nothing is created. When the menu save is refused after the dashboard was created, the dashboard is removed again, the mode stays on and the reason is said. The machine name is generated from the name (a Chinese name through its pinyin), unused by any dashboard. A report cannot be created this way yet: a report needs a dataset and measures before it can be published. New `@object-ui/i18n` keys under `designMode.menu`. +In the design mode's 「Add menu item」 picker, the 「Dashboards」 list now starts with 「New dashboard…」, above the existing dashboards that are not in the menu yet. It asks for a name only. 「Create」 creates the dashboard, empty, in the package the menu is saved to (the app's package when it is writable, else its customization package), publishes it, puts its entry in the place the editor held for it, and saves the menu with every other change staged in the mode; the mode is then left and the new dashboard opens in its page's edit state. A dashboard with no cards yet now says so on its page (「No cards yet」) instead of drawing a blank canvas, so members see an empty dashboard, not an error. 「Cancel」 writes nothing and leaves nothing in the menu. Where the menu cannot be saved (the app's package is not listed, an installed app states no version, or its customization package cannot be had or written) nothing is created. When the menu save is refused after the dashboard was created, the dashboard is removed again, the mode stays on and the reason is said. The machine name is generated from the name (a Chinese name through its pinyin), unused by any dashboard. A report cannot be created this way yet: a report needs a dataset and measures before it can be published. New `@object-ui/i18n` keys under `designMode.menu` and `dashboard.noCards`. 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 fa01dea2670..7138104ef47 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 @@ -378,3 +378,23 @@ describe('DashboardView arrival from the design mode (objectstack#36364)', () => expect(client.value.layered).not.toHaveBeenCalled(); }); }); + +describe('DashboardView with no cards yet (objectstack#36364)', () => { + it('a dashboard with no cards says so instead of drawing a blank page; one with cards does not', async () => { + mount({ name: 'ops_board', label: 'Payment analysis', _packageId: 'crm', widgets: [] }); + expect(await screen.findByTestId('dashboard-no-cards')).toHaveTextContent('No cards yetThis dashboard has no cards yet.'); + cleanup(); + mount(); + await screen.findAllByText('Total (served)'); + expect(screen.queryByTestId('dashboard-no-cards')).not.toBeInTheDocument(); + }); + + it('the edit state draws no such notice: the editor is the place to add cards', async () => { + route.state = { designModeNewDashboard: 'ops_board' }; + route.navigate = vi.fn(); + client.value = makeClient({ layered: vi.fn(async () => ({ code: null, overlay: null, effective: { name: 'ops_board', label: 'P', widgets: [] } })) }); + mount({ name: 'ops_board', label: 'Payment analysis', _packageId: 'crm', widgets: [] }); + await screen.findByTestId('dashboard-editing-badge'); + expect(screen.queryByTestId('dashboard-no-cards')).not.toBeInTheDocument(); + }); +}); diff --git a/ui/packages/app-shell/src/views/DashboardView.tsx b/ui/packages/app-shell/src/views/DashboardView.tsx index b2796b1f449..07a68e09965 100644 --- a/ui/packages/app-shell/src/views/DashboardView.tsx +++ b/ui/packages/app-shell/src/views/DashboardView.tsx @@ -519,6 +519,18 @@ export function DashboardView({ dataSource }: { dataSource?: any }) { } : {})} /> + {/* objectstack#36364 — a dashboard with no cards yet (one just + created in the design mode, say) says so, rather than + drawing a blank page. */} + {!editing && Array.isArray((dashboard as { widgets?: unknown }).widgets) && (dashboard as { widgets: unknown[] }).widgets.length === 0 && ( + +
    +
    + {tt('dashboard.noCards.title', 'No cards yet')} + {tt('dashboard.noCards.message', 'This dashboard has no cards yet.')} +
    + )} diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 98b70ea77c2..e15f344e79f 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1965,6 +1965,10 @@ const ar = { widgetForbiddenTitle: "لا تملك صلاحية الوصول", widgetForbiddenMessage: "ليست لديك صلاحية لعرض البيانات الخاصة بهذه الأداة.", allWidgetsForbiddenMessage: "ليست لديك صلاحية لعرض البيانات الخاصة بلوحة التحكم هذه.", + noCards: { + title: 'لا توجد بطاقات بعد', + message: 'لا تحتوي لوحة المعلومات هذه على بطاقات بعد.', + }, details: "التفاصيل", openInList: "فتح في القائمة", inPageEdit: { diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 70bea0a8c3b..82913ca8af2 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1733,6 +1733,10 @@ const de = { widgetForbiddenTitle: "Kein Zugriff", widgetForbiddenMessage: "Sie haben keine Berechtigung, die Daten dieses Widgets anzuzeigen.", allWidgetsForbiddenMessage: "Sie haben keine Berechtigung, die Daten dieses Dashboards anzuzeigen.", + noCards: { + title: 'Noch keine Karten', + message: 'Dieses Dashboard hat noch keine Karten.', + }, details: "Details", openInList: "In Liste öffnen", inPageEdit: { diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 0c56cab8060..94e0f013dd9 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -2167,6 +2167,10 @@ const en = { widgetForbiddenTitle: 'You don’t have access', widgetForbiddenMessage: 'You don’t have permission to view the data behind this widget.', allWidgetsForbiddenMessage: 'You don’t have permission to view the data behind this dashboard.', + noCards: { + title: 'No cards yet', + message: 'This dashboard has no cards yet.', + }, details: 'Details', openInList: 'Open in list', config: { diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 721d74e4276..447619241bc 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1793,6 +1793,10 @@ const es = { widgetForbiddenTitle: "Sin acceso", widgetForbiddenMessage: "No tienes permiso para ver los datos de este widget.", allWidgetsForbiddenMessage: "No tienes permiso para ver los datos de este panel.", + noCards: { + title: 'Aún no hay tarjetas', + message: 'Este panel aún no tiene tarjetas.', + }, details: "Detalles", openInList: "Abrir en la lista", inPageEdit: { diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index d491d65d7ca..7ffc37b68a9 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1789,6 +1789,10 @@ const fr = { widgetForbiddenTitle: "Accès refusé", widgetForbiddenMessage: "Vous n’avez pas l’autorisation de voir les données de ce widget.", allWidgetsForbiddenMessage: "Vous n’avez pas l’autorisation de voir les données de ce tableau de bord.", + noCards: { + title: 'Pas encore de cartes', + message: 'Ce tableau de bord n’a pas encore de cartes.', + }, details: "Détails", openInList: "Ouvrir dans la liste", inPageEdit: { diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 8ceb75c236c..3ec98d6c81b 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1733,6 +1733,10 @@ const ja = { widgetForbiddenTitle: "アクセス権がありません", widgetForbiddenMessage: "このウィジェットのデータを表示する権限がありません。", allWidgetsForbiddenMessage: "このダッシュボードのデータを表示する権限がありません。", + noCards: { + title: 'カードはまだありません', + message: 'このダッシュボードにはまだカードがありません。', + }, details: "詳細", openInList: "リストで開く", inPageEdit: { diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 59c958abe22..e0209acaaf2 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1733,6 +1733,10 @@ const ko = { widgetForbiddenTitle: "접근 권한 없음", widgetForbiddenMessage: "이 위젯의 데이터를 볼 수 있는 권한이 없습니다.", allWidgetsForbiddenMessage: "이 대시보드의 데이터를 볼 수 있는 권한이 없습니다.", + noCards: { + title: '아직 카드가 없습니다', + message: '이 대시보드에는 아직 카드가 없습니다.', + }, details: "세부 정보", openInList: "목록에서 열기", inPageEdit: { diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 6b02717d390..31c394a3e52 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1788,6 +1788,10 @@ const pt = { widgetForbiddenTitle: "Sem acesso", widgetForbiddenMessage: "Você não tem permissão para ver os dados deste widget.", allWidgetsForbiddenMessage: "Você não tem permissão para ver os dados deste painel.", + noCards: { + title: 'Ainda não há cartões', + message: 'Este painel ainda não tem cartões.', + }, details: "Detalhes", openInList: "Abrir na lista", inPageEdit: { diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index e652765333d..6ff5c45668e 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1853,6 +1853,10 @@ const ru = { widgetForbiddenTitle: "Нет доступа", widgetForbiddenMessage: "У вас нет прав на просмотр данных этого виджета.", allWidgetsForbiddenMessage: "У вас нет прав на просмотр данных этой панели.", + noCards: { + title: 'Карточек пока нет', + message: 'На этой панели пока нет карточек.', + }, details: "Подробности", openInList: "Открыть в списке", inPageEdit: { diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 992c15ce192..d0ed26ba954 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1805,6 +1805,10 @@ const zh = { widgetForbiddenTitle: '无权访问', widgetForbiddenMessage: '你没有查看该组件数据的权限。', allWidgetsForbiddenMessage: '你没有查看该仪表盘数据的权限。', + noCards: { + title: '还没有卡片', + message: '这个仪表盘还没有卡片。', + }, details: '明细', openInList: '在列表中打开', config: { diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 1ab049a5af4..1019318070b 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1805,6 +1805,10 @@ const zhHant = { widgetForbiddenTitle: '無權訪問', widgetForbiddenMessage: '你沒有檢視該元件資料的權限。', allWidgetsForbiddenMessage: '你沒有檢視該儀表盤資料的權限。', + noCards: { + title: '還沒有卡片', + message: '這個儀表盤還沒有卡片。', + }, details: '明細', openInList: '在列表中開啟', config: { From 0647077ca61e5fedc5616b7fba3f811f2a18c42e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 01:34:08 +0000 Subject: [PATCH 5/6] fix(i18n): regenerate zh-Hant and count the new de quote pair Claude-Session: https://claude.ai/code/session_01ADHkmPiTdmLxHXBjakSvJy Co-authored-by: Claude --- .../i18n/src/__tests__/de-quote-pairing-3876.test.ts | 9 +++++++-- ui/packages/i18n/src/locales/zh-Hant.ts | 4 ++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts index 8abffe74835..84a3cbcec98 100644 --- a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts +++ b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts @@ -465,7 +465,10 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // 125 once objectstack-ai/objectstack#36363 added `designMode.menu.iconHint`, // the menu editor's icon field naming an example icon („briefcase“) — one // literal span. - expect(okSpans, 'correctly paired spans').toBe(125); + // 126 once objectstack-ai/objectstack#36364 added `designMode.menu.newItemLeft`, + // the design mode naming a new dashboard it could not remove („{{name}}“) + // — one interpolated span, the name the reader gave it. + expect(okSpans, 'correctly paired spans').toBe(126); }); it('keeps the count identity that replaces the card’s count(„) === count(“)', () => { @@ -591,7 +594,9 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // `console.commandPalette.createAs`, one more matched pair. // 125 / 125 / 0 after objectstack-ai/objectstack#36363 added // `designMode.menu.iconHint`, one more matched pair. - expect({ open, close, rdq }).toEqual({ open: 125, close: 125, rdq: 0 }); + // 126 / 126 / 0 after objectstack-ai/objectstack#36364 added + // `designMode.menu.newItemLeft`, one more matched pair. + expect({ open, close, rdq }).toEqual({ open: 126, close: 126, rdq: 0 }); // The durable shape: every „ closed by a “, every surplus “ an English // opener answered by a ”. Survived translating the two English values. expect(close).toBe(open + rdq); diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 1019318070b..9dc7122ba35 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -3645,10 +3645,10 @@ const zhHant = { notWritable: '這個應用的定製包不可寫,選單無法儲存。', newDashboard: '新建儀表盤…', newDashboardTitle: '新建儀表盤', - newItemSavesAll: '建立時會一併儲存設計模式裡的其他變更,然後開啟它進行編輯。', + newItemSavesAll: '建立時會一併儲存設計模式裡的其他改動,然後開啟它進行編輯。', create: '建立', creating: '正在建立…', - newItemPendingDraft: '這個名稱下已有一份未發佈的草稿,請再試一次。', + newItemPendingDraft: '這個名稱下已有一份未釋出的草稿,請再試一次。', newItemLeft: '新建的儀表盤「{{name}}」沒能刪除,請在 Studio 裡刪除它。', }, }, From 313b6bf896dd4092754d63edd2c732300f3ac315 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 07:19:59 +0000 Subject: [PATCH 6/6] test(app-shell): pin the new dashboard's menu entry under the menu order rule A new dashboard's entry, held between two entries of a level that carries `order`, is saved numbered in that place, with every entry of the level renumbered in its shown place (objectstack#36591's rule, now applied by prepareAppMenuSave to the create-and-save path as well). Claude-Session: https://claude.ai/code/session_01ADHkmPiTdmLxHXBjakSvJy Co-authored-by: Claude --- .../designModeMenuCreate-36364.test.ts | 26 +++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) 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 3059396ce1e..dedef463bfa 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 @@ -21,7 +21,7 @@ vi.mock('../../assistant/assistantBus', async (importOriginal) => ({ })); import { loadHanRomanizer } from '../../views/metadata-admin/romanizeHan'; -import type { Menu } from '../designModeMenuModel'; +import { inShownOrder, insertEntry, withEntryIds, type Menu } from '../designModeMenuModel'; import type { AppMenuSaveDoors } from '../designModeMenuSave'; import { freeItemName, @@ -51,6 +51,7 @@ function doors(opts: { writable: boolean; version?: string; pairWritable?: boolean; + stored?: Menu; ensure?: () => Promise; refuse?: (call: Call) => unknown; }) { @@ -75,7 +76,7 @@ function doors(opts: { }, client: { layered: async () => { - const code = { name: 'crm', label: 'CRM', navigation: SERVED }; + const code = { name: 'crm', label: 'CRM', navigation: opts.stored ?? SERVED }; return { code, effective: code }; }, save: (...args) => record(['save', ...args]), @@ -200,3 +201,24 @@ describe('the new dashboard’s machine name (objectstack#36364)', () => { await expect(freeItemName('dashboard', 'Payment analysis', [], { get })).rejects.toThrow('read failed'); }); }); + +describe('the new dashboard’s entry in a menu that carries `order` (objectstack#36364 over objectstack#36591)', () => { + const object = (id: string, label: string, order: number) => ({ id, type: 'object', objectName: `crm_${id}`, label, order }); + /** As stored, authored out of `order`; the sidebar reads Customers, Contacts, Opportunities. */ + const STORED: Menu = [object('opportunity', 'Opportunities', 2), object('contact', 'Contacts', 1), object('customer', 'Customers', 0)]; + + it('the entry held between two entries is numbered in that place, and every entry of the level gets its shown place', async () => { + const served = withEntryIds(inShownOrder(STORED)); + const navigation = insertEntry(served, null, 1, ENTRY); + const { d, calls } = doors({ writable: true, stored: STORED }); + await saveAppMenuWithNewItem({ ...input, served, navigation }, TEXTS, d); + expect(calls.map(([verb, type]) => `${verb} ${type}`)).toEqual(['save dashboard', 'publish dashboard', 'save app', 'publish app']); + const saved = (calls[2][3] as { navigation: Array<{ id: string; order?: number }> }).navigation; + expect(saved.map((e) => [e.id, e.order])).toEqual([ + ['customer', 0], + ['nav_item_1', 1], + ['contact', 2], + ['opportunity', 3], + ]); + }); +});