Skip to content
Merged
12 changes: 12 additions & 0 deletions .changeset/36591-design-menu-order.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@object-ui/app-shell': patch
---

fix(app-shell): a menu reordered in design mode is saved in the order the sidebar draws it, in apps whose menu entries carry `order`

Clause-②: no
Metadata-protocol: none

The sidebar sorts each level of an app's `navigation` by `order` (lower first, an absent `order` as 0, ties in array order), but design mode listed and saved the array as authored. In an app whose entries carry `order` — AI-built apps write one on every entry — 「Move up」, 「Move down」, 「Move to group」, a drag and an added item were saved and published without error and changed nothing on screen; re-entering design mode then listed the menu in an order the sidebar did not show.

Design mode now lists each level in the sidebar's order, and the save writes that order back: every level in which any entry carries `order` has each of its entries, groups and group children alike, renumbered `0`, `1`, … in the order design mode showed. A level in which no entry carries `order` is saved by array order as before and gains no `order` key, so apps authored by array order (HotCRM's) are unchanged. Saving a menu with `order` therefore rewrites its `order` values to consecutive numbers; the order they draw is the one design mode showed.
9 changes: 8 additions & 1 deletion ui/packages/app-shell/src/layout/DesignModeMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@
* change. Groups are not added, removed or renamed here, and nothing about
* who sees an entry is changed: both stay in Studio.
*
* Each level is drawn in the order the sidebar draws it, `order` first
* (`inShownOrder`, objectstack#36591), so the menu reads the same in and out
* of the mode, and a move is saved as `order` where the level carries it.
*
* Loaded only while the mode is on (`UnifiedSidebar` lazy-loads it): it
* brings the metadata client and the package doors the menu's write needs.
*
Expand Down Expand Up @@ -121,6 +125,7 @@ import {
entryFor,
entryOf,
groupsOf,
inShownOrder,
insertEntry,
isGroup,
menuTargets,
Expand Down Expand Up @@ -186,7 +191,9 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso
const client = useMetadataClient();
const packageId = typeof app._packageId === 'string' ? app._packageId : '';
const served = React.useMemo(
() => withEntryIds(Array.isArray(app.navigation) ? (app.navigation as Menu) : []),
// Each level in the sidebar's order (objectstack#36591): the edits read a
// level's array order as its shown order, and the save writes it back.
() => withEntryIds(inShownOrder(Array.isArray(app.navigation) ? (app.navigation as Menu) : [])),
[app.navigation],
);
const menu = change.value ?? served;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ 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 { SidebarProvider } from '@object-ui/components';
import { NavigationRenderer } from '@object-ui/layout';
import type { NavigationItem } from '@object-ui/types';

const session = vi.hoisted(() => ({ language: 'en', defaultLocale: 'en' }));
vi.mock('@object-ui/i18n', async (importOriginal) => ({
Expand Down Expand Up @@ -65,6 +67,8 @@ const listed = vi.hoisted(() => ({
{ name: 'crm_lead_record', label: 'Lead record', type: 'record' },
],
}) as Record<string, Array<Record<string, unknown>>>);
/** The app's menu as served (`null`: `NAVIGATION`). */
const servedNav = vi.hoisted(() => ({ current: null as unknown[] | null }));
/** The app's menu as stored (`null`: as served). */
const storedNav = vi.hoisted(() => ({ current: null as unknown[] | null, failReads: 0 }));
const client = vi.hoisted(() => ({
Expand All @@ -74,7 +78,7 @@ const client = vi.hoisted(() => ({
storedNav.failReads -= 1;
throw new Error('layered read failed');
}
const code = { name: 'crm', label: 'CRM', navigation: storedNav.current ?? NAVIGATION };
const code = { name: 'crm', label: 'CRM', navigation: storedNav.current ?? servedNav.current ?? NAVIGATION };
return { code, effective: code };
},
save: async (...args: unknown[]) => {
Expand Down Expand Up @@ -134,7 +138,7 @@ function Harness() {
<SidebarProvider>
{mode.active && (
<DesignModeMenu
app={{ name: 'crm', navigation: NAVIGATION, _packageId: 'com.acme.crm' }}
app={{ name: 'crm', navigation: servedNav.current ?? NAVIGATION, _packageId: 'com.acme.crm' }}
basePath="/apps/crm"
resolveTargetLabel={(target) => (target.kind === 'object' ? OBJECT_LABELS[target.objectName] : undefined)}
/>
Expand Down Expand Up @@ -202,6 +206,7 @@ beforeEach(() => {
session.defaultLocale = 'en';
storedNav.current = null;
storedNav.failReads = 0;
servedNav.current = null;
__resetDefaultLocale();
vi.stubGlobal(
'fetch',
Expand Down Expand Up @@ -648,3 +653,164 @@ describe('the menu under the design mode (objectstack#36363)', () => {
expect(switchedTo).toEqual(['hr']);
});
});

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

/**
* objectstack#36591 — the design mode's menu reads, and saves, in the order
* the sidebar draws it.
*
* The sidebar sorts each level by `order` (`byNavOrder`, internal to
* `@object-ui/layout`); the editor read and saved array order, so a move in an
* app whose entries carry `order` (an AI-built app's do) was saved and changed
* nothing on screen. The sidebar here is the real one (`NavigationRenderer`),
* drawn over what the save wrote, so these pins state no sort of their own.
*/
describe('the design-mode menu in the sidebar order (objectstack#36591)', () => {
const object = (id: string, objectName: string, label: string, order?: number) => ({
id,
type: 'object',
objectName,
label,
...(order === undefined ? {} : { order }),
});

/** Authored out of `order`: the sidebar reads Customers, Contacts, Opportunities, Reports (Follow-ups, Pipeline). */
const ORDERED = () => [
object('opps', 'crm_opportunity', 'Opportunities', 2),
object('customers', 'crm_customer', 'Customers', 0),
{
id: 'reports',
type: 'group',
label: 'Reports',
order: 3,
expanded: true,
children: [
{ id: 'pipeline', type: 'report', reportName: 'pipeline', label: 'Pipeline', order: 1 },
object('followups', 'crm_follow_up', 'Follow-ups', 0),
],
},
object('contacts', 'crm_contact', 'Contacts', 1),
];

const LABELS = ['Customers', 'Contacts', 'Opportunities', 'Reports', 'Follow-ups', 'Pipeline', 'Cases', 'Leads', 'Accounts', 'Home', 'Sales', 'Insights'];

/** The labels `el` shows, in the order it shows them; each must show once. */
function labelsIn(el: Element): string[] {
const text = el.textContent ?? '';
const shown = LABELS.filter((l) => text.includes(l));
for (const l of shown) expect(text.indexOf(l)).toBe(text.lastIndexOf(l));
return shown.sort((a, b) => text.indexOf(a) - text.indexOf(b));
}

/** The running app's sidebar over `nav`. */
function sidebarOrder(nav: unknown): string[] {
const { container, unmount } = render(
<MemoryRouter initialEntries={['/apps/crm']}>
<SidebarProvider defaultOpen>
<NavigationRenderer
items={nav as NavigationItem[]}
basePath="/apps/crm"
resolveTargetLabel={(target) => (target.kind === 'object' ? OBJECT_LABELS[target.objectName] : undefined)}
/>
</SidebarProvider>
</MemoryRouter>,
);
const shown = labelsIn(container);
unmount();
return shown;
}

/** The design mode's menu, as it reads. */
const editorOrder = () => labelsIn(screen.getByTestId('design-mode-menu'));

async function save(): Promise<Array<Record<string, unknown>>> {
fireEvent.click(screen.getByTestId('design-mode-save'));
await flush();
await flush();
expect(written.map(([verb]) => verb)).toEqual(['save', 'publish']);
return (written[0][3] as { navigation: Array<Record<string, unknown>> }).navigation;
}

/** Every `order` key of `nav`, at every depth. */
const orderKeys = (nav: unknown): unknown[] =>
(nav as Array<Record<string, unknown>>).flatMap((e) => [
...('order' in e ? [e.order] : []),
...(Array.isArray(e.children) ? orderKeys(e.children) : []),
]);

it('an app whose entries carry `order` reads in the design mode as in the sidebar', () => {
servedNav.current = ORDERED();
start();
expect(editorOrder()).toEqual(['Customers', 'Contacts', 'Opportunities', 'Reports', 'Follow-ups', 'Pipeline']);
cleanup();
expect(sidebarOrder(ORDERED())).toEqual(['Customers', 'Contacts', 'Opportunities', 'Reports', 'Follow-ups', 'Pipeline']);
});

it('「Move up」 on Contacts, saved: the sidebar reads Contacts, Customers, …, and the design mode reads the same again', async () => {
servedNav.current = ORDERED();
start();
await act_on('contacts', 'Move up');
const shown = editorOrder();
expect(shown).toEqual(['Contacts', 'Customers', 'Opportunities', 'Reports', 'Follow-ups', 'Pipeline']);
const saved = await save();
cleanup();
expect(sidebarOrder(saved)).toEqual(shown);
// The saved app, served again, opens the design mode in that order.
servedNav.current = saved;
storedNav.current = saved;
start();
expect(editorOrder()).toEqual(shown);
});

it('「Add an item after」 and 「Move to group」, saved: the sidebar puts both where the design mode showed them', async () => {
servedNav.current = ORDERED();
start();
await flush();
await act_on('contacts', 'Add an item after');
const picker = await screen.findByTestId('design-menu-picker');
fireEvent.click(within(picker).getByRole('button', { name: 'Objects' }));
await flush();
fireEvent.click(within(picker).getByRole('button', { name: 'Cases' }));
await flush();
const trigger = within(entry('customers')).getByTestId('design-menu-actions');
fireEvent.pointerDown(trigger, { button: 0, pointerType: 'mouse' });
await flush();
fireEvent.click(await screen.findByRole('menuitem', { name: 'Move to group' }));
await flush();
fireEvent.click(await screen.findByRole('menuitem', { name: 'Reports' }));
await flush();
const shown = editorOrder();
expect(shown).toEqual(['Contacts', 'Cases', 'Opportunities', 'Reports', 'Follow-ups', 'Pipeline', 'Customers']);
const saved = await save();
cleanup();
expect(sidebarOrder(saved)).toEqual(shown);
});

it('CONTROL: an app whose entries carry no `order` saves a move by array order, and gains no `order` key', async () => {
start();
await act_on('accounts', 'Move up');
const shown = editorOrder();
expect(shown).toEqual(['Home', 'Sales', 'Accounts', 'Leads', 'Insights']);
const saved = await save();
expect(orderKeys(saved)).toEqual([]);
cleanup();
// The sidebar draws no empty group: Insights is the editor's alone.
expect(sidebarOrder(saved)).toEqual(shown.filter((label) => label !== 'Insights'));
});

it('a level where some entries carry `order` and some do not: one save, and the sidebar reads as the design mode', async () => {
// The sidebar reads an absent `order` as 0: Customers, Contacts, Opportunities.
const MIXED = () => [object('opps', 'crm_opportunity', 'Opportunities', 1), object('customers', 'crm_customer', 'Customers'), object('contacts', 'crm_contact', 'Contacts')];
servedNav.current = MIXED();
start();
expect(editorOrder()).toEqual(['Customers', 'Contacts', 'Opportunities']);
await act_on('opps', 'Move up');
const shown = editorOrder();
expect(shown).toEqual(['Customers', 'Opportunities', 'Contacts']);
const saved = await save();
expect(orderKeys(saved)).toEqual([0, 1, 2]);
cleanup();
expect(sidebarOrder(saved)).toEqual(shown);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
canMoveBy,
entryFor,
groupsOf,
inShownOrder,
insertEntry,
menuTargets,
moveBy,
Expand All @@ -23,6 +24,7 @@ import {
targetKeyFor,
targetKeyOf,
withEntryIds,
withOrderRewritten,
type Menu,
} from '../designModeMenuModel';

Expand Down Expand Up @@ -223,3 +225,39 @@ describe('the edits replayed on the stored menu (objectstack#36363, review 70812
expect(storedEntriesById(served, stored).get('nav_item_1')).toBe(lead);
});
});

describe('a level in the sidebar order, and that order written back as `order` (objectstack#36591)', () => {
const at = (id: string, order?: number, children?: Menu) => ({
id,
type: children ? 'group' : 'page',
...(children ? { children } : { pageName: id }),
...(order === undefined ? {} : { order }),
});
const orders = (menu: Menu): unknown[] =>
menu.map((e) => (Array.isArray(e.children) ? [e.order, orders(e.children as Menu)] : e.order));

it('each level is put in `order`, an absent one as 0, ties as authored; the group with its children', () => {
const menu: Menu = Object.freeze([at('c', 2), at('a'), at('g', 1, [at('y', 1), at('x', 0)]), at('b')]);
expect(ids(inShownOrder(menu))).toEqual(['a', 'b', ['g', ['x', 'y']], 'c']);
});

it('a menu with no `order` is the menu itself', () => {
expect(inShownOrder(MENU)).toBe(MENU);
});

it('a level carrying `order` is numbered 0… in array order, every entry of it, those without one included', () => {
const menu: Menu = Object.freeze([at('b', 5), at('a'), at('g', 9, [at('y', 1), at('x')])]);
const next = withOrderRewritten(menu);
expect(ids(next)).toEqual(['b', 'a', ['g', ['y', 'x']]]);
expect(orders(next)).toEqual([0, 1, [2, [0, 1]]]);
expect(ids(inShownOrder(next))).toEqual(ids(next));
});

it('a level carrying no `order` gains none, though its group, or a group in it, does', () => {
const menu: Menu = Object.freeze([at('a'), at('g', undefined, [at('y', 3), at('x')]), at('h', undefined, [at('z')])]);
const next = withOrderRewritten(menu);
expect(orders(next)).toEqual([undefined, [undefined, [0, 1]], [undefined, [undefined]]]);
expect(next[2]).toBe(menu[2]);
expect(withOrderRewritten(MENU)).toBe(MENU);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ vi.mock('../../assistant/assistantBus', async (importOriginal) => ({
emitMetadataRefresh,
}));

import { withEntryIds, moveBy, insertEntry, patchEntry, type Menu } from '../designModeMenuModel';
import { withEntryIds, moveBy, inShownOrder, insertEntry, patchEntry, type Menu } from '../designModeMenuModel';
import { isSameLanguage, saveAppMenu, type AppMenuSaveDoors } from '../designModeMenuSave';

const TEXTS = { notListed: 'not listed', pendingDraft: 'pending draft', noVersion: 'no version', notWritable: 'not writable' };
Expand Down Expand Up @@ -219,6 +219,58 @@ describe('the save writes the stored menu with the edits, never the served one (
});
});

describe('the save writes the order the editor showed as `order` (objectstack#36591)', () => {
const object = (id: string, label: string, order?: number, extra: Record<string, unknown> = {}) => ({
id,
type: 'object',
objectName: `crm_${id}`,
label,
...(order === undefined ? {} : { order }),
...extra,
});
/** As stored, authored out of `order`; the sidebar reads Customers, Contacts, Opportunities. */
const STORED: Menu = [object('opportunity', 'Opportunities', 2), object('contact', 'Contacts', 1), object('customer', 'Customers', 0)];
/** The editor's seed, as `DesignModeMenu` makes it. */
const seed = (nav: Menu) => withEntryIds(inShownOrder(nav));
const written = async (stored: Menu, served: Menu, edit: (m: Menu) => Menu) => {
const { d, calls } = doors({ writable: true, stored });
await saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served, navigation: edit(served) }, TEXTS, d);
return savedNav(calls).map((e) => [e.id, e.order]);
};

it('an entry added at the end is numbered after the rest, and each entry gets its shown place', async () => {
const served = seed(STORED);
const nav = await written(STORED, served, (m) => insertEntry(m, null, 3, { id: 'nav_item_1', type: 'object', objectName: 'crm_case' }));
expect(nav).toEqual([['customer', 0], ['contact', 1], ['opportunity', 2], ['nav_item_1', 3]]);
});

it('a move up is written as `order`; a rename beside it writes its label, and `order` is never read as an edit', async () => {
const served = seed(STORED);
const { d, calls } = doors({ writable: true, stored: STORED });
const navigation = patchEntry(moveBy(served, 'contact', -1), 'opportunity', { label: 'Deals' });
await saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served, navigation }, TEXTS, d);
expect(savedNav(calls)).toEqual([
object('contact', 'Contacts', 0),
object('customer', 'Customers', 1),
object('opportunity', 'Deals', 2),
]);
});

it('an entry pruned from the reader keeps its shown place among the rest', async () => {
const stored: Menu = [...STORED, object('payroll', 'Payroll', 1.5, { requiredPermissions: ['hr.admin'] })];
const served = seed(STORED);
const nav = await written(stored, served, (m) => moveBy(m, 'customer', 1));
expect(nav).toEqual([['contact', 0], ['customer', 1], ['payroll', 2], ['opportunity', 3]]);
});

it('CONTROL: a menu carrying no `order` is saved by array order and gains no `order` key', async () => {
const stored: Menu = STORED.map(({ order: _order, ...e }) => e);
const served = seed(stored);
const nav = await written(stored, served, (m) => moveBy(m, 'customer', -1));
expect(nav).toEqual([['opportunity', undefined], ['customer', undefined], ['contact', undefined]]);
});
});

describe('the session language against the default one', () => {
it.each([
['en', 'en', true],
Expand Down
Loading
Loading