diff --git a/.changeset/36591-design-menu-order.md b/.changeset/36591-design-menu-order.md new file mode 100644 index 00000000000..144efb8dd56 --- /dev/null +++ b/.changeset/36591-design-menu-order.md @@ -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. diff --git a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx index 8352226f30d..e262b2af678 100644 --- a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx +++ b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx @@ -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. * @@ -121,6 +125,7 @@ import { entryFor, entryOf, groupsOf, + inShownOrder, insertEntry, isGroup, menuTargets, @@ -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; 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 56ddeb7ce41..75272f21096 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 @@ -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) => ({ @@ -65,6 +67,8 @@ const listed = vi.hoisted(() => ({ { name: 'crm_lead_record', label: 'Lead record', type: 'record' }, ], }) as Record>>); +/** 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(() => ({ @@ -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[]) => { @@ -134,7 +138,7 @@ function Harness() { {mode.active && ( (target.kind === 'object' ? OBJECT_LABELS[target.objectName] : undefined)} /> @@ -202,6 +206,7 @@ beforeEach(() => { session.defaultLocale = 'en'; storedNav.current = null; storedNav.failReads = 0; + servedNav.current = null; __resetDefaultLocale(); vi.stubGlobal( 'fetch', @@ -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( + + + (target.kind === 'object' ? OBJECT_LABELS[target.objectName] : undefined)} + /> + + , + ); + 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>> { + 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> }).navigation; + } + + /** Every `order` key of `nav`, at every depth. */ + const orderKeys = (nav: unknown): unknown[] => + (nav as Array>).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); + }); +}); diff --git a/ui/packages/app-shell/src/layout/__tests__/designModeMenuModel-36363.test.ts b/ui/packages/app-shell/src/layout/__tests__/designModeMenuModel-36363.test.ts index 03a6544ddfc..81deaaa934e 100644 --- a/ui/packages/app-shell/src/layout/__tests__/designModeMenuModel-36363.test.ts +++ b/ui/packages/app-shell/src/layout/__tests__/designModeMenuModel-36363.test.ts @@ -10,6 +10,7 @@ import { canMoveBy, entryFor, groupsOf, + inShownOrder, insertEntry, menuTargets, moveBy, @@ -23,6 +24,7 @@ import { targetKeyFor, targetKeyOf, withEntryIds, + withOrderRewritten, type Menu, } from '../designModeMenuModel'; @@ -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); + }); +}); diff --git a/ui/packages/app-shell/src/layout/__tests__/designModeMenuSave-36363.test.ts b/ui/packages/app-shell/src/layout/__tests__/designModeMenuSave-36363.test.ts index d78eac1b697..9cea4981a15 100644 --- a/ui/packages/app-shell/src/layout/__tests__/designModeMenuSave-36363.test.ts +++ b/ui/packages/app-shell/src/layout/__tests__/designModeMenuSave-36363.test.ts @@ -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' }; @@ -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 = {}) => ({ + 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], diff --git a/ui/packages/app-shell/src/layout/designModeMenuModel.ts b/ui/packages/app-shell/src/layout/designModeMenuModel.ts index ad45602e297..b3f8791c807 100644 --- a/ui/packages/app-shell/src/layout/designModeMenuModel.ts +++ b/ui/packages/app-shell/src/layout/designModeMenuModel.ts @@ -16,9 +16,16 @@ * added, removed or renamed here (out of the card); entries move within a * group, between groups and to the menu's top level. * + * The edits read a level's ARRAY order as its shown order. The sidebar sorts + * each level by `order` (objectstack#36591), so the editor is seeded with each + * level put in that order ({@link inShownOrder}), and a save writes the order + * back as `order` ({@link withOrderRewritten}). + * * @module */ +import { inMenuOrder } from '../views/metadata-admin/previews/AppNavCanvas.js'; + /** One menu entry, as the app document holds it. */ export type MenuEntry = Readonly> & { readonly id?: unknown; readonly type?: unknown }; @@ -84,6 +91,44 @@ export function withEntryIds(menu: Menu): Menu { return changed ? answer : menu; } +/** + * The menu with each level, at every depth, in the order the sidebar draws it + * (objectstack#36591): through `inMenuOrder`, the menu's own rule (`order` + * ascending, an absent `order` as `0`, ties in array order). A level already + * in that order (one whose entries carry no `order`, say) is the same array, + * and an entry whose children are already in it is the same object. + */ +export function inShownOrder(menu: Menu): Menu { + const sorted = inMenuOrder(menu as ReadonlyArray).map(([entry]) => { + if (!Array.isArray(entry.children)) return entry; + const kids = inShownOrder(entry.children as Menu); + return kids === entry.children ? entry : { ...entry, children: kids }; + }); + return sorted.every((entry, i) => entry === menu[i]) ? menu : sorted; +} + +/** + * The menu with `order` written as each entry's place in its level, at every + * depth (objectstack#36591): a level in which any entry carries `order` has + * every entry numbered `0`, `1`, … in array order, so the sidebar's sort + * (`order` ascending) draws the level as the array reads. A level in which no + * entry carries `order` is left without it, so a menu authored by array order + * gains no key. An entry already holding its number is the same object. + */ +export function withOrderRewritten(menu: Menu): Menu { + const numbered = menu.some((entry) => entry.order !== undefined); + const next = menu.map((entry, i) => { + let out: MenuEntry = entry; + if (Array.isArray(entry.children)) { + const kids = withOrderRewritten(entry.children as Menu); + if (kids !== entry.children) out = { ...out, children: kids }; + } + if (numbered && out.order !== i) out = { ...out, order: i }; + return out; + }); + return next.every((entry, i) => entry === menu[i]) ? menu : next; +} + /** A new entry id no entry of `menu` holds. */ export function newEntryId(menu: Menu, stem = 'nav_item'): string { const taken = new Set(); diff --git a/ui/packages/app-shell/src/layout/designModeMenuSave.ts b/ui/packages/app-shell/src/layout/designModeMenuSave.ts index c6c51792399..b319aa8229c 100644 --- a/ui/packages/app-shell/src/layout/designModeMenuSave.ts +++ b/ui/packages/app-shell/src/layout/designModeMenuSave.ts @@ -24,6 +24,13 @@ * replayed on its navigation by entry id (`rebaseMenuEdits`); an entry * naming no target is left out (`navPayloadOf`, as Studio's nav save). * + * The order written is the order the editor showed (objectstack#36591). The + * sidebar sorts each level by `order`, so the editor shows each level, and the + * edits are replayed on each stored level, in that order (`inShownOrder`); + * each level whose entries carry `order` then has it rewritten from the + * result's order (`withOrderRewritten`). A level with no `order` is saved by + * array order alone, as before. + * * Nothing is created before every check has passed: the base's version is * read before the customization package is asked for, and a pair the server * does not list writable is refused before anything is written to it. @@ -51,7 +58,7 @@ import { type ListedPackageManifest, } from '../views/studio-design/packages-io.js'; import { navPayloadOf } from '../views/metadata-admin/previews/AppNavCanvas.js'; -import { rebaseMenuEdits, type Menu } from './designModeMenuModel.js'; +import { inShownOrder, rebaseMenuEdits, withOrderRewritten, type Menu } from './designModeMenuModel.js'; /** The doors the save goes through; the defaults are the console's own. */ export interface AppMenuSaveDoors { @@ -108,7 +115,11 @@ export async function saveAppMenu( // The app as stored, a customization of an installed app folded in. const stored = storedApp(await doors.client.layered('app', appName, { packageId })); const storedNav = Array.isArray(stored.navigation) ? (stored.navigation as Menu) : []; - const nextNav = navPayloadOf(rebaseMenuEdits(served, navigation, storedNav) as unknown[]); + // The stored menu in its shown order, as the editor's is (`inShownOrder`), + // so the edits land where the editor showed them; the result's order is + // then written as `order` on each level that carries it (objectstack#36591). + const rebased = rebaseMenuEdits(served, navigation, inShownOrder(storedNav)); + const nextNav = withOrderRewritten(navPayloadOf(rebased as unknown[]) as Menu); let body: Record | null = { ...stored, name: appName, navigation: nextNav }; let target = packageId; if (!listed.writable) {