diff --git a/.changeset/36364-design-mode-new-dashboard.md b/.changeset/36364-design-mode-new-dashboard.md new file mode 100644 index 00000000000..8b70beaa528 --- /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. 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/layout/DesignModeMenu.tsx b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx index e262b2af678..03b3bc5b5d1 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 @@ -49,7 +56,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, @@ -150,6 +158,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 @@ -362,6 +372,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); @@ -467,6 +522,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} /> )} @@ -754,12 +810,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(); @@ -767,6 +826,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' }), @@ -854,6 +930,19 @@ function MenuItemPicker({ ) : (
    + {kind !== null && isNewMenuItemKind(kind) && ( +
  • + +
  • + )} {loading ? (
  • {t('designMode.menu.loading', { defaultValue: 'Loading…' })}
  • ) : offered.length === 0 ? ( @@ -885,6 +974,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/__tests__/DesignModeMenu-36363.test.tsx b/ui/packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx index 75272f21096..ac9ef895ba5 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 @@ -67,6 +67,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 served (`null`: `NAVIGATION`). */ const servedNav = vi.hoisted(() => ({ current: null as unknown[] | null })); /** The app's menu as stored (`null`: as served). */ @@ -81,15 +83,20 @@ const client = vi.hoisted(() => ({ const code = { name: 'crm', label: 'CRM', navigation: storedNav.current ?? servedNav.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>()), @@ -206,6 +213,8 @@ beforeEach(() => { session.defaultLocale = 'en'; storedNav.current = null; storedNav.failReads = 0; + server.held.clear(); + server.appSave = null; servedNav.current = null; __resetDefaultLocale(); vi.stubGlobal( @@ -654,6 +663,120 @@ describe('the menu under the design mode (objectstack#36363)', () => { }); }); +/** 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'); + }); +}); + // ── objectstack#36591 ───────────────────────────────────────────────────────── /** 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..dedef463bfa --- /dev/null +++ b/ui/packages/app-shell/src/layout/__tests__/designModeMenuCreate-36364.test.ts @@ -0,0 +1,224 @@ +// 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 { inShownOrder, insertEntry, withEntryIds, type Menu } from '../designModeMenuModel'; +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; + stored?: Menu; + 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: opts.stored ?? 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'); + }); +}); + +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], + ]); + }); +}); 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..df2d2d0e787 --- /dev/null +++ b/ui/packages/app-shell/src/layout/designModeMenuCreate.ts @@ -0,0 +1,157 @@ +// 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 { loadHanRomanizer, romanizeHan, romanizerPending } from '../views/metadata-admin/romanizeHan.js'; +import { saveDashboardInPlace } from '../views/runtime-metadata-persistence.js'; +import type { Menu } from './designModeMenuModel.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. A Chinese name + * waits for the pinyin dictionary first, so its machine name reads as it. + */ +export async function freeItemName( + kind: NewMenuItemKind, + label: string, + 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); + 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 b319aa8229c..9a9b8bc89fe 100644 --- a/ui/packages/app-shell/src/layout/designModeMenuSave.ts +++ b/ui/packages/app-shell/src/layout/designModeMenuSave.ts @@ -99,15 +99,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); @@ -129,6 +146,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) { @@ -149,6 +176,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.inPageEdit-36372.test.tsx b/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx index a89eec415bc..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 @@ -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,54 @@ 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(); + }); +}); + +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 e4507c81e0b..36e48e7955c 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 @@ -300,6 +301,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; @@ -503,6 +523,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/__tests__/de-quote-pairing-3876.test.ts b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts index 4beb0ed04c4..20b34907517 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 @@ -468,7 +468,10 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // 127 once objectstack-ai/objectstack#36370 added `kanban.laneMenu.hideHint` // and `list.optionsMenu.kanbanHiddenLanesHint`, the board's two lines naming // the lane hidden cards land in („Nicht kategorisiert“) — two literal spans. - expect(okSpans, 'correctly paired spans').toBe(127); + // 128 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(128); }); it('keeps the count identity that replaces the card’s count(„) === count(“)', () => { @@ -597,7 +600,9 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // 127 / 127 / 0 after objectstack-ai/objectstack#36370 added // `kanban.laneMenu.hideHint` and `list.optionsMenu.kanbanHiddenLanesHint`, // two more matched pairs. - expect({ open, close, rdq }).toEqual({ open: 127, close: 127, rdq: 0 }); + // 128 / 128 / 0 after objectstack-ai/objectstack#36364 added + // `designMode.menu.newItemLeft`, one more matched pair. + expect({ open, close, rdq }).toEqual({ open: 128, close: 128, 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/ar.ts b/ui/packages/i18n/src/locales/ar.ts index a09ce5dbb49..d1521edcdaf 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1992,6 +1992,10 @@ const ar = { widgetForbiddenTitle: "لا تملك صلاحية الوصول", widgetForbiddenMessage: "ليست لديك صلاحية لعرض البيانات الخاصة بهذه الأداة.", allWidgetsForbiddenMessage: "ليست لديك صلاحية لعرض البيانات الخاصة بلوحة التحكم هذه.", + noCards: { + title: 'لا توجد بطاقات بعد', + message: 'لا تحتوي لوحة المعلومات هذه على بطاقات بعد.', + }, details: "التفاصيل", openInList: "فتح في القائمة", inPageEdit: { @@ -3909,6 +3913,13 @@ const ar = { pendingDraft: 'لهذا التطبيق تغييرات غير منشورة في Studio. انشرها أو تجاهلها هناك، ثم احفظ مرة أخرى.', noVersion: 'حزمة هذا التطبيق لا تذكر إصدارًا، لذا لا يمكن تخصيص قائمته.', notWritable: 'حزمة تخصيص هذا التطبيق غير قابلة للكتابة، لذا لا يمكن حفظ قائمته.', + newDashboard: 'لوحة معلومات جديدة…', + newDashboardTitle: 'لوحة معلومات جديدة', + newItemSavesAll: 'يؤدي إنشاؤها إلى حفظ تغييرات التصميم الأخرى أيضًا، ثم تُفتح للتحرير.', + create: 'إنشاء', + creating: 'جارٍ الإنشاء…', + newItemPendingDraft: 'توجد مسودة غير منشورة بهذا الاسم بالفعل. حاول مرة أخرى.', + newItemLeft: 'تعذّرت إزالة لوحة المعلومات الجديدة "{{name}}"؛ أزلها في Studio.', }, recordTabs: { entry: 'تكوين علامات التبويب', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 84f895d6ede..b31429c1835 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1760,6 +1760,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: { @@ -3586,6 +3590,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.', }, recordTabs: { entry: 'Tabs konfigurieren', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 28369a7ff43..710835dcdbe 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -2197,6 +2197,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: { @@ -4271,6 +4275,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.', }, recordTabs: { entry: 'Configure tabs', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 9ae1afc50fe..4fef613ddf2 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1820,6 +1820,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: { @@ -3668,6 +3672,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.', }, recordTabs: { entry: 'Configurar pestañas', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 5c07b13755a..9b58e0ac289 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1816,6 +1816,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: { @@ -3664,6 +3668,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.', }, recordTabs: { entry: 'Configurer les onglets', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 53848d82b5a..44a7751add2 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1760,6 +1760,10 @@ const ja = { widgetForbiddenTitle: "アクセス権がありません", widgetForbiddenMessage: "このウィジェットのデータを表示する権限がありません。", allWidgetsForbiddenMessage: "このダッシュボードのデータを表示する権限がありません。", + noCards: { + title: 'カードはまだありません', + message: 'このダッシュボードにはまだカードがありません。', + }, details: "詳細", openInList: "リストで開く", inPageEdit: { @@ -3588,6 +3592,13 @@ const ja = { pendingDraft: 'このアプリには Studio に未公開の変更があります。そちらで公開または破棄してから、もう一度保存してください。', noVersion: 'このアプリのパッケージにはバージョンがないため、メニューをカスタマイズできません。', notWritable: 'このアプリのカスタマイズパッケージに書き込めないため、メニューを保存できません。', + newDashboard: '新しいダッシュボード…', + newDashboardTitle: '新しいダッシュボード', + newItemSavesAll: '作成すると、デザインモードの他の変更も保存され、編集用に開きます。', + create: '作成', + creating: '作成中…', + newItemPendingDraft: 'この名前の未公開の下書きがすでにあります。もう一度お試しください。', + newItemLeft: '新しいダッシュボード「{{name}}」を削除できませんでした。Studio で削除してください。', }, recordTabs: { entry: 'タブを設定', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index f7544571ffc..ee9f79d224e 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1760,6 +1760,10 @@ const ko = { widgetForbiddenTitle: "접근 권한 없음", widgetForbiddenMessage: "이 위젯의 데이터를 볼 수 있는 권한이 없습니다.", allWidgetsForbiddenMessage: "이 대시보드의 데이터를 볼 수 있는 권한이 없습니다.", + noCards: { + title: '아직 카드가 없습니다', + message: '이 대시보드에는 아직 카드가 없습니다.', + }, details: "세부 정보", openInList: "목록에서 열기", inPageEdit: { @@ -3586,6 +3590,13 @@ const ko = { pendingDraft: '이 앱에는 Studio에 게시되지 않은 변경 사항이 있습니다. 그곳에서 게시하거나 취소한 뒤 다시 저장하세요.', noVersion: '이 앱의 패키지에 버전이 없어 메뉴를 사용자 지정할 수 없습니다.', notWritable: '이 앱의 사용자 지정 패키지에 쓸 수 없어 메뉴를 저장할 수 없습니다.', + newDashboard: '새 대시보드…', + newDashboardTitle: '새 대시보드', + newItemSavesAll: '만들면 디자인 모드의 다른 변경 사항도 함께 저장되고 편집할 수 있게 열립니다.', + create: '만들기', + creating: '만드는 중…', + newItemPendingDraft: '이 이름으로 게시되지 않은 초안이 이미 있습니다. 다시 시도하세요.', + newItemLeft: '새 대시보드 "{{name}}"을(를) 삭제하지 못했습니다. Studio에서 삭제하세요.', }, recordTabs: { entry: '탭 구성', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 29af8f6208f..0dc6006f4b9 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1815,6 +1815,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: { @@ -3663,6 +3667,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.', }, recordTabs: { entry: 'Configurar abas', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 787316e5df2..1b1b70a1fac 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1880,6 +1880,10 @@ const ru = { widgetForbiddenTitle: "Нет доступа", widgetForbiddenMessage: "У вас нет прав на просмотр данных этого виджета.", allWidgetsForbiddenMessage: "У вас нет прав на просмотр данных этой панели.", + noCards: { + title: 'Карточек пока нет', + message: 'На этой панели пока нет карточек.', + }, details: "Подробности", openInList: "Открыть в списке", inPageEdit: { @@ -3755,6 +3759,13 @@ const ru = { pendingDraft: 'В Studio есть неопубликованные изменения этого приложения. Опубликуйте или отмените их там и сохраните снова.', noVersion: 'Пакет этого приложения не указывает версию, поэтому меню нельзя настроить.', notWritable: 'Пакет настроек этого приложения недоступен для записи, поэтому меню нельзя сохранить.', + newDashboard: 'Новая панель…', + newDashboardTitle: 'Новая панель', + newItemSavesAll: 'При создании сохраняются и другие изменения режима дизайна, затем панель открывается для редактирования.', + create: 'Создать', + creating: 'Создание…', + newItemPendingDraft: 'Под этим именем уже есть неопубликованный черновик. Повторите попытку.', + newItemLeft: 'Не удалось удалить новую панель «{{name}}»; удалите её в Studio.', }, recordTabs: { entry: 'Настроить вкладки', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 9ebb4f3d79a..0cb1b5b0aa0 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1832,6 +1832,10 @@ const zh = { widgetForbiddenTitle: '无权访问', widgetForbiddenMessage: '你没有查看该组件数据的权限。', allWidgetsForbiddenMessage: '你没有查看该仪表盘数据的权限。', + noCards: { + title: '还没有卡片', + message: '这个仪表盘还没有卡片。', + }, details: '明细', openInList: '在列表中打开', config: { @@ -3667,6 +3671,13 @@ const zh = { pendingDraft: '这个应用在 Studio 里有未发布的改动。请先在那里发布或丢弃,再保存。', noVersion: '这个应用所在的包没有声明版本,菜单无法定制。', notWritable: '这个应用的定制包不可写,菜单无法保存。', + newDashboard: '新建仪表盘…', + newDashboardTitle: '新建仪表盘', + newItemSavesAll: '创建时会一并保存设计模式里的其他改动,然后打开它进行编辑。', + create: '创建', + creating: '正在创建…', + newItemPendingDraft: '这个名称下已有一份未发布的草稿,请再试一次。', + newItemLeft: '新建的仪表盘「{{name}}」没能删除,请在 Studio 里删除它。', }, recordTabs: { entry: '配置页签', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 5cd07b1bb9f..6906ee04cfb 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1832,6 +1832,10 @@ const zhHant = { widgetForbiddenTitle: '無權訪問', widgetForbiddenMessage: '你沒有檢視該元件資料的權限。', allWidgetsForbiddenMessage: '你沒有檢視該儀表盤資料的權限。', + noCards: { + title: '還沒有卡片', + message: '這個儀表盤還沒有卡片。', + }, details: '明細', openInList: '在列表中開啟', config: { @@ -3667,6 +3671,13 @@ const zhHant = { pendingDraft: '這個應用在 Studio 裡有未釋出的改動。請先在那裡釋出或丟棄,再儲存。', noVersion: '這個應用所在的包沒有宣告版本,選單無法定製。', notWritable: '這個應用的定製包不可寫,選單無法儲存。', + newDashboard: '新建儀表盤…', + newDashboardTitle: '新建儀表盤', + newItemSavesAll: '建立時會一併儲存設計模式裡的其他改動,然後開啟它進行編輯。', + create: '建立', + creating: '正在建立…', + newItemPendingDraft: '這個名稱下已有一份未釋出的草稿,請再試一次。', + newItemLeft: '新建的儀表盤「{{name}}」沒能刪除,請在 Studio 裡刪除它。', }, recordTabs: { entry: '配置頁籤',