Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/36364-design-mode-new-report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
'@object-ui/app-shell': patch
'@object-ui/i18n': patch
---

feat(console): a new report is built from the design mode's 「Add menu item」 and lands in the place held for it

Clause-②: yes (widening) — new `@object-ui/i18n` keys (`designMode.menu.newReport`, `designMode.menu.newReportLeft`, `report.builder.addsToMenu`) in all 11 locales; no package export, spec or schema change
Metadata-protocol: none

In the design mode's 「Add menu item」 picker, the 「Reports」 list now starts with 「New report…」. A report needs a data source and a measure before it can be published, so it is not created from a name: the place stays held in the menu (「New report…」) and the report builder opens at the app's `reports/new`, saying that saving adds the report to the menu. The builder's Save creates and publishes the report in the package the menu is saved to (the app's package when it is writable, else its customization package), puts its entry in the held place, and saves the menu with every other change staged in the mode; the mode is then left and the report's page opens. When the menu save is refused the report is removed again, the mode and the held place stay, and the builder stays open with the reason. The builder's Close, or leaving the builder any other way, drops the held place and writes nothing. Opened outside the design mode, `reports/new` saves on its own as before.
113 changes: 107 additions & 6 deletions ui/packages/app-shell/src/layout/DesignModeMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@
* place, and the mode saves at once, every other staged change with it
* (`saveAppMenuWithNewItem`); then the mode is left and the new dashboard
* opens for editing (`dashboardEditArrival`). 「Cancel」 writes nothing.
* In 「Reports」 the first row is 「New report…」: a report needs a data source
* and a measure, so the place stays held and the report builder opens; its
* Save creates the report and saves the mode the same way
* (`designModeReportSlot`), and its Close drops the place, writing nothing.
*
* Every edit is staged with the mode (`useDesignModeChange`), under one key
* for the app's menu: the mode's 「Save」 writes it (`saveAppMenu`), its
Expand All @@ -56,7 +60,7 @@
*/

import * as React from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import {
DndContext,
Expand Down Expand Up @@ -160,6 +164,7 @@ import {
} from './designModeMenuSave.js';
import { freeItemName, isNewMenuItemKind, saveAppMenuWithNewItem, type NewMenuItemKind } from './designModeMenuCreate.js';
import { dashboardEditArrival } from './designModeArrival.js';
import { offerNewReportSlot, withdrawNewReportSlot, type NewReportSlot } from './designModeReportSlot.js';

/**
* The group label's icon-mode hiding, as the sidebar's own labels declare it
Expand Down Expand Up @@ -417,6 +422,83 @@ 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<string, unknown>): Promise<boolean> => {
if (!addAt) return false;
// A report entry with no label shows its machine name (only an object,
// view or dashboard entry inherits its target's label), so the entry
// carries the name the reader gave the report.
const entry = { ...entryFor('report', name, newEntryId([...menu, ...(storedMenu ?? [])])), label };
const itemTexts = {
...texts,
itemPendingDraft: t('designMode.menu.newItemPendingDraft', {
defaultValue: 'A draft with this name is already pending. Try again.',
}),
itemLeft: t('designMode.menu.newReportLeft', {
defaultValue: 'The new report "{{name}}" could not be removed again; remove it in Studio.',
name: label,
}),
};
const saved = await saveWith(insertEntry(menu, addAt.parentId, addAt.index, entry), (navigation) =>
saveAppMenuWithNewItem(
{ appName, packageId, served, navigation, item: { kind: 'report', name, label, body } },
itemTexts,
consoleAppMenuDoors(client as never),
),
);
if (!saved) return false;
setAddAt(null);
setBuildingReport(false);
return true;
};
// The builder's address the held place waits on.
const newReportPath = `${basePath}/reports/new`;
const saveNewReportRef = React.useRef(saveNewReport);
React.useLayoutEffect(() => {
saveNewReportRef.current = saveNewReport;
});
React.useEffect(() => {
if (!buildingReport) return;
const slot: NewReportSlot = {
path: newReportPath,
save: (name, label, body) => saveNewReportRef.current(name, label, body),
cancel: () => {
setBuildingReport(false);
setAddAt(null);
},
};
offerNewReportSlot(slot);
// Withdrawn when the place is no longer held, and when the menu unmounts
// (the design mode ended): the builder then saves on its own, off the menu.
return () => withdrawNewReportSlot(slot);
}, [buildingReport, newReportPath]);
// Leaving the builder another way than its Save or Close (a menu link, the
// browser's Back) drops the place too, so no held row waits for a builder
// that is gone. Read once the builder has been reached.
const { pathname } = useLocation();
const [reachedBuilder, setReachedBuilder] = React.useState(false);
const onBuilder = pathname === newReportPath || pathname.endsWith(newReportPath);
if (buildingReport && onBuilder && !reachedBuilder) setReachedBuilder(true);
if (!buildingReport && reachedBuilder) setReachedBuilder(false);
if (buildingReport && reachedBuilder && !onBuilder) {
setBuildingReport(false);
setReachedBuilder(false);
setAddAt(null);
}
const startNewReport = () => {
if (!addAt) return;
setBuildingReport(true);
navigate(newReportPath);
};

const renderLeaf = (entry: MenuEntry, depth: number) => {
const id = String(entry.id);
const place = placeOf(menu, id);
Expand Down Expand Up @@ -456,7 +538,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(<Placeholder key="placeholder" depth={depth} />);
if (addAt && addAt.parentId === parentId && addAt.index === index) rows.push(<Placeholder key="placeholder" depth={depth} buildingReport={buildingReport} />);
if (isGroup(entry)) {
const gid = String(entry.id);
rows.push(
Expand All @@ -477,7 +559,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(<Placeholder key="placeholder" depth={depth} />);
if (addAt && addAt.parentId === parentId && addAt.index >= entries.length) rows.push(<Placeholder key="placeholder" depth={depth} buildingReport={buildingReport} />);
rows.push(
<AddRow
key="add"
Expand Down Expand Up @@ -516,13 +598,14 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso
</SortableContext>
</DndContext>
</SidebarGroupContent>
{addAt && (
{addAt && !buildingReport && (
<MenuItemPicker
packageId={packageId}
inMenu={menuTargets(menu)}
onClose={() => setAddAt(null)}
onPick={(kind, name, link) => pick(entryFor(kind, name, newEntryId([...menu, ...(storedMenu ?? [])]), link))}
onCreate={createItem}
onNewReport={startNewReport}
language={language}
/>
)}
Expand Down Expand Up @@ -612,12 +695,14 @@ function MenuLeaf({
);
}

function Placeholder({ depth }: { depth: number }) {
function Placeholder({ depth, buildingReport }: { depth: number; buildingReport?: boolean }) {
const { t } = useObjectTranslation();
return (
<li className="list-none" style={indent(depth)} data-testid="design-menu-placeholder">
<div className="mx-0.5 flex h-8 items-center rounded-md border border-dashed border-sidebar-border px-2 text-sm text-sidebar-foreground/60">
{t('designMode.menu.placeholder', { defaultValue: 'Choose a menu item…' })}
{buildingReport
? t('designMode.menu.newReport', { defaultValue: 'New report…' })
: t('designMode.menu.placeholder', { defaultValue: 'Choose a menu item…' })}
</div>
</li>
);
Expand Down Expand Up @@ -811,6 +896,7 @@ function MenuItemPicker({
onClose,
onPick,
onCreate,
onNewReport,
language,
}: {
packageId: string;
Expand All @@ -819,6 +905,8 @@ function MenuItemPicker({
onPick: (kind: MenuTargetKind, name: string, link?: { label: string; url: string }) => void;
/** Create a new `kind` named `label`; `taken` is every name of that kind the picker lists. */
onCreate: (kind: NewMenuItemKind, label: string, taken: readonly string[]) => Promise<boolean>;
/** Build a new report for the held place, in the report builder. */
onNewReport: () => void;
language: string;
}) {
const { t } = useObjectTranslation();
Expand Down Expand Up @@ -943,6 +1031,19 @@ function MenuItemPicker({
</button>
</li>
)}
{kind === 'report' && (
<li>
<button
type="button"
onClick={onNewReport}
className="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm font-medium text-primary hover:bg-accent"
data-testid="design-menu-picker-new-report"
>
<Plus className="h-4 w-4 shrink-0" aria-hidden="true" />
<span className="flex-1 truncate">{t('designMode.menu.newReport', { defaultValue: 'New report…' })}</span>
</button>
</li>
)}
{loading ? (
<li className="px-2 py-2 text-sm text-muted-foreground">{t('designMode.menu.loading', { defaultValue: 'Loading…' })}</li>
) : offered.length === 0 ? (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import '@testing-library/jest-dom/vitest';
import * as React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react';
import { MemoryRouter, useLocation } from 'react-router-dom';
import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom';
import { SidebarProvider } from '@object-ui/components';
import { NavigationRenderer } from '@object-ui/layout';
import type { NavigationItem } from '@object-ui/types';
Expand Down Expand Up @@ -117,6 +117,7 @@ import { DesignModeBar } from '../DesignModeBar';
import DesignModeMenu from '../DesignModeMenu';
import { confirmUnsavedLeave } from '../../chrome/unsavedEdits';
import { __resetDefaultLocale } from '../designModeMenuSave';
import { newReportSlotFor } from '../designModeReportSlot';

const NAVIGATION = [
{ id: 'home', type: 'report', reportName: 'pipeline', label: 'Home' },
Expand Down Expand Up @@ -777,6 +778,147 @@ describe('a new dashboard from 「Add menu item」 (objectstack#36364)', () => {
});
});

/** 「Add menu item」 under Insights, then 「Reports」. */
async function openReports() {
fireEvent.click(screen.getByTestId('design-menu-add-insights'));
const picker = await screen.findByTestId('design-menu-picker');
fireEvent.click(within(picker).getByRole('button', { name: 'Reports' }));
await flush();
return picker;
}

/** A link elsewhere in the app, as the sidebar would follow one. */
function GoElsewhere() {
const navigate = useNavigate();
return (
<button type="button" onClick={() => navigate('/apps/crm/object/crm_lead')}>
go elsewhere
</button>
);
}

function startOnBuilderPath() {
render(
<MemoryRouter initialEntries={['/apps/crm']}>
<Harness />
<Landing />
<GoElsewhere />
</MemoryRouter>,
);
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();
});

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([]);
});
});

// ── objectstack#36591 ─────────────────────────────────────────────────────────

/**
Expand Down
Loading
Loading