diff --git a/.changeset/36692-report-editing-own-entry.md b/.changeset/36692-report-editing-own-entry.md new file mode 100644 index 00000000000..8b9655b5900 --- /dev/null +++ b/.changeset/36692-report-editing-own-entry.md @@ -0,0 +1,19 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +fix(console): report editing is its own entry, and report and dashboard editing exclude the design mode both ways + +Clause-②: no +Metadata-protocol: none + +The console's design mode no longer hosts the report builder, so the screen shows one Save/Cancel set at a time: + +- The design mode's 「Add menu item → Reports」 lists only reports that exist; its 「New report…」 row is gone, with the hand-off that let the builder save into the menu. A new report is made from the reports index, then linked from the design mode. +- The reports index offers 「New report」 in its header, opening the report builder. It is offered to workspace admins, as the builder is, and not while the design mode is on. +- While the design mode is on, a dashboard's and a report's own 「Edit」 are not offered. +- While a dashboard or report editor is open, 「Design layout」 refuses with a prompt to save or cancel those changes first, so the design mode's 「Cancel」 can no longer end the mode under an editor left open. +- The report builder's own address reached with the design mode already on (the browser's Back) shows a prompt to finish designing the layout instead of the builder; the builder opens there once the mode is saved or cancelled. + +The design mode's 「New dashboard…」 is unchanged. In `@object-ui/i18n`, `designMode.menu.newReport`, `designMode.menu.newReportLeft` and `report.builder.addsToMenu` are removed from every pack, and `designMode.editorOpen`, `console.reportIndex.newReport`, `report.builder.designModeOnTitle` and `report.builder.designModeOn` are added. Nothing to migrate. diff --git a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx index 64b6b79e338..b766fa9bdf5 100644 --- a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx +++ b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx @@ -47,10 +47,9 @@ * place, and the mode saves at once, every other staged change with it * (`saveAppMenuWithNewItem`); then the mode is left and the new dashboard * opens for editing (`dashboardEditArrival`). 「Cancel」 writes nothing. - * In 「Reports」 the first row is 「New report…」: a report needs a data source - * and a measure, so the place stays held and the report builder opens; its - * Save creates the report and saves the mode the same way - * (`designModeReportSlot`), and its Close drops the place, writing nothing. + * 「Reports」 lists only reports that exist (objectstack#36692, the + * maintainer's ruling to keep report editing its own entry, as Twenty does): + * a new report is made from the reports index, then linked here. * * Every edit is staged with the mode (`useDesignModeChange`), under one key * for the app's menu: the mode's 「Save」 writes it (`saveAppMenu`), its @@ -69,7 +68,7 @@ */ import * as React from 'react'; -import { Link, useLocation, useNavigate } from 'react-router-dom'; +import { Link, useNavigate } from 'react-router-dom'; import { toast } from 'sonner'; import { DndContext, @@ -180,7 +179,6 @@ import { } from './designModeMenuSave.js'; import { freeItemName, isNewMenuItemKind, saveAppMenuWithNewItem, type NewMenuItemKind } from './designModeMenuCreate.js'; import { dashboardEditArrival } from './designModeArrival.js'; -import { offerNewReportSlot, withdrawNewReportSlot, type NewReportSlot } from './designModeReportSlot.js'; /** * The group label's icon-mode hiding, as the sidebar's own labels declare it @@ -503,83 +501,6 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso return true; }; - // objectstack#36364 (report half) — 「New report…」: a report cannot be - // made from a name (the spec wants `dataset` and `values`), so the place - // stays held and the report builder opens at `reports/new`. The builder - // saves through the slot offered here (`designModeReportSlot`): the report - // is created in the menu's package and its entry saved in the held place - // with every other staged change, in one act; nothing is written before. - // The builder's Close drops the place. Resolves `false` when nothing was - // saved (the mode has said why); the builder stays open for another try. - const [buildingReport, setBuildingReport] = React.useState(false); - const saveNewReport = async (name: string, label: string, body: Record): Promise => { - if (!addAt) return false; - // A report entry with no label shows its machine name (only an object, - // view or dashboard entry inherits its target's label), so the entry - // carries the name the reader gave the report. - const entry = { ...entryFor('report', name, newEntryId([...menu, ...(storedMenu ?? [])])), label }; - const itemTexts = { - ...texts, - itemPendingDraft: t('designMode.menu.newItemPendingDraft', { - defaultValue: 'A draft with this name is already pending. Try again.', - }), - itemLeft: t('designMode.menu.newReportLeft', { - defaultValue: 'The new report "{{name}}" could not be removed again; remove it in Studio.', - name: label, - }), - }; - const saved = await saveWith(insertEntry(menu, addAt.parentId, addAt.index, entry), (navigation) => - saveAppMenuWithNewItem( - { appName, packageId, served, navigation, labels, item: { kind: 'report', name, label, body } }, - itemTexts, - consoleAppMenuDoors(client as never), - ), - ); - if (!saved) return false; - setAddAt(null); - setBuildingReport(false); - return true; - }; - // The builder's address the held place waits on. - const newReportPath = `${basePath}/reports/new`; - const saveNewReportRef = React.useRef(saveNewReport); - React.useLayoutEffect(() => { - saveNewReportRef.current = saveNewReport; - }); - React.useEffect(() => { - if (!buildingReport) return; - const slot: NewReportSlot = { - path: newReportPath, - save: (name, label, body) => saveNewReportRef.current(name, label, body), - cancel: () => { - setBuildingReport(false); - setAddAt(null); - }, - }; - offerNewReportSlot(slot); - // Withdrawn when the place is no longer held, and when the menu unmounts - // (the design mode ended): the builder then saves on its own, off the menu. - return () => withdrawNewReportSlot(slot); - }, [buildingReport, newReportPath]); - // Leaving the builder another way than its Save or Close (a menu link, the - // browser's Back) drops the place too, so no held row waits for a builder - // that is gone. Read once the builder has been reached. - const { pathname } = useLocation(); - const [reachedBuilder, setReachedBuilder] = React.useState(false); - const onBuilder = pathname === newReportPath || pathname.endsWith(newReportPath); - if (buildingReport && onBuilder && !reachedBuilder) setReachedBuilder(true); - if (!buildingReport && reachedBuilder) setReachedBuilder(false); - if (buildingReport && reachedBuilder && !onBuilder) { - setBuildingReport(false); - setReachedBuilder(false); - setAddAt(null); - } - const startNewReport = () => { - if (!addAt) return; - setBuildingReport(true); - navigate(newReportPath); - }; - const renderLeaf = (entry: MenuEntry, depth: number) => { const id = String(entry.id); const place = placeOf(menu, id); @@ -620,7 +541,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( @@ -641,7 +562,7 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso rows.push(renderLeaf(entry, depth)); } }); - if (addAt && addAt.parentId === parentId && addAt.index >= entries.length) rows.push(); + if (addAt && addAt.parentId === parentId && addAt.index >= entries.length) rows.push(); // Another package's group takes no own entry: no 「Add menu item」, no drop at its end. if (foreignGroup(parentId)) return rows; rows.push( @@ -695,14 +616,13 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso - {addAt && !buildingReport && ( + {addAt && ( setAddAt(null)} onPick={(kind, name, link) => pick(entryFor(kind, name, newEntryId([...menu, ...(storedMenu ?? [])]), link))} onCreate={createItem} - onNewReport={startNewReport} language={language} /> )} @@ -794,14 +714,12 @@ function MenuLeaf({ ); } -function Placeholder({ depth, buildingReport }: { depth: number; buildingReport?: boolean }) { +function Placeholder({ depth }: { depth: number }) { const { t } = useObjectTranslation(); return (
  • - {buildingReport - ? t('designMode.menu.newReport', { defaultValue: 'New report…' }) - : t('designMode.menu.placeholder', { defaultValue: 'Choose a menu item…' })} + {t('designMode.menu.placeholder', { defaultValue: 'Choose a menu item…' })}
  • ); @@ -998,7 +916,6 @@ function MenuItemPicker({ onClose, onPick, onCreate, - onNewReport, language, }: { packageId: string; @@ -1007,8 +924,6 @@ function MenuItemPicker({ onPick: (kind: MenuTargetKind, name: string, link?: { label: string; url: string }) => void; /** Create a new `kind` named `label`; `taken` is every name of that kind the picker lists. */ onCreate: (kind: NewMenuItemKind, label: string, taken: readonly string[]) => Promise; - /** Build a new report for the held place, in the report builder. */ - onNewReport: () => void; language: string; }) { const { t } = useObjectTranslation(); @@ -1133,19 +1048,6 @@ function MenuItemPicker({ )} - {kind === 'report' && ( -
  • - -
  • - )} {loading ? (
  • {t('designMode.menu.loading', { defaultValue: 'Loading…' })}
  • ) : offered.length === 0 ? ( diff --git a/ui/packages/app-shell/src/layout/SidebarAppMenu.tsx b/ui/packages/app-shell/src/layout/SidebarAppMenu.tsx index d33dc388b1e..ab346d49f42 100644 --- a/ui/packages/app-shell/src/layout/SidebarAppMenu.tsx +++ b/ui/packages/app-shell/src/layout/SidebarAppMenu.tsx @@ -74,6 +74,11 @@ export const APP_MENU_SEARCH_FROM = 8; * (objectstack#36363: its changes are saved as this environment's * customization), except where the customization door is walled off for this * caller. Not drawn where no shell holds the mode, nor while the mode is on. + * + * objectstack#36692 — while a dashboard's or a report's own editor is open + * it stays drawn, and choosing it refuses, saying to save or cancel those + * changes first: the mode's `enter` refuses while an editor holds it out + * (`useHoldDesignModeOut`), so the screen never shows two Save/Cancel sets. */ function useEnterDesignMode(apps: Parameters[0], activeAppName: string): (() => void) | null { const entry = useStudioEntryGate(appStudioDesignPath(matchAppBySegment(apps, activeAppName), true)); diff --git a/ui/packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx b/ui/packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx index f2ba86d537c..f8bda51a23e 100644 --- a/ui/packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx @@ -16,7 +16,7 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'; -import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom'; +import { MemoryRouter, useLocation } from 'react-router-dom'; import { SidebarProvider } from '@object-ui/components'; import { NavigationRenderer } from '@object-ui/layout'; import type { NavigationItem } from '@object-ui/types'; @@ -146,7 +146,6 @@ import DesignModeMenu from '../DesignModeMenu'; import { closestCenter, type CollisionDetection } from '@dnd-kit/core'; import { confirmUnsavedLeave } from '../../chrome/unsavedEdits'; import { __resetDefaultLocale } from '../designModeMenuSave'; -import { newReportSlotFor } from '../designModeReportSlot'; const NAVIGATION = [ { id: 'home', type: 'report', reportName: 'pipeline', label: 'Home' }, @@ -855,135 +854,45 @@ async function openReports() { return picker; } -/** A link elsewhere in the app, as the sidebar would follow one. */ -function GoElsewhere() { - const navigate = useNavigate(); - return ( - - ); -} - -function startOnBuilderPath() { - render( - - - - - , - ); - fireEvent.click(screen.getByText('enter')); -} - -const REPORT_BODY = { - label: 'Payment analysis', - type: 'summary', - dataset: 'invoice_metrics', - values: ['invoice_count'], - chart: { type: 'metric', xAxis: '', yAxis: 'invoice_count' }, -}; - -describe('a new report from 「Add menu item」 (objectstack#36364, report half)', () => { - it('「Reports」 lists 「New report…」 first; it holds the place and opens the report builder, writing nothing', async () => { - startOnBuilderPath(); - const picker = await openReports(); - const rows = within(within(picker).getByTestId('design-menu-picker-rows')).getAllByRole('button').map((b) => b.textContent); - // The report the menu already opens (Home → pipeline) is not offered again. - expect(rows).toEqual(['New report…']); - fireEvent.click(within(picker).getByTestId('design-menu-picker-new-report')); - await flush(); - expect(screen.queryByTestId('design-menu-picker')).toBeNull(); - expect(screen.getByTestId('landing')).toHaveTextContent('/apps/crm/reports/new null'); - // The place stays held, saying what it waits for. - expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', ['…']]]); - expect(screen.getByTestId('design-menu-placeholder')).toHaveTextContent('New report…'); - expect(newReportSlotFor('/apps/crm/reports/new')).not.toBeNull(); - expect(newReportSlotFor('/apps/hr/reports/new')).toBeNull(); - expect(written).toEqual([]); - }); - - it('the builder\'s Save: the report, then the menu with its entry in the held place and every other staged edit; the mode is left', async () => { - startOnBuilderPath(); - await act_on('accounts', 'Move up'); // another staged edit, saved with it - const picker = await openReports(); - fireEvent.click(within(picker).getByTestId('design-menu-picker-new-report')); - await flush(); - const slot = newReportSlotFor('/apps/crm/reports/new')!; - let saved: boolean | undefined; - await act(async () => { - saved = await slot.save('payment_analysis', 'Payment analysis', { ...REPORT_BODY, name: 'payment_analysis' }); - }); - await flush(); - - expect(saved).toBe(true); - expect(written.map(([verb, type, name]) => `${verb} ${type} ${name}`)).toEqual([ - 'save report payment_analysis', - 'publish report payment_analysis', - 'save app crm', - 'publish app crm', - ]); - expect(written[0][3]).toEqual({ ...REPORT_BODY, name: 'payment_analysis' }); - expect(written[0][4]).toEqual({ mode: 'draft', ifNoneMatch: '*', packageId: 'com.acme.crm' }); - const navigation = (written[2][3] as { navigation: Array<{ id: string; children?: unknown[] }> }).navigation; - expect(navigation[1].children!.map((c) => (c as { id: string }).id)).toEqual(['accounts', 'leads']); - expect(navigation[2].children).toEqual([ - { id: 'nav_item_1', type: 'report', reportName: 'payment_analysis', label: 'Payment analysis' }, - ]); - expect(screen.queryByTestId('design-mode-bar')).toBeNull(); - expect(newReportSlotFor('/apps/crm/reports/new')).toBeNull(); - }); - - it('a refused menu removes the new report; the mode, the held place and the other staged edits stay', async () => { - server.appSave = new Error('the app was refused'); - startOnBuilderPath(); - await act_on('accounts', 'Move up'); - const picker = await openReports(); - fireEvent.click(within(picker).getByTestId('design-menu-picker-new-report')); - await flush(); - let saved: boolean | undefined; - await act(async () => { - saved = await newReportSlotFor('/apps/crm/reports/new')!.save('payment_analysis', 'Payment analysis', { ...REPORT_BODY, name: 'payment_analysis' }); - }); - await flush(); - - expect(saved).toBe(false); - expect(written.map(([verb, type, name, opt]) => `${verb} ${type} ${name} ${verb === 'reset' ? JSON.stringify(opt) : ''}`.trim())).toEqual([ - 'save report payment_analysis', - 'publish report payment_analysis', - 'save app crm', - 'reset report payment_analysis {"packageId":"com.acme.crm"}', - ]); - expect(toastError).toHaveBeenCalledWith('Some changes were not saved: the app was refused'); - expect(screen.getByTestId('design-mode-bar')).toBeInTheDocument(); - expect(order()).toEqual(['home', ['sales', ['accounts', 'leads']], ['insights', ['…']]]); - expect(newReportSlotFor('/apps/crm/reports/new')).not.toBeNull(); - }); - - it('the builder\'s Close drops the held place and writes nothing; the mode and its other edits stay', async () => { - startOnBuilderPath(); - await act_on('accounts', 'Move up'); - const picker = await openReports(); - fireEvent.click(within(picker).getByTestId('design-menu-picker-new-report')); - await flush(); - act(() => newReportSlotFor('/apps/crm/reports/new')!.cancel()); - await flush(); - expect(order()).toEqual(['home', ['sales', ['accounts', 'leads']], ['insights', []]]); - expect(newReportSlotFor('/apps/crm/reports/new')).toBeNull(); - expect(written).toEqual([]); - expect(screen.getByTestId('design-mode-save')).toBeEnabled(); +/** + * objectstack#36692 — the design mode stops hosting the report builder (the + * maintainer's 「照 Twenty 分开」): 「Reports」 only links reports that exist; + * a new report is made from the reports index, with its own Save. + */ +describe('「Reports」 links existing reports only (objectstack#36692)', () => { + it('lists the reports not in the menu yet, and no 「New report…」 row', async () => { + listed.report = [ + { name: 'pipeline', label: 'Pipeline' }, + { name: 'revenue_by_month', label: 'Revenue by month' }, + ]; + try { + start(); + const picker = await openReports(); + const rows = within(within(picker).getByTestId('design-menu-picker-rows')).getAllByRole('button').map((b) => b.textContent); + // The report the menu already opens (Home → pipeline) is not offered again. + expect(rows).toEqual(['Revenue by month']); + expect(within(picker).queryByTestId('design-menu-picker-new-report')).toBeNull(); + expect(within(picker).queryByText('New report…')).toBeNull(); + } finally { + listed.report = [{ name: 'pipeline', label: 'Pipeline' }]; + } }); - it('leaving the builder another way drops the held place too', async () => { - startOnBuilderPath(); - const picker = await openReports(); - fireEvent.click(within(picker).getByTestId('design-menu-picker-new-report')); - await flush(); - fireEvent.click(screen.getByText('go elsewhere')); - await flush(); - expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', []]]); - expect(newReportSlotFor('/apps/crm/reports/new')).toBeNull(); - expect(written).toEqual([]); + it('picking one links it in the held place, staged with the mode; nothing is written, nothing navigates', async () => { + listed.report = [{ name: 'revenue_by_month', label: 'Revenue by month' }]; + try { + startWithLanding(); + const picker = await openReports(); + fireEvent.click(within(picker).getByRole('button', { name: 'Revenue by month' })); + await flush(); + expect(screen.queryByTestId('design-menu-picker')).toBeNull(); + expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', ['nav_item_1']]]); + expect(written).toEqual([]); + expect(screen.getByTestId('landing')).toHaveTextContent('/apps/crm null'); + expect(screen.getByTestId('design-mode-save')).toBeEnabled(); + } finally { + listed.report = [{ name: 'pipeline', label: 'Pipeline' }]; + } }); }); diff --git a/ui/packages/app-shell/src/layout/__tests__/SidebarAppMenu-36112.test.tsx b/ui/packages/app-shell/src/layout/__tests__/SidebarAppMenu-36112.test.tsx index 161c5b1ac43..a4dd6949056 100644 --- a/ui/packages/app-shell/src/layout/__tests__/SidebarAppMenu-36112.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/SidebarAppMenu-36112.test.tsx @@ -24,14 +24,26 @@ * posture, and reads 「View in Studio」 (zh 「在 Studio 中查看」) for an * installed (read-only) package. Real subject added: the built-in en and * zh-Hans packs, for the words. + * + * objectstack#36692 — while a dashboard's or a report's own editor is open, + * 「Design layout」 stays drawn and choosing it refuses with the prompt to + * save or cancel those changes first; the mode stays off. `sonner`'s toast is + * spied. */ import '@testing-library/jest-dom/vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; +import * as React from 'react'; import type { ReactNode } from 'react'; +const toastError = vi.hoisted(() => vi.fn()); +vi.mock('sonner', async (importOriginal) => ({ + ...(await importOriginal>()), + toast: { error: toastError, success: vi.fn() }, +})); + type MockProps = Record & { children?: ReactNode; onSelect?: () => void; className?: string }; vi.mock('@object-ui/components', async (importOriginal) => ({ @@ -95,7 +107,7 @@ vi.mock('../../runtime-config', async (importOriginal) => ({ import { builtInLocales } from '@object-ui/i18n/locales'; import { SidebarAppMenu, APP_MENU_SEARCH_FROM } from '../SidebarAppMenu'; -import { DesignModeProvider, useDesignModeController } from '../designMode'; +import { DesignModeProvider, useDesignModeController, useHoldDesignModeOut } from '../designMode'; const CRM = { name: 'crm', label: 'CRM', icon: 'flame', _packageId: 'com.acme.crm' }; const SERVICE = { name: 'service', label: 'Service', icon: 'headset' }; @@ -141,6 +153,7 @@ afterEach(() => { admin = false; canAuthor = true; authOverride = {}; + toastError.mockReset(); vi.unstubAllGlobals(); }); @@ -405,3 +418,72 @@ describe('the words: the door and the bar share one name (objectstack#36758)', ( expect(EN.designMode.title).toBe('Design layout'); }); }); + +describe('「Design layout」 refuses while a dashboard or report editor is open (objectstack#36692)', () => { + /** The shell's hold on the mode, and a page whose own editor can be opened and closed. */ + function Shell({ children }: { children: ReactNode }) { + const mode = useDesignModeController({ appName: 'crm', appBasePath: '/apps/crm', enabled: true }); + return ( + + {mode.active ? 'on' : 'off'} + {children} + + ); + } + function EditorPage() { + const [open, setOpen] = React.useState(false); + useHoldDesignModeOut(open); + return ( + + ); + } + + async function mountMenu() { + render( + + + + + + , + ); + await act(() => new Promise((resolve) => setTimeout(resolve, 0))); + await act(() => new Promise((resolve) => setTimeout(resolve, 0))); + } + + const designLayout = () => menu().queryByTestId('sidebar-app-menu-design-layout'); + + beforeEach(() => { + apps = [CRM, SERVICE, SETUP]; + admin = true; + }); + + it('it stays drawn; choosing it says to save or cancel those changes first, and the mode stays off', async () => { + await mountMenu(); + fireEvent.click(screen.getByTestId('editor-toggle')); + expect(designLayout()).not.toBeNull(); + await act(async () => fireEvent.click(designLayout()!)); + expect(screen.getByTestId('mode')).toHaveTextContent('off'); + expect(toastError).toHaveBeenCalledTimes(1); + expect(toastError).toHaveBeenCalledWith('Save or cancel your dashboard or report changes before designing the layout.'); + }); + + it('control: the editor closed, choosing it enters the mode and says nothing', async () => { + await mountMenu(); + fireEvent.click(screen.getByTestId('editor-toggle')); + fireEvent.click(screen.getByTestId('editor-toggle')); + await act(async () => fireEvent.click(designLayout()!)); + expect(screen.getByTestId('mode')).toHaveTextContent('on'); + expect(toastError).not.toHaveBeenCalled(); + }); + + it('the prompt is in every built-in pack, and zh-Hans reads as the design mode is named', () => { + const packs = builtInLocales as unknown as Record; + for (const [locale, pack] of Object.entries(packs)) { + expect(pack.designMode.editorOpen, locale).toBeTruthy(); + } + expect(packs['zh-Hans'].designMode.editorOpen).toContain(packs['zh-Hans'].designMode.title); + }); +}); diff --git a/ui/packages/app-shell/src/layout/__tests__/designMode-36362.test.tsx b/ui/packages/app-shell/src/layout/__tests__/designMode-36362.test.tsx index bb4e415f6ab..93509936f1f 100644 --- a/ui/packages/app-shell/src/layout/__tests__/designMode-36362.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/designMode-36362.test.tsx @@ -43,8 +43,10 @@ import { DesignModeProvider, isPageOfApp, useDesignMode, + useDesignModeActive, useDesignModeChange, useDesignModeController, + useHoldDesignModeOut, } from '../designMode'; import { DesignModeBar } from '../DesignModeBar'; @@ -355,3 +357,101 @@ describe('staging a change and saving at once (objectstack#36364)', () => { expect(commit).not.toHaveBeenCalled(); }); }); + +/** + * objectstack#36692 — a dashboard's or a report's own editor and the mode + * exclude each other through one hold: an open editor holds the mode out, so + * `enter` refuses and says why; the mode on, `useDesignModeActive` is what an + * editor reads to not offer its Edit. + */ +describe('an editor of its own holds the mode out (objectstack#36692)', () => { + /** An editor that holds the mode out while it is open, and says whether it may be offered. */ + function Editor({ name }: { name: string }) { + const [open, setOpen] = React.useState(false); + useHoldDesignModeOut(open); + const offered = !useDesignModeActive(); + return ( +
    + {offered ? 'yes' : 'no'} + +
    + ); + } + + /** The door, with what `enter` answered. */ + function Door() { + const mode = useDesignMode(); + const [answer, setAnswer] = React.useState(''); + return ( + + ); + } + + const PROMPT = 'Save or cancel your dashboard or report changes before designing the layout.'; + + it('while an editor is open, entering refuses with the prompt and the mode stays off', () => { + render(); + fireEvent.click(screen.getByText('toggle dashboard')); + fireEvent.click(screen.getByText(/^door/)); + expect(screen.getByText(/^door/)).toHaveTextContent('door false'); + expect(bar()).toBeNull(); + expect(toastError).toHaveBeenCalledTimes(1); + expect(toastError).toHaveBeenCalledWith(PROMPT); + }); + + it('the hold is let go when the editor closes: entering works again', () => { + render(); + fireEvent.click(screen.getByText('toggle dashboard')); + fireEvent.click(screen.getByText('toggle dashboard')); + fireEvent.click(screen.getByText(/^door/)); + expect(screen.getByText(/^door/)).toHaveTextContent('door true'); + expect(bar()).not.toBeNull(); + expect(toastError).not.toHaveBeenCalled(); + }); + + it('two editors hold it out until both close', () => { + render(); + fireEvent.click(screen.getByText('toggle dashboard')); + fireEvent.click(screen.getByText('toggle report')); + fireEvent.click(screen.getByText('toggle dashboard')); + fireEvent.click(screen.getByText(/^door/)); + expect(bar()).toBeNull(); + fireEvent.click(screen.getByText('toggle report')); + fireEvent.click(screen.getByText(/^door/)); + expect(bar()).not.toBeNull(); + }); + + it('an editor unmounted while open lets go too', () => { + function Page() { + const [shown, setShown] = React.useState(true); + return ( + <> + {shown && } + + + ); + } + render(); + fireEvent.click(screen.getByText('toggle report')); + fireEvent.click(screen.getByText('leave page')); + fireEvent.click(screen.getByText(/^door/)); + expect(bar()).not.toBeNull(); + }); + + it('while the mode is on, an editor reads that it is not offered; outside a shell it always is', () => { + render(); + expect(screen.getByTestId('offered-dashboard')).toHaveTextContent('yes'); + fireEvent.click(screen.getByText(/^door/)); + expect(screen.getByTestId('offered-dashboard')).toHaveTextContent('no'); + fireEvent.click(screen.getByTestId('design-mode-cancel')); + expect(screen.getByTestId('offered-dashboard')).toHaveTextContent('yes'); + cleanup(); + render(); + fireEvent.click(screen.getByText('toggle bare')); + expect(screen.getByTestId('offered-bare')).toHaveTextContent('yes'); + }); +}); diff --git a/ui/packages/app-shell/src/layout/__tests__/designModeMenuCreate-36364.test.ts b/ui/packages/app-shell/src/layout/__tests__/designModeMenuCreate-36364.test.ts index f46950b6c10..df94c44b7e3 100644 --- a/ui/packages/app-shell/src/layout/__tests__/designModeMenuCreate-36364.test.ts +++ b/ui/packages/app-shell/src/layout/__tests__/designModeMenuCreate-36364.test.ts @@ -24,7 +24,9 @@ import { loadHanRomanizer } from '../../views/metadata-admin/romanizeHan'; import { inShownOrder, insertEntry, withEntryIds, type Menu } from '../designModeMenuModel'; import type { AppMenuSaveDoors } from '../designModeMenuSave'; import { + NEW_MENU_ITEM_KINDS, freeItemName, + isNewMenuItemKind, newItemBody, saveAppMenuWithNewItem, uniqueItemName, @@ -223,56 +225,10 @@ describe('the new dashboard’s entry in a menu that carries `order` (objectstac }); }); -describe('a new report from the design mode (objectstack#36364, report half)', () => { - const REPORT_BODY = { - label: '回款分析', - type: 'summary', - dataset: 'invoice_metrics', - values: ['invoice_count'], - chart: { type: 'metric', xAxis: '', yAxis: 'invoice_count' }, - }; - const REPORT: NewMenuItem = { kind: 'report', name: 'hui_kuan_fen_xi', label: '回款分析', body: REPORT_BODY }; - const REPORT_ENTRY = { id: 'nav_item_1', type: 'report', reportName: 'hui_kuan_fen_xi' }; - const reportInput = { - ...input, - navigation: [{ id: 'insights', type: 'group', label: 'Insights', children: [REPORT_ENTRY] }] as Menu, - item: REPORT, - }; - - it('is created as the report builder made it, under the new name', () => { - expect(newItemBody(REPORT)).toEqual({ ...REPORT_BODY, name: 'hui_kuan_fen_xi' }); - }); - - it("is created and published in the menu's package, then the menu, in that order", async () => { - const { d, calls } = doors({ writable: false, version: '1.4.0' }); - await saveAppMenuWithNewItem(reportInput, TEXTS, d); - expect(calls.map(([verb, type]) => `${verb} ${type ?? ''}`.trim())).toEqual([ - 'ensure com.acme.crm', - 'save report', - 'publish report', - 'save app', - 'publish app', - ]); - expect(calls[1]).toEqual([ - 'save', - 'report', - 'hui_kuan_fen_xi', - { ...REPORT_BODY, name: 'hui_kuan_fen_xi' }, - { mode: 'draft', ifNoneMatch: '*', packageId: 'com.acme.crm.custom' }, - ]); - expect(calls[2]).toEqual(['publish', 'report', 'hui_kuan_fen_xi', { packageId: 'com.acme.crm.custom' }]); - }); - - it('a refused menu removes the report it was made for', async () => { - const refused = new Error('the app publish was refused'); - const { d, calls } = doors({ writable: true, refuse: ([verb, type]) => (verb === 'publish' && type === 'app' ? refused : null) }); - await expect(saveAppMenuWithNewItem(reportInput, TEXTS, d)).rejects.toBe(refused); - expect(calls.at(-1)).toEqual(['reset', 'report', 'hui_kuan_fen_xi', { packageId: 'com.acme.crm' }]); - }); - - it('where the menu cannot be saved, no report is created', async () => { - const { d, calls } = doors({ listed: false, writable: true }); - await expect(saveAppMenuWithNewItem(reportInput, TEXTS, d)).rejects.toThrow('not listed'); - expect(calls).toEqual([]); +describe('no report is created from the design mode (objectstack#36692)', () => { + it('a dashboard is the one kind made from a name; a report is made from the reports index', () => { + expect(NEW_MENU_ITEM_KINDS).toEqual(['dashboard']); + expect(isNewMenuItemKind('dashboard')).toBe(true); + expect(isNewMenuItemKind('report')).toBe(false); }); }); diff --git a/ui/packages/app-shell/src/layout/designMode.tsx b/ui/packages/app-shell/src/layout/designMode.tsx index 06051a33303..473cab2c738 100644 --- a/ui/packages/app-shell/src/layout/designMode.tsx +++ b/ui/packages/app-shell/src/layout/designMode.tsx @@ -44,6 +44,21 @@ * app and the app switcher ask first. A link to another page of the same app * does not ask: the mode, and what it holds, go along. * + * ## What the mode excludes + * + * A dashboard's and a report's own editors are not the mode's: each saves on + * its own, with its own 「Save」 in its page header (objectstack#36692, the + * maintainer's ruling to keep them two entries, as Twenty does). So the + * screen never shows two Save/Cancel sets, and no editor outlives a mode + * that has ended, the two exclude each other, both ways, through this one + * hold: + * + * - while the mode is on, those editors are not offered + * ({@link useDesignModeActive}); + * - while one of them is open it holds the mode out + * ({@link useHoldDesignModeOut}), and entering refuses, saying to save or + * cancel those changes first. + * * Who may enter is the header button's gate (`useAppStudioEntry`, a workspace * administrator holding `manage_metadata`), read where the button is drawn * (`ShellPageActions`). The app's package need not be writable: a read-only @@ -79,8 +94,11 @@ export interface DesignModeValue { readonly dirty: boolean; /** A save is under way: the bar's buttons wait, and so should every editor. */ readonly saving: boolean; - /** Turn the mode on for the app on screen. */ - readonly enter: () => void; + /** + * Turn the mode on for the app on screen; `false`, and the reason said, + * while a dashboard or report editor holds the mode out. + */ + readonly enter: () => boolean; /** Drop every staged change and leave the mode. */ readonly cancel: () => void; /** Commit every staged change, then leave the mode; `false` when one failed. */ @@ -93,6 +111,8 @@ interface DesignModeStore extends DesignModeValue { readonly unstage: (key: string) => void; /** Save every staged change with `change` in `key`'s place; `false` when one failed. */ readonly saveWith: (key: string, change: DesignModeChange) => Promise; + /** Hold the mode out while an editor of its own is open; the answer lets go. */ + readonly holdOut: () => () => void; } const DesignModeContext = React.createContext(null); @@ -132,6 +152,8 @@ export function useDesignModeController({ const { t } = useObjectTranslation(); const [held, setHeld] = React.useState(OFF); const [saving, setSaving] = React.useState(false); + /** How many editors of their own hold the mode out. */ + const [heldOut, setHeldOut] = React.useState(0); // Another app: the mode and what it held were the previous app's. if (held.app !== null && held.app !== appName) setHeld(OFF); @@ -146,9 +168,28 @@ export function useDesignModeController({ heldRef.current = held; }); - const enter = React.useCallback(() => { + const enter = React.useCallback((): boolean => { + if (heldOut > 0) { + toast.error( + t('designMode.editorOpen', { + defaultValue: 'Save or cancel your dashboard or report changes before designing the layout.', + }), + ); + return false; + } setHeld((prev) => (prev.app === appName ? prev : { app: appName, changes: NO_CHANGES })); - }, [appName]); + return true; + }, [appName, heldOut, t]); + + const holdOut = React.useCallback(() => { + setHeldOut((n) => n + 1); + let released = false; + return () => { + if (released) return; + released = true; + setHeldOut((n) => n - 1); + }; + }, []); const cancel = React.useCallback(() => { setHeld(OFF); @@ -229,8 +270,8 @@ export function useDesignModeController({ }, [dirty, leaveMessage, appBasePath]); return React.useMemo( - () => ({ active, dirty, saving, enter, cancel, save, changes, stage, unstage, saveWith }), - [active, dirty, saving, enter, cancel, save, changes, stage, unstage, saveWith], + () => ({ active, dirty, saving, enter, cancel, save, changes, stage, unstage, saveWith, holdOut }), + [active, dirty, saving, enter, cancel, save, changes, stage, unstage, saveWith, holdOut], ); } @@ -249,6 +290,16 @@ export function useDesignModeActive(): boolean { return React.useContext(DesignModeContext)?.active ?? false; } +/** + * The other half of the exclusion: a dashboard's or a report's own editor + * holds the mode out while `open`, so entering it refuses and says why + * (objectstack#36692). Outside a shell that holds the mode, nothing. + */ +export function useHoldDesignModeOut(open: boolean): void { + const holdOut = React.useContext(DesignModeContext)?.holdOut; + React.useEffect(() => (open && holdOut ? holdOut() : undefined), [open, holdOut]); +} + /** * The extension point: a surface that changes something under the mode stages * its change under `key` (one key per thing changed, such as the app's menu), diff --git a/ui/packages/app-shell/src/layout/designModeMenuCreate.ts b/ui/packages/app-shell/src/layout/designModeMenuCreate.ts index 5797227f64c..bcd9603041a 100644 --- a/ui/packages/app-shell/src/layout/designModeMenuCreate.ts +++ b/ui/packages/app-shell/src/layout/designModeMenuCreate.ts @@ -15,9 +15,8 @@ * * 1. every check of the menu save is made first, and nothing is written * before they pass; - * 2. the item is created and published in that package (a dashboard empty, - * `saveDashboardInPlace`; a report as the builder made it, - * `saveAndPublishInPackage`), so everyone the menu shows it to finds it, + * 2. the item is created, empty, and published in that package + * (`saveDashboardInPlace`), so everyone the menu shows it to finds it, * never a missing one; * 3. the menu is written and published (`writeAppMenu`), the new entry and * every other staged menu edit with it; @@ -25,12 +24,9 @@ * (the item's delete in its package), and the refusal is said. Should that * removal be refused too, the refusal says the item was left. * - * A dashboard is created from its name alone. A report is not: the spec - * refuses a report without `dataset` and `values`, so 「New report…」 opens - * the report builder instead (the seat's option A), and the report is - * created here, by the same steps, with the body the builder made, once the - * builder saves (`designModeReportSlot`). Cancelling the builder writes - * nothing. + * Only a dashboard is created here, from its name alone. A report is never + * made from the design mode (objectstack#36692): it is made from the reports + * index, with its own Save, and the menu then links it. * * @module */ @@ -38,7 +34,7 @@ import { emitMetadataRefresh } from '../assistant/assistantBus.js'; import { slugify } from '../views/metadata-admin/createDerive.js'; import { loadHanRomanizer, romanizeHan, romanizerPending } from '../views/metadata-admin/romanizeHan.js'; -import { saveAndPublishInPackage, saveDashboardInPlace } from '../views/runtime-metadata-persistence.js'; +import { saveDashboardInPlace } from '../views/runtime-metadata-persistence.js'; import { prepareAppMenuSave, writeAppMenu, @@ -51,20 +47,16 @@ import { export const NEW_MENU_ITEM_KINDS = ['dashboard'] as const; export type NewMenuItemKind = (typeof NEW_MENU_ITEM_KINDS)[number]; -/** Every kind a menu entry can be created with: a report comes from the report builder. */ -export type CreatedMenuItemKind = NewMenuItemKind | 'report'; - export function isNewMenuItemKind(kind: string): kind is NewMenuItemKind { return (NEW_MENU_ITEM_KINDS as readonly string[]).includes(kind); } -/** - * The thing to create: its kind, its machine name and the name the reader - * gave it; a report also carries the body the report builder made. - */ -export type NewMenuItem = - | { readonly kind: NewMenuItemKind; readonly name: string; readonly label: string } - | { readonly kind: 'report'; readonly name: string; readonly label: string; readonly body: Record }; +/** The thing to create: its kind, its machine name and the name the reader gave it. */ +export interface NewMenuItem { + readonly kind: NewMenuItemKind; + readonly name: string; + readonly label: string; +} /** The sentences a refused create is said with, in the viewer's language. */ export interface NewMenuItemTexts extends AppMenuSaveTexts { @@ -121,14 +113,9 @@ export async function freeItemName( throw new Error(`No free ${kind} name was found for "${label}".`); } -/** The body a new `kind` is created with: an empty dashboard, or the report the builder made. */ +/** The body a new `kind` is created with: an empty dashboard. */ export function newItemBody(item: NewMenuItem): Record { - switch (item.kind) { - case 'dashboard': - return { name: item.name, label: item.label, widgets: [] }; - case 'report': - return { ...item.body, name: item.name }; - } + return { name: item.name, label: item.label, widgets: [] }; } /** @@ -143,17 +130,12 @@ export async function saveAppMenuWithNewItem( ): Promise { const { item } = input; const prepared = await prepareAppMenuSave(input, texts, doors); - const outcome = - item.kind === 'dashboard' - ? await saveDashboardInPlace( - item.name, - newItemBody(item), - { kind: 'package', packageId: prepared.target }, - { metadataClient: doors.client }, - ) - : await saveAndPublishInPackage(item.kind, item.name, newItemBody(item), prepared.target, { - metadataClient: doors.client, - }); + const outcome = await saveDashboardInPlace( + item.name, + newItemBody(item), + { kind: 'package', packageId: prepared.target }, + { metadataClient: doors.client }, + ); if (outcome === 'pending-draft') throw new Error(texts.itemPendingDraft); try { await writeAppMenu(prepared, texts, doors); diff --git a/ui/packages/app-shell/src/layout/designModeReportSlot.ts b/ui/packages/app-shell/src/layout/designModeReportSlot.ts deleted file mode 100644 index 3f8bc98e837..00000000000 --- a/ui/packages/app-shell/src/layout/designModeReportSlot.ts +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * The place a new report is being built for (objectstack#36364, report half). - * - * 「New report…」 in the design mode's 「Add menu item」 cannot create the - * report from a name: the spec refuses a report without `dataset` and - * `values`. So the menu holds the place (its dashed row stays), offers this - * slot, and opens the report builder at the app's `reports/new`. The builder - * fills it: its Save hands the report here, and the menu creates it in the - * menu's package and saves its entry in the held place with every other - * staged design change, in one act (`saveAppMenuWithNewItem`). Its Close - * cancels: the held place is dropped and nothing is written. - * - * The menu (in the sidebar) and the builder (in the page) are not in one - * tree that could pass a callback down, so the slot is held here, one at a - * time. The menu withdraws it when it unmounts, which is when the design mode - * ends, so the builder never saves into a mode that is gone: without a slot - * it is the plain new-report page. - * - * @module - */ - -import * as React from 'react'; - -/** What the builder's Save and Close do while a menu place waits for the report. */ -export interface NewReportSlot { - /** - * The builder's address the place waits on (`/reports/new`): - * the page there fills it. The address, not the app's name, because the - * console addresses an app by its route segment, which need not be its name. - */ - readonly path: string; - /** - * Create the report `name` with `body` (its `label` the one the builder - * shows) and save the menu with its entry. `false` when nothing was saved: - * the design mode has said why, and the builder stays open. - */ - readonly save: (name: string, label: string, body: Record) => Promise; - /** Drop the held place; nothing is written. */ - readonly cancel: () => void; -} - -let current: NewReportSlot | null = null; -const listeners = new Set<() => void>(); - -function emit(): void { - for (const listener of listeners) listener(); -} - -/** Offer `slot` to the builder, in place of any slot offered before. */ -export function offerNewReportSlot(slot: NewReportSlot): void { - current = slot; - emit(); -} - -/** Withdraw `slot`, if it is still the one offered. */ -export function withdrawNewReportSlot(slot: NewReportSlot): void { - if (current !== slot) return; - current = null; - emit(); -} - -/** Whether the page at `pathname` is the builder `slot` waits on (a router basename in front counts). */ -function isAt(slot: NewReportSlot, pathname: string | undefined): boolean { - return !!pathname && (pathname === slot.path || pathname.endsWith(slot.path)); -} - -/** The slot the page at `pathname` fills, or `null`. */ -export function newReportSlotFor(pathname: string | undefined): NewReportSlot | null { - return current && isAt(current, pathname) ? current : null; -} - -function subscribe(listener: () => void): () => void { - listeners.add(listener); - return () => listeners.delete(listener); -} - -/** The slot the page at `pathname` fills, read as it changes. */ -export function useNewReportSlot(pathname: string | undefined): NewReportSlot | null { - const slot = React.useSyncExternalStore(subscribe, () => current, () => null); - return slot && isAt(slot, pathname) ? slot : null; -} diff --git a/ui/packages/app-shell/src/views/AppReportIndexView.tsx b/ui/packages/app-shell/src/views/AppReportIndexView.tsx index abb11acd574..4ee901d5951 100644 --- a/ui/packages/app-shell/src/views/AppReportIndexView.tsx +++ b/ui/packages/app-shell/src/views/AppReportIndexView.tsx @@ -30,13 +30,23 @@ * list carries no creator. * * Which sections are collapsed is this visit's state only. + * + * ## 「New report」 (objectstack#36692) + * + * A report is made from its own entry: the header's 「New report」 opens the + * report builder at `reports/new`, whose own Save and Close are the screen's + * one Save/Cancel set. It is gated as the builder is (a workspace admin: a + * report is shared by every member), and not offered while the shell's + * design mode is on, which only links reports that exist. */ import { useId, useState, type ReactNode } from 'react'; import { Link, useParams } from 'react-router-dom'; -import { BarChart3, ChevronDown, ChevronRight, Loader2, Search } from 'lucide-react'; -import { Empty, EmptyTitle, EmptyDescription, Input, cn } from '@object-ui/components'; +import { BarChart3, ChevronDown, ChevronRight, Loader2, Plus, Search } from 'lucide-react'; +import { Button, Empty, EmptyTitle, EmptyDescription, Input, cn } from '@object-ui/components'; import { useDisplayLocale, useObjectTranslation } from '@object-ui/i18n'; +import { useWorkspaceAdminStatus } from '@object-ui/auth'; +import { useDesignModeActive } from '../layout/designMode.js'; import { useServedAppLabel } from '../hooks/useServedAppLabel.js'; import { PageHeader } from '../layout/PageHeader.js'; import { useMetadata } from '../providers/MetadataProvider.js'; @@ -94,6 +104,17 @@ export function AppReportIndexView() { const { apps: launcherApps } = useLauncherApps(metadataApps); const otherApps = useOtherAppsWithReports(launcherApps, app); const { appLabel } = useServedAppLabel(); + const { isAdmin, isResolved } = useWorkspaceAdminStatus(); + const designing = useDesignModeActive(); + const newReport = + isResolved && isAdmin && !designing && appName ? ( + + ) : undefined; if (loading) { return ( @@ -172,7 +193,7 @@ export function AppReportIndexView() {
    {/* objectstack#36111 — the console page header, as every list and dashboard draws it; the shell's top-right group sits at its right. */} - } /> + } actions={newReport} /> {entries.length === 0 ? (
    diff --git a/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx b/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx index 7133377da52..6e91e49edb6 100644 --- a/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx +++ b/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx @@ -22,6 +22,11 @@ * published): that draft is its saver's, and is never published on their * behalf. * + * The edit state and the shell's design mode exclude each other + * (objectstack#36692): while the mode is on the Edit button is not offered, + * and while the edit state is open (or opening) it holds the mode out, so + * entering the mode refuses. The screen shows one Save/Cancel set at a time. + * * Out of scope here: undo, a business user's own copy, a new dashboard, chart * drawing and drill-down. */ @@ -42,6 +47,7 @@ import { type SaveAndPublishOutcome, } from './runtime-metadata-persistence.js'; import { useStudioEntryGate } from '../hooks/useStudioDesignGate.js'; +import { useDesignModeActive, useHoldDesignModeOut } from '../layout/designMode.js'; import { DashboardWidgetInspector } from './metadata-admin/inspectors/DashboardWidgetInspector.js'; import { DashboardDefaultInspector } from './metadata-admin/inspectors/DashboardDefaultInspector.js'; import { AddWidgetPicker } from './metadata-admin/previews/AddWidgetPicker.js'; @@ -192,10 +198,14 @@ export function filtersSectionLabel(locale: SupportedLocale): string | null { * (`useStudioEntryGate`: a workspace admin who may author metadata, on a * package Studio lists, writable or not; never a kernel package). A * read-only package's dashboard is edited through its customization package. + * Not while the shell's design mode is on (objectstack#36692): the two are + * separate entries, never open together. */ export function useDashboardEditOffered(ownerPackageId: string | null | undefined): boolean { const path = ownerPackageId ? `/studio/${encodeURIComponent(ownerPackageId)}` : null; - return useStudioEntryGate(path) !== null; + const gated = useStudioEntryGate(path) !== null; + const designing = useDesignModeActive(); + return gated && !designing; } /** The page header's Edit button. */ @@ -405,6 +415,8 @@ export function useDashboardInPageEdit({ const [saving, setSaving] = React.useState(false); const [selection, setSelection] = React.useState(null); const [revealFilters, setRevealFilters] = React.useState(false); + // Open, or opening: the design mode is held out (objectstack#36692). + useHoldDesignModeOut(session !== null || opening); // Another dashboard on the same route drops the edit state. React.useEffect(() => { diff --git a/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx b/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx index 7138104ef47..20c2cd4624f 100644 --- a/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx +++ b/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx @@ -119,6 +119,8 @@ vi.mock('./metadata-admin/previews/AddWidgetPicker', () => ({ })); import { DashboardView } from './DashboardView'; +import { DesignModeProvider, useDesignModeController } from '../layout/designMode'; +import { DesignModeBar } from '../layout/DesignModeBar'; /** The served dashboard: translated for the session, with its read's decorations. */ const served = { @@ -398,3 +400,80 @@ describe('DashboardView with no cards yet (objectstack#36364)', () => { expect(screen.queryByTestId('dashboard-no-cards')).not.toBeInTheDocument(); }); }); + +/** + * objectstack#36692 — the dashboard's own edit state and the shell's design + * mode are two entries that exclude each other, both ways (the maintainer's + * 「照 Twenty 分开」): no Edit while the mode is on, and the mode's door + * refuses, saying why, while the edit state is open. So the screen never + * shows two Save/Cancel sets, and the bar's Cancel can never end the mode + * under a dashboard left in edit. + * + * Real subjects added: the shell's design-mode controller and its bar. + */ +describe('DashboardView and the design mode exclude each other (objectstack#36692)', () => { + function Shell({ children }: { children: React.ReactNode }) { + const mode = useDesignModeController({ appName: 'crm', appBasePath: '/apps/crm', enabled: true }); + return ( + + {mode.active && } + + {children} + + ); + } + + function mountInShell() { + meta.value = { + apps: [], + objects: [], + dashboards: [served], + reports: [], + pages: [], + loading: false, + error: null, + refresh: async () => {}, + invalidate: () => {}, + ensureType: async () => [], + getItem: vi.fn(async () => null), + getItemsByType: () => [], + getTypeStatus: () => 'ready', + }; + render( + }> + + + + , + ); + } + + it('while the mode is on, Edit is not offered; the mode left, it is again', async () => { + mountInShell(); + await screen.findByTestId('dashboard-edit'); + fireEvent.click(screen.getByTestId('enter-design-mode')); + expect(await screen.findByTestId('design-mode-bar')).toBeInTheDocument(); + expect(screen.queryByTestId('dashboard-edit')).not.toBeInTheDocument(); + fireEvent.click(screen.getByTestId('design-mode-cancel')); + expect(await screen.findByTestId('dashboard-edit')).toBeInTheDocument(); + }); + + it('while the edit state is open, entering the mode is refused with the prompt: one Save/Cancel set, and no bar Cancel to strand the edit', async () => { + mountInShell(); + await openEdit(); + fireEvent.click(screen.getByTestId('enter-design-mode')); + await act(async () => { await new Promise((r) => setTimeout(r, 0)); }); + expect(screen.queryByTestId('design-mode-bar')).not.toBeInTheDocument(); + expect(screen.queryByTestId('design-mode-cancel')).not.toBeInTheDocument(); + expect(toasts.error).toEqual([['Save or cancel your dashboard or report changes before designing the layout.']]); + expect(screen.getByTestId('dashboard-editing-badge')).toBeInTheDocument(); + expect(screen.getByTestId('dashboard-edit-save')).toBeInTheDocument(); + // The edit state closed, the door opens. + fireEvent.click(screen.getByTestId('dashboard-edit-discard')); + fireEvent.click(screen.getByTestId('enter-design-mode')); + expect(await screen.findByTestId('design-mode-bar')).toBeInTheDocument(); + expect(toasts.error).toHaveLength(1); + }); +}); diff --git a/ui/packages/app-shell/src/views/ReportNewPage-36692.test.tsx b/ui/packages/app-shell/src/views/ReportNewPage-36692.test.tsx new file mode 100644 index 00000000000..088e026c6e7 --- /dev/null +++ b/ui/packages/app-shell/src/views/ReportNewPage-36692.test.tsx @@ -0,0 +1,232 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36692 — the new-report builder page is reached from the reports + * index only, and saves on its own: the design mode no longer hands it a menu + * place (the maintainer's 「照 Twenty 分开」). + * + * - Save creates and publishes the report itself and lands on its page; the + * page says nothing about a menu; + * - Close goes back to the app's reports index; + * - while the builder is open it holds the design mode out, so entering the + * mode refuses with the prompt and the screen keeps one Save/Cancel set; + * - reached with the mode already on (the browser's Back), the page draws a + * prompt in place of the builder, and the builder opens once the mode is + * left. + * + * Real subjects: `ReportNewPage` and the shell's design-mode controller. The + * builder is a stub with a Save and a Close (the real one is + * `reportBuilder-36374`'s subject); the metadata client and the save door are + * fakes. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { MemoryRouter, Route, Routes, useLocation, useNavigate } from 'react-router-dom'; + +const DRAFT = vi.hoisted(() => ({ + name: '', + label: 'Payment analysis', + type: 'summary', + dataset: 'invoice_metrics', + values: ['invoice_count'], + chart: { type: 'metric', xAxis: '', yAxis: 'invoice_count' }, +})); + +vi.mock('./ReportBuilderHost.js', () => ({ + ReportBuilderHost: (props: { + onSave: (draft: Record) => Promise; + onClose: () => void; + banner?: React.ReactNode; + }) => ( +
    + {props.banner} + + +
    + ), +})); + +const saveAndPublish = vi.hoisted(() => vi.fn(async () => 'published' as const)); +vi.mock('./runtime-metadata-persistence.js', async (importOriginal) => ({ + ...(await importOriginal>()), + saveAndPublishRuntimeMetadata: saveAndPublish, +})); + +const client = vi.hoisted(() => ({ get: vi.fn(async () => null) })); +vi.mock('./metadata-admin/useMetadata.js', () => ({ useMetadataClient: () => client })); + +const refresh = vi.hoisted(() => vi.fn(async () => {})); +vi.mock('../providers/MetadataProvider.js', () => ({ + useMetadata: () => ({ reports: [], loading: false, refresh }), +})); + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), +})); + +const toastError = vi.hoisted(() => vi.fn()); +vi.mock('sonner', async (importOriginal) => ({ + ...(await importOriginal>()), + toast: { error: toastError, success: vi.fn() }, +})); + +import { ReportNewPage } from './ReportNewPage'; +import { DesignModeProvider, useDesignModeController } from '../layout/designMode'; + +function Where() { + return {useLocation().pathname}; +} + +/** The shell's hold on the design mode, and its door. */ +function Shell({ children }: { children: React.ReactNode }) { + const mode = useDesignModeController({ appName: 'crm', appBasePath: '/apps/crm', enabled: true }); + return ( + + {mode.active ? 'on' : 'off'} + + + {children} + + ); +} + +function mount() { + render( + + + + } /> + + + + + , + ); +} + +/** A link inside the app, standing in for the browser's Back to `reports/new`. */ +function GoNew() { + const navigate = useNavigate(); + return ( + + ); +} + +/** Starts on the reports index, where nothing holds the mode out. */ +function mountOnIndex() { + render( + + + + } /> + } /> + + + + , + ); +} + +const flush = () => + act(async () => { + await new Promise((r) => setTimeout(r, 0)); + }); + +beforeEach(() => { + saveAndPublish.mockClear(); + client.get.mockClear(); + toastError.mockReset(); +}); +afterEach(() => { + cleanup(); +}); + +describe('the new-report page saves on its own (objectstack#36692)', () => { + it('Save creates and publishes the report and lands on its page; nothing speaks of a menu', async () => { + mount(); + expect(screen.queryByTestId('report-new-adds-to-menu')).toBeNull(); + fireEvent.click(screen.getByText('save')); + await flush(); + await flush(); + expect(saveAndPublish).toHaveBeenCalledWith( + 'report', + 'payment_analysis', + { ...DRAFT, name: 'payment_analysis' }, + expect.objectContaining({ metadataClient: client }), + ); + expect(screen.getByTestId('where')).toHaveTextContent('/apps/crm/report/payment_analysis'); + }); + + it('Close goes back to the reports index, writing nothing', async () => { + mount(); + fireEvent.click(screen.getByText('close')); + await flush(); + expect(saveAndPublish).not.toHaveBeenCalled(); + expect(screen.getByTestId('where').textContent).toBe('/apps/crm/reports'); + }); + + it('while the builder is open, entering the design mode refuses with the prompt', async () => { + mount(); + fireEvent.click(screen.getByText('enter design mode')); + await flush(); + expect(screen.getByTestId('mode')).toHaveTextContent('off'); + expect(toastError).toHaveBeenCalledWith('Save or cancel your dashboard or report changes before designing the layout.'); + expect(screen.getByTestId('builder')).toBeInTheDocument(); + }); +}); + +describe('reached with the design mode already on, the page draws no builder (objectstack#36692)', () => { + it('mode on, then reports/new mounts: no builder and no second Save, the prompt instead', async () => { + mountOnIndex(); + fireEvent.click(screen.getByText('enter design mode')); + await flush(); + expect(screen.getByTestId('mode')).toHaveTextContent('on'); + fireEvent.click(screen.getByText('go to new report')); + await flush(); + expect(screen.getByTestId('where').textContent).toBe('/apps/crm/reports/new'); + expect(screen.getByTestId('mode')).toHaveTextContent('on'); + expect(screen.queryByTestId('builder')).toBeNull(); + expect(screen.queryByText('save')).toBeNull(); + expect(screen.getByTestId('report-new-design-mode')).toBeInTheDocument(); + }); + + it('once the mode is left, the builder opens there and holds the mode out', async () => { + mountOnIndex(); + fireEvent.click(screen.getByText('enter design mode')); + await flush(); + fireEvent.click(screen.getByText('go to new report')); + await flush(); + fireEvent.click(screen.getByText('cancel design mode')); + await flush(); + expect(screen.getByTestId('mode')).toHaveTextContent('off'); + expect(screen.getByTestId('builder')).toBeInTheDocument(); + fireEvent.click(screen.getByText('enter design mode')); + await flush(); + expect(screen.getByTestId('mode')).toHaveTextContent('off'); + expect(screen.getByTestId('builder')).toBeInTheDocument(); + }); + + it('control: with the mode off, reports/new draws the builder and no prompt', async () => { + mountOnIndex(); + fireEvent.click(screen.getByText('go to new report')); + await flush(); + expect(screen.getByTestId('mode')).toHaveTextContent('off'); + expect(screen.getByTestId('builder')).toBeInTheDocument(); + expect(screen.getByText('save')).toBeInTheDocument(); + expect(screen.queryByTestId('report-new-design-mode')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/ReportNewPage.menuSlot-36364.test.tsx b/ui/packages/app-shell/src/views/ReportNewPage.menuSlot-36364.test.tsx deleted file mode 100644 index 3bd3ddfb8f7..00000000000 --- a/ui/packages/app-shell/src/views/ReportNewPage.menuSlot-36364.test.tsx +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#36364 (report half) — the new-report builder page filling the - * design mode's held menu place: with a slot offered for the app, Save hands - * the report to it and writes nothing itself, Close cancels the place, and - * the page says that saving adds the report to the menu. With no slot the - * page saves on its own, as before. - * - * Real subjects: `ReportNewPage` and the slot store. The builder is a stub - * with a Save and a Close (the real one is `reportBuilder-36374`'s subject); - * the metadata client, the menu's slot and the save door are fakes. - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; -import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; - -const DRAFT = vi.hoisted(() => ({ - name: '', - label: 'Payment analysis', - type: 'summary', - dataset: 'invoice_metrics', - values: ['invoice_count'], - chart: { type: 'metric', xAxis: '', yAxis: 'invoice_count' }, -})); - -vi.mock('./ReportBuilderHost.js', () => ({ - ReportBuilderHost: (props: { - onSave: (draft: Record) => Promise; - onClose: () => void; - banner?: React.ReactNode; - }) => ( -
    - {props.banner} - - -
    - ), -})); - -const saveAndPublish = vi.hoisted(() => vi.fn(async () => 'published' as const)); -vi.mock('./runtime-metadata-persistence.js', async (importOriginal) => ({ - ...(await importOriginal>()), - saveAndPublishRuntimeMetadata: saveAndPublish, -})); - -const client = vi.hoisted(() => ({ get: vi.fn(async () => null) })); -vi.mock('./metadata-admin/useMetadata.js', () => ({ useMetadataClient: () => client })); - -const refresh = vi.hoisted(() => vi.fn(async () => {})); -vi.mock('../providers/MetadataProvider.js', () => ({ - useMetadata: () => ({ reports: [], loading: false, refresh }), -})); - -vi.mock('@object-ui/auth', async (importOriginal) => ({ - ...(await importOriginal>()), - useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), -})); - -import { ReportNewPage } from './ReportNewPage'; -import { offerNewReportSlot, withdrawNewReportSlot, type NewReportSlot } from '../layout/designModeReportSlot'; - -function Where() { - return {useLocation().pathname}; -} - -function mount(app = 'crm') { - render( - - - } /> - - - - , - ); -} - -const flush = () => - act(async () => { - await new Promise((r) => setTimeout(r, 0)); - }); - -let slot: NewReportSlot; -beforeEach(() => { - saveAndPublish.mockClear(); - client.get.mockClear(); - slot = { path: '/apps/crm/reports/new', save: vi.fn(async () => true), cancel: vi.fn() }; -}); -afterEach(() => { - withdrawNewReportSlot(slot); - cleanup(); -}); - -describe('the new-report page for a held menu place (objectstack#36364)', () => { - it('Save hands the report to the menu, which writes it; the page writes nothing itself', async () => { - offerNewReportSlot(slot); - mount(); - expect(screen.getByTestId('report-new-adds-to-menu')).toBeInTheDocument(); - fireEvent.click(screen.getByText('save')); - await flush(); - await flush(); - expect(slot.save).toHaveBeenCalledWith('payment_analysis', 'Payment analysis', { - ...DRAFT, - name: 'payment_analysis', - }); - expect(saveAndPublish).not.toHaveBeenCalled(); - expect(screen.getByTestId('where')).toHaveTextContent('/apps/crm/report/payment_analysis'); - }); - - it('a save the menu refuses keeps the builder open', async () => { - slot = { ...slot, save: vi.fn(async () => false) }; - offerNewReportSlot(slot); - mount(); - fireEvent.click(screen.getByText('save')); - await flush(); - await flush(); - expect(slot.save).toHaveBeenCalled(); - expect(screen.getByTestId('where')).toHaveTextContent('/apps/crm/reports/new'); - }); - - it('Close cancels the held place and goes back, writing nothing', async () => { - offerNewReportSlot(slot); - mount(); - fireEvent.click(screen.getByText('close')); - await flush(); - expect(slot.cancel).toHaveBeenCalled(); - expect(slot.save).not.toHaveBeenCalled(); - expect(saveAndPublish).not.toHaveBeenCalled(); - expect(screen.getByTestId('where')).toHaveTextContent('/apps/crm/object/crm_lead'); - }); - - it('an app addressed by a route segment other than its name finds its slot by the address', async () => { - // The console addresses the showcase app as `com.example.showcase` while - // its name is `showcase_app`: the place waits on the builder's address. - slot = { ...slot, path: '/apps/com.acme.crm/reports/new' }; - offerNewReportSlot(slot); - mount('com.acme.crm'); - expect(screen.getByTestId('report-new-adds-to-menu')).toBeInTheDocument(); - fireEvent.click(screen.getByText('save')); - await flush(); - await flush(); - expect(slot.save).toHaveBeenCalled(); - expect(saveAndPublish).not.toHaveBeenCalled(); - expect(screen.getByTestId('where')).toHaveTextContent('/apps/com.acme.crm/report/payment_analysis'); - }); - - it("another app's slot is not this page's: it saves on its own", async () => { - slot = { ...slot, path: '/apps/hr/reports/new' }; - offerNewReportSlot(slot); - mount(); - expect(screen.queryByTestId('report-new-adds-to-menu')).toBeNull(); - fireEvent.click(screen.getByText('save')); - await flush(); - await flush(); - expect(slot.save).not.toHaveBeenCalled(); - expect(saveAndPublish).toHaveBeenCalledWith( - 'report', - 'payment_analysis', - { ...DRAFT, name: 'payment_analysis' }, - expect.objectContaining({ metadataClient: client }), - ); - }); -}); diff --git a/ui/packages/app-shell/src/views/ReportNewPage.tsx b/ui/packages/app-shell/src/views/ReportNewPage.tsx index d7a28664b12..f81d258a824 100644 --- a/ui/packages/app-shell/src/views/ReportNewPage.tsx +++ b/ui/packages/app-shell/src/views/ReportNewPage.tsx @@ -15,18 +15,21 @@ * romanised, as the Studio inspector derives it) and made unique against the * reports the console already knows, so a new report never writes over one. * - * Opened from the design mode's 「Add menu item → Reports → New report…」 - * (objectstack#36364), the page fills the menu's held place: a slot is - * offered for this app (`designModeReportSlot`), and Save hands the report to - * it, which creates the report in the menu's package and saves its menu entry - * with every other staged design change. Close cancels the place and writes - * nothing. + * Opened from the reports index's 「New report」 (objectstack#36692): a report + * is made from its own entry, never from the design mode, whose menu only + * links reports that exist. The builder's Save and Close in its own header + * are the screen's one Save/Cancel set: while the builder is open it holds + * the design mode out (`useHoldDesignModeOut`), so entering the mode refuses. + * The address can still be reached with the mode already on (the browser's + * Back from a page of the app the mode was entered on), so while the mode is + * on the page draws a prompt in place of the builder, and the builder opens + * once the mode is saved or cancelled. * * @module */ import * as React from 'react'; -import { useLocation, useNavigate, useParams } from 'react-router-dom'; +import { useNavigate, useParams } from 'react-router-dom'; import { toast } from 'sonner'; import { Loader2 } from 'lucide-react'; import { Empty, EmptyDescription, EmptyTitle } from '@object-ui/components'; @@ -36,7 +39,7 @@ import { formatMetadataError } from '@object-ui/data-objectstack'; import type { DataSource } from '@object-ui/types'; import type { ReportDraft } from '@object-ui/plugin-report'; import { ReportBuilderHost } from './ReportBuilderHost.js'; -import { useNewReportSlot } from '../layout/designModeReportSlot.js'; +import { useDesignModeActive, useHoldDesignModeOut } from '../layout/designMode.js'; import { saveAndPublishRuntimeMetadata } from './runtime-metadata-persistence.js'; import { useMetadataClient } from './metadata-admin/useMetadata.js'; import { useMetadata } from '../providers/MetadataProvider.js'; @@ -91,17 +94,14 @@ export function ReportNewPage({ dataSource }: { dataSource?: DataSource }) { const metadataClient = useMetadataClient(); const { reports, loading, refresh } = useMetadata(); const { isAdmin, isResolved } = useWorkspaceAdminStatus(); - /** The menu place this report fills, when the design mode opened the page for one. */ - const slot = useNewReportSlot(useLocation().pathname); + const designing = useDesignModeActive(); + // The builder is open whenever this page draws it (objectstack#36692). + useHoldDesignModeOut(isResolved && isAdmin && !designing); const backToReports = React.useCallback(() => { - if (slot) { - // Back to the page the design mode was on; the held place is dropped. - slot.cancel(); - navigate(-1); - } else if (appName) navigate(`/apps/${appName}/reports`); + if (appName) navigate(`/apps/${appName}/reports`); else navigate(-1); - }, [navigate, appName, slot]); + }, [navigate, appName]); const handleSave = React.useCallback( async (draft: ReportDraft): Promise => { @@ -124,18 +124,13 @@ export function ReportNewPage({ dataSource }: { dataSource?: DataSource }) { return false; } const body = { ...draft, label, name }; - if (slot) { - // The design mode creates it with its menu entry, and says why when it cannot. - if (!(await slot.save(name, typed || String(label), body))) return false; - } else { - const outcome = await saveAndPublishRuntimeMetadata('report', name, body, { - metadataClient, - dataSource: dataSource as any, - }); - if (outcome === 'pending-draft') { - toast.error(t('form.saveError'), { description: t('report.builder.pendingDraft') }); - return false; - } + const outcome = await saveAndPublishRuntimeMetadata('report', name, body, { + metadataClient, + dataSource: dataSource as any, + }); + if (outcome === 'pending-draft') { + toast.error(t('form.saveError'), { description: t('report.builder.pendingDraft') }); + return false; } } catch (err) { toast.error(t('form.saveError'), { @@ -150,7 +145,7 @@ export function ReportNewPage({ dataSource }: { dataSource?: DataSource }) { }); return true; }, - [metadataClient, reports, language, dataSource, refresh, navigate, appName, t, slot], + [metadataClient, reports, language, dataSource, refresh, navigate, appName, t], ); if (loading || !isResolved) { @@ -172,19 +167,24 @@ export function ReportNewPage({ dataSource }: { dataSource?: DataSource }) { ); } + // Never a second Save/Cancel set under the design mode's bar (objectstack#36692). + if (designing) { + return ( +
    + + {t('report.builder.designModeOnTitle')} + {t('report.builder.designModeOn')} + +
    + ); + } + return ( - {t('report.builder.addsToMenu')} -

    - ) : undefined - } /> ); } diff --git a/ui/packages/app-shell/src/views/ReportView.designModeExclusion-36692.test.tsx b/ui/packages/app-shell/src/views/ReportView.designModeExclusion-36692.test.tsx new file mode 100644 index 00000000000..de5653426c3 --- /dev/null +++ b/ui/packages/app-shell/src/views/ReportView.designModeExclusion-36692.test.tsx @@ -0,0 +1,207 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36692 — the report page's own editors (the report builder, and + * the inspector panel of a pre-dataset report) and the shell's design mode + * are two entries that exclude each other, both ways (the maintainer's + * 「照 Twenty 分开」): + * + * - while the mode is on, the report page's Edit is not offered; once the + * mode is left, it is again; + * - while an editor is open, entering the mode refuses, saying to save or + * cancel those changes first, so no bar and no second Save/Cancel set + * appear; the editor closed, the mode enters. + * + * The harness is `ReportView.saveRefusal-11583.test.tsx`'s (the real + * `ReportView`, `ReportBuilderHost` and `ReportConfigPanel`, the builder and + * the inspector reduced to their buttons), with the shell's real design-mode + * controller and its bar around the page. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, waitFor, fireEvent, act, cleanup } from '@testing-library/react'; +import { toast } from 'sonner'; +import { DesignModeProvider, useDesignModeController } from '../layout/designMode'; +import { DesignModeBar } from '../layout/DesignModeBar'; + +vi.mock('sonner', () => ({ + toast: Object.assign(vi.fn(), { + success: vi.fn(), error: vi.fn(), info: vi.fn(), + warning: vi.fn(), loading: vi.fn(), dismiss: vi.fn(), + }), +})); + +vi.mock('@object-ui/plugin-report', async (importOriginal) => ({ + ...(await importOriginal>()), + ReportRenderer: () => null, + // objectstack#36374 — the report builder, reduced to one edit and its + // buttons; the host around it (`ReportBuilderHost`) is the real one. + ReportBuilder: ({ report, onChange, onSave, onClose, banner }: any) => ( +
    + {banner} + + + +
    + ), +})); +// The builder host's catalog reads, answered empty: the stub draws no picker. +vi.mock('./metadata-admin/previews/useDatasetCatalog', () => ({ + useDatasetCatalog: () => ({ datasets: [], loading: false, error: null }), + useDatasetSemantics: () => ({ dimensions: [], measures: [], loading: false, error: null }), +})); +vi.mock('@object-ui/plugin-dashboard', async (importOriginal) => ({ + ...(await importOriginal>()), + DrillDownDrawer: () => null, +})); +// The panel's spec inspector, reduced to one edit: a new title. +vi.mock('./metadata-admin/inspectors/ReportDefaultInspector', () => ({ + ReportDefaultInspector: ({ onPatch, draft }: any) => ( + + ), +})); +vi.mock('./RuntimeDraftBar', () => ({ RuntimeDraftBar: () => null })); + +const meta = vi.hoisted(() => ({ value: null as any })); +vi.mock('../providers/MetadataProvider', () => ({ useMetadata: () => meta.value })); + +vi.mock('react-router-dom', () => ({ + useParams: () => ({ reportName: 'revenue_by_month' }), + useNavigate: () => vi.fn(), + useLocation: () => ({ pathname: '/reports/revenue_by_month', search: '' }), +})); + +vi.mock('./useOpenRecordList', () => ({ + useRecordListDrillNavigation: () => ({ openRecordList: vi.fn(), canOpenRecordList: () => true }), +})); +vi.mock('./MetadataInspector', () => ({ + MetadataPanel: () => null, + useMetadataInspector: () => ({ showDebug: false }), +})); +const client = vi.hoisted(() => ({ value: null as any })); +vi.mock('./metadata-admin/useMetadata', () => ({ useMetadataClient: () => client.value })); +vi.mock('../providers/AdapterProvider', () => ({ useAdapter: () => ({}) })); +vi.mock('../providers/ExpressionProvider', () => ({ useExpressionContext: () => ({ app: undefined }) })); +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + // The report editor is admin-only. + useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), +})); + +// `ReportView` reaches a dynamic `import('@objectstack/lint')` (through the panel's +// inspector): pay its load at collection, never inside a case's clocked window +// (`check:test-source-alias`). +import '@objectstack/lint'; +import { ReportView } from './ReportView'; + +const PROMPT = 'Save or cancel your dashboard or report changes before designing the layout.'; + +/** A dataset report opens in the builder; a pre-dataset one in the panel. */ +const DATASET_REPORT = { name: 'revenue_by_month', label: 'Revenue by Month', type: 'summary', dataset: 'ds_revenue', values: ['amount'] }; +const LEGACY_REPORT = { name: 'revenue_by_month', label: 'Revenue by Month', dataSource: { object: 'acct' } }; + +function Shell({ children }: { children: React.ReactNode }) { + const mode = useDesignModeController({ appName: 'crm', appBasePath: '/apps/crm', enabled: true }); + return ( + + {mode.active && } + + {children} + + ); +} + +function mountReport(report: Record) { + client.value = { + get: vi.fn(async () => null), + getDraft: vi.fn(async () => null), + layered: vi.fn(async () => ({ code: null, overlay: null, overlayScope: null, effective: report, draft: null })), + save: vi.fn(async () => ({})), + publish: vi.fn(async () => ({})), + }; + meta.value = { + apps: [], + objects: [{ name: 'acct', label: 'Account', fields: { industry: { label: 'Industry', type: 'text' } } }], + dashboards: [], + reports: [report], + pages: [], + loading: false, + error: null, + refresh: vi.fn(async () => {}), + invalidate: () => {}, + ensureType: async () => [], + getItem: vi.fn(async () => null), + getItemsByType: () => [], + getTypeStatus: () => 'ready', + }; + render( + + ({ data: [] })) } as any} /> + , + ); +} + +const flush = () => act(async () => { await new Promise((r) => setTimeout(r, 0)); }); + +beforeEach(() => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); +}); + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + vi.clearAllMocks(); +}); + +describe('the report page and the design mode exclude each other (objectstack#36692)', () => { + it('while the mode is on, Edit is not offered; the mode left, it is again', async () => { + mountReport(DATASET_REPORT); + await screen.findByTestId('report-edit-button'); + fireEvent.click(screen.getByTestId('enter-design-mode')); + expect(await screen.findByTestId('design-mode-bar')).toBeTruthy(); + expect(screen.queryByTestId('report-edit-button')).toBeNull(); + fireEvent.click(screen.getByTestId('design-mode-cancel')); + expect(await screen.findByTestId('report-edit-button')).toBeTruthy(); + }); + + it('while the builder is open, entering the mode is refused with the prompt; the builder closed, it enters', async () => { + mountReport(DATASET_REPORT); + fireEvent.click(await screen.findByTestId('report-edit-button')); + await screen.findByTestId('report-builder'); + fireEvent.click(screen.getByTestId('enter-design-mode')); + await flush(); + expect(screen.queryByTestId('design-mode-bar')).toBeNull(); + expect(toast.error).toHaveBeenCalledTimes(1); + expect(toast.error).toHaveBeenCalledWith(PROMPT); + expect(screen.getByTestId('report-builder')).toBeTruthy(); + + fireEvent.click(screen.getByTestId('report-builder-close')); + await waitFor(() => expect(screen.queryByTestId('report-builder')).toBeNull()); + fireEvent.click(screen.getByTestId('enter-design-mode')); + expect(await screen.findByTestId('design-mode-bar')).toBeTruthy(); + expect(toast.error).toHaveBeenCalledTimes(1); + }); + + it('the inspector panel holds the mode out too', async () => { + mountReport(LEGACY_REPORT); + fireEvent.click(await screen.findByTestId('report-edit-button')); + await screen.findByTestId('report-config-panel'); + fireEvent.click(screen.getByTestId('enter-design-mode')); + await flush(); + expect(screen.queryByTestId('design-mode-bar')).toBeNull(); + expect(toast.error).toHaveBeenCalledWith(PROMPT); + }); +}); diff --git a/ui/packages/app-shell/src/views/ReportView.tsx b/ui/packages/app-shell/src/views/ReportView.tsx index b3be4ed4865..d8bb685d949 100644 --- a/ui/packages/app-shell/src/views/ReportView.tsx +++ b/ui/packages/app-shell/src/views/ReportView.tsx @@ -14,6 +14,7 @@ import { ReportConfigPanel } from './ReportConfigPanel.js'; import { readReportBuilderArrival, withoutReportBuilderArrival } from './reportBuilderArrival.js'; import { Pencil, BarChart3, Loader2 } from 'lucide-react'; import { PageHeader } from '../layout/PageHeader.js'; +import { useDesignModeActive, useHoldDesignModeOut } from '../layout/designMode.js'; import { useObjectTranslation } from '@object-ui/i18n'; import { MetadataPanel, useMetadataInspector } from './MetadataInspector.js'; import { useMetadata } from '../providers/MetadataProvider.js'; @@ -118,6 +119,10 @@ export function ReportView({ dataSource }: { dataSource?: DataSource }) { // Editing a report mutates the SHARED definition, so it is an admin-only // quick-edit affordance (mirrors ObjectView's view-config gate). const { isAdmin } = useWorkspaceAdminStatus(); + // objectstack#36692 — the report's editors and the shell's design mode + // exclude each other: no Edit while the mode is on, and an open (or + // opening) editor holds the mode out (`useHoldDesignModeOut` below). + const designing = useDesignModeActive(); // objectstack#36374 — which editor is open: the report builder (it // replaces the page), or the inspector panel beside the report. const [editor, setEditor] = useState<'builder' | 'panel' | null>(null); @@ -334,6 +339,7 @@ export function ReportView({ dataSource }: { dataSource?: DataSource }) { // buffer is the untranslated source, so a close with no landed save draws // the served report again, which is the display copy for this locale. const [openingEditor, setOpeningEditor] = useState(false); + useHoldDesignModeOut(editor !== null || openingEditor); // The authored buffer as the builder opened on it, and the served text of // the report's name and description paired with the published layer — the // builder's name and description boxes read it, and the page draws the @@ -451,13 +457,13 @@ export function ReportView({ dataSource }: { dataSource?: DataSource }) { const navigate = useNavigate(); const arrivalReadRef = useRef(null); useEffect(() => { - if (!isAdmin || loading || !initialReport || !reportName) return; + if (!isAdmin || designing || loading || !initialReport || !reportName) return; if (!readReportBuilderArrival(location.state, reportName)) return; if (arrivalReadRef.current === location.key) return; arrivalReadRef.current = location.key; navigate(location.pathname + location.search, { replace: true, state: withoutReportBuilderArrival(location.state) }); void handleOpenBuilder(); - }, [isAdmin, loading, initialReport, reportName, location, navigate, handleOpenBuilder]); + }, [isAdmin, designing, loading, initialReport, reportName, location, navigate, handleOpenBuilder]); // Sync reportData when metadata finishes loading or reportName changes useEffect(() => { @@ -684,7 +690,7 @@ export function ReportView({ dataSource }: { dataSource?: DataSource }) { title={heading} subtitle={description || undefined} icon={} - actions={isAdmin ? ( + actions={isAdmin && !designing ? ( + + {children} + + ); +} + +function renderIndex(reports: unknown[] = REPORTS) { + const fetcher = vi.fn(async () => ({ ok: true, status: 200, json: async () => ANSWER }) as unknown as Response); + render( + + + + + + + + } /> + builder

    } /> +
    +
    +
    +
    +
    +
    +
    , + ); +} + +beforeEach(() => { + cleanup(); + localStorage.clear(); + sessionStorage.clear(); + admin.isAdmin = true; + admin.isResolved = true; +}); + +describe('「New report」 on the reports index (objectstack#36692)', () => { + it('a workspace admin sees it in the header; it opens the report builder', async () => { + renderIndex(); + await screen.findByTestId('report-index-entry-crm_win_rate'); + const link = screen.getByTestId('report-index-new'); + expect(link).toHaveTextContent('New report'); + expect(link).toHaveAttribute('href', '/apps/crm/reports/new'); + fireEvent.click(link); + expect(await screen.findByTestId('builder-page')).toBeInTheDocument(); + }); + + it('an index with no report yet offers it too', async () => { + renderIndex([]); + await screen.findByText('No reports'); + expect(screen.getByTestId('report-index-new')).toHaveAttribute('href', '/apps/crm/reports/new'); + }); + + it('gated as the builder is: a member gets none', async () => { + admin.isAdmin = false; + renderIndex(); + await screen.findByTestId('report-index-entry-crm_win_rate'); + expect(screen.queryByTestId('report-index-new')).toBeNull(); + }); + + it('not offered while the design mode is on; offered again once it is left', async () => { + renderIndex(); + await screen.findByTestId('report-index-entry-crm_win_rate'); + fireEvent.click(screen.getByText('enter design mode')); + expect(screen.queryByTestId('report-index-new')).toBeNull(); + fireEvent.click(screen.getByText('leave design mode')); + expect(screen.getByTestId('report-index-new')).toBeInTheDocument(); + }); +}); 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 43bf8a8ed52..cb6f0a6bcc1 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 @@ -480,7 +480,10 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // 134 once objectstack-ai/objectstack#36758 named the design mode by its // door in `empty.appMenuEmptyDescription` („Layout // gestalten“) — one literal span. - expect(okSpans, 'correctly paired spans').toBe(134); + // 133 once objectstack-ai/objectstack#36692 retired the design mode's + // new-report flow, and with it `designMode.menu.newReportLeft` („{{name}}“) + // — one interpolated span fewer. + expect(okSpans, 'correctly paired spans').toBe(133); }); it('keeps the count identity that replaces the card’s count(„) === count(“)', () => { @@ -617,7 +620,9 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // `designMode.pins`, four more matched pairs. // 134 / 134 / 0 after objectstack-ai/objectstack#36758 named the design // mode „Layout gestalten“ in `empty.appMenuEmptyDescription`, one more pair. - expect({ open, close, rdq }).toEqual({ open: 134, close: 134, rdq: 0 }); + // 133 / 133 / 0 after objectstack-ai/objectstack#36692 retired + // `designMode.menu.newReportLeft`, one matched pair fewer. + expect({ open, close, rdq }).toEqual({ open: 133, close: 133, 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 6481e93f10f..275d0601c8d 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -2970,6 +2970,7 @@ const ar = { }, reportIndex: { title: "التقارير", + newReport: 'تقرير جديد', emptyTitle: "لا توجد تقارير", emptyDescription: "لا يحتوي هذا التطبيق على تقارير يمكنك فتحها.", otherApps: "التقارير في تطبيقاتك الأخرى:", @@ -3910,6 +3911,7 @@ const ar = { title: 'تصميم التخطيط', leaveUnsaved: 'هل تريد مغادرة تصميم التخطيط؟ ستفقد التغييرات غير المحفوظة.', saveFailed: 'لم يتم حفظ بعض التغييرات: {{reason}}', + editorOpen: 'احفظ تغييرات لوحة القيادة أو التقرير أو تجاهلها قبل تصميم التخطيط.', menu: { title: 'القائمة', addItem: 'إضافة عنصر قائمة', @@ -3954,13 +3956,11 @@ const ar = { keyboardHint: 'اسحب عنصرًا لنقله، أو ركّز عليه واضغط مفتاح المسافة ثم مفاتيح الأسهم. يفتحه مفتاح Enter.', newDashboard: 'لوحة معلومات جديدة…', newDashboardTitle: 'لوحة معلومات جديدة', - newReport: 'تقرير جديد…', newItemSavesAll: 'يؤدي إنشاؤها إلى حفظ تغييرات التصميم الأخرى أيضًا، ثم تُفتح للتحرير.', create: 'إنشاء', creating: 'جارٍ الإنشاء…', newItemPendingDraft: 'توجد مسودة غير منشورة بهذا الاسم بالفعل. حاول مرة أخرى.', newItemLeft: 'تعذّرت إزالة لوحة المعلومات الجديدة "{{name}}"؛ أزلها في Studio.', - newReportLeft: 'تعذّرت إزالة التقرير الجديد "{{name}}"؛ أزله في Studio.', }, pins: { button: 'أزرار الترويسة', @@ -4470,9 +4470,10 @@ const ar = { settings: "إعدادات التقرير", pendingDraft: "يحتوي هذا التقرير على تغييرات غير منشورة. انشرها أو تجاهلها في الأعلى، ثم احفظ.", nameTaken: "كل المعرّفات المشتقة من هذا الاسم مستخدمة بالفعل. أعطِ التقرير اسمًا آخر ثم احفظ.", - addsToMenu: "الحفظ ينشئ هذا التقرير ويضيفه إلى القائمة في المكان الذي اخترته، مع تغييرات التصميم الأخرى.", adminOnlyTitle: "يمكن لمسؤولي مساحة العمل فقط إنشاء التقارير", adminOnly: "التقرير مشترك مع الجميع في مساحة العمل، لذا ينشئه مسؤول.", + designModeOnTitle: "أنهِ تصميم التخطيط أولاً", + designModeOn: "يُنشأ التقرير خارج وضع التصميم. احفظ التخطيط أو تجاهله، وسيُفتح المحرر هنا.", type: { label: "نوع التقرير", snapshot: "الوضع الحالي", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 3618aa66269..717921b8381 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -2682,6 +2682,7 @@ const de = { }, reportIndex: { title: "Berichte", + newReport: 'Neuer Bericht', emptyTitle: "Keine Berichte", emptyDescription: "Diese App hat keine Berichte, die Sie öffnen können.", otherApps: "Berichte in Ihren anderen Apps:", @@ -3587,6 +3588,7 @@ const de = { title: 'Layout gestalten', leaveUnsaved: 'Layout-Gestaltung verlassen? Nicht gespeicherte Änderungen gehen verloren.', saveFailed: 'Einige Änderungen wurden nicht gespeichert: {{reason}}', + editorOpen: 'Speichern oder verwerfen Sie zuerst Ihre Änderungen am Dashboard oder Bericht, dann gestalten Sie das Layout.', menu: { title: 'Menü', addItem: 'Menüeintrag hinzufügen', @@ -3631,13 +3633,11 @@ const de = { keyboardHint: 'Ziehen Sie einen Eintrag, um ihn zu verschieben, oder fokussieren Sie ihn und drücken Sie die Leertaste, dann die Pfeiltasten. Die Eingabetaste öffnet ihn.', newDashboard: 'Neues Dashboard…', newDashboardTitle: 'Neues Dashboard', - newReport: 'Neuer Bericht…', 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.', }, pins: { button: 'Kopfzeilen-Schaltflächen', @@ -4112,9 +4112,10 @@ 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.", + designModeOnTitle: "Schließen Sie zuerst die Layoutgestaltung ab", + designModeOn: "Berichte werden außerhalb des Designmodus erstellt. Speichern oder verwerfen Sie das Layout, dann öffnet sich der Editor hier.", type: { label: "Berichtstyp", snapshot: "Aktueller Stand", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index c93b6f83dec..d46b32cefce 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -2207,9 +2207,10 @@ 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.', + designModeOnTitle: 'Finish designing the layout first', + designModeOn: 'A report is built outside the design mode. Save or cancel the layout, and the builder opens here.', type: { label: 'Report type', snapshot: 'Current state', @@ -2939,6 +2940,7 @@ const en = { }, reportIndex: { title: 'Reports', + newReport: 'New report', emptyTitle: 'No reports', emptyDescription: 'This app has no reports you can open.', otherApps: 'Reports in your other apps:', @@ -4336,6 +4338,7 @@ const en = { title: 'Design layout', leaveUnsaved: 'Leave Design layout? Your unsaved changes will be lost.', saveFailed: 'Some changes were not saved: {{reason}}', + editorOpen: 'Save or cancel your dashboard or report changes before designing the layout.', menu: { title: 'Menu', addItem: 'Add menu item', @@ -4380,13 +4383,11 @@ const en = { keyboardHint: 'Drag an item to move it, or focus it and press Space, then the arrow keys. Enter opens it.', newDashboard: 'New dashboard…', newDashboardTitle: 'New dashboard', - newReport: 'New report…', 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.', }, pins: { button: 'Header buttons', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index f68c888e982..3982e2ca724 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -2756,6 +2756,7 @@ const es = { }, reportIndex: { title: "Informes", + newReport: 'Nuevo informe', emptyTitle: "No hay informes", emptyDescription: "Esta aplicación no tiene informes que puedas abrir.", otherApps: "Informes en tus otras aplicaciones:", @@ -3669,6 +3670,7 @@ const es = { title: 'Diseñar la disposición', leaveUnsaved: '¿Salir del diseño de la disposición? Se perderán los cambios no guardados.', saveFailed: 'Algunos cambios no se guardaron: {{reason}}', + editorOpen: 'Guarda o descarta los cambios del panel de control o del informe antes de diseñar la disposición.', menu: { title: 'Menú', addItem: 'Añadir elemento de menú', @@ -3713,13 +3715,11 @@ const es = { keyboardHint: 'Arrastra un elemento para moverlo, o enfócalo y pulsa Espacio y luego las flechas. Intro lo abre.', newDashboard: 'Nuevo panel…', newDashboardTitle: 'Nuevo panel', - newReport: 'Nuevo informe…', 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.', }, pins: { button: 'Botones del encabezado', @@ -4202,9 +4202,10 @@ 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.", + designModeOnTitle: "Termina primero de diseñar la disposición", + designModeOn: "Los informes se crean fuera del modo de diseño. Guarda o descarta la disposición y el editor se abrirá aquí.", type: { label: "Tipo de informe", snapshot: "Estado actual", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index c42e540aaa9..a3c3fab397c 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -2752,6 +2752,7 @@ const fr = { }, reportIndex: { title: "Rapports", + newReport: 'Nouveau rapport', emptyTitle: "Aucun rapport", emptyDescription: "Cette application n’a aucun rapport que vous pouvez ouvrir.", otherApps: "Rapports dans vos autres applications :", @@ -3665,6 +3666,7 @@ const fr = { title: 'Concevoir la mise en page', leaveUnsaved: 'Quitter la conception de la mise en page ? Les modifications non enregistrées seront perdues.', saveFailed: 'Certaines modifications n’ont pas été enregistrées : {{reason}}', + editorOpen: 'Enregistrez ou abandonnez vos modifications du tableau de bord ou du rapport avant de concevoir la mise en page.', menu: { title: 'Menu', addItem: 'Ajouter un élément de menu', @@ -3709,13 +3711,11 @@ const fr = { keyboardHint: 'Faites glisser un élément pour le déplacer, ou placez le focus dessus et appuyez sur Espace, puis sur les flèches. Entrée l’ouvre.', newDashboard: 'Nouveau tableau de bord…', newDashboardTitle: 'Nouveau tableau de bord', - newReport: 'Nouveau rapport…', 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.', }, pins: { button: 'Boutons de l’en-tête', @@ -4198,9 +4198,10 @@ 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.", + designModeOnTitle: "Terminez d’abord la conception de la mise en page", + designModeOn: "Un rapport se crée en dehors du mode conception. Enregistrez ou abandonnez la mise en page, puis l’éditeur s’ouvre ici.", type: { label: "Type de rapport", snapshot: "État actuel", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index a1fdd70062b..d707d855fa5 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -2684,6 +2684,7 @@ const ja = { }, reportIndex: { title: "レポート", + newReport: '新規レポート', emptyTitle: "レポートはありません", emptyDescription: "このアプリには開けるレポートがありません。", otherApps: "ほかのアプリのレポート:", @@ -3589,6 +3590,7 @@ const ja = { title: 'レイアウトをデザイン', leaveUnsaved: 'レイアウトのデザインを終了しますか?保存されていない変更は失われます。', saveFailed: '一部の変更が保存されませんでした:{{reason}}', + editorOpen: 'レイアウトをデザインする前に、ダッシュボードまたはレポートの変更を保存するか破棄してください。', menu: { title: 'メニュー', addItem: 'メニュー項目を追加', @@ -3633,13 +3635,11 @@ const ja = { keyboardHint: '項目をドラッグして移動するか、フォーカスしてスペースキーを押し、矢印キーで移動します。Enter キーで開きます。', newDashboard: '新しいダッシュボード…', newDashboardTitle: '新しいダッシュボード', - newReport: '新規レポート…', newItemSavesAll: '作成すると、レイアウトのデザインでの他の変更も保存され、編集用に開きます。', create: '作成', creating: '作成中…', newItemPendingDraft: 'この名前の未公開の下書きがすでにあります。もう一度お試しください。', newItemLeft: '新しいダッシュボード「{{name}}」を削除できませんでした。Studio で削除してください。', - newReportLeft: '新しいレポート「{{name}}」を削除できませんでした。Studio で削除してください。', }, pins: { button: 'ヘッダーのボタン', @@ -4114,9 +4114,10 @@ const ja = { settings: "レポート設定", pendingDraft: "このレポートには未公開の変更があります。上で公開または破棄してから保存してください。", nameTaken: "この名前から作れる識別子はすべて使用済みです。レポートに別の名前を付けてから保存してください。", - addsToMenu: "保存するとこのレポートが作成され、選んだ位置のメニューに追加されます。デザインのほかの変更も一緒に保存されます。", adminOnlyTitle: "レポートを作成できるのはワークスペース管理者のみです", adminOnly: "レポートはワークスペースの全員に共有されるため、管理者が作成します。", + designModeOnTitle: "先にレイアウトのデザインを終えてください", + designModeOn: "レポートはデザインモードの外で作成します。レイアウトを保存するか破棄すると、ここでエディターが開きます。", type: { label: "レポートの種類", snapshot: "現状分析", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 25678dcb68a..aac455456a4 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -2682,6 +2682,7 @@ const ko = { }, reportIndex: { title: "보고서", + newReport: '새 보고서', emptyTitle: "보고서 없음", emptyDescription: "이 앱에는 열 수 있는 보고서가 없습니다.", otherApps: "다른 앱의 보고서:", @@ -3587,6 +3588,7 @@ const ko = { title: '레이아웃 디자인', leaveUnsaved: '레이아웃 디자인을 종료할까요? 저장하지 않은 변경 사항은 사라집니다.', saveFailed: '일부 변경 사항이 저장되지 않았습니다: {{reason}}', + editorOpen: '레이아웃을 디자인하기 전에 대시보드나 보고서의 변경 사항을 저장하거나 취소하세요.', menu: { title: '메뉴', addItem: '메뉴 항목 추가', @@ -3631,13 +3633,11 @@ const ko = { keyboardHint: '항목을 끌어서 옮기거나, 포커스한 뒤 스페이스 키를 누르고 화살표 키로 옮기세요. Enter 키를 누르면 열립니다.', newDashboard: '새 대시보드…', newDashboardTitle: '새 대시보드', - newReport: '새 보고서…', newItemSavesAll: '만들면 레이아웃 디자인의 다른 변경 사항도 함께 저장되고 편집할 수 있게 열립니다.', create: '만들기', creating: '만드는 중…', newItemPendingDraft: '이 이름으로 게시되지 않은 초안이 이미 있습니다. 다시 시도하세요.', newItemLeft: '새 대시보드 "{{name}}"을(를) 삭제하지 못했습니다. Studio에서 삭제하세요.', - newReportLeft: '새 보고서 "{{name}}"을(를) 삭제하지 못했습니다. Studio에서 삭제하세요.', }, pins: { button: '헤더 버튼', @@ -4111,9 +4111,10 @@ const ko = { settings: "보고서 설정", pendingDraft: "이 보고서에 게시되지 않은 변경 사항이 있습니다. 위에서 게시하거나 버린 후 저장하세요.", nameTaken: "이 이름으로 만들 수 있는 식별자가 모두 사용 중입니다. 보고서 이름을 바꾼 뒤 저장하세요.", - addsToMenu: "저장하면 이 보고서가 만들어지고 지정한 메뉴 위치에 추가되며, 다른 디자인 변경도 함께 저장됩니다.", adminOnlyTitle: "워크스페이스 관리자만 보고서를 만들 수 있습니다", adminOnly: "보고서는 워크스페이스의 모든 사람에게 공유되므로 관리자가 만듭니다.", + designModeOnTitle: "먼저 레이아웃 디자인을 마치세요", + designModeOn: "보고서는 디자인 모드 밖에서 만듭니다. 레이아웃을 저장하거나 취소하면 여기에서 편집기가 열립니다.", type: { label: "보고서 유형", snapshot: "현황 분석", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index f200d78d394..a13eb5a01b3 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -2751,6 +2751,7 @@ const pt = { }, reportIndex: { title: "Relatórios", + newReport: 'Novo relatório', emptyTitle: "Nenhum relatório", emptyDescription: "Este aplicativo não tem relatórios que você possa abrir.", otherApps: "Relatórios nos seus outros aplicativos:", @@ -3664,6 +3665,7 @@ const pt = { title: 'Projetar layout', leaveUnsaved: 'Sair do design do layout? As alterações não salvas serão perdidas.', saveFailed: 'Algumas alterações não foram salvas: {{reason}}', + editorOpen: 'Salve ou descarte as alterações do painel ou do relatório antes de projetar o layout.', menu: { title: 'Menu', addItem: 'Adicionar item de menu', @@ -3708,13 +3710,11 @@ const pt = { keyboardHint: 'Arraste um item para movê-lo, ou foque-o e pressione Espaço e depois as setas. Enter o abre.', newDashboard: 'Novo painel…', newDashboardTitle: 'Novo painel', - newReport: 'Novo relatório…', 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.', }, pins: { button: 'Botões do cabeçalho', @@ -4197,9 +4197,10 @@ 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.", + designModeOnTitle: "Termine primeiro de projetar o layout", + designModeOn: "Relatórios são criados fora do modo de design. Salve ou descarte o layout e o editor abrirá aqui.", type: { label: "Tipo de relatório", snapshot: "Situação atual", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 0e654cd1e4b..7ccc0076bb5 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -2832,6 +2832,7 @@ const ru = { }, reportIndex: { title: "Отчёты", + newReport: 'Новый отчёт', emptyTitle: "Нет отчётов", emptyDescription: "В этом приложении нет отчётов, которые вы можете открыть.", otherApps: "Отчёты в других ваших приложениях:", @@ -3756,6 +3757,7 @@ const ru = { title: 'Дизайн макета', leaveUnsaved: 'Выйти из дизайна макета? Несохранённые изменения будут потеряны.', saveFailed: 'Некоторые изменения не сохранены: {{reason}}', + editorOpen: 'Сохраните или отмените изменения дашборда или отчёта, прежде чем менять дизайн макета.', menu: { title: 'Меню', addItem: 'Добавить пункт меню', @@ -3800,13 +3802,11 @@ const ru = { keyboardHint: 'Перетащите пункт, чтобы переместить его, или выделите его и нажмите Пробел, затем клавиши со стрелками. Enter открывает его.', newDashboard: 'Новая панель…', newDashboardTitle: 'Новая панель', - newReport: 'Новый отчёт…', newItemSavesAll: 'При создании сохраняются и другие изменения дизайна макета, затем панель открывается для редактирования.', create: 'Создать', creating: 'Создание…', newItemPendingDraft: 'Под этим именем уже есть неопубликованный черновик. Повторите попытку.', newItemLeft: 'Не удалось удалить новую панель «{{name}}»; удалите её в Studio.', - newReportLeft: 'Не удалось удалить новый отчёт «{{name}}»; удалите его в Studio.', }, pins: { button: 'Кнопки заголовка', @@ -4301,9 +4301,10 @@ const ru = { settings: "Настройки отчёта", pendingDraft: "В этом отчёте есть неопубликованные изменения. Опубликуйте или отмените их выше, затем сохраните.", nameTaken: "Все идентификаторы, полученные из этого имени, уже заняты. Дайте отчёту другое имя и сохраните.", - addsToMenu: "При сохранении этот отчёт будет создан и добавлен в меню на выбранное место вместе с остальными изменениями дизайна.", adminOnlyTitle: "Создавать отчёты могут только администраторы рабочего пространства", adminOnly: "Отчёт виден всем в рабочем пространстве, поэтому его создаёт администратор.", + designModeOnTitle: "Сначала завершите дизайн макета", + designModeOn: "Отчёт создаётся вне режима дизайна. Сохраните или отмените изменения макета, и редактор откроется здесь.", type: { label: "Тип отчёта", snapshot: "Текущее состояние", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index e7d97485756..46ebf142409 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1845,9 +1845,10 @@ const zh = { settings: '报表设置', pendingDraft: '这张报表有一份还没发布的修改。先在上方发布或丢弃它,再保存。', nameTaken: '由这个名称生成的标识都已被占用。请给报表换个名称再保存。', - addsToMenu: '保存后会建好这张报表,放进菜单里你占好的位置,并一并保存设计布局里的其他改动。', adminOnlyTitle: '只有系统管理员能搭建报表', adminOnly: '报表对工作区里所有人生效,所以由系统管理员搭建。', + designModeOnTitle: '请先完成布局设计', + designModeOn: '报表在设计布局之外搭建。保存或取消布局后,搭建器会在这里打开。', type: { label: '报表类型', snapshot: '现状分析', @@ -2484,6 +2485,7 @@ const zh = { }, reportIndex: { title: '报表', + newReport: '新建报表', emptyTitle: '暂无报表', emptyDescription: '此应用没有你可以打开的报表。', otherApps: '你的其它应用中的报表:', @@ -3730,6 +3732,7 @@ const zh = { title: '设计布局', leaveUnsaved: '离开设计布局?未保存的改动将会丢失。', saveFailed: '部分改动没有保存:{{reason}}', + editorOpen: '请先保存或取消仪表盘、报表的修改,再设计布局。', menu: { title: '菜单', addItem: '添加菜单项', @@ -3774,13 +3777,11 @@ const zh = { keyboardHint: '拖动菜单项即可移动;也可以聚焦后按空格键,再用方向键移动。按回车键打开。', newDashboard: '新建仪表盘…', newDashboardTitle: '新建仪表盘', - newReport: '新建报表…', newItemSavesAll: '创建时会一并保存设计布局里的其他改动,然后打开它进行编辑。', create: '创建', creating: '正在创建…', newItemPendingDraft: '这个名称下已有一份未发布的草稿,请再试一次。', newItemLeft: '新建的仪表盘「{{name}}」没能删除,请在 Studio 里删除它。', - newReportLeft: '新建的报表「{{name}}」没能删除,请在 Studio 里删除它。', }, pins: { button: '页头按钮', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 39fba0d8405..34bf7fff963 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1845,9 +1845,10 @@ const zhHant = { settings: '報表設定', pendingDraft: '這張報表有一份還沒釋出的修改。先在上方釋出或丟棄它,再儲存。', nameTaken: '由這個名稱生成的標識都已被佔用。請給報表換個名稱再儲存。', - addsToMenu: '儲存後會建好這張報表,放進選單裡你佔好的位置,並一併儲存設計佈局裡的其他改動。', adminOnlyTitle: '只有系統管理員能搭建報表', adminOnly: '報表對工作區裡所有人生效,所以由系統管理員搭建。', + designModeOnTitle: '請先完成佈局設計', + designModeOn: '報表在設計佈局之外搭建。儲存或取消佈局後,搭建器會在這裡開啟。', type: { label: '報表型別', snapshot: '現狀分析', @@ -2484,6 +2485,7 @@ const zhHant = { }, reportIndex: { title: '報表', + newReport: '新建報表', emptyTitle: '暫無報表', emptyDescription: '此應用沒有你可以開啟的報表。', otherApps: '你的其它應用中的報表:', @@ -3730,6 +3732,7 @@ const zhHant = { title: '設計佈局', leaveUnsaved: '離開設計佈局?未儲存的改動將會丟失。', saveFailed: '部分改動沒有儲存:{{reason}}', + editorOpen: '請先儲存或取消儀表盤、報表的修改,再設計佈局。', menu: { title: '選單', addItem: '新增選單項', @@ -3774,13 +3777,11 @@ const zhHant = { keyboardHint: '拖動選單項即可移動;也可以聚焦後按空格鍵,再用方向鍵移動。按回車鍵開啟。', newDashboard: '新建儀表盤…', newDashboardTitle: '新建儀表盤', - newReport: '新建報表…', newItemSavesAll: '建立時會一併儲存設計佈局裡的其他改動,然後開啟它進行編輯。', create: '建立', creating: '正在建立…', newItemPendingDraft: '這個名稱下已有一份未釋出的草稿,請再試一次。', newItemLeft: '新建的儀表盤「{{name}}」沒能刪除,請在 Studio 裡刪除它。', - newReportLeft: '新建的報表「{{name}}」沒能刪除,請在 Studio 裡刪除它。', }, pins: { button: '頁頭按鈕',