Skip to content

Commit 93d8921

Browse files
fix(app-shell): a menu reordered in design mode is saved in the order the sidebar draws it (#36622)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi92ncfFpPUpTD8314otX5oaG)_ Fixes #36591 Clause-②: no Metadata-protocol: none ## 维护者速读 - 管理员在运行界面的设计模式里调整菜单顺序(上移、下移、移到分组、在前后加一项、添加菜单项、拖动)并保存后,侧栏现在按设计模式里显示的顺序排列;以前在 AI 搭建、菜单项带排序号的应用里,保存成功却毫无变化,再进设计模式看到的顺序也和侧栏相反。 - 属于「运行界面的设计模式」专题,替用 AI 搭建应用、要在应用里直接调菜单的管理员解决「改了不生效、也不报错」的问题。 - 出错时,带排序号的应用保存菜单后侧栏顺序会和设计模式不一致;只影响菜单顺序,不丢菜单项,可以在设计模式里再调一次保存,或撤回本次合并恢复旧行为。 - 无。 ## What changes The sidebar sorts each level of an app's `navigation` by `order` (`byNavOrder` in `@object-ui/layout`: lower first, an absent `order` as 0, ties in array order). Design mode listed and saved the array as authored, so in an app whose entries carry `order` a move was saved and published and changed nothing on screen. Route taken (the claim's Route, the card's first option): **rewrite `order` on save, never drop it.** - **Display** — design mode seeds its menu with every level put in the sidebar's order (`inShownOrder` in `designModeMenuModel.ts`, which sorts each level through `inMenuOrder`, the app-shell statement of the sidebar's rule; no new comparator). The menu reads the same in and out of the mode. - **Save** — `saveAppMenu` puts the stored menu in that same shown order before the edits are replayed on it (`rebaseMenuEdits`), then rewrites `order` on the result (`withOrderRewritten`): each level in which **any** entry carries `order` has **every** entry numbered `0, 1, …` in the order design mode showed; group entries and each group's children are numbered per level. A level where no entry carries `order` is saved by array order and gains no key (HotCRM-shaped apps are unchanged). - **Why `0..n-1`**: it is the smallest rule that makes `byNavOrder` draw exactly the array order (no ties are possible inside a renumbered level), it covers the mixed level the card names, and it is idempotent: a second save of the same menu writes the same numbers. Dropping `order` was rejected because it deletes authored keys from AI-built apps. - **Why the stored menu is sorted first**: the edits are replayed by place ("after the entry before it"), and the stored array of an `order`-carrying app is not in shown order. Without the sort an entry added at the end of `[X(2), Y(1), Z(0)]` lands after `X` in the array and is numbered between `X` and `Y`. A stored entry the reader was never shown (pruned) keeps its shown place among the rest. - `rebaseMenuEdits` and `order`: the editor never writes `order`, so the served and edited copies of an entry always agree on it and it is never a patch key; the stored value travels with the entry and is then rewritten. Nothing is treated as a conflict and nothing is dropped. Pinned by "a move up is written as `order`; a rename beside it writes its label, and `order` is never read as an edit". ### Why #36363's tests did not catch it Every fixture in the three #36363 test files authored its menu **without `order`** (HotCRM-shaped), where array order is the sidebar order. The save pins read the written navigation's **array positions** (`navigation[1].children.map((c) => c.id)`), and nothing drew the saved menu through the sidebar's renderer. Its acceptance line "上移并保存:顺序变了;刷新后还在" was therefore true of every fixture and false of the AI-built app the coordinator saved. The new pins draw what the save wrote through the real `NavigationRenderer` and compare it with what design mode showed, over menus that carry `order`. ## Tests Read first (by risk): 1. `ui/packages/app-shell/src/layout/designModeMenuSave.ts` — the two lines around `rebaseMenuEdits`: the sort before the replay and the rewrite after the payload. 2. `ui/packages/app-shell/src/layout/designModeMenuModel.ts` — `inShownOrder` and `withOrderRewritten`. 3. `ui/packages/app-shell/src/layout/DesignModeMenu.tsx` — the `served` seed. New pins, each a top-level `describe` in the existing shared harness of its subject (no new test files): - `DesignModeMenu-36363.test.tsx` · "the design-mode menu in the sidebar order (objectstack#36591)" — real `DesignModeMenu` + mode save, the sidebar read from a rendered `NavigationRenderer` (no sort written in the test): ordered app reads the same in design mode and in the sidebar; Move up on Contacts then Save → sidebar reads Contacts, Customers, …, and the saved app re-opens design mode in that order; Add an item after + Move to group → the sidebar places both where design mode showed them; CONTROL: an app with no `order` saves a move by array order and gains no `order` key; a mixed level reads as design mode after one save. - `designModeMenuSave-36363.test.ts` · "the save writes the order the editor showed as `order` (objectstack#36591)" — added at the end, move up with a rename beside it, a pruned entry, and the no-`order` control. - `designModeMenuModel-36363.test.ts` · "a level in the sidebar order, and that order written back as `order` (objectstack#36591)". <details><summary>Runs (head f4425f4)</summary> - `pnpm --dir ui exec vitest run --maxWorkers=2 packages/app-shell/src/layout/` → `Test Files 155 passed (155)`, `Tests 1247 passed (1247)`; lock `VERDICT command-exit 0`. - The three touched files alone → `Test Files 3 passed (3)`, `Tests 75 passed (75)`. - `pnpm --filter @object-ui/app-shell type-check` (both `tsconfig.json` and `tsconfig.test.json`) → lock `VERDICT command-exit 0`, after rebuilding the dependency closure the `origin/main` merge moved (a first run against the pre-merge `dist` reported `RecordDetailView.tsx` TS2322 from main's merged change; gone after the rebuild). </details> <details><summary>Ablation — the order rewrite removed</summary> `node scripts/ablation-replace.mjs --file ui/packages/app-shell/src/layout/designModeMenuSave.ts --anchor 'const nextNav = withOrderRewritten(navPayloadOf(rebased as unknown[]) as Menu);' --replacement 'const nextNav = navPayloadOf(rebased as unknown[]) as Menu; void withOrderRewritten;'` over the three files: - `ok mutation landed: anchor 1 -> 0, blob b319aa8 -> fd40d9929ee0` - `Test Files 2 failed | 1 passed (3)`, `Tests 6 failed | 69 passed (75)` — red: the three `order` save pins, and in the render harness Move up, Add after + Move to group, and the mixed level. The two CONTROL pins (no `order`) and the display pin stay green, as they should. - `ok restored: blob == HEAD (b319aa8) and git diff HEAD is empty`. </details> ## Acceptance notes - **Renumbering rewrites authored values.** Saving a menu whose level carries `order` writes consecutive numbers on every entry of that level (an authored `10, 20, 30` becomes `0, 1, 2`), even when the save only renamed an entry. The order drawn is unchanged; the values are not preserved. - **Another package's entries (`navigationContributions`) keep their own `order`.** They are not in the stored menu, so they are not renumbered. One that carries no `order` keeps its place (it sorts as 0 right after the app's first entry, as design mode now shows it); one that carries its own `order` can sit in a different place relative to the renumbered entries than design mode showed. No live app was found with such a contribution; noted, not filed. - **Two save rules for one key.** Studio's nav canvas (`AppNavCanvas` `moveItem`) writes `order` on the moved entry only; design mode now renumbers the level. Both draw the order their editor showed; they differ in how many keys a save writes. Observation only. - **Browser check: NOT MEASURED**, reason: the worktree has no built runtime or Console (`packages/console/dist` absent), and a full build plus a seeded backend on this shared 4-core box was not taken on for this card; the sidebar half is measured instead by rendering the real `NavigationRenderer` over the written navigation. - **Overlap**: `node scripts/pm/overlap-check.mjs` exits 1 against #36606 (shares `DesignModeMenu.tsx`, `designModeMenuSave.ts`, conflicts in `DesignModeMenu-36363.test.tsx`); the seat sequenced this card first and #36606 rebases on it. ## Verification Two minutes: `pnpm --dir ui exec vitest run packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx -t "sidebar order"` — expect 5 passed, among them "「Move up」 on Contacts, saved: the sidebar reads Contacts, Customers, …". Local gates: `node scripts/pm/dispatch-gates.mjs --commands` derived 38 commands for this diff; all 38 ran with exit 0 and `--ran` reconciles "38 run, 0 NOT-MEASURED". The `ui/scripts` vitest family was run with `--maxWorkers=2` added (dispatch order). Families CI runs are read from this PR's check-runs. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmRB34k9WUWeGpRnVNm <!-- signed: repo:objectstack#2 · os-steve · session_01ADHkmRB34k9WUWeGpRnVNm --> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 695b9db commit 93d8921

7 files changed

Lines changed: 337 additions & 6 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
---
4+
5+
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`
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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.
11+
12+
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.

‎ui/packages/app-shell/src/layout/DesignModeMenu.tsx‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,10 @@
3838
* change. Groups are not added, removed or renamed here, and nothing about
3939
* who sees an entry is changed: both stay in Studio.
4040
*
41+
* Each level is drawn in the order the sidebar draws it, `order` first
42+
* (`inShownOrder`, objectstack#36591), so the menu reads the same in and out
43+
* of the mode, and a move is saved as `order` where the level carries it.
44+
*
4145
* Loaded only while the mode is on (`UnifiedSidebar` lazy-loads it): it
4246
* brings the metadata client and the package doors the menu's write needs.
4347
*
@@ -121,6 +125,7 @@ import {
121125
entryFor,
122126
entryOf,
123127
groupsOf,
128+
inShownOrder,
124129
insertEntry,
125130
isGroup,
126131
menuTargets,
@@ -186,7 +191,9 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso
186191
const client = useMetadataClient();
187192
const packageId = typeof app._packageId === 'string' ? app._packageId : '';
188193
const served = React.useMemo(
189-
() => withEntryIds(Array.isArray(app.navigation) ? (app.navigation as Menu) : []),
194+
// Each level in the sidebar's order (objectstack#36591): the edits read a
195+
// level's array order as its shown order, and the save writes it back.
196+
() => withEntryIds(inShownOrder(Array.isArray(app.navigation) ? (app.navigation as Menu) : [])),
190197
[app.navigation],
191198
);
192199
const menu = change.value ?? served;

‎ui/packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx‎

Lines changed: 168 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
1818
import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react';
1919
import { MemoryRouter, useLocation } from 'react-router-dom';
2020
import { SidebarProvider } from '@object-ui/components';
21+
import { NavigationRenderer } from '@object-ui/layout';
22+
import type { NavigationItem } from '@object-ui/types';
2123

2224
const session = vi.hoisted(() => ({ language: 'en', defaultLocale: 'en' }));
2325
vi.mock('@object-ui/i18n', async (importOriginal) => ({
@@ -65,6 +67,8 @@ const listed = vi.hoisted(() => ({
6567
{ name: 'crm_lead_record', label: 'Lead record', type: 'record' },
6668
],
6769
}) as Record<string, Array<Record<string, unknown>>>);
70+
/** The app's menu as served (`null`: `NAVIGATION`). */
71+
const servedNav = vi.hoisted(() => ({ current: null as unknown[] | null }));
6872
/** The app's menu as stored (`null`: as served). */
6973
const storedNav = vi.hoisted(() => ({ current: null as unknown[] | null, failReads: 0 }));
7074
const client = vi.hoisted(() => ({
@@ -74,7 +78,7 @@ const client = vi.hoisted(() => ({
7478
storedNav.failReads -= 1;
7579
throw new Error('layered read failed');
7680
}
77-
const code = { name: 'crm', label: 'CRM', navigation: storedNav.current ?? NAVIGATION };
81+
const code = { name: 'crm', label: 'CRM', navigation: storedNav.current ?? servedNav.current ?? NAVIGATION };
7882
return { code, effective: code };
7983
},
8084
save: async (...args: unknown[]) => {
@@ -134,7 +138,7 @@ function Harness() {
134138
<SidebarProvider>
135139
{mode.active && (
136140
<DesignModeMenu
137-
app={{ name: 'crm', navigation: NAVIGATION, _packageId: 'com.acme.crm' }}
141+
app={{ name: 'crm', navigation: servedNav.current ?? NAVIGATION, _packageId: 'com.acme.crm' }}
138142
basePath="/apps/crm"
139143
resolveTargetLabel={(target) => (target.kind === 'object' ? OBJECT_LABELS[target.objectName] : undefined)}
140144
/>
@@ -202,6 +206,7 @@ beforeEach(() => {
202206
session.defaultLocale = 'en';
203207
storedNav.current = null;
204208
storedNav.failReads = 0;
209+
servedNav.current = null;
205210
__resetDefaultLocale();
206211
vi.stubGlobal(
207212
'fetch',
@@ -648,3 +653,164 @@ describe('the menu under the design mode (objectstack#36363)', () => {
648653
expect(switchedTo).toEqual(['hr']);
649654
});
650655
});
656+
657+
// ── objectstack#36591 ─────────────────────────────────────────────────────────
658+
659+
/**
660+
* objectstack#36591 — the design mode's menu reads, and saves, in the order
661+
* the sidebar draws it.
662+
*
663+
* The sidebar sorts each level by `order` (`byNavOrder`, internal to
664+
* `@object-ui/layout`); the editor read and saved array order, so a move in an
665+
* app whose entries carry `order` (an AI-built app's do) was saved and changed
666+
* nothing on screen. The sidebar here is the real one (`NavigationRenderer`),
667+
* drawn over what the save wrote, so these pins state no sort of their own.
668+
*/
669+
describe('the design-mode menu in the sidebar order (objectstack#36591)', () => {
670+
const object = (id: string, objectName: string, label: string, order?: number) => ({
671+
id,
672+
type: 'object',
673+
objectName,
674+
label,
675+
...(order === undefined ? {} : { order }),
676+
});
677+
678+
/** Authored out of `order`: the sidebar reads Customers, Contacts, Opportunities, Reports (Follow-ups, Pipeline). */
679+
const ORDERED = () => [
680+
object('opps', 'crm_opportunity', 'Opportunities', 2),
681+
object('customers', 'crm_customer', 'Customers', 0),
682+
{
683+
id: 'reports',
684+
type: 'group',
685+
label: 'Reports',
686+
order: 3,
687+
expanded: true,
688+
children: [
689+
{ id: 'pipeline', type: 'report', reportName: 'pipeline', label: 'Pipeline', order: 1 },
690+
object('followups', 'crm_follow_up', 'Follow-ups', 0),
691+
],
692+
},
693+
object('contacts', 'crm_contact', 'Contacts', 1),
694+
];
695+
696+
const LABELS = ['Customers', 'Contacts', 'Opportunities', 'Reports', 'Follow-ups', 'Pipeline', 'Cases', 'Leads', 'Accounts', 'Home', 'Sales', 'Insights'];
697+
698+
/** The labels `el` shows, in the order it shows them; each must show once. */
699+
function labelsIn(el: Element): string[] {
700+
const text = el.textContent ?? '';
701+
const shown = LABELS.filter((l) => text.includes(l));
702+
for (const l of shown) expect(text.indexOf(l)).toBe(text.lastIndexOf(l));
703+
return shown.sort((a, b) => text.indexOf(a) - text.indexOf(b));
704+
}
705+
706+
/** The running app's sidebar over `nav`. */
707+
function sidebarOrder(nav: unknown): string[] {
708+
const { container, unmount } = render(
709+
<MemoryRouter initialEntries={['/apps/crm']}>
710+
<SidebarProvider defaultOpen>
711+
<NavigationRenderer
712+
items={nav as NavigationItem[]}
713+
basePath="/apps/crm"
714+
resolveTargetLabel={(target) => (target.kind === 'object' ? OBJECT_LABELS[target.objectName] : undefined)}
715+
/>
716+
</SidebarProvider>
717+
</MemoryRouter>,
718+
);
719+
const shown = labelsIn(container);
720+
unmount();
721+
return shown;
722+
}
723+
724+
/** The design mode's menu, as it reads. */
725+
const editorOrder = () => labelsIn(screen.getByTestId('design-mode-menu'));
726+
727+
async function save(): Promise<Array<Record<string, unknown>>> {
728+
fireEvent.click(screen.getByTestId('design-mode-save'));
729+
await flush();
730+
await flush();
731+
expect(written.map(([verb]) => verb)).toEqual(['save', 'publish']);
732+
return (written[0][3] as { navigation: Array<Record<string, unknown>> }).navigation;
733+
}
734+
735+
/** Every `order` key of `nav`, at every depth. */
736+
const orderKeys = (nav: unknown): unknown[] =>
737+
(nav as Array<Record<string, unknown>>).flatMap((e) => [
738+
...('order' in e ? [e.order] : []),
739+
...(Array.isArray(e.children) ? orderKeys(e.children) : []),
740+
]);
741+
742+
it('an app whose entries carry `order` reads in the design mode as in the sidebar', () => {
743+
servedNav.current = ORDERED();
744+
start();
745+
expect(editorOrder()).toEqual(['Customers', 'Contacts', 'Opportunities', 'Reports', 'Follow-ups', 'Pipeline']);
746+
cleanup();
747+
expect(sidebarOrder(ORDERED())).toEqual(['Customers', 'Contacts', 'Opportunities', 'Reports', 'Follow-ups', 'Pipeline']);
748+
});
749+
750+
it('「Move up」 on Contacts, saved: the sidebar reads Contacts, Customers, …, and the design mode reads the same again', async () => {
751+
servedNav.current = ORDERED();
752+
start();
753+
await act_on('contacts', 'Move up');
754+
const shown = editorOrder();
755+
expect(shown).toEqual(['Contacts', 'Customers', 'Opportunities', 'Reports', 'Follow-ups', 'Pipeline']);
756+
const saved = await save();
757+
cleanup();
758+
expect(sidebarOrder(saved)).toEqual(shown);
759+
// The saved app, served again, opens the design mode in that order.
760+
servedNav.current = saved;
761+
storedNav.current = saved;
762+
start();
763+
expect(editorOrder()).toEqual(shown);
764+
});
765+
766+
it('「Add an item after」 and 「Move to group」, saved: the sidebar puts both where the design mode showed them', async () => {
767+
servedNav.current = ORDERED();
768+
start();
769+
await flush();
770+
await act_on('contacts', 'Add an item after');
771+
const picker = await screen.findByTestId('design-menu-picker');
772+
fireEvent.click(within(picker).getByRole('button', { name: 'Objects' }));
773+
await flush();
774+
fireEvent.click(within(picker).getByRole('button', { name: 'Cases' }));
775+
await flush();
776+
const trigger = within(entry('customers')).getByTestId('design-menu-actions');
777+
fireEvent.pointerDown(trigger, { button: 0, pointerType: 'mouse' });
778+
await flush();
779+
fireEvent.click(await screen.findByRole('menuitem', { name: 'Move to group' }));
780+
await flush();
781+
fireEvent.click(await screen.findByRole('menuitem', { name: 'Reports' }));
782+
await flush();
783+
const shown = editorOrder();
784+
expect(shown).toEqual(['Contacts', 'Cases', 'Opportunities', 'Reports', 'Follow-ups', 'Pipeline', 'Customers']);
785+
const saved = await save();
786+
cleanup();
787+
expect(sidebarOrder(saved)).toEqual(shown);
788+
});
789+
790+
it('CONTROL: an app whose entries carry no `order` saves a move by array order, and gains no `order` key', async () => {
791+
start();
792+
await act_on('accounts', 'Move up');
793+
const shown = editorOrder();
794+
expect(shown).toEqual(['Home', 'Sales', 'Accounts', 'Leads', 'Insights']);
795+
const saved = await save();
796+
expect(orderKeys(saved)).toEqual([]);
797+
cleanup();
798+
// The sidebar draws no empty group: Insights is the editor's alone.
799+
expect(sidebarOrder(saved)).toEqual(shown.filter((label) => label !== 'Insights'));
800+
});
801+
802+
it('a level where some entries carry `order` and some do not: one save, and the sidebar reads as the design mode', async () => {
803+
// The sidebar reads an absent `order` as 0: Customers, Contacts, Opportunities.
804+
const MIXED = () => [object('opps', 'crm_opportunity', 'Opportunities', 1), object('customers', 'crm_customer', 'Customers'), object('contacts', 'crm_contact', 'Contacts')];
805+
servedNav.current = MIXED();
806+
start();
807+
expect(editorOrder()).toEqual(['Customers', 'Contacts', 'Opportunities']);
808+
await act_on('opps', 'Move up');
809+
const shown = editorOrder();
810+
expect(shown).toEqual(['Customers', 'Opportunities', 'Contacts']);
811+
const saved = await save();
812+
expect(orderKeys(saved)).toEqual([0, 1, 2]);
813+
cleanup();
814+
expect(sidebarOrder(saved)).toEqual(shown);
815+
});
816+
});

‎ui/packages/app-shell/src/layout/__tests__/designModeMenuModel-36363.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
canMoveBy,
1111
entryFor,
1212
groupsOf,
13+
inShownOrder,
1314
insertEntry,
1415
menuTargets,
1516
moveBy,
@@ -23,6 +24,7 @@ import {
2324
targetKeyFor,
2425
targetKeyOf,
2526
withEntryIds,
27+
withOrderRewritten,
2628
type Menu,
2729
} from '../designModeMenuModel';
2830

@@ -223,3 +225,39 @@ describe('the edits replayed on the stored menu (objectstack#36363, review 70812
223225
expect(storedEntriesById(served, stored).get('nav_item_1')).toBe(lead);
224226
});
225227
});
228+
229+
describe('a level in the sidebar order, and that order written back as `order` (objectstack#36591)', () => {
230+
const at = (id: string, order?: number, children?: Menu) => ({
231+
id,
232+
type: children ? 'group' : 'page',
233+
...(children ? { children } : { pageName: id }),
234+
...(order === undefined ? {} : { order }),
235+
});
236+
const orders = (menu: Menu): unknown[] =>
237+
menu.map((e) => (Array.isArray(e.children) ? [e.order, orders(e.children as Menu)] : e.order));
238+
239+
it('each level is put in `order`, an absent one as 0, ties as authored; the group with its children', () => {
240+
const menu: Menu = Object.freeze([at('c', 2), at('a'), at('g', 1, [at('y', 1), at('x', 0)]), at('b')]);
241+
expect(ids(inShownOrder(menu))).toEqual(['a', 'b', ['g', ['x', 'y']], 'c']);
242+
});
243+
244+
it('a menu with no `order` is the menu itself', () => {
245+
expect(inShownOrder(MENU)).toBe(MENU);
246+
});
247+
248+
it('a level carrying `order` is numbered 0… in array order, every entry of it, those without one included', () => {
249+
const menu: Menu = Object.freeze([at('b', 5), at('a'), at('g', 9, [at('y', 1), at('x')])]);
250+
const next = withOrderRewritten(menu);
251+
expect(ids(next)).toEqual(['b', 'a', ['g', ['y', 'x']]]);
252+
expect(orders(next)).toEqual([0, 1, [2, [0, 1]]]);
253+
expect(ids(inShownOrder(next))).toEqual(ids(next));
254+
});
255+
256+
it('a level carrying no `order` gains none, though its group, or a group in it, does', () => {
257+
const menu: Menu = Object.freeze([at('a'), at('g', undefined, [at('y', 3), at('x')]), at('h', undefined, [at('z')])]);
258+
const next = withOrderRewritten(menu);
259+
expect(orders(next)).toEqual([undefined, [undefined, [0, 1]], [undefined, [undefined]]]);
260+
expect(next[2]).toBe(menu[2]);
261+
expect(withOrderRewritten(MENU)).toBe(MENU);
262+
});
263+
});

‎ui/packages/app-shell/src/layout/__tests__/designModeMenuSave-36363.test.ts‎

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ vi.mock('../../assistant/assistantBus', async (importOriginal) => ({
1616
emitMetadataRefresh,
1717
}));
1818

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

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

222+
describe('the save writes the order the editor showed as `order` (objectstack#36591)', () => {
223+
const object = (id: string, label: string, order?: number, extra: Record<string, unknown> = {}) => ({
224+
id,
225+
type: 'object',
226+
objectName: `crm_${id}`,
227+
label,
228+
...(order === undefined ? {} : { order }),
229+
...extra,
230+
});
231+
/** As stored, authored out of `order`; the sidebar reads Customers, Contacts, Opportunities. */
232+
const STORED: Menu = [object('opportunity', 'Opportunities', 2), object('contact', 'Contacts', 1), object('customer', 'Customers', 0)];
233+
/** The editor's seed, as `DesignModeMenu` makes it. */
234+
const seed = (nav: Menu) => withEntryIds(inShownOrder(nav));
235+
const written = async (stored: Menu, served: Menu, edit: (m: Menu) => Menu) => {
236+
const { d, calls } = doors({ writable: true, stored });
237+
await saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served, navigation: edit(served) }, TEXTS, d);
238+
return savedNav(calls).map((e) => [e.id, e.order]);
239+
};
240+
241+
it('an entry added at the end is numbered after the rest, and each entry gets its shown place', async () => {
242+
const served = seed(STORED);
243+
const nav = await written(STORED, served, (m) => insertEntry(m, null, 3, { id: 'nav_item_1', type: 'object', objectName: 'crm_case' }));
244+
expect(nav).toEqual([['customer', 0], ['contact', 1], ['opportunity', 2], ['nav_item_1', 3]]);
245+
});
246+
247+
it('a move up is written as `order`; a rename beside it writes its label, and `order` is never read as an edit', async () => {
248+
const served = seed(STORED);
249+
const { d, calls } = doors({ writable: true, stored: STORED });
250+
const navigation = patchEntry(moveBy(served, 'contact', -1), 'opportunity', { label: 'Deals' });
251+
await saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served, navigation }, TEXTS, d);
252+
expect(savedNav(calls)).toEqual([
253+
object('contact', 'Contacts', 0),
254+
object('customer', 'Customers', 1),
255+
object('opportunity', 'Deals', 2),
256+
]);
257+
});
258+
259+
it('an entry pruned from the reader keeps its shown place among the rest', async () => {
260+
const stored: Menu = [...STORED, object('payroll', 'Payroll', 1.5, { requiredPermissions: ['hr.admin'] })];
261+
const served = seed(STORED);
262+
const nav = await written(stored, served, (m) => moveBy(m, 'customer', 1));
263+
expect(nav).toEqual([['contact', 0], ['customer', 1], ['payroll', 2], ['opportunity', 3]]);
264+
});
265+
266+
it('CONTROL: a menu carrying no `order` is saved by array order and gains no `order` key', async () => {
267+
const stored: Menu = STORED.map(({ order: _order, ...e }) => e);
268+
const served = seed(stored);
269+
const nav = await written(stored, served, (m) => moveBy(m, 'customer', -1));
270+
expect(nav).toEqual([['opportunity', undefined], ['customer', undefined], ['contact', undefined]]);
271+
});
272+
});
273+
222274
describe('the session language against the default one', () => {
223275
it.each([
224276
['en', 'en', true],

0 commit comments

Comments
 (0)