From f7737e36b67496d3c16738190165b1482a04ac63 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 09:07:19 +0000 Subject: [PATCH 1/3] feat(console): a new report is built from the design mode's Add menu item MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 「Reports」 in the picker starts with 「New report…」: the place stays held and the report builder opens; its Save creates the report in the menu's package and saves the entry with every other staged design change, its Close (or leaving it) drops the place and writes nothing. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbXq2Dxb31zZNmSqCtz --- .changeset/36364-design-mode-new-report.md | 11 ++ .../app-shell/src/layout/DesignModeMenu.tsx | 109 +++++++++++- .../__tests__/DesignModeMenu-36363.test.tsx | 142 +++++++++++++++- .../designModeMenuCreate-36364.test.ts | 54 ++++++ .../src/layout/designModeMenuCreate.ts | 61 ++++--- .../src/layout/designModeReportSlot.ts | 74 +++++++++ .../ReportNewPage.menuSlot-36364.test.tsx | 156 ++++++++++++++++++ .../app-shell/src/views/ReportNewPage.tsx | 46 ++++-- .../src/views/runtime-metadata-persistence.ts | 21 ++- .../__tests__/de-quote-pairing-3876.test.ts | 9 +- ui/packages/i18n/src/locales/ar.ts | 3 + ui/packages/i18n/src/locales/de.ts | 3 + ui/packages/i18n/src/locales/en.ts | 3 + ui/packages/i18n/src/locales/es.ts | 3 + ui/packages/i18n/src/locales/fr.ts | 3 + ui/packages/i18n/src/locales/ja.ts | 3 + ui/packages/i18n/src/locales/ko.ts | 3 + ui/packages/i18n/src/locales/pt-BR.ts | 3 + ui/packages/i18n/src/locales/ru.ts | 3 + ui/packages/i18n/src/locales/zh-Hans.ts | 3 + ui/packages/i18n/src/locales/zh-Hant.ts | 3 + 21 files changed, 672 insertions(+), 44 deletions(-) create mode 100644 .changeset/36364-design-mode-new-report.md create mode 100644 ui/packages/app-shell/src/layout/designModeReportSlot.ts create mode 100644 ui/packages/app-shell/src/views/ReportNewPage.menuSlot-36364.test.tsx diff --git a/.changeset/36364-design-mode-new-report.md b/.changeset/36364-design-mode-new-report.md new file mode 100644 index 00000000000..0a2989e49a8 --- /dev/null +++ b/.changeset/36364-design-mode-new-report.md @@ -0,0 +1,11 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(console): a new report is built from the design mode's 「Add menu item」 and lands in the place held for it + +Clause-②: yes (widening) — new `@object-ui/i18n` keys (`designMode.menu.newReport`, `designMode.menu.newReportLeft`, `report.builder.addsToMenu`) in all 11 locales; no package export, spec or schema change +Metadata-protocol: none + +In the design mode's 「Add menu item」 picker, the 「Reports」 list now starts with 「New report…」. A report needs a data source and a measure before it can be published, so it is not created from a name: the place stays held in the menu (「New report…」) and the report builder opens at the app's `reports/new`, saying that saving adds the report to the menu. The builder's Save creates and publishes the report in the package the menu is saved to (the app's package when it is writable, else its customization package), puts its entry in the held place, and saves the menu with every other change staged in the mode; the mode is then left and the report's page opens. When the menu save is refused the report is removed again, the mode and the held place stay, and the builder stays open with the reason. The builder's Close, or leaving the builder any other way, drops the held place and writes nothing. Opened outside the design mode, `reports/new` saves on its own as before. diff --git a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx index 03b3bc5b5d1..13e2fe869f1 100644 --- a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx +++ b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx @@ -38,6 +38,10 @@ * place, and the mode saves at once, every other staged change with it * (`saveAppMenuWithNewItem`); then the mode is left and the new dashboard * opens for editing (`dashboardEditArrival`). 「Cancel」 writes nothing. + * In 「Reports」 the first row is 「New report…」: a report needs a data source + * and a measure, so the place stays held and the report builder opens; its + * Save creates the report and saves the mode the same way + * (`designModeReportSlot`), and its Close drops the place, writing nothing. * * Every edit is staged with the mode (`useDesignModeChange`), under one key * for the app's menu: the mode's 「Save」 writes it (`saveAppMenu`), its @@ -56,7 +60,7 @@ */ import * as React from 'react'; -import { Link, useNavigate } from 'react-router-dom'; +import { Link, useLocation, useNavigate } from 'react-router-dom'; import { toast } from 'sonner'; import { DndContext, @@ -160,6 +164,7 @@ import { } from './designModeMenuSave.js'; import { freeItemName, isNewMenuItemKind, saveAppMenuWithNewItem, type NewMenuItemKind } from './designModeMenuCreate.js'; import { dashboardEditArrival } from './designModeArrival.js'; +import { offerNewReportSlot, withdrawNewReportSlot, type NewReportSlot } from './designModeReportSlot.js'; /** * The group label's icon-mode hiding, as the sidebar's own labels declare it @@ -417,6 +422,79 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso return true; }; + // objectstack#36364 (report half) — 「New report…」: a report cannot be + // made from a name (the spec wants `dataset` and `values`), so the place + // stays held and the report builder opens at `reports/new`. The builder + // saves through the slot offered here (`designModeReportSlot`): the report + // is created in the menu's package and its entry saved in the held place + // with every other staged change, in one act; nothing is written before. + // The builder's Close drops the place. Resolves `false` when nothing was + // saved (the mode has said why); the builder stays open for another try. + const [buildingReport, setBuildingReport] = React.useState(false); + const saveNewReport = async (name: string, label: string, body: Record): Promise => { + if (!addAt) return false; + const entry = entryFor('report', name, newEntryId([...menu, ...(storedMenu ?? [])])); + const itemTexts = { + ...texts, + itemPendingDraft: t('designMode.menu.newItemPendingDraft', { + defaultValue: 'A draft with this name is already pending. Try again.', + }), + itemLeft: t('designMode.menu.newReportLeft', { + defaultValue: 'The new report "{{name}}" could not be removed again; remove it in Studio.', + name: label, + }), + }; + const saved = await saveWith(insertEntry(menu, addAt.parentId, addAt.index, entry), (navigation) => + saveAppMenuWithNewItem( + { appName, packageId, served, navigation, item: { kind: 'report', name, label, body } }, + itemTexts, + consoleAppMenuDoors(client as never), + ), + ); + if (!saved) return false; + setAddAt(null); + setBuildingReport(false); + return true; + }; + const saveNewReportRef = React.useRef(saveNewReport); + React.useLayoutEffect(() => { + saveNewReportRef.current = saveNewReport; + }); + React.useEffect(() => { + if (!buildingReport) return; + const slot: NewReportSlot = { + appName, + save: (name, label, body) => saveNewReportRef.current(name, label, body), + cancel: () => { + setBuildingReport(false); + setAddAt(null); + }, + }; + offerNewReportSlot(slot); + // Withdrawn when the place is no longer held, and when the menu unmounts + // (the design mode ended): the builder then saves on its own, off the menu. + return () => withdrawNewReportSlot(slot); + }, [buildingReport, appName]); + // Leaving the builder another way than its Save or Close (a menu link, the + // browser's Back) drops the place too, so no held row waits for a builder + // that is gone. Read once the builder has been reached. + const { pathname } = useLocation(); + const newReportPath = `${basePath}/reports/new`; + const [reachedBuilder, setReachedBuilder] = React.useState(false); + const onBuilder = pathname === newReportPath || pathname.endsWith(newReportPath); + if (buildingReport && onBuilder && !reachedBuilder) setReachedBuilder(true); + if (!buildingReport && reachedBuilder) setReachedBuilder(false); + if (buildingReport && reachedBuilder && !onBuilder) { + setBuildingReport(false); + setReachedBuilder(false); + setAddAt(null); + } + const startNewReport = () => { + if (!addAt) return; + setBuildingReport(true); + navigate(newReportPath); + }; + const renderLeaf = (entry: MenuEntry, depth: number) => { const id = String(entry.id); const place = placeOf(menu, id); @@ -456,7 +534,7 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso const renderEntries = (entries: Menu, parentId: string | null, depth: number): React.ReactNode[] => { const rows: React.ReactNode[] = []; entries.forEach((entry, index) => { - if (addAt && addAt.parentId === parentId && addAt.index === index) rows.push(); + if (addAt && addAt.parentId === parentId && addAt.index === index) rows.push(); if (isGroup(entry)) { const gid = String(entry.id); rows.push( @@ -477,7 +555,7 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso rows.push(renderLeaf(entry, depth)); } }); - if (addAt && addAt.parentId === parentId && addAt.index >= entries.length) rows.push(); + if (addAt && addAt.parentId === parentId && addAt.index >= entries.length) rows.push(); rows.push( - {addAt && ( + {addAt && !buildingReport && ( setAddAt(null)} onPick={(kind, name, link) => pick(entryFor(kind, name, newEntryId([...menu, ...(storedMenu ?? [])]), link))} onCreate={createItem} + onNewReport={startNewReport} language={language} /> )} @@ -612,12 +691,14 @@ function MenuLeaf({ ); } -function Placeholder({ depth }: { depth: number }) { +function Placeholder({ depth, buildingReport }: { depth: number; buildingReport?: boolean }) { const { t } = useObjectTranslation(); return (
  • - {t('designMode.menu.placeholder', { defaultValue: 'Choose a menu item…' })} + {buildingReport + ? t('designMode.menu.newReport', { defaultValue: 'New report…' }) + : t('designMode.menu.placeholder', { defaultValue: 'Choose a menu item…' })}
  • ); @@ -811,6 +892,7 @@ function MenuItemPicker({ onClose, onPick, onCreate, + onNewReport, language, }: { packageId: string; @@ -819,6 +901,8 @@ function MenuItemPicker({ onPick: (kind: MenuTargetKind, name: string, link?: { label: string; url: string }) => void; /** Create a new `kind` named `label`; `taken` is every name of that kind the picker lists. */ onCreate: (kind: NewMenuItemKind, label: string, taken: readonly string[]) => Promise; + /** Build a new report for the held place, in the report builder. */ + onNewReport: () => void; language: string; }) { const { t } = useObjectTranslation(); @@ -943,6 +1027,19 @@ function MenuItemPicker({ )} + {kind === 'report' && ( +
  • + +
  • + )} {loading ? (
  • {t('designMode.menu.loading', { defaultValue: 'Loading…' })}
  • ) : offered.length === 0 ? ( diff --git a/ui/packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx b/ui/packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx index ac9ef895ba5..dd925a70aa8 100644 --- a/ui/packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx @@ -16,7 +16,7 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'; -import { MemoryRouter, useLocation } from 'react-router-dom'; +import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom'; import { SidebarProvider } from '@object-ui/components'; import { NavigationRenderer } from '@object-ui/layout'; import type { NavigationItem } from '@object-ui/types'; @@ -117,6 +117,7 @@ import { DesignModeBar } from '../DesignModeBar'; import DesignModeMenu from '../DesignModeMenu'; import { confirmUnsavedLeave } from '../../chrome/unsavedEdits'; import { __resetDefaultLocale } from '../designModeMenuSave'; +import { newReportSlotFor } from '../designModeReportSlot'; const NAVIGATION = [ { id: 'home', type: 'report', reportName: 'pipeline', label: 'Home' }, @@ -777,6 +778,145 @@ describe('a new dashboard from 「Add menu item」 (objectstack#36364)', () => { }); }); +/** 「Add menu item」 under Insights, then 「Reports」. */ +async function openReports() { + fireEvent.click(screen.getByTestId('design-menu-add-insights')); + const picker = await screen.findByTestId('design-menu-picker'); + fireEvent.click(within(picker).getByRole('button', { name: 'Reports' })); + await flush(); + return picker; +} + +/** A link elsewhere in the app, as the sidebar would follow one. */ +function GoElsewhere() { + const navigate = useNavigate(); + return ( + + ); +} + +function startOnBuilderPath() { + render( + + + + + , + ); + fireEvent.click(screen.getByText('enter')); +} + +const REPORT_BODY = { + label: 'Payment analysis', + type: 'summary', + dataset: 'invoice_metrics', + values: ['invoice_count'], + chart: { type: 'metric', xAxis: '', yAxis: 'invoice_count' }, +}; + +describe('a new report from 「Add menu item」 (objectstack#36364, report half)', () => { + it('「Reports」 lists 「New report…」 first; it holds the place and opens the report builder, writing nothing', async () => { + startOnBuilderPath(); + const picker = await openReports(); + const rows = within(within(picker).getByTestId('design-menu-picker-rows')).getAllByRole('button').map((b) => b.textContent); + // The report the menu already opens (Home → pipeline) is not offered again. + expect(rows).toEqual(['New report…']); + fireEvent.click(within(picker).getByTestId('design-menu-picker-new-report')); + await flush(); + expect(screen.queryByTestId('design-menu-picker')).toBeNull(); + expect(screen.getByTestId('landing')).toHaveTextContent('/apps/crm/reports/new null'); + // The place stays held, saying what it waits for. + expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', ['…']]]); + expect(screen.getByTestId('design-menu-placeholder')).toHaveTextContent('New report…'); + expect(newReportSlotFor('crm')).not.toBeNull(); + expect(newReportSlotFor('hr')).toBeNull(); + expect(written).toEqual([]); + }); + + it('the builder\'s Save: the report, then the menu with its entry in the held place and every other staged edit; the mode is left', async () => { + startOnBuilderPath(); + await act_on('accounts', 'Move up'); // another staged edit, saved with it + const picker = await openReports(); + fireEvent.click(within(picker).getByTestId('design-menu-picker-new-report')); + await flush(); + const slot = newReportSlotFor('crm')!; + let saved: boolean | undefined; + await act(async () => { + saved = await slot.save('payment_analysis', 'Payment analysis', { ...REPORT_BODY, name: 'payment_analysis' }); + }); + await flush(); + + expect(saved).toBe(true); + expect(written.map(([verb, type, name]) => `${verb} ${type} ${name}`)).toEqual([ + 'save report payment_analysis', + 'publish report payment_analysis', + 'save app crm', + 'publish app crm', + ]); + expect(written[0][3]).toEqual({ ...REPORT_BODY, name: 'payment_analysis' }); + expect(written[0][4]).toEqual({ mode: 'draft', ifNoneMatch: '*', packageId: 'com.acme.crm' }); + const navigation = (written[2][3] as { navigation: Array<{ id: string; children?: unknown[] }> }).navigation; + expect(navigation[1].children!.map((c) => (c as { id: string }).id)).toEqual(['accounts', 'leads']); + expect(navigation[2].children).toEqual([{ id: 'nav_item_1', type: 'report', reportName: 'payment_analysis' }]); + expect(screen.queryByTestId('design-mode-bar')).toBeNull(); + expect(newReportSlotFor('crm')).toBeNull(); + }); + + it('a refused menu removes the new report; the mode, the held place and the other staged edits stay', async () => { + server.appSave = new Error('the app was refused'); + startOnBuilderPath(); + await act_on('accounts', 'Move up'); + const picker = await openReports(); + fireEvent.click(within(picker).getByTestId('design-menu-picker-new-report')); + await flush(); + let saved: boolean | undefined; + await act(async () => { + saved = await newReportSlotFor('crm')!.save('payment_analysis', 'Payment analysis', { ...REPORT_BODY, name: 'payment_analysis' }); + }); + await flush(); + + expect(saved).toBe(false); + expect(written.map(([verb, type, name, opt]) => `${verb} ${type} ${name} ${verb === 'reset' ? JSON.stringify(opt) : ''}`.trim())).toEqual([ + 'save report payment_analysis', + 'publish report payment_analysis', + 'save app crm', + 'reset report payment_analysis {"packageId":"com.acme.crm"}', + ]); + expect(toastError).toHaveBeenCalledWith('Some changes were not saved: the app was refused'); + expect(screen.getByTestId('design-mode-bar')).toBeInTheDocument(); + expect(order()).toEqual(['home', ['sales', ['accounts', 'leads']], ['insights', ['…']]]); + expect(newReportSlotFor('crm')).not.toBeNull(); + }); + + it('the builder\'s Close drops the held place and writes nothing; the mode and its other edits stay', async () => { + startOnBuilderPath(); + await act_on('accounts', 'Move up'); + const picker = await openReports(); + fireEvent.click(within(picker).getByTestId('design-menu-picker-new-report')); + await flush(); + act(() => newReportSlotFor('crm')!.cancel()); + await flush(); + expect(order()).toEqual(['home', ['sales', ['accounts', 'leads']], ['insights', []]]); + expect(newReportSlotFor('crm')).toBeNull(); + expect(written).toEqual([]); + expect(screen.getByTestId('design-mode-save')).toBeEnabled(); + }); + + it('leaving the builder another way drops the held place too', async () => { + startOnBuilderPath(); + const picker = await openReports(); + fireEvent.click(within(picker).getByTestId('design-menu-picker-new-report')); + await flush(); + fireEvent.click(screen.getByText('go elsewhere')); + await flush(); + expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', []]]); + expect(newReportSlotFor('crm')).toBeNull(); + expect(written).toEqual([]); + }); +}); + // ── objectstack#36591 ───────────────────────────────────────────────────────── /** 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 dedef463bfa..f46950b6c10 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 @@ -222,3 +222,57 @@ describe('the new dashboard’s entry in a menu that carries `order` (objectstac ]); }); }); + +describe('a new report from the design mode (objectstack#36364, report half)', () => { + const REPORT_BODY = { + label: '回款分析', + type: 'summary', + dataset: 'invoice_metrics', + values: ['invoice_count'], + chart: { type: 'metric', xAxis: '', yAxis: 'invoice_count' }, + }; + const REPORT: NewMenuItem = { kind: 'report', name: 'hui_kuan_fen_xi', label: '回款分析', body: REPORT_BODY }; + const REPORT_ENTRY = { id: 'nav_item_1', type: 'report', reportName: 'hui_kuan_fen_xi' }; + const reportInput = { + ...input, + navigation: [{ id: 'insights', type: 'group', label: 'Insights', children: [REPORT_ENTRY] }] as Menu, + item: REPORT, + }; + + it('is created as the report builder made it, under the new name', () => { + expect(newItemBody(REPORT)).toEqual({ ...REPORT_BODY, name: 'hui_kuan_fen_xi' }); + }); + + it("is created and published in the menu's package, then the menu, in that order", async () => { + const { d, calls } = doors({ writable: false, version: '1.4.0' }); + await saveAppMenuWithNewItem(reportInput, TEXTS, d); + expect(calls.map(([verb, type]) => `${verb} ${type ?? ''}`.trim())).toEqual([ + 'ensure com.acme.crm', + 'save report', + 'publish report', + 'save app', + 'publish app', + ]); + expect(calls[1]).toEqual([ + 'save', + 'report', + 'hui_kuan_fen_xi', + { ...REPORT_BODY, name: 'hui_kuan_fen_xi' }, + { mode: 'draft', ifNoneMatch: '*', packageId: 'com.acme.crm.custom' }, + ]); + expect(calls[2]).toEqual(['publish', 'report', 'hui_kuan_fen_xi', { packageId: 'com.acme.crm.custom' }]); + }); + + it('a refused menu removes the report it was made for', async () => { + const refused = new Error('the app publish was refused'); + const { d, calls } = doors({ writable: true, refuse: ([verb, type]) => (verb === 'publish' && type === 'app' ? refused : null) }); + await expect(saveAppMenuWithNewItem(reportInput, TEXTS, d)).rejects.toBe(refused); + expect(calls.at(-1)).toEqual(['reset', 'report', 'hui_kuan_fen_xi', { packageId: 'com.acme.crm' }]); + }); + + it('where the menu cannot be saved, no report is created', async () => { + const { d, calls } = doors({ listed: false, writable: true }); + await expect(saveAppMenuWithNewItem(reportInput, TEXTS, d)).rejects.toThrow('not listed'); + expect(calls).toEqual([]); + }); +}); diff --git a/ui/packages/app-shell/src/layout/designModeMenuCreate.ts b/ui/packages/app-shell/src/layout/designModeMenuCreate.ts index df2d2d0e787..6d02915e796 100644 --- a/ui/packages/app-shell/src/layout/designModeMenuCreate.ts +++ b/ui/packages/app-shell/src/layout/designModeMenuCreate.ts @@ -15,18 +15,22 @@ * * 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; + * 2. the item is created and published in that package (a dashboard empty, + * `saveDashboardInPlace`; a report as the builder made it, + * `saveAndPublishInPackage`), so everyone the menu shows it to finds it, + * 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 + * 4. when the menu is refused, the item 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. + * removal be refused too, the refusal says the item 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. + * A dashboard is created from its name alone. A report is not: the spec + * refuses a report without `dataset` and `values`, so 「New report…」 opens + * the report builder instead (the seat's option A), and the report is + * created here, by the same steps, with the body the builder made, once the + * builder saves (`designModeReportSlot`). Cancelling the builder writes + * nothing. * * @module */ @@ -34,7 +38,7 @@ import { emitMetadataRefresh } from '../assistant/assistantBus.js'; import { slugify } from '../views/metadata-admin/createDerive.js'; import { loadHanRomanizer, romanizeHan, romanizerPending } from '../views/metadata-admin/romanizeHan.js'; -import { saveDashboardInPlace } from '../views/runtime-metadata-persistence.js'; +import { saveAndPublishInPackage, saveDashboardInPlace } from '../views/runtime-metadata-persistence.js'; import type { Menu } from './designModeMenuModel.js'; import { prepareAppMenuSave, @@ -43,20 +47,24 @@ import { type AppMenuSaveTexts, } from './designModeMenuSave.js'; -/** The kinds of thing the picker creates. */ +/** The kinds of thing the picker creates from a name alone. */ export const NEW_MENU_ITEM_KINDS = ['dashboard'] as const; export type NewMenuItemKind = (typeof NEW_MENU_ITEM_KINDS)[number]; +/** Every kind a menu entry can be created with: a report comes from the report builder. */ +export type CreatedMenuItemKind = NewMenuItemKind | 'report'; + export function isNewMenuItemKind(kind: string): kind is NewMenuItemKind { return (NEW_MENU_ITEM_KINDS as readonly string[]).includes(kind); } -/** The thing to create: its kind, its machine name and the name the reader gave it. */ -export interface NewMenuItem { - readonly kind: NewMenuItemKind; - readonly name: string; - readonly label: string; -} +/** + * The thing to create: its kind, its machine name and the name the reader + * gave it; a report also carries the body the report builder made. + */ +export type NewMenuItem = + | { readonly kind: NewMenuItemKind; readonly name: string; readonly label: string } + | { readonly kind: 'report'; readonly name: string; readonly label: string; readonly body: Record }; /** The sentences a refused create is said with, in the viewer's language. */ export interface NewMenuItemTexts extends AppMenuSaveTexts { @@ -113,11 +121,13 @@ export async function freeItemName( throw new Error(`No free ${kind} name was found for "${label}".`); } -/** The body a new, empty `kind` is created with. */ +/** The body a new `kind` is created with: an empty dashboard, or the report the builder made. */ export function newItemBody(item: NewMenuItem): Record { switch (item.kind) { case 'dashboard': return { name: item.name, label: item.label, widgets: [] }; + case 'report': + return { ...item.body, name: item.name }; } } @@ -133,12 +143,17 @@ export async function saveAppMenuWithNewItem( ): 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 }, - ); + const outcome = + item.kind === 'dashboard' + ? await saveDashboardInPlace( + item.name, + newItemBody(item), + { kind: 'package', packageId: prepared.target }, + { metadataClient: doors.client }, + ) + : await saveAndPublishInPackage(item.kind, item.name, newItemBody(item), prepared.target, { + metadataClient: doors.client, + }); if (outcome === 'pending-draft') throw new Error(texts.itemPendingDraft); try { await writeAppMenu(prepared, texts, doors); diff --git a/ui/packages/app-shell/src/layout/designModeReportSlot.ts b/ui/packages/app-shell/src/layout/designModeReportSlot.ts new file mode 100644 index 00000000000..0163b07b75c --- /dev/null +++ b/ui/packages/app-shell/src/layout/designModeReportSlot.ts @@ -0,0 +1,74 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The place a new report is being built for (objectstack#36364, report half). + * + * 「New report…」 in the design mode's 「Add menu item」 cannot create the + * report from a name: the spec refuses a report without `dataset` and + * `values`. So the menu holds the place (its dashed row stays), offers this + * slot, and opens the report builder at the app's `reports/new`. The builder + * fills it: its Save hands the report here, and the menu creates it in the + * menu's package and saves its entry in the held place with every other + * staged design change, in one act (`saveAppMenuWithNewItem`). Its Close + * cancels: the held place is dropped and nothing is written. + * + * The menu (in the sidebar) and the builder (in the page) are not in one + * tree that could pass a callback down, so the slot is held here, one at a + * time. The menu withdraws it when it unmounts, which is when the design mode + * ends, so the builder never saves into a mode that is gone: without a slot + * it is the plain new-report page. + * + * @module + */ + +import * as React from 'react'; + +/** What the builder's Save and Close do while a menu place waits for the report. */ +export interface NewReportSlot { + /** The app whose menu holds the place. */ + readonly appName: string; + /** + * Create the report `name` with `body` (its `label` the one the builder + * shows) and save the menu with its entry. `false` when nothing was saved: + * the design mode has said why, and the builder stays open. + */ + readonly save: (name: string, label: string, body: Record) => Promise; + /** Drop the held place; nothing is written. */ + readonly cancel: () => void; +} + +let current: NewReportSlot | null = null; +const listeners = new Set<() => void>(); + +function emit(): void { + for (const listener of listeners) listener(); +} + +/** Offer `slot` to the builder, in place of any slot offered before. */ +export function offerNewReportSlot(slot: NewReportSlot): void { + current = slot; + emit(); +} + +/** Withdraw `slot`, if it is still the one offered. */ +export function withdrawNewReportSlot(slot: NewReportSlot): void { + if (current !== slot) return; + current = null; + emit(); +} + +/** The slot offered for `appName`, or `null`. */ +export function newReportSlotFor(appName: string | undefined): NewReportSlot | null { + return current && appName && current.appName === appName ? current : null; +} + +function subscribe(listener: () => void): () => void { + listeners.add(listener); + return () => listeners.delete(listener); +} + +/** The slot offered for `appName`, read as it changes. */ +export function useNewReportSlot(appName: string | undefined): NewReportSlot | null { + const slot = React.useSyncExternalStore(subscribe, () => current, () => null); + return slot && appName && slot.appName === appName ? slot : null; +} diff --git a/ui/packages/app-shell/src/views/ReportNewPage.menuSlot-36364.test.tsx b/ui/packages/app-shell/src/views/ReportNewPage.menuSlot-36364.test.tsx new file mode 100644 index 00000000000..b595c537efa --- /dev/null +++ b/ui/packages/app-shell/src/views/ReportNewPage.menuSlot-36364.test.tsx @@ -0,0 +1,156 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36364 (report half) — the new-report builder page filling the + * design mode's held menu place: with a slot offered for the app, Save hands + * the report to it and writes nothing itself, Close cancels the place, and + * the page says that saving adds the report to the menu. With no slot the + * page saves on its own, as before. + * + * Real subjects: `ReportNewPage` and the slot store. The builder is a stub + * with a Save and a Close (the real one is `reportBuilder-36374`'s subject); + * the metadata client, the menu's slot and the save door are fakes. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; + +const DRAFT = vi.hoisted(() => ({ + name: '', + label: 'Payment analysis', + type: 'summary', + dataset: 'invoice_metrics', + values: ['invoice_count'], + chart: { type: 'metric', xAxis: '', yAxis: 'invoice_count' }, +})); + +vi.mock('./ReportBuilderHost.js', () => ({ + ReportBuilderHost: (props: { + onSave: (draft: Record) => Promise; + onClose: () => void; + banner?: React.ReactNode; + }) => ( +
    + {props.banner} + + +
    + ), +})); + +const saveAndPublish = vi.hoisted(() => vi.fn(async () => 'published' as const)); +vi.mock('./runtime-metadata-persistence.js', async (importOriginal) => ({ + ...(await importOriginal>()), + saveAndPublishRuntimeMetadata: saveAndPublish, +})); + +const client = vi.hoisted(() => ({ get: vi.fn(async () => null) })); +vi.mock('./metadata-admin/useMetadata.js', () => ({ useMetadataClient: () => client })); + +const refresh = vi.hoisted(() => vi.fn(async () => {})); +vi.mock('../providers/MetadataProvider.js', () => ({ + useMetadata: () => ({ reports: [], loading: false, refresh }), +})); + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), +})); + +import { ReportNewPage } from './ReportNewPage'; +import { offerNewReportSlot, withdrawNewReportSlot, type NewReportSlot } from '../layout/designModeReportSlot'; + +function Where() { + return {useLocation().pathname}; +} + +function mount() { + render( + + + } /> + + + + , + ); +} + +const flush = () => + act(async () => { + await new Promise((r) => setTimeout(r, 0)); + }); + +let slot: NewReportSlot; +beforeEach(() => { + saveAndPublish.mockClear(); + client.get.mockClear(); + slot = { appName: 'crm', save: vi.fn(async () => true), cancel: vi.fn() }; +}); +afterEach(() => { + withdrawNewReportSlot(slot); + cleanup(); +}); + +describe('the new-report page for a held menu place (objectstack#36364)', () => { + it('Save hands the report to the menu, which writes it; the page writes nothing itself', async () => { + offerNewReportSlot(slot); + mount(); + expect(screen.getByTestId('report-new-adds-to-menu')).toBeInTheDocument(); + fireEvent.click(screen.getByText('save')); + await flush(); + await flush(); + expect(slot.save).toHaveBeenCalledWith('payment_analysis', 'Payment analysis', { + ...DRAFT, + name: 'payment_analysis', + }); + expect(saveAndPublish).not.toHaveBeenCalled(); + expect(screen.getByTestId('where')).toHaveTextContent('/apps/crm/report/payment_analysis'); + }); + + it('a save the menu refuses keeps the builder open', async () => { + slot = { ...slot, save: vi.fn(async () => false) }; + offerNewReportSlot(slot); + mount(); + fireEvent.click(screen.getByText('save')); + await flush(); + await flush(); + expect(slot.save).toHaveBeenCalled(); + expect(screen.getByTestId('where')).toHaveTextContent('/apps/crm/reports/new'); + }); + + it('Close cancels the held place and goes back, writing nothing', async () => { + offerNewReportSlot(slot); + mount(); + fireEvent.click(screen.getByText('close')); + await flush(); + expect(slot.cancel).toHaveBeenCalled(); + expect(slot.save).not.toHaveBeenCalled(); + expect(saveAndPublish).not.toHaveBeenCalled(); + expect(screen.getByTestId('where')).toHaveTextContent('/apps/crm/object/crm_lead'); + }); + + it("another app's slot is not this page's: it saves on its own", async () => { + slot = { ...slot, appName: 'hr' }; + offerNewReportSlot(slot); + mount(); + expect(screen.queryByTestId('report-new-adds-to-menu')).toBeNull(); + fireEvent.click(screen.getByText('save')); + await flush(); + await flush(); + expect(slot.save).not.toHaveBeenCalled(); + expect(saveAndPublish).toHaveBeenCalledWith( + 'report', + 'payment_analysis', + { ...DRAFT, name: 'payment_analysis' }, + expect.objectContaining({ metadataClient: client }), + ); + }); +}); diff --git a/ui/packages/app-shell/src/views/ReportNewPage.tsx b/ui/packages/app-shell/src/views/ReportNewPage.tsx index 8f63e32d3f9..04d5a8842ea 100644 --- a/ui/packages/app-shell/src/views/ReportNewPage.tsx +++ b/ui/packages/app-shell/src/views/ReportNewPage.tsx @@ -15,6 +15,13 @@ * romanised, as the Studio inspector derives it) and made unique against the * reports the console already knows, so a new report never writes over one. * + * Opened from the design mode's 「Add menu item → Reports → New report…」 + * (objectstack#36364), the page fills the menu's held place: a slot is + * offered for this app (`designModeReportSlot`), and Save hands the report to + * it, which creates the report in the menu's package and saves its menu entry + * with every other staged design change. Close cancels the place and writes + * nothing. + * * @module */ @@ -29,6 +36,7 @@ import { formatMetadataError } from '@object-ui/data-objectstack'; import type { DataSource } from '@object-ui/types'; import type { ReportDraft } from '@object-ui/plugin-report'; import { ReportBuilderHost } from './ReportBuilderHost.js'; +import { useNewReportSlot } from '../layout/designModeReportSlot.js'; import { saveAndPublishRuntimeMetadata } from './runtime-metadata-persistence.js'; import { useMetadataClient } from './metadata-admin/useMetadata.js'; import { useMetadata } from '../providers/MetadataProvider.js'; @@ -83,11 +91,17 @@ export function ReportNewPage({ dataSource }: { dataSource?: DataSource }) { const metadataClient = useMetadataClient(); const { reports, loading, refresh } = useMetadata(); const { isAdmin, isResolved } = useWorkspaceAdminStatus(); + /** The menu place this report fills, when the design mode opened the page for one. */ + const slot = useNewReportSlot(appName); const backToReports = React.useCallback(() => { - if (appName) navigate(`/apps/${appName}/reports`); + if (slot) { + // Back to the page the design mode was on; the held place is dropped. + slot.cancel(); + navigate(-1); + } else if (appName) navigate(`/apps/${appName}/reports`); else navigate(-1); - }, [navigate, appName]); + }, [navigate, appName, slot]); const handleSave = React.useCallback( async (draft: ReportDraft): Promise => { @@ -110,13 +124,18 @@ export function ReportNewPage({ dataSource }: { dataSource?: DataSource }) { return false; } const body = { ...draft, label, name }; - const outcome = await saveAndPublishRuntimeMetadata('report', name, body, { - metadataClient, - dataSource: dataSource as any, - }); - if (outcome === 'pending-draft') { - toast.error(t('form.saveError'), { description: t('report.builder.pendingDraft') }); - return false; + if (slot) { + // The design mode creates it with its menu entry, and says why when it cannot. + if (!(await slot.save(name, typed || String(label), body))) return false; + } else { + const outcome = await saveAndPublishRuntimeMetadata('report', name, body, { + metadataClient, + dataSource: dataSource as any, + }); + if (outcome === 'pending-draft') { + toast.error(t('form.saveError'), { description: t('report.builder.pendingDraft') }); + return false; + } } } catch (err) { toast.error(t('form.saveError'), { @@ -131,7 +150,7 @@ export function ReportNewPage({ dataSource }: { dataSource?: DataSource }) { }); return true; }, - [metadataClient, reports, language, dataSource, refresh, navigate, appName, t], + [metadataClient, reports, language, dataSource, refresh, navigate, appName, t, slot], ); if (loading || !isResolved) { @@ -159,6 +178,13 @@ export function ReportNewPage({ dataSource }: { dataSource?: DataSource }) { onSave={handleSave} onClose={backToReports} dataSource={dataSource} + banner={ + slot ? ( +

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

    + ) : undefined + } /> ); } diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts index fc18e929b42..c99d583bb67 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts @@ -721,9 +721,26 @@ export async function saveDashboardInPlace( ctx: RuntimePersistCtx, ): Promise { if (target.kind === 'unbound') return saveAndPublishRuntimeMetadata('dashboard', name, body, ctx); - return saveAndPublishRuntimeMetadata('dashboard', name, body, { + return saveAndPublishInPackage('dashboard', name, body, target.packageId, ctx); +} + +/** + * {@link saveAndPublishRuntimeMetadata} into the package `packageId`: the + * draft, its publish and the discard of a refused publish all name it. Used + * where an item is created in a known package, such as a dashboard or report + * made from the design mode's 「Add menu item」 (objectstack#36364), which is + * saved where the menu is. + */ +export function saveAndPublishInPackage( + type: RuntimeArtifactType, + name: string, + body: Record, + packageId: string, + ctx: RuntimePersistCtx, +): Promise { + return saveAndPublishRuntimeMetadata(type, name, body, { ...ctx, - metadataClient: boundToPackage(ctx.metadataClient, target.packageId), + metadataClient: boundToPackage(ctx.metadataClient, packageId), }); } 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 20b34907517..057754f93b9 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 @@ -471,7 +471,10 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // 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); + // 129 once objectstack-ai/objectstack#36364's report half added + // `designMode.menu.newReportLeft`, the same sentence for a new report + // („{{name}}“) — one interpolated span. + expect(okSpans, 'correctly paired spans').toBe(129); }); it('keeps the count identity that replaces the card’s count(„) === count(“)', () => { @@ -602,7 +605,9 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // two more matched pairs. // 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 }); + // 129 / 129 / 0 after its report half added `designMode.menu.newReportLeft`, + // one more matched pair. + expect({ open, close, rdq }).toEqual({ open: 129, close: 129, 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 0679e2e1ccf..740b61f2381 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -3936,11 +3936,13 @@ const ar = { notWritable: 'حزمة تخصيص هذا التطبيق غير قابلة للكتابة، لذا لا يمكن حفظ قائمته.', newDashboard: 'لوحة معلومات جديدة…', newDashboardTitle: 'لوحة معلومات جديدة', + newReport: 'تقرير جديد…', newItemSavesAll: 'يؤدي إنشاؤها إلى حفظ تغييرات التصميم الأخرى أيضًا، ثم تُفتح للتحرير.', create: 'إنشاء', creating: 'جارٍ الإنشاء…', newItemPendingDraft: 'توجد مسودة غير منشورة بهذا الاسم بالفعل. حاول مرة أخرى.', newItemLeft: 'تعذّرت إزالة لوحة المعلومات الجديدة "{{name}}"؛ أزلها في Studio.', + newReportLeft: 'تعذّرت إزالة التقرير الجديد "{{name}}"؛ أزله في Studio.', }, recordTabs: { entry: 'تكوين علامات التبويب', @@ -4425,6 +4427,7 @@ const ar = { settings: "إعدادات التقرير", pendingDraft: "يحتوي هذا التقرير على تغييرات غير منشورة. انشرها أو تجاهلها في الأعلى، ثم احفظ.", nameTaken: "كل المعرّفات المشتقة من هذا الاسم مستخدمة بالفعل. أعطِ التقرير اسمًا آخر ثم احفظ.", + addsToMenu: "الحفظ ينشئ هذا التقرير ويضيفه إلى القائمة في المكان الذي اخترته، مع تغييرات التصميم الأخرى.", adminOnlyTitle: "يمكن لمسؤولي مساحة العمل فقط إنشاء التقارير", adminOnly: "التقرير مشترك مع الجميع في مساحة العمل، لذا ينشئه مسؤول.", type: { diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 910717801c8..43804b504ab 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -3613,11 +3613,13 @@ const de = { notWritable: 'Das Anpassungspaket dieser App ist nicht beschreibbar, daher kann ihr Menü nicht gespeichert werden.', newDashboard: 'Neues Dashboard…', newDashboardTitle: 'Neues Dashboard', + newReport: 'Neuer Bericht…', 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.', + newReportLeft: 'Der neue Bericht „{{name}}“ konnte nicht wieder entfernt werden; entfernen Sie ihn in Studio.', }, recordTabs: { entry: 'Tabs konfigurieren', @@ -4067,6 +4069,7 @@ const de = { settings: "Berichtseinstellungen", pendingDraft: "Dieser Bericht hat unveröffentlichte Änderungen. Veröffentlichen oder verwerfen Sie sie oben und speichern Sie dann.", nameTaken: "Alle aus diesem Namen gebildeten Kennungen sind bereits vergeben. Geben Sie dem Bericht einen anderen Namen und speichern Sie dann erneut.", + addsToMenu: "Beim Speichern wird dieser Bericht erstellt und an der gewählten Stelle ins Menü aufgenommen, zusammen mit Ihren anderen Designänderungen.", adminOnlyTitle: "Nur Workspace-Administratoren können Berichte erstellen", adminOnly: "Ein Bericht gilt für alle im Workspace, daher erstellt ihn ein Administrator.", type: { diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index ccc2bfd0238..3a4e2da2357 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -2195,6 +2195,7 @@ const en = { settings: 'Report settings', pendingDraft: 'This report has unpublished changes. Publish or discard them above, then save.', nameTaken: 'Every name made from this one is already taken. Give the report another name, then save.', + addsToMenu: 'Saving creates this report and adds it to the menu where you placed it, with your other design changes.', adminOnlyTitle: 'Only workspace admins can build reports', adminOnly: 'A report is shared with everyone in the workspace, so an admin builds it.', type: { @@ -4354,11 +4355,13 @@ const en = { notWritable: 'This app\'s customization package cannot be written, so its menu cannot be saved.', newDashboard: 'New dashboard…', newDashboardTitle: 'New dashboard', + newReport: 'New report…', 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.', + newReportLeft: 'The new report "{{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 6aee49a0be6..b29cba12ce9 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -3695,11 +3695,13 @@ const es = { 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', + newReport: 'Nuevo informe…', 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.', + newReportLeft: 'No se pudo eliminar el nuevo informe "{{name}}"; elimínalo en Studio.', }, recordTabs: { entry: 'Configurar pestañas', @@ -4157,6 +4159,7 @@ const es = { settings: "Configuración del informe", pendingDraft: "Este informe tiene cambios sin publicar. Publícalos o descártalos arriba y luego guarda.", nameTaken: "Todos los identificadores derivados de este nombre ya están en uso. Ponle otro nombre al informe y guarda.", + addsToMenu: "Al guardar se crea este informe y se añade al menú en el lugar que elegiste, junto con tus otros cambios de diseño.", adminOnlyTitle: "Solo los administradores del espacio de trabajo pueden crear informes", adminOnly: "Un informe se comparte con todo el espacio de trabajo, así que lo crea un administrador.", type: { diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 39b45f2e033..53ed8ad3adf 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -3691,11 +3691,13 @@ const fr = { 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', + newReport: 'Nouveau rapport…', 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.', + newReportLeft: 'Le nouveau rapport « {{name}} » n\'a pas pu être retiré ; retirez-le dans Studio.', }, recordTabs: { entry: 'Configurer les onglets', @@ -4153,6 +4155,7 @@ const fr = { settings: "Paramètres du rapport", pendingDraft: "Ce rapport a des modifications non publiées. Publiez-les ou supprimez-les ci-dessus, puis enregistrez.", nameTaken: "Tous les identifiants dérivés de ce nom sont déjà pris. Donnez un autre nom au rapport, puis enregistrez.", + addsToMenu: "L'enregistrement crée ce rapport et l'ajoute au menu à l'emplacement choisi, avec vos autres modifications de conception.", adminOnlyTitle: "Seuls les administrateurs de l’espace de travail peuvent créer des rapports", adminOnly: "Un rapport est partagé avec tout l’espace de travail ; c’est donc un administrateur qui le crée.", type: { diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 3fe7cbbe72d..740f465f267 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -3615,11 +3615,13 @@ const ja = { notWritable: 'このアプリのカスタマイズパッケージに書き込めないため、メニューを保存できません。', newDashboard: '新しいダッシュボード…', newDashboardTitle: '新しいダッシュボード', + newReport: '新規レポート…', newItemSavesAll: '作成すると、デザインモードの他の変更も保存され、編集用に開きます。', create: '作成', creating: '作成中…', newItemPendingDraft: 'この名前の未公開の下書きがすでにあります。もう一度お試しください。', newItemLeft: '新しいダッシュボード「{{name}}」を削除できませんでした。Studio で削除してください。', + newReportLeft: '新しいレポート「{{name}}」を削除できませんでした。Studio で削除してください。', }, recordTabs: { entry: 'タブを設定', @@ -4069,6 +4071,7 @@ const ja = { settings: "レポート設定", pendingDraft: "このレポートには未公開の変更があります。上で公開または破棄してから保存してください。", nameTaken: "この名前から作れる識別子はすべて使用済みです。レポートに別の名前を付けてから保存してください。", + addsToMenu: "保存するとこのレポートが作成され、選んだ位置のメニューに追加されます。デザインのほかの変更も一緒に保存されます。", adminOnlyTitle: "レポートを作成できるのはワークスペース管理者のみです", adminOnly: "レポートはワークスペースの全員に共有されるため、管理者が作成します。", type: { diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 18a7a4d3436..7031cd06cd7 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -3613,11 +3613,13 @@ const ko = { notWritable: '이 앱의 사용자 지정 패키지에 쓸 수 없어 메뉴를 저장할 수 없습니다.', newDashboard: '새 대시보드…', newDashboardTitle: '새 대시보드', + newReport: '새 보고서…', newItemSavesAll: '만들면 디자인 모드의 다른 변경 사항도 함께 저장되고 편집할 수 있게 열립니다.', create: '만들기', creating: '만드는 중…', newItemPendingDraft: '이 이름으로 게시되지 않은 초안이 이미 있습니다. 다시 시도하세요.', newItemLeft: '새 대시보드 "{{name}}"을(를) 삭제하지 못했습니다. Studio에서 삭제하세요.', + newReportLeft: '새 보고서 "{{name}}"을(를) 삭제하지 못했습니다. Studio에서 삭제하세요.', }, recordTabs: { entry: '탭 구성', @@ -4066,6 +4068,7 @@ const ko = { settings: "보고서 설정", pendingDraft: "이 보고서에 게시되지 않은 변경 사항이 있습니다. 위에서 게시하거나 버린 후 저장하세요.", nameTaken: "이 이름으로 만들 수 있는 식별자가 모두 사용 중입니다. 보고서 이름을 바꾼 뒤 저장하세요.", + addsToMenu: "저장하면 이 보고서가 만들어지고 지정한 메뉴 위치에 추가되며, 다른 디자인 변경도 함께 저장됩니다.", adminOnlyTitle: "워크스페이스 관리자만 보고서를 만들 수 있습니다", adminOnly: "보고서는 워크스페이스의 모든 사람에게 공유되므로 관리자가 만듭니다.", type: { diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 9ba1bffd5a6..4cf38797d7e 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -3690,11 +3690,13 @@ const pt = { 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', + newReport: 'Novo relatório…', 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.', + newReportLeft: 'Não foi possível remover o novo relatório "{{name}}"; remova-o no Studio.', }, recordTabs: { entry: 'Configurar abas', @@ -4152,6 +4154,7 @@ const pt = { settings: "Configurações do relatório", pendingDraft: "Este relatório tem alterações não publicadas. Publique ou descarte-as acima e depois salve.", nameTaken: "Todos os identificadores gerados a partir deste nome já estão em uso. Dê outro nome ao relatório e salve.", + addsToMenu: "Ao salvar, este relatório é criado e adicionado ao menu no lugar escolhido, junto com suas outras alterações de design.", adminOnlyTitle: "Somente administradores do espaço de trabalho podem criar relatórios", adminOnly: "Um relatório é compartilhado com todo o espaço de trabalho, por isso um administrador o cria.", type: { diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index ee2a1dd4590..9cf7197aee6 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -3782,11 +3782,13 @@ const ru = { notWritable: 'Пакет настроек этого приложения недоступен для записи, поэтому меню нельзя сохранить.', newDashboard: 'Новая панель…', newDashboardTitle: 'Новая панель', + newReport: 'Новый отчёт…', newItemSavesAll: 'При создании сохраняются и другие изменения режима дизайна, затем панель открывается для редактирования.', create: 'Создать', creating: 'Создание…', newItemPendingDraft: 'Под этим именем уже есть неопубликованный черновик. Повторите попытку.', newItemLeft: 'Не удалось удалить новую панель «{{name}}»; удалите её в Studio.', + newReportLeft: 'Не удалось удалить новый отчёт «{{name}}»; удалите его в Studio.', }, recordTabs: { entry: 'Настроить вкладки', @@ -4256,6 +4258,7 @@ const ru = { settings: "Настройки отчёта", pendingDraft: "В этом отчёте есть неопубликованные изменения. Опубликуйте или отмените их выше, затем сохраните.", nameTaken: "Все идентификаторы, полученные из этого имени, уже заняты. Дайте отчёту другое имя и сохраните.", + addsToMenu: "При сохранении этот отчёт будет создан и добавлен в меню на выбранное место вместе с остальными изменениями дизайна.", adminOnlyTitle: "Создавать отчёты могут только администраторы рабочего пространства", adminOnly: "Отчёт виден всем в рабочем пространстве, поэтому его создаёт администратор.", type: { diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 64aa3bb029b..a968c6eeac8 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1835,6 +1835,7 @@ const zh = { settings: '报表设置', pendingDraft: '这张报表有一份还没发布的修改。先在上方发布或丢弃它,再保存。', nameTaken: '由这个名称生成的标识都已被占用。请给报表换个名称再保存。', + addsToMenu: '保存后会建好这张报表,放进菜单里你占好的位置,并一并保存设计模式里的其他改动。', adminOnlyTitle: '只有系统管理员能搭建报表', adminOnly: '报表对工作区里所有人生效,所以由系统管理员搭建。', type: { @@ -3750,11 +3751,13 @@ const zh = { notWritable: '这个应用的定制包不可写,菜单无法保存。', newDashboard: '新建仪表盘…', newDashboardTitle: '新建仪表盘', + newReport: '新建报表…', newItemSavesAll: '创建时会一并保存设计模式里的其他改动,然后打开它进行编辑。', create: '创建', creating: '正在创建…', newItemPendingDraft: '这个名称下已有一份未发布的草稿,请再试一次。', newItemLeft: '新建的仪表盘「{{name}}」没能删除,请在 Studio 里删除它。', + newReportLeft: '新建的报表「{{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 f3c31a110dc..b539c5d3c82 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1835,6 +1835,7 @@ const zhHant = { settings: '報表設定', pendingDraft: '這張報表有一份還沒釋出的修改。先在上方釋出或丟棄它,再儲存。', nameTaken: '由這個名稱生成的標識都已被佔用。請給報表換個名稱再儲存。', + addsToMenu: '儲存後會建好這張報表,放進選單裡你佔好的位置,並一併儲存設計模式裡的其他改動。', adminOnlyTitle: '只有系統管理員能搭建報表', adminOnly: '報表對工作區裡所有人生效,所以由系統管理員搭建。', type: { @@ -3750,11 +3751,13 @@ const zhHant = { notWritable: '這個應用的定製包不可寫,選單無法儲存。', newDashboard: '新建儀表盤…', newDashboardTitle: '新建儀表盤', + newReport: '新建報表…', newItemSavesAll: '建立時會一併儲存設計模式裡的其他改動,然後開啟它進行編輯。', create: '建立', creating: '正在建立…', newItemPendingDraft: '這個名稱下已有一份未釋出的草稿,請再試一次。', newItemLeft: '新建的儀表盤「{{name}}」沒能刪除,請在 Studio 裡刪除它。', + newReportLeft: '新建的報表「{{name}}」沒能刪除,請在 Studio 裡刪除它。', }, recordTabs: { entry: '配置頁籤', From f3021225fcc3bc00b93973688fe9b9256ca64636 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 09:21:21 +0000 Subject: [PATCH 2/3] fix(app-shell): key the held report place by the builder's address The console addresses an app by its route segment, which need not be its name, so the builder page finds the place it fills by its own address. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbXq2Dxb31zZNmSqCtz --- .../app-shell/src/layout/DesignModeMenu.tsx | 7 +++--- .../__tests__/DesignModeMenu-36363.test.tsx | 18 ++++++------- .../src/layout/designModeReportSlot.ts | 25 +++++++++++++------ .../ReportNewPage.menuSlot-36364.test.tsx | 23 ++++++++++++++--- .../app-shell/src/views/ReportNewPage.tsx | 4 +-- 5 files changed, 51 insertions(+), 26 deletions(-) diff --git a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx index 13e2fe869f1..2b5198d5337 100644 --- a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx +++ b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx @@ -456,6 +456,8 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso setBuildingReport(false); return true; }; + // The builder's address the held place waits on. + const newReportPath = `${basePath}/reports/new`; const saveNewReportRef = React.useRef(saveNewReport); React.useLayoutEffect(() => { saveNewReportRef.current = saveNewReport; @@ -463,7 +465,7 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso React.useEffect(() => { if (!buildingReport) return; const slot: NewReportSlot = { - appName, + path: newReportPath, save: (name, label, body) => saveNewReportRef.current(name, label, body), cancel: () => { setBuildingReport(false); @@ -474,12 +476,11 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso // Withdrawn when the place is no longer held, and when the menu unmounts // (the design mode ended): the builder then saves on its own, off the menu. return () => withdrawNewReportSlot(slot); - }, [buildingReport, appName]); + }, [buildingReport, newReportPath]); // Leaving the builder another way than its Save or Close (a menu link, the // browser's Back) drops the place too, so no held row waits for a builder // that is gone. Read once the builder has been reached. const { pathname } = useLocation(); - const newReportPath = `${basePath}/reports/new`; const [reachedBuilder, setReachedBuilder] = React.useState(false); const onBuilder = pathname === newReportPath || pathname.endsWith(newReportPath); if (buildingReport && onBuilder && !reachedBuilder) setReachedBuilder(true); diff --git a/ui/packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx b/ui/packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx index dd925a70aa8..a43b775c335 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 @@ -830,8 +830,8 @@ describe('a new report from 「Add menu item」 (objectstack#36364, report half) // The place stays held, saying what it waits for. expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', ['…']]]); expect(screen.getByTestId('design-menu-placeholder')).toHaveTextContent('New report…'); - expect(newReportSlotFor('crm')).not.toBeNull(); - expect(newReportSlotFor('hr')).toBeNull(); + expect(newReportSlotFor('/apps/crm/reports/new')).not.toBeNull(); + expect(newReportSlotFor('/apps/hr/reports/new')).toBeNull(); expect(written).toEqual([]); }); @@ -841,7 +841,7 @@ describe('a new report from 「Add menu item」 (objectstack#36364, report half) const picker = await openReports(); fireEvent.click(within(picker).getByTestId('design-menu-picker-new-report')); await flush(); - const slot = newReportSlotFor('crm')!; + const slot = newReportSlotFor('/apps/crm/reports/new')!; let saved: boolean | undefined; await act(async () => { saved = await slot.save('payment_analysis', 'Payment analysis', { ...REPORT_BODY, name: 'payment_analysis' }); @@ -861,7 +861,7 @@ describe('a new report from 「Add menu item」 (objectstack#36364, report half) expect(navigation[1].children!.map((c) => (c as { id: string }).id)).toEqual(['accounts', 'leads']); expect(navigation[2].children).toEqual([{ id: 'nav_item_1', type: 'report', reportName: 'payment_analysis' }]); expect(screen.queryByTestId('design-mode-bar')).toBeNull(); - expect(newReportSlotFor('crm')).toBeNull(); + expect(newReportSlotFor('/apps/crm/reports/new')).toBeNull(); }); it('a refused menu removes the new report; the mode, the held place and the other staged edits stay', async () => { @@ -873,7 +873,7 @@ describe('a new report from 「Add menu item」 (objectstack#36364, report half) await flush(); let saved: boolean | undefined; await act(async () => { - saved = await newReportSlotFor('crm')!.save('payment_analysis', 'Payment analysis', { ...REPORT_BODY, name: 'payment_analysis' }); + saved = await newReportSlotFor('/apps/crm/reports/new')!.save('payment_analysis', 'Payment analysis', { ...REPORT_BODY, name: 'payment_analysis' }); }); await flush(); @@ -887,7 +887,7 @@ describe('a new report from 「Add menu item」 (objectstack#36364, report half) expect(toastError).toHaveBeenCalledWith('Some changes were not saved: the app was refused'); expect(screen.getByTestId('design-mode-bar')).toBeInTheDocument(); expect(order()).toEqual(['home', ['sales', ['accounts', 'leads']], ['insights', ['…']]]); - expect(newReportSlotFor('crm')).not.toBeNull(); + expect(newReportSlotFor('/apps/crm/reports/new')).not.toBeNull(); }); it('the builder\'s Close drops the held place and writes nothing; the mode and its other edits stay', async () => { @@ -896,10 +896,10 @@ describe('a new report from 「Add menu item」 (objectstack#36364, report half) const picker = await openReports(); fireEvent.click(within(picker).getByTestId('design-menu-picker-new-report')); await flush(); - act(() => newReportSlotFor('crm')!.cancel()); + act(() => newReportSlotFor('/apps/crm/reports/new')!.cancel()); await flush(); expect(order()).toEqual(['home', ['sales', ['accounts', 'leads']], ['insights', []]]); - expect(newReportSlotFor('crm')).toBeNull(); + expect(newReportSlotFor('/apps/crm/reports/new')).toBeNull(); expect(written).toEqual([]); expect(screen.getByTestId('design-mode-save')).toBeEnabled(); }); @@ -912,7 +912,7 @@ describe('a new report from 「Add menu item」 (objectstack#36364, report half) fireEvent.click(screen.getByText('go elsewhere')); await flush(); expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', []]]); - expect(newReportSlotFor('crm')).toBeNull(); + expect(newReportSlotFor('/apps/crm/reports/new')).toBeNull(); expect(written).toEqual([]); }); }); diff --git a/ui/packages/app-shell/src/layout/designModeReportSlot.ts b/ui/packages/app-shell/src/layout/designModeReportSlot.ts index 0163b07b75c..3f8bc98e837 100644 --- a/ui/packages/app-shell/src/layout/designModeReportSlot.ts +++ b/ui/packages/app-shell/src/layout/designModeReportSlot.ts @@ -25,8 +25,12 @@ import * as React from 'react'; /** What the builder's Save and Close do while a menu place waits for the report. */ export interface NewReportSlot { - /** The app whose menu holds the place. */ - readonly appName: string; + /** + * The builder's address the place waits on (`/reports/new`): + * the page there fills it. The address, not the app's name, because the + * console addresses an app by its route segment, which need not be its name. + */ + readonly path: string; /** * Create the report `name` with `body` (its `label` the one the builder * shows) and save the menu with its entry. `false` when nothing was saved: @@ -57,9 +61,14 @@ export function withdrawNewReportSlot(slot: NewReportSlot): void { emit(); } -/** The slot offered for `appName`, or `null`. */ -export function newReportSlotFor(appName: string | undefined): NewReportSlot | null { - return current && appName && current.appName === appName ? current : null; +/** Whether the page at `pathname` is the builder `slot` waits on (a router basename in front counts). */ +function isAt(slot: NewReportSlot, pathname: string | undefined): boolean { + return !!pathname && (pathname === slot.path || pathname.endsWith(slot.path)); +} + +/** The slot the page at `pathname` fills, or `null`. */ +export function newReportSlotFor(pathname: string | undefined): NewReportSlot | null { + return current && isAt(current, pathname) ? current : null; } function subscribe(listener: () => void): () => void { @@ -67,8 +76,8 @@ function subscribe(listener: () => void): () => void { return () => listeners.delete(listener); } -/** The slot offered for `appName`, read as it changes. */ -export function useNewReportSlot(appName: string | undefined): NewReportSlot | null { +/** The slot the page at `pathname` fills, read as it changes. */ +export function useNewReportSlot(pathname: string | undefined): NewReportSlot | null { const slot = React.useSyncExternalStore(subscribe, () => current, () => null); - return slot && appName && slot.appName === appName ? slot : null; + return slot && isAt(slot, pathname) ? slot : null; } diff --git a/ui/packages/app-shell/src/views/ReportNewPage.menuSlot-36364.test.tsx b/ui/packages/app-shell/src/views/ReportNewPage.menuSlot-36364.test.tsx index b595c537efa..3bd3ddfb8f7 100644 --- a/ui/packages/app-shell/src/views/ReportNewPage.menuSlot-36364.test.tsx +++ b/ui/packages/app-shell/src/views/ReportNewPage.menuSlot-36364.test.tsx @@ -71,9 +71,9 @@ function Where() { return {useLocation().pathname}; } -function mount() { +function mount(app = 'crm') { render( - + } /> @@ -92,7 +92,7 @@ let slot: NewReportSlot; beforeEach(() => { saveAndPublish.mockClear(); client.get.mockClear(); - slot = { appName: 'crm', save: vi.fn(async () => true), cancel: vi.fn() }; + slot = { path: '/apps/crm/reports/new', save: vi.fn(async () => true), cancel: vi.fn() }; }); afterEach(() => { withdrawNewReportSlot(slot); @@ -137,8 +137,23 @@ describe('the new-report page for a held menu place (objectstack#36364)', () => expect(screen.getByTestId('where')).toHaveTextContent('/apps/crm/object/crm_lead'); }); + it('an app addressed by a route segment other than its name finds its slot by the address', async () => { + // The console addresses the showcase app as `com.example.showcase` while + // its name is `showcase_app`: the place waits on the builder's address. + slot = { ...slot, path: '/apps/com.acme.crm/reports/new' }; + offerNewReportSlot(slot); + mount('com.acme.crm'); + expect(screen.getByTestId('report-new-adds-to-menu')).toBeInTheDocument(); + fireEvent.click(screen.getByText('save')); + await flush(); + await flush(); + expect(slot.save).toHaveBeenCalled(); + expect(saveAndPublish).not.toHaveBeenCalled(); + expect(screen.getByTestId('where')).toHaveTextContent('/apps/com.acme.crm/report/payment_analysis'); + }); + it("another app's slot is not this page's: it saves on its own", async () => { - slot = { ...slot, appName: 'hr' }; + slot = { ...slot, path: '/apps/hr/reports/new' }; offerNewReportSlot(slot); mount(); expect(screen.queryByTestId('report-new-adds-to-menu')).toBeNull(); diff --git a/ui/packages/app-shell/src/views/ReportNewPage.tsx b/ui/packages/app-shell/src/views/ReportNewPage.tsx index 04d5a8842ea..d7a28664b12 100644 --- a/ui/packages/app-shell/src/views/ReportNewPage.tsx +++ b/ui/packages/app-shell/src/views/ReportNewPage.tsx @@ -26,7 +26,7 @@ */ import * as React from 'react'; -import { useNavigate, useParams } from 'react-router-dom'; +import { useLocation, useNavigate, useParams } from 'react-router-dom'; import { toast } from 'sonner'; import { Loader2 } from 'lucide-react'; import { Empty, EmptyDescription, EmptyTitle } from '@object-ui/components'; @@ -92,7 +92,7 @@ export function ReportNewPage({ dataSource }: { dataSource?: DataSource }) { const { reports, loading, refresh } = useMetadata(); const { isAdmin, isResolved } = useWorkspaceAdminStatus(); /** The menu place this report fills, when the design mode opened the page for one. */ - const slot = useNewReportSlot(appName); + const slot = useNewReportSlot(useLocation().pathname); const backToReports = React.useCallback(() => { if (slot) { From ecbe0f66cd19c4e6132ee6fe3d04ec49ca6dbee1 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 09:25:19 +0000 Subject: [PATCH 3/3] fix(app-shell): a new report's menu entry carries the report's name Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbXq2Dxb31zZNmSqCtz --- ui/packages/app-shell/src/layout/DesignModeMenu.tsx | 5 ++++- .../src/layout/__tests__/DesignModeMenu-36363.test.tsx | 4 +++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx index 2b5198d5337..42bcf898dd3 100644 --- a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx +++ b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx @@ -433,7 +433,10 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso const [buildingReport, setBuildingReport] = React.useState(false); const saveNewReport = async (name: string, label: string, body: Record): Promise => { if (!addAt) return false; - const entry = entryFor('report', name, newEntryId([...menu, ...(storedMenu ?? [])])); + // A report entry with no label shows its machine name (only an object, + // view or dashboard entry inherits its target's label), so the entry + // carries the name the reader gave the report. + const entry = { ...entryFor('report', name, newEntryId([...menu, ...(storedMenu ?? [])])), label }; const itemTexts = { ...texts, itemPendingDraft: t('designMode.menu.newItemPendingDraft', { 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 a43b775c335..811f753cecf 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 @@ -859,7 +859,9 @@ describe('a new report from 「Add menu item」 (objectstack#36364, report half) expect(written[0][4]).toEqual({ mode: 'draft', ifNoneMatch: '*', packageId: 'com.acme.crm' }); const navigation = (written[2][3] as { navigation: Array<{ id: string; children?: unknown[] }> }).navigation; expect(navigation[1].children!.map((c) => (c as { id: string }).id)).toEqual(['accounts', 'leads']); - expect(navigation[2].children).toEqual([{ id: 'nav_item_1', type: 'report', reportName: 'payment_analysis' }]); + expect(navigation[2].children).toEqual([ + { id: 'nav_item_1', type: 'report', reportName: 'payment_analysis', label: 'Payment analysis' }, + ]); expect(screen.queryByTestId('design-mode-bar')).toBeNull(); expect(newReportSlotFor('/apps/crm/reports/new')).toBeNull(); });