diff --git a/.changeset/36363-design-mode-menu-editing.md b/.changeset/36363-design-mode-menu-editing.md new file mode 100644 index 00000000000..127690972ce --- /dev/null +++ b/.changeset/36363-design-mode-menu-editing.md @@ -0,0 +1,15 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(console): the app's menu is edited in the design mode, and an installed app enters it too + +Clause-②: yes (widening) +Metadata-protocol: none + +While the design mode is on, the sidebar draws the app's menu with its editor. Each group, and the menu's top level, ends with 「Add menu item」: it holds a dashed row 「Choose a menu item…」 where the entry will go and opens a picker that searches the app's existing objects, views, dashboards, reports and pages (and takes a link), offering only what is not in the menu yet. Each entry has a 「⋮」 menu (move up, move down, move to a group, add an item before or after it, rename and icon, remove from the menu) and can be dragged to another place or group. Removing takes the entry off the menu only; the picker offers it again. + +The edits are staged with the mode: 「Save」 writes the app with its new menu where Studio's menu editing writes it (the app's package when it is writable, else its customization package, declaring the override at the package's version) and publishes it, so every member sees it; 「Cancel」 drops them. A draft of the app already pending (in Studio) is not overwritten: the save says so and keeps the mode on. The save is composed from the app as stored, never as served: the menu a member is shown is translated into their language and pruned of what they may not open, so the edits are replayed by entry id on the stored menu, and every entry they did not touch is written back as it was. Renaming an entry is offered in the deployment's default language only, and only while the entry shows its stored name; in any other language the name field is closed and says that menu names are changed in the app's source language. Adding, moving and the icon stay open in every language. An entry another package puts into the menu (its `navigationContributions`) is not in the app's stored menu, so its 「⋮」 says it is changed in that package, and it is not moved, renamed or removed here. Such entries are added after the app's own entries when the app is served, so, once the editor has read the app's stored menu, an entry added or moved to the end of a group the app itself holds is drawn before them, where everyone will see it. A group another package adds, and the moment before that read lands, are not handled this way yet. + +「Edit app」 now enters the mode on an installed (read-only) app as well, where the customization door takes the caller; where it is walled off (a walled deployment, not the platform operator) the eye into Studio stays. An app whose menu is split in areas keeps its menu unedited in the mode. New `@object-ui/i18n` keys under `designMode.menu`. diff --git a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx new file mode 100644 index 00000000000..10afd48377f --- /dev/null +++ b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx @@ -0,0 +1,948 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The app's menu while the design mode is on (objectstack#36363): the + * sidebar draws this in place of the menu, with the edits the card asks for + * and nothing else. + * + * - Under each group, and under the top level, a row 「Add menu item」. It + * first puts a dashed row 「Choose a menu item…」 where the entry will go, + * then opens the picker: a search box over the kinds of existing thing an + * entry opens (objects, views, dashboards, reports, pages, a link); a kind + * lists those that exist and are not in the menu yet, and the one picked + * takes the dashed row's place. + * - On each entry, on hover or focus, a 「⋮」 menu: move up, move down, move + * to a group, add an item before or after it, rename and icon, remove from + * the menu. Removing takes the entry off the menu only; what it opened is + * kept, and the picker offers it again. + * - An entry can be dragged to another place, in its group or another one. + * + * A name is changed only in the app's source language (objectstack#36363, + * ruling (4)): the stored labels are the app's own, and a translation is + * written elsewhere. The rename's name field is open when the session + * language is the deployment's default (`GET /i18n/locales`, the server + * stating no source language of its own yet, objectstack#36504) and the + * entry's shown label is its stored one; else it is closed and says why. + * The icon, adding and moving are open in every language. + * + * An entry another package puts into the menu (its manifest's + * `navigationContributions`, appended when the app is served) is not in the + * app's stored menu, so it is not moved, renamed or removed here: its + * 「⋮」 says it is changed in that package, and it is not dragged. Adding an + * item before or after it stays open; no other entry is moved past it (a + * move up, a move down or a drop onto it), since its place is that package's. + * + * Every edit is staged with the mode (`useDesignModeChange`), under one key + * for the app's menu: the mode's 「Save」 writes it (`saveAppMenu`), its + * 「Cancel」 drops it. The menu drawn is the staged one, so it survives a page + * change. Groups are not added, removed or renamed here, and nothing about + * who sees an entry is changed: both stay in Studio. + * + * 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. + * + * @module + */ + +import * as React from 'react'; +import { Link } from 'react-router-dom'; +import { + DndContext, + KeyboardSensor, + PointerSensor, + closestCenter, + useDroppable, + useSensor, + useSensors, + type DragEndEvent, +} from '@dnd-kit/core'; +import { SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable'; +import { CSS } from '@dnd-kit/utilities'; +import { + ArrowLeft, + ChevronRight, + FileText, + LayoutDashboard, + Link2, + MoreVertical, + Plus, + Search, + Table2, + BarChart3, + Database, +} from 'lucide-react'; +import { + Button, + Dialog, + DialogContent, + DialogFooter, + DialogHeader, + DialogTitle, + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, + DropdownMenuTrigger, + Input, + Label, + SidebarGroup, + SidebarGroupContent, + SidebarGroupLabel, + SidebarMenu, + SidebarMenuAction, + SidebarMenuButton, + SidebarMenuItem, + cn, +} from '@object-ui/components'; +import { + resolveHref, + resolveNavItemIcon, + resolveNavItemLabel, + resolveNavKindIcon, + type NavTargetIconResolver, + type NavTargetLabelResolver, +} from '@object-ui/layout'; +import type { NavigationItem } from '@object-ui/types'; +import { useObjectTranslation } from '@object-ui/i18n'; +import { resolveI18nLabel } from '@objectstack/spec/ui'; +import { getIcon } from '../utils/getIcon.js'; +import { useMetadataClient } from '../views/metadata-admin/useMetadata.js'; +import { + fetchListedPackageManifests, + listedCustomizationPairOf, +} from '../views/studio-design/packages-io.js'; +import { useDesignModeChange } from './designMode.js'; +import { + MENU_TARGET_KINDS, + canMoveBy, + entryFor, + entryOf, + groupsOf, + insertEntry, + isGroup, + menuTargets, + moveBy, + moveEntry, + newEntryId, + patchEntry, + placeOf, + removeEntry, + siblingsAt, + storedEntriesById, + targetKeyFor, + withEntryIds, + type Menu, + type MenuEntry, + type MenuTargetKind, +} from './designModeMenu.js'; +import { + consoleAppMenuDoors, + fetchDefaultLocale, + isSameLanguage, + readStoredMenu, + saveAppMenu, +} from './designModeMenuSave.js'; + +/** + * The group label's icon-mode hiding, as the sidebar's own labels declare it + * (objectui#12795): invisible, so it leaves focus and the accessibility tree + * when the rail collapses to icons. + */ +const HIDDEN_ICON_LABEL_NOT_FOCUSABLE = + 'group-data-[state=collapsed]:group-data-[collapsible=icon]:invisible ' + + 'group-data-[state=collapsed]:group-data-[collapsible=icon]:transition-[margin,opacity,visibility]'; + +/** The key the app's menu is staged under. */ +const APP_MENU_CHANGE_KEY = 'app-menu'; + +/** Where the next picked entry goes. */ +interface AddAt { + readonly parentId: string | null; + readonly index: number; +} + +/** The drop zone at the end of a group (`null`: the top level). */ +const endZoneId = (parentId: string | null) => `design-menu-end:${parentId ?? ''}`; +const parentOfEndZone = (id: string): string | null | undefined => { + if (!id.startsWith('design-menu-end:')) return undefined; + const rest = id.slice('design-menu-end:'.length); + return rest === '' ? null : rest; +}; + +export interface DesignModeMenuProps { + /** The app on screen: its name, its served `navigation` and its package. */ + readonly app: { readonly name: string; readonly navigation?: unknown; readonly _packageId?: unknown }; + readonly basePath: string; + readonly resolveTargetLabel?: NavTargetLabelResolver; + readonly resolveTargetIcon?: NavTargetIconResolver; +} + +export default function DesignModeMenu({ app, basePath, resolveTargetLabel, resolveTargetIcon }: DesignModeMenuProps) { + const { t, language } = useObjectTranslation(); + const change = useDesignModeChange(APP_MENU_CHANGE_KEY); + const client = useMetadataClient(); + const packageId = typeof app._packageId === 'string' ? app._packageId : ''; + const served = React.useMemo( + () => withEntryIds(Array.isArray(app.navigation) ? (app.navigation as Menu) : []), + [app.navigation], + ); + const menu = change.value ?? served; + + const texts = React.useMemo( + () => ({ + notListed: t('designMode.menu.notListed', { + defaultValue: "This app's package is not listed, so its menu cannot be saved.", + }), + pendingDraft: t('designMode.menu.pendingDraft', { + defaultValue: 'This app has unpublished changes in Studio. Publish or discard them there, then save again.', + }), + noVersion: t('designMode.menu.noVersion', { + defaultValue: "This app's package states no version, so its menu cannot be customized.", + }), + notWritable: t('designMode.menu.notWritable', { + defaultValue: "This app's customization package cannot be written, so its menu cannot be saved.", + }), + }), + [t], + ); + const appName = app.name; + const commit = React.useCallback( + (navigation: Menu) => + saveAppMenu({ appName, packageId, served, navigation }, texts, consoleAppMenuDoors(client as never)), + [appName, packageId, served, texts, client], + ); + const stage = change.stage; + const update = React.useCallback((next: Menu) => stage(next, commit), [stage, commit]); + + const [addAt, setAddAt] = React.useState(null); + const [renaming, setRenaming] = React.useState(null); + + // The stored menu and the deployment's default language, for the rename's + // source-language rule; both `undefined` while read. + const [storedMenu, setStoredMenu] = React.useState(undefined); + const [defaultLocale, setDefaultLocale] = React.useState(undefined); + React.useEffect(() => { + let cancelled = false; + void readStoredMenu(appName, packageId, client as never).then((nav) => !cancelled && setStoredMenu(nav)); + void fetchDefaultLocale().then((code) => !cancelled && setDefaultLocale(code)); + return () => { + cancelled = true; + }; + }, [appName, packageId, client]); + const storedById = React.useMemo( + () => (storedMenu ? storedEntriesById(served, storedMenu) : null), + [served, storedMenu], + ); + /** Whether the entry `id` is another package's (served, and not in the stored menu). */ + const contributed = (id: string): boolean => !!storedById && !storedById.has(id) && !!entryOf(served, id); + /** Whether the entry beside `id`, `by` places away in its group, is another package's. */ + const besideContributed = (id: string, by: -1 | 1): boolean => { + const place = placeOf(menu, id); + const beside = place ? (siblingsAt(menu, place.parentId) ?? [])[place.index + by] : undefined; + return typeof beside?.id === 'string' && contributed(beside.id); + }; + /** + * Where the group `parentId` of `list` ends for the app's own entries: before + * the run of other packages' entries that closes it (its length when none). + * Contributions are appended to a group when the app is served, so an own + * entry put at or past that run is stored, and served, before it; the editor + * puts it there too, so it shows where everyone will see it. + */ + const ownEndOf = (list: Menu, parentId: string | null): number => { + const siblings = siblingsAt(list, parentId) ?? []; + let end = siblings.length; + while (end > 0 && typeof siblings[end - 1]?.id === 'string' && contributed(String(siblings[end - 1].id))) end -= 1; + return end; + }; + /** The entry `id` moved to the own end of the group `parentId`. */ + const moveToOwnEnd = (id: string, parentId: string | null): Menu => + moveEntry(menu, id, parentId, ownEndOf(removeEntry(menu, id), parentId)); + + const labelOf = React.useCallback( + (entry: MenuEntry) => + resolveNavItemLabel(entry as unknown as NavigationItem, t as never, resolveTargetLabel, language) || + String(entry.id ?? ''), + [t, resolveTargetLabel, language], + ); + const groups = React.useMemo(() => groupsOf(menu), [menu]); + + const sensors = useSensors( + useSensor(PointerSensor, { activationConstraint: { distance: 5 } }), + useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }), + ); + const leafIds = React.useMemo(() => { + const out: string[] = []; + const walk = (entries: Menu) => { + for (const entry of entries) { + if (isGroup(entry)) walk((entry.children as Menu) ?? []); + else if (entry.type !== 'separator' && typeof entry.id === 'string') out.push(entry.id); + } + }; + walk(menu); + return out; + }, [menu]); + + // The click that ends a pointer drag lands on the dragged entry's link when + // the drop moved nothing (a drop refused on another package's entry, say): + // it is not a click, so it opens nothing. dnd-kit stops that click's + // propagation in the document's capture phase but leaves its default (a full + // navigation), so the default is cancelled before it, on the window. + const lastDragEnd = React.useRef(0); + const dragging = React.useRef(false); + const onDragStart = () => { + dragging.current = true; + }; + const endDrag = () => { + dragging.current = false; + lastDragEnd.current = Date.now(); + }; + React.useEffect(() => { + const onClick = (event: MouseEvent) => { + const justDragged = dragging.current || Date.now() - lastDragEnd.current < 300; + if (justDragged && event.target instanceof Element && event.target.closest('[data-design-menu-link]')) event.preventDefault(); + }; + // The drag's end is stamped from the pointer itself too: dnd-kit reports a + // drag's end only after its start has rendered, so a flick released before + // that would leave the flag set and every link of the editor shut. A new + // press starts over. + const onPress = () => { + dragging.current = false; + }; + const onRelease = () => { + if (!dragging.current) return; + dragging.current = false; + lastDragEnd.current = Date.now(); + }; + window.addEventListener('click', onClick, true); + window.addEventListener('pointerdown', onPress, true); + window.addEventListener('pointerup', onRelease, true); + window.addEventListener('pointercancel', onRelease, true); + return () => { + window.removeEventListener('click', onClick, true); + window.removeEventListener('pointerdown', onPress, true); + window.removeEventListener('pointerup', onRelease, true); + window.removeEventListener('pointercancel', onRelease, true); + }; + }, []); + + const onDragEnd = (event: DragEndEvent) => { + endDrag(); + const id = String(event.active.id); + const overId = event.over ? String(event.over.id) : null; + if (!overId || overId === id) return; + const endParent = parentOfEndZone(overId); + if (endParent !== undefined) { + update(moveToOwnEnd(id, endParent)); + return; + } + const from = placeOf(menu, id); + const to = placeOf(menu, overId); + if (!from || !to || contributed(overId)) return; + // `to.index` read after the entry leaves: below its old place in the same + // group it lands after the entry dropped on, elsewhere before it. + update(moveEntry(menu, id, to.parentId, to.index)); + }; + + const startAdd = (at: AddAt) => { + setAddAt({ parentId: at.parentId, index: Math.min(at.index, ownEndOf(menu, at.parentId)) }); + }; + const pick = (entry: MenuEntry) => { + if (!addAt) return; + update(insertEntry(menu, addAt.parentId, addAt.index, entry)); + setAddAt(null); + }; + + const renderLeaf = (entry: MenuEntry, depth: number) => { + const id = String(entry.id); + const place = placeOf(menu, id); + return ( + g.id !== place?.parentId) + .map((g) => ({ id: g.id, label: labelOf(g.entry), depth: g.depth }))} + atTopLevel={place?.parentId === null} + onUp={() => update(moveBy(menu, id, -1))} + onDown={() => update(moveBy(menu, id, 1))} + onMoveTo={(groupId) => update(moveToOwnEnd(id, groupId))} + onAddBefore={() => place && startAdd({ parentId: place.parentId, index: place.index })} + onAddAfter={() => place && startAdd({ parentId: place.parentId, index: place.index + 1 })} + onRename={() => setRenaming(id)} + onRemove={() => update(removeEntry(menu, id))} + /> + } + /> + ); + }; + + 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 (isGroup(entry)) { + const gid = String(entry.id); + rows.push( +
  • +
    +
    +
      {renderEntries((entry.children as Menu) ?? [], gid, depth + 1)}
    +
  • , + ); + } else if (entry.type === 'separator') { + rows.push(
  • ); + } else { + rows.push(renderLeaf(entry, depth)); + } + }); + if (addAt && addAt.parentId === parentId && addAt.index >= entries.length) rows.push(); + rows.push( + startAdd({ parentId, index: entries.length })} + />, + ); + return rows; + }; + + const renamed = renaming ? entryOf(menu, renaming) : null; + /** Whether the entry `id`'s name may be changed here (ruling (4)). */ + const nameOpen = (id: string): boolean => { + if (!defaultLocale || !isSameLanguage(language, defaultLocale)) return false; + const shown = entryOf(served, id); + if (!shown) return true; // added in this session: its name is the editor's own + const stored = storedById?.get(id); + return !!stored && labelOf(shown) === labelOf(stored); + }; + + return ( + + {t('designMode.menu.title', { defaultValue: 'Menu' })} + + + + {renderEntries(menu, null, 0)} + + + + {addAt && ( + setAddAt(null)} + onPick={(kind, name, link) => pick(entryFor(kind, name, newEntryId([...menu, ...(storedMenu ?? [])]), link))} + language={language} + /> + )} + {renamed && ( + setRenaming(null)} + onDone={(label, icon) => { + // A name left as it was stays inherited (or as authored); a cleared one inherits again. + const patch: Record = { icon: icon || undefined }; + if (nameOpen(String(renamed.id)) && label !== labelOf(renamed)) patch.label = label || undefined; + update(patchEntry(menu, String(renamed.id), patch)); + setRenaming(null); + }} + /> + )} + + ); +} + +function indent(depth: number): React.CSSProperties | undefined { + return depth > 0 ? { paddingLeft: `${depth * 0.75}rem` } : undefined; +} + +function MenuLeaf({ + id, + depth, + entry, + label, + basePath, + resolveTargetIcon, + fixed, + actions, +}: { + id: string; + depth: number; + entry: MenuEntry; + label: string; + basePath: string; + resolveTargetIcon?: NavTargetIconResolver; + /** Another package's entry: not dragged. */ + fixed: boolean; + actions: React.ReactNode; +}) { + const sortable = useSortable({ id, disabled: fixed }); + const item = entry as unknown as NavigationItem; + const iconName = + item.type === 'object' && item.objectName + ? resolveNavItemIcon(item, resolveTargetIcon) + : resolveNavKindIcon(item) ?? resolveNavItemIcon(item); + const icon = React.createElement(getIcon(iconName), { className: 'h-4 w-4' }); + const { href, external } = resolveHref(item, basePath); + // The editor's drag is dnd-kit's alone: the browser's own drag of the link + // is off too. `data-design-menu-link` marks the link whose post-drag click + // the editor cancels. + const link = { + draggable: false, + onDragStart: (event: React.DragEvent) => event.preventDefault(), + 'data-design-menu-link': '', + ...sortable.attributes, + ...sortable.listeners, + }; + return ( + + + {external ? ( + + {icon} + {label} + + ) : ( + + {icon} + {label} + + )} + + {actions} + + ); +} + +function Placeholder({ depth }: { depth: number }) { + const { t } = useObjectTranslation(); + return ( +
  • +
    + {t('designMode.menu.placeholder', { defaultValue: 'Choose a menu item…' })} +
    +
  • + ); +} + +function AddRow({ parentId, depth, label, onAdd }: { parentId: string | null; depth: number; label: string; onAdd: () => void }) { + const drop = useDroppable({ id: endZoneId(parentId) }); + return ( + + + + {label} + + + ); +} + +function EntryActions({ + label, + fixed, + canUp, + canDown, + groups, + atTopLevel, + onUp, + onDown, + onMoveTo, + onAddBefore, + onAddAfter, + onRename, + onRemove, +}: { + label: string; + /** Another package's entry: only adding beside it is open. */ + fixed: boolean; + canUp: boolean; + canDown: boolean; + groups: Array<{ id: string; label: string; depth: number }>; + atTopLevel: boolean; + onUp: () => void; + onDown: () => void; + onMoveTo: (groupId: string | null) => void; + onAddBefore: () => void; + onAddAfter: () => void; + onRename: () => void; + onRemove: () => void; +}) { + const { t } = useObjectTranslation(); + return ( + + + + + + + + {fixed && ( + <> +

    + {t('designMode.menu.contributed', { defaultValue: 'Another package adds this item. It is moved, renamed or removed there.' })} +

    + + + )} + + {t('designMode.menu.moveUp', { defaultValue: 'Move up' })} + + + {t('designMode.menu.moveDown', { defaultValue: 'Move down' })} + + + + {t('designMode.menu.moveToGroup', { defaultValue: 'Move to group' })} + + + {!atTopLevel && ( + onMoveTo(null)}> + {t('designMode.menu.topLevel', { defaultValue: 'Top level' })} + + )} + {groups.map((g) => ( + onMoveTo(g.id)} style={indent(g.depth)}> + {g.label} + + ))} + + + + + {t('designMode.menu.addBefore', { defaultValue: 'Add an item before' })} + + + {t('designMode.menu.addAfter', { defaultValue: 'Add an item after' })} + + + {t('designMode.menu.rename', { defaultValue: 'Rename and icon' })} + + + + {t('designMode.menu.remove', { defaultValue: 'Remove from menu' })} + +
    +
    + ); +} + +/** The metadata type each picked kind lists (a link lists nothing). */ +const KIND_METADATA: Record, string> = { + object: 'object', + view: 'view', + dashboard: 'dashboard', + report: 'report', + page: 'page', +}; + +const KIND_ICON: Record> = { + object: Database, + view: Table2, + dashboard: LayoutDashboard, + report: BarChart3, + page: FileText, + url: Link2, +}; + +interface TargetRow { + readonly kind: MenuTargetKind; + readonly name: string; + readonly label: string; +} + +/** + * The existing things of every kind, of the app's package and of its paired + * customization package when there is one, by name. A failed read is an + * empty list for that kind: the picker says there is nothing to add. + */ +function useTargetRows(packageId: string, language: string): { rows: TargetRow[]; loading: boolean } { + const client = useMetadataClient(); + const [state, setState] = React.useState<{ rows: TargetRow[]; loading: boolean }>({ rows: [], loading: true }); + React.useEffect(() => { + let cancelled = false; + (async () => { + let packages = packageId ? [packageId] : []; + try { + const pair = packageId ? listedCustomizationPairOf(await fetchListedPackageManifests(), packageId) : null; + if (pair) packages = [...packages, pair]; + } catch { + /* the base's rows alone */ + } + const rows: TargetRow[] = []; + for (const kind of Object.keys(KIND_METADATA) as Array>) { + const seen = new Set(); + for (const pkg of packages) { + let listed: Array>; + try { + listed = ((await client.list(KIND_METADATA[kind], { packageId: pkg })) ?? []) as Array>; + } catch { + listed = []; + } + for (const row of listed) { + const name = typeof row?.name === 'string' ? row.name : ''; + if (!name || seen.has(name)) continue; + // A record page needs a record to open: no menu entry can pass one. + if (kind === 'page' && row.type === 'record') continue; + seen.add(name); + const label = resolveI18nLabel(row.label as never, language) || name; + rows.push({ kind, name, label }); + } + } + } + if (!cancelled) setState({ rows, loading: false }); + })(); + return () => { + cancelled = true; + }; + }, [client, packageId, language]); + return state; +} + +function MenuItemPicker({ + packageId, + inMenu, + onClose, + onPick, + language, +}: { + packageId: string; + inMenu: ReadonlySet; + onClose: () => void; + onPick: (kind: MenuTargetKind, name: string, link?: { label: string; url: string }) => void; + language: string; +}) { + const { t } = useObjectTranslation(); + const { rows, loading } = useTargetRows(packageId, language); + const [kind, setKind] = React.useState(null); + const [query, setQuery] = React.useState(''); + const [link, setLink] = React.useState({ label: '', url: '' }); + // Each key written whole, so the i18n call-site gate sees every one. + const kindTexts: Record = { + object: t('designMode.menu.kind.object', { defaultValue: 'Objects' }), + view: t('designMode.menu.kind.view', { defaultValue: 'Views' }), + dashboard: t('designMode.menu.kind.dashboard', { defaultValue: 'Dashboards' }), + report: t('designMode.menu.kind.report', { defaultValue: 'Reports' }), + page: t('designMode.menu.kind.page', { defaultValue: 'Pages' }), + url: t('designMode.menu.kind.url', { defaultValue: 'Link' }), + }; + const kindText = (k: MenuTargetKind) => kindTexts[k]; + const q = query.trim().toLowerCase(); + const offered = rows.filter( + (row) => + !inMenu.has(targetKeyFor(row.kind, row.name)) && + (kind === null || row.kind === kind) && + (!q || row.label.toLowerCase().includes(q) || row.name.toLowerCase().includes(q)), + ); + const title = t('designMode.menu.pickerTitle', { defaultValue: 'Add menu item' }); + return ( + !open && onClose()}> + + + {title} + + {kind !== 'url' && ( +
    +
    + )} + {kind !== null && ( + + )} + {kind === 'url' ? ( +
    { + e.preventDefault(); + if (link.label.trim() && link.url.trim()) onPick('url', link.url.trim(), { label: link.label.trim(), url: link.url.trim() }); + }} + > +
    + + setLink({ ...link, label: e.target.value })} /> +
    +
    + + setLink({ ...link, url: e.target.value })} placeholder="https://" /> +
    + + + +
    + ) : kind === null && !q ? ( +
      + {MENU_TARGET_KINDS.map((k) => { + const Icon = KIND_ICON[k]; + return ( +
    • + +
    • + ); + })} +
    + ) : ( +
      + {loading ? ( +
    • {t('designMode.menu.loading', { defaultValue: 'Loading…' })}
    • + ) : offered.length === 0 ? ( +
    • + {t('designMode.menu.none', { defaultValue: 'Nothing to add here' })} +
    • + ) : ( + offered.map((row) => { + const Icon = KIND_ICON[row.kind]; + return ( +
    • + +
    • + ); + }) + )} +
    + )} +
    +
    + ); +} + +function RenameDialog({ + label, + icon, + nameLocked, + onClose, + onDone, +}: { + label: string; + icon: string; + /** The name is shown, not changed: the session is not in the app's source language. */ + nameLocked: boolean; + onClose: () => void; + onDone: (label: string, icon: string) => void; +}) { + const { t } = useObjectTranslation(); + const [name, setName] = React.useState(label); + const [iconName, setIconName] = React.useState(icon); + const preview = React.createElement(getIcon(iconName || undefined), { className: 'h-4 w-4' }); + return ( + !open && onClose()}> + + + {t('designMode.menu.rename', { defaultValue: 'Rename and icon' })} + +
    { + e.preventDefault(); + onDone(name.trim(), iconName.trim()); + }} + > +
    + + setName(e.target.value)} + /> + {nameLocked && ( +

    + {t('designMode.menu.renameSourceOnly', { defaultValue: "Menu names are changed in the app's source language" })} +

    + )} +
    +
    + +
    + + {preview} + + setIconName(e.target.value)} placeholder="briefcase" /> +
    +

    + {t('designMode.menu.iconHint', { defaultValue: 'A Lucide icon name, such as "briefcase".' })} +

    +
    + + + +
    +
    +
    + ); +} + diff --git a/ui/packages/app-shell/src/layout/ShellPageActions.tsx b/ui/packages/app-shell/src/layout/ShellPageActions.tsx index 470f7f4582a..c5a941844cb 100644 --- a/ui/packages/app-shell/src/layout/ShellPageActions.tsx +++ b/ui/packages/app-shell/src/layout/ShellPageActions.tsx @@ -56,6 +56,8 @@ import { LocalizedSidebarTrigger } from './LocalizedSidebarTrigger.js'; import { AssistantTopBarButton } from './AssistantTopBarButton.js'; import { HelpMenu } from './HelpMenu.js'; import { useDesignMode, type DesignModeValue } from './designMode.js'; +import { useAuth } from '@object-ui/auth'; +import { postureHasOrgWall, useTenancyPosture } from '../hooks/useTenancyPosture.js'; /** * Counts the headers under a scope that place the expand button, so the @@ -210,7 +212,9 @@ export function useAppStudioEntry(enabled: boolean, activeAppName?: string): { * and 「Open {app} in Studio」 (ADR-0146 D5) at the same place. * * objectstack#36362 — under a shell that holds the design mode, 「Edit app」 - * turns the mode on, in place, and opens no Studio. + * turns the mode on, in place, and opens no Studio. objectstack#36363 — so + * does a read-only package's app, where the customization door takes this + * caller: its changes are saved as this environment's customization. */ function EditAppButton({ entry, @@ -222,7 +226,14 @@ function EditAppButton({ designMode: DesignModeValue | null; }) { const { t } = useObjectTranslation(); - if (entry.posture === 'view') { + // objectstack#36363 — a read-only package's app (an installed one) enters + // the mode too: what the mode saves goes to the package's customization, + // as Studio's menu editing does. Not where the customization door is walled + // off for this caller (only the platform operator may call it there). + const posture = useTenancyPosture(); + const { user } = useAuth(); + const customizable = !postureHasOrgWall(posture) || user?.isPlatformAdmin === true; + if (entry.posture === 'view' && !(designMode && customizable)) { const viewText = t('topbar.openAppInStudio', { defaultValue: 'Open {{app}} in Studio', app: appText }); return ( + ); +} + +/** The app menu's switch, as the sidebar wires it: `confirmUnsavedLeave` around the change of app. */ +const switchedTo = vi.hoisted(() => [] as string[]); +function SwitchApp() { + return ( + + ); +} + +const flush = () => act(async () => { await new Promise((r) => setTimeout(r, 0)); }); +const entry = (id: string) => screen.getByTestId(`design-menu-entry-${id}`); +/** The link the entry `id` is drawn as (dnd-kit gives it the role of a button). */ +const linkOf = (id: string) => entry(id).querySelector('a')!; +/** The entries of the group `id` (the top level for `null`), in order. */ +function order(): unknown[] { + const list = screen.getByTestId('design-mode-menu').querySelector('ul')!; + const read = (ul: Element): unknown[] => + [...ul.children].flatMap((li): unknown[] => { + const testid = li.getAttribute('data-testid') ?? ''; + if (testid.startsWith('design-menu-entry-')) return [testid.slice('design-menu-entry-'.length)]; + if (testid.startsWith('design-menu-group-')) return [[testid.slice('design-menu-group-'.length), read(li.querySelector('ul')!)]]; + if (testid === 'design-menu-placeholder') return ['…']; + return []; + }); + return read(list); +} + +/** Opens the 「⋮」 menu of the entry `id` and picks `item`. */ +async function act_on(id: string, item: string) { + const trigger = within(entry(id)).getByTestId('design-menu-actions'); + fireEvent.pointerDown(trigger, { button: 0, pointerType: 'mouse' }); + await flush(); + fireEvent.click(await screen.findByRole('menuitem', { name: item })); + await flush(); +} + +beforeEach(() => { + written.length = 0; + switchedTo.length = 0; + toastError.mockReset(); + session.language = 'en'; + session.defaultLocale = 'en'; + storedNav.current = null; + storedNav.failReads = 0; + __resetDefaultLocale(); + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => { + if (String(url).endsWith('/api/v1/i18n/locales')) { + const locales = ['en', 'zh-CN'].map((code) => ({ code, label: code, isDefault: code === session.defaultLocale })); + return new Response(JSON.stringify({ success: true, data: { locales } }), { status: 200 }); + } + throw new Error(`unexpected fetch ${url}`); + }), + ); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +function start() { + render( + + + , + ); + fireEvent.click(screen.getByText('enter')); +} + +describe('the menu under the design mode (objectstack#36363)', () => { + it('each group and the top level end with 「Add menu item」; each entry has a 「⋮」 menu', () => { + start(); + expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', []]]); + for (const at of ['sales', 'insights', 'top']) expect(screen.getByTestId(`design-menu-add-${at}`)).toHaveTextContent('Add menu item'); + expect(within(entry('leads')).getByRole('button', { name: 'Actions for Leads' })).toBeInTheDocument(); + }); + + it('「⋮ → Move up」 is staged, and 「Save」 writes the app with the new menu and publishes it', async () => { + start(); + await act_on('accounts', 'Move up'); + expect(order()).toEqual(['home', ['sales', ['accounts', 'leads']], ['insights', []]]); + expect(written).toEqual([]); + + fireEvent.click(screen.getByTestId('design-mode-save')); + await flush(); + await flush(); + const [save, publish] = written; + expect(save[0]).toBe('save'); + expect((save[3] as { navigation: Array<{ children?: Array<{ id: string }> }> }).navigation[1].children!.map((c) => c.id)).toEqual([ + 'accounts', + 'leads', + ]); + expect(save[4]).toEqual({ mode: 'draft', packageId: 'com.acme.crm', ifNoneMatch: '*' }); + expect(publish).toEqual(['publish', 'app', 'crm', { packageId: 'com.acme.crm' }]); + expect(screen.queryByTestId('design-mode-bar')).toBeNull(); + }); + + it('「Move to group」 lists the other groups and moves the entry to the end of the one picked', async () => { + start(); + const trigger = within(entry('leads')).getByTestId('design-menu-actions'); + fireEvent.pointerDown(trigger, { button: 0, pointerType: 'mouse' }); + await flush(); + const sub = await screen.findByRole('menuitem', { name: 'Move to group' }); + fireEvent.keyDown(sub, { key: 'ArrowRight' }); + await flush(); + const groups = (await screen.findAllByRole('menuitem')).map((m) => m.textContent); + expect(groups).toEqual(expect.arrayContaining(['Top level', 'Insights'])); + expect(groups).not.toContain('Sales'); + fireEvent.click(screen.getByRole('menuitem', { name: 'Insights' })); + await flush(); + expect(order()).toEqual(['home', ['sales', ['accounts']], ['insights', ['leads']]]); + }); + + it('「Add menu item」 holds a dashed row there, and the picker offers only what exists and is not in the menu', async () => { + start(); + fireEvent.click(screen.getByTestId('design-menu-add-insights')); + expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', ['…']]]); + const picker = await screen.findByTestId('design-menu-picker'); + fireEvent.click(within(picker).getByRole('button', { name: 'Objects' })); + await flush(); + expect(within(picker).getAllByRole('button').map((b) => b.textContent)).toEqual(expect.arrayContaining(['Cases'])); + expect(within(picker).queryByRole('button', { name: 'Leads' })).toBeNull(); + + fireEvent.click(within(picker).getByRole('button', { name: 'Cases' })); + await flush(); + expect(screen.queryByTestId('design-menu-picker')).toBeNull(); + expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', ['nav_item_1']]]); + expect(screen.getByTestId('design-mode-menu')).toHaveTextContent('Cases'); + }); + + it('the search runs over every kind; a record page is never offered', async () => { + start(); + fireEvent.click(screen.getByTestId('design-menu-add-top')); + const picker = await screen.findByTestId('design-menu-picker'); + fireEvent.change(within(picker).getByTestId('design-menu-picker-search'), { target: { value: 'e' } }); + await flush(); + const rows = within(within(picker).getByTestId('design-menu-picker-rows')).getAllByRole('button').map((b) => b.textContent); + expect(rows).toEqual(expect.arrayContaining(['CasesObjects', 'Hot leadsViews', 'WelcomePages'])); + expect(rows.join()).not.toContain('Lead record'); + // Pipeline is in the menu (Home opens it). + expect(rows.join()).not.toContain('Pipeline'); + }); + + it('「Remove from menu」 takes the entry off, and the picker offers it again', async () => { + start(); + await act_on('leads', 'Remove from menu'); + expect(order()).toEqual(['home', ['sales', ['accounts']], ['insights', []]]); + fireEvent.click(screen.getByTestId('design-menu-add-sales')); + const picker = await screen.findByTestId('design-menu-picker'); + fireEvent.click(within(picker).getByRole('button', { name: 'Objects' })); + await flush(); + expect(within(picker).getByRole('button', { name: 'Leads' })).toBeInTheDocument(); + }); + + it('「Rename and icon」 renames the entry in the menu', async () => { + start(); + await act_on('leads', 'Rename and icon'); + const dialog = await screen.findByTestId('design-menu-rename'); + const name = within(dialog).getByLabelText('Name'); + fireEvent.change(name, { target: { value: 'Prospects' } }); + fireEvent.change(within(dialog).getByLabelText('Icon'), { target: { value: 'user-plus' } }); + fireEvent.click(within(dialog).getByRole('button', { name: 'Done' })); + await flush(); + expect(entry('leads')).toHaveTextContent('Prospects'); + }); + + // Ruling (4) on review 7081226692: a name is changed in the app's source language only. + it('under zh-CN, with English the default, the name is not changed: the field is closed and says why; the icon still is', async () => { + session.language = 'zh-CN'; + start(); + await flush(); + await act_on('leads', 'Rename and icon'); + const dialog = await screen.findByTestId('design-menu-rename'); + expect(within(dialog).getByLabelText('Name')).toBeDisabled(); + expect(within(dialog).getByTestId('design-menu-rename-source-only')).toHaveTextContent( + "Menu names are changed in the app's source language", + ); + fireEvent.change(within(dialog).getByLabelText('Icon'), { target: { value: 'user-plus' } }); + fireEvent.click(within(dialog).getByRole('button', { name: 'Done' })); + await flush(); + fireEvent.click(screen.getByTestId('design-mode-save')); + await flush(); + await flush(); + const leads = (written[0][3] as { navigation: Array<{ children?: Array> }> }).navigation[1].children![0]; + expect(leads).toEqual({ id: 'leads', type: 'object', objectName: 'crm_lead', label: 'Leads', icon: 'user-plus' }); + }); + + it('in the default language, an entry shown under a label other than its stored one is not renamed here', async () => { + storedNav.current = NAVIGATION.map((e) => (e.id === 'home' ? { ...e, label: 'apps.crm.home' } : e)); + start(); + await flush(); + await act_on('home', 'Rename and icon'); + expect(within(await screen.findByTestId('design-menu-rename')).getByLabelText('Name')).toBeDisabled(); + }); + + it("another package's entry (served, not in the stored menu) says where it is changed, and is not moved or removed here", async () => { + storedNav.current = NAVIGATION.map((e) => + e.id === 'sales' ? { ...e, children: (e.children ?? []).filter((c) => c.id !== 'accounts') } : e, + ); + start(); + await flush(); + const trigger = within(entry('accounts')).getByTestId('design-menu-actions'); + fireEvent.pointerDown(trigger, { button: 0, pointerType: 'mouse' }); + await flush(); + expect(await screen.findByTestId('design-menu-contributed')).toHaveTextContent('Another package adds this item'); + for (const name of ['Move up', 'Rename and icon', 'Remove from menu']) { + expect(screen.getByRole('menuitem', { name })).toHaveAttribute('aria-disabled', 'true'); + } + expect(screen.getByRole('menuitem', { name: 'Add an item after' })).not.toHaveAttribute('aria-disabled'); + }); + + it("no entry is moved past another package's entry: 「Move down」 above it is off, and a drop on it does nothing", async () => { + storedNav.current = NAVIGATION.map((e) => + e.id === 'sales' ? { ...e, children: (e.children ?? []).filter((c) => c.id !== 'accounts') } : e, + ); + start(); + await flush(); + const trigger = within(entry('leads')).getByTestId('design-menu-actions'); + fireEvent.pointerDown(trigger, { button: 0, pointerType: 'mouse' }); + await flush(); + expect(await screen.findByRole('menuitem', { name: 'Move down' })).toHaveAttribute('aria-disabled', 'true'); + fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' }); + await flush(); + act(() => dragEnd.current!({ active: { id: 'home' }, over: { id: 'accounts' } })); + expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', []]]); + }); + + it("when the stored menu could not be read on entry, a move of another package's entry still writes none of it", async () => { + storedNav.current = NAVIGATION.map((e) => + e.id === 'sales' ? { ...e, children: (e.children ?? []).filter((c) => c.id !== 'accounts') } : e, + ); + storedNav.failReads = 1; // the editor's read on entry; the save's read answers + start(); + await flush(); + await act_on('accounts', 'Move up'); + expect(order()).toEqual(['home', ['sales', ['accounts', 'leads']], ['insights', []]]); + fireEvent.click(screen.getByTestId('design-mode-save')); + await flush(); + await flush(); + const nav = (written[0][3] as { navigation: Array<{ id: string; children?: Array<{ id: string }> }> }).navigation; + expect(nav[1].children!.map((c) => c.id)).toEqual(['leads']); + }); + + // L1-e review 7083961269 (1): contributions are appended when the app is + // served, so an own entry put at or past them is drawn before them. + const ACCOUNTS_CONTRIBUTED = () => + NAVIGATION.map((e) => (e.id === 'sales' ? { ...e, children: (e.children ?? []).filter((c) => c.id !== 'accounts') } : e)); + + it("「Add menu item」 at the end of a group that ends with another package's entries holds the row, and puts the pick, before them", async () => { + storedNav.current = ACCOUNTS_CONTRIBUTED(); + start(); + await flush(); + fireEvent.click(screen.getByTestId('design-menu-add-sales')); + expect(order()).toEqual(['home', ['sales', ['leads', '…', 'accounts']], ['insights', []]]); + 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(); + expect(order()).toEqual(['home', ['sales', ['leads', 'nav_item_1', 'accounts']], ['insights', []]]); + fireEvent.click(screen.getByTestId('design-mode-save')); + await flush(); + await flush(); + const nav = (written[0][3] as { navigation: Array<{ id: string; children?: Array<{ id: string }> }> }).navigation; + expect(nav[1].children!.map((c) => c.id)).toEqual(['leads', 'nav_item_1']); + }); + + it("「Add an item after」 on another package's entry, and 「Move to group」 into its group, land before it", async () => { + storedNav.current = ACCOUNTS_CONTRIBUTED(); + start(); + await flush(); + await act_on('accounts', 'Add an item after'); + expect(order()).toEqual(['home', ['sales', ['leads', '…', 'accounts']], ['insights', []]]); + fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' }); + await flush(); + const trigger = within(entry('home')).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: 'Sales' })); + await flush(); + expect(order()).toEqual([['sales', ['leads', 'home', 'accounts']], ['insights', []]]); + }); + + it("dropped on the end of a group that ends with another package's entries, an entry lands before them", async () => { + storedNav.current = ACCOUNTS_CONTRIBUTED(); + start(); + await flush(); + act(() => dragEnd.current!({ active: { id: 'home' }, over: { id: 'design-menu-end:sales' } })); + expect(order()).toEqual([['sales', ['leads', 'home', 'accounts']], ['insights', []]]); + }); + + // L1-e review 7083961269 (2): the browser's own drag of an entry's link + // would, dropped where the editor does not move it, open the link as a new + // document; and the click a drag ends with is no click. + it("an entry's link is not dragged by the browser, and the click a drag ends with opens nothing", async () => { + storedNav.current = ACCOUNTS_CONTRIBUTED(); + render( + + + + , + ); + fireEvent.click(screen.getByText('enter')); + await flush(); + const leads = linkOf('leads'); + expect(leads).toHaveAttribute('draggable', 'false'); + expect(fireEvent.dragStart(leads)).toBe(false); // the native drag is refused + expect(fireEvent.dragStart(linkOf('accounts'))).toBe(false); + + // Control: a plain click opens the entry's page, in the app. + fireEvent.click(linkOf('home')); + const opened = screen.getByTestId('where').textContent; + expect(opened).not.toBe('/apps/crm'); + + // A drag of leads refused on another package's entry, then the click it ends with. + act(() => dragStart.current!({ active: { id: 'leads' } })); + act(() => dragEnd.current!({ active: { id: 'leads' }, over: { id: 'accounts' } })); + fireEvent.click(leads); + expect(screen.getByTestId('where').textContent).toBe(opened); + expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', []]]); + expect(screen.getByTestId('design-mode-bar')).toBeInTheDocument(); + }); + + // L1-e review 7084606001: on the real event order. dnd-kit's pointer sensor, + // once a drag is active, stops the click that follows in the document's + // capture phase without cancelling it, so a handler on React's root never + // sees it and the link's default (a full navigation) would run. + it('the click a real pointer drag ends with is cancelled before dnd-kit stops it', async () => { + storedNav.current = ACCOUNTS_CONTRIBUTED(); + render( + + + + , + ); + fireEvent.click(screen.getByText('enter')); + await flush(); + const leads = linkOf('leads'); + const pointer = (type: string, target: EventTarget, x: number) => { + const event = new MouseEvent(type, { bubbles: true, cancelable: true, clientX: x, clientY: 10, button: 0, buttons: 1 }); + Object.defineProperty(event, 'isPrimary', { value: true }); + Object.defineProperty(event, 'pointerType', { value: 'mouse' }); + act(() => { + target.dispatchEvent(event); + }); + }; + let stoppedInDocument = false; + const watch = () => { + stoppedInDocument = true; + }; + pointer('pointerdown', leads, 10); + pointer('pointermove', document, 30); // past the 5 px activation distance + pointer('pointermove', document, 40); + pointer('pointerup', document, 40); + const released = linkOf('leads'); // the link under the pointer when it is released + document.addEventListener('click', watch); // bubble: reached only if dnd-kit did not stop it + const click = new MouseEvent('click', { bubbles: true, cancelable: true, button: 0 }); + act(() => { + released.dispatchEvent(click); + }); + document.removeEventListener('click', watch); + // dnd-kit takes its click listener off 50 ms after the drag; wait before + // asserting, so a failure here leaves no listener to the next case. + await act(async () => { + await new Promise((r) => setTimeout(r, 350)); + }); + expect(stoppedInDocument).toBe(false); // dnd-kit stopped it, as in the browser + expect(click.defaultPrevented).toBe(true); // and its default is cancelled + + // A plain click afterwards is a click again: it opens the entry's page. + const before = screen.getByTestId('where').textContent; + fireEvent.click(linkOf('leads')); + expect(screen.getByTestId('where').textContent).not.toBe(before); + expect(screen.getByTestId('design-mode-bar')).toBeInTheDocument(); + }); + + // Review 7085270448 S3: dnd-kit reports a drag's start at 5 px but its end + // only after the start has rendered, so a flick released first can end with + // no end reported. The release itself ends it: links open again. + it('a drag whose end dnd-kit never reports (a fast flick) does not leave the links shut', async () => { + render( + + + + , + ); + fireEvent.click(screen.getByText('enter')); + await flush(); + act(() => dragStart.current!({ active: { id: 'leads' } })); // started, and no end reported + fireEvent.pointerUp(window); + await act(async () => { + await new Promise((r) => setTimeout(r, 350)); + }); + fireEvent.click(linkOf('home')); + expect(screen.getByTestId('where').textContent).not.toBe('/apps/crm'); + }); + + it('adding and moving stay open under zh-CN', async () => { + session.language = 'zh-CN'; + start(); + await flush(); + await act_on('accounts', 'Move up'); + expect(order()).toEqual(['home', ['sales', ['accounts', 'leads']], ['insights', []]]); + fireEvent.click(screen.getByTestId('design-menu-add-insights')); + expect(await screen.findByTestId('design-menu-picker')).toBeInTheDocument(); + }); + + // N4 on review 7081253549: the drop's wiring, to another group. + it('an entry dropped on another group\'s end moves there; dropped on an entry elsewhere, it takes that place', async () => { + start(); + act(() => dragEnd.current!({ active: { id: 'leads' }, over: { id: 'design-menu-end:insights' } })); + expect(order()).toEqual(['home', ['sales', ['accounts']], ['insights', ['leads']]]); + act(() => dragEnd.current!({ active: { id: 'accounts' }, over: { id: 'home' } })); + expect(order()).toEqual(['accounts', 'home', ['sales', []], ['insights', ['leads']]]); + act(() => dragEnd.current!({ active: { id: 'home' }, over: { id: 'design-menu-end:' } })); + expect(order()).toEqual(['accounts', ['sales', []], ['insights', ['leads']], 'home']); + + fireEvent.click(screen.getByTestId('design-mode-save')); + await flush(); + await flush(); + const nav = (written[0][3] as { navigation: Array<{ id: string; children?: Array<{ id: string }> }> }).navigation; + expect(nav.map((e) => [e.id, e.children?.map((c) => c.id)])).toEqual([ + ['accounts', undefined], + ['sales', []], + ['insights', ['leads']], + ['home', undefined], + ]); + }); + + it('「Cancel」 after three edits leaves the menu as it was, and writes nothing', async () => { + start(); + await act_on('accounts', 'Move up'); + await act_on('home', 'Remove from menu'); + await act_on('leads', 'Move down'); + fireEvent.click(screen.getByTestId('design-mode-cancel')); + fireEvent.click(screen.getByText('enter')); + expect(order()).toEqual(['home', ['sales', ['leads', 'accounts']], ['insights', []]]); + expect(written).toEqual([]); + }); + + // Card comment 7079728193: unsaved menu changes ask before the app is left, + // in the shell's one unsaved-changes prompt (stay, or leave and drop them). + it('a moved entry not yet saved: switching app asks first; staying keeps the change, leaving goes on', async () => { + const confirmSpy = vi.fn((_message?: string): boolean => false); + vi.stubGlobal('confirm', confirmSpy); + start(); + await act_on('accounts', 'Move up'); + expect(order()).toEqual(['home', ['sales', ['accounts', 'leads']], ['insights', []]]); + + fireEvent.click(screen.getByText('switch to hr')); + expect(confirmSpy).toHaveBeenCalledWith('Leave design mode? Your unsaved changes will be lost.'); + expect(switchedTo).toEqual([]); + expect(screen.getByTestId('design-mode-bar')).toBeInTheDocument(); + expect(order()).toEqual(['home', ['sales', ['accounts', 'leads']], ['insights', []]]); + expect(written).toEqual([]); + + confirmSpy.mockReturnValue(true); + fireEvent.click(screen.getByText('switch to hr')); + expect(switchedTo).toEqual(['hr']); + expect(written).toEqual([]); + }); + + it('a reload or a tab close is held while a menu change is unsaved, and not once it is saved', async () => { + const held = () => { + const unload = new Event('beforeunload', { cancelable: true }); + window.dispatchEvent(unload); + return unload.defaultPrevented; + }; + start(); + expect(held()).toBe(false); + await act_on('accounts', 'Move up'); + expect(held()).toBe(true); + fireEvent.click(screen.getByTestId('design-mode-save')); + await flush(); + await flush(); + expect(held()).toBe(false); + }); + + it('with nothing changed, switching app asks nothing', () => { + const confirmSpy = vi.fn((_message?: string): boolean => false); + vi.stubGlobal('confirm', confirmSpy); + start(); + fireEvent.click(screen.getByText('switch to hr')); + expect(confirmSpy).not.toHaveBeenCalled(); + expect(switchedTo).toEqual(['hr']); + }); +}); diff --git a/ui/packages/app-shell/src/layout/__tests__/ShellPageActions-36111.test.tsx b/ui/packages/app-shell/src/layout/__tests__/ShellPageActions-36111.test.tsx index 03af587b91f..60560fe904a 100644 --- a/ui/packages/app-shell/src/layout/__tests__/ShellPageActions-36111.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/ShellPageActions-36111.test.tsx @@ -27,10 +27,17 @@ import { act, cleanup, render, screen, within } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; import { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from '@object-ui/permissions'; -vi.mock('@object-ui/auth', async (importOriginal) => ({ - ...(await importOriginal>()), - useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), -})); +/** What the session's auth answers beyond the real hook: the deployment's posture, the platform operator flag. */ +const authOverride = vi.hoisted(() => ({ value: {} as Record })); +vi.mock('@object-ui/auth', async (importOriginal) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- the real module, spread whole + const actual = await importOriginal>(); + return { + ...actual, + useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), + useAuth: () => ({ ...actual.useAuth(), ...authOverride.value }), + }; +}); vi.mock('@object-ui/i18n', async (importOriginal) => ({ ...(await importOriginal>()), @@ -270,10 +277,35 @@ describe('「Edit app」 turns the shell\'s design mode on instead of opening St expect(screen.queryByTestId('shell-page-actions-edit-app')).not.toBeInTheDocument(); }); - it('a read-only package keeps the eye into Studio', async () => { + it('a read-only package (an installed app) enters the mode too: its changes are this environment\'s customization (objectstack#36363)', async () => { writable = false; await mount(group); - expect(screen.queryByTestId('shell-page-actions-edit-app')).not.toBeInTheDocument(); - expect(screen.getByTestId('shell-page-actions-view-app')).toHaveAccessibleName('Open Cloud in Studio'); + expect(screen.queryByTestId('shell-page-actions-view-app')).not.toBeInTheDocument(); + const button = screen.getByTestId('shell-page-actions-edit-app'); + expect(button.tagName).toBe('BUTTON'); + await act(async () => button.click()); + expect(screen.getByTestId('mode')).toHaveTextContent('on'); + }); + + it('where the customization door is walled off for this caller, a read-only package keeps the eye into Studio', async () => { + writable = false; + authOverride.value = { getAuthConfig: async () => ({ features: { tenancyPosture: 'isolated' } }), user: { isPlatformAdmin: false } }; + try { + await mount(group); + expect(screen.queryByTestId('shell-page-actions-edit-app')).not.toBeInTheDocument(); + expect(screen.getByTestId('shell-page-actions-view-app')).toHaveAccessibleName('Open Cloud in Studio'); + } finally { + authOverride.value = {}; + } + }); + + it('a writable package under the same wall still enters the mode: nothing of it goes through that door', async () => { + authOverride.value = { getAuthConfig: async () => ({ features: { tenancyPosture: 'isolated' } }), user: { isPlatformAdmin: false } }; + try { + await mount(group); + expect(screen.getByTestId('shell-page-actions-edit-app').tagName).toBe('BUTTON'); + } finally { + authOverride.value = {}; + } }); }); diff --git a/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.favoritesMenu-12427.test.tsx b/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.favoritesMenu-12427.test.tsx index 1c8ce4adf49..e575ec245d7 100644 --- a/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.favoritesMenu-12427.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.favoritesMenu-12427.test.tsx @@ -465,10 +465,40 @@ describe('UnifiedSidebar: no Favorites while the design mode is on (objectstack# fireEvent.click(screen.getByText('enter design')); expect(favoritesSection()).toBeNull(); - // The app's own entries stay, the pinned one included, in the menu. - expect(menuRows().map((row) => row.textContent)).toEqual(expect.arrayContaining([expect.stringContaining('Accounts')])); + // The app's own entries stay, the pinned one included, in the menu, which + // the mode's editor draws (objectstack#36363). + const editor = await screen.findByTestId('design-mode-menu'); + expect(within(editor).getByTestId('design-menu-entry-nav_accounts')).toHaveTextContent('Accounts'); fireEvent.click(screen.getByText('leave design')); expect(favoriteLabels()).toEqual(['Accounts', 'Acme']); }); + + it('outside the mode the menu offers no 「Add menu item」 and no 「⋮」 of the editor (objectstack#36363)', async () => { + metadataState = { + apps: [{ name: 'crm', label: 'CRM', active: true, _packageId: 'com.acme.crm', navigation: NAVIGATION }], + objects: [], + }; + render( + + + + + + + + + + , + ); + await tick(); + const editorParts = () => document.querySelectorAll('[data-testid^="design-menu-"], [data-testid="design-mode-menu"]'); + expect(menuRows().length).toBeGreaterThan(0); + expect(editorParts()).toHaveLength(0); + fireEvent.click(screen.getByText('enter design')); + await screen.findByTestId('design-mode-menu'); + expect(editorParts().length).toBeGreaterThan(0); + fireEvent.click(screen.getByText('leave design')); + expect(editorParts()).toHaveLength(0); + }); }); diff --git a/ui/packages/app-shell/src/layout/__tests__/designModeMenu-36363.test.ts b/ui/packages/app-shell/src/layout/__tests__/designModeMenu-36363.test.ts new file mode 100644 index 00000000000..857e9d8df83 --- /dev/null +++ b/ui/packages/app-shell/src/layout/__tests__/designModeMenu-36363.test.ts @@ -0,0 +1,225 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The menu edits of the design mode (objectstack#36363) as functions of the + * app's `navigation`: each answers a new tree, the one given is untouched. + */ + +import { describe, expect, it } from 'vitest'; +import { + canMoveBy, + entryFor, + groupsOf, + insertEntry, + menuTargets, + moveBy, + moveEntry, + newEntryId, + patchEntry, + placeOf, + rebaseMenuEdits, + removeEntry, + storedEntriesById, + targetKeyFor, + targetKeyOf, + withEntryIds, + type Menu, +} from '../designModeMenu'; + +const MENU: Menu = Object.freeze([ + { id: 'home', type: 'dashboard', dashboardName: 'home' }, + { + id: 'sales', + type: 'group', + label: 'Sales', + children: [ + { id: 'leads', type: 'object', objectName: 'crm_lead' }, + { id: 'opps', type: 'object', objectName: 'crm_opportunity' }, + { id: 'mine', type: 'object', objectName: 'crm_opportunity', viewName: 'crm_opportunity.mine' }, + ], + }, + { id: 'insights', type: 'group', label: 'Insights', children: [{ id: 'pipeline', type: 'report', reportName: 'pipeline' }] }, +]); + +const ids = (menu: Menu): unknown[] => + menu.map((e) => (Array.isArray(e.children) ? [e.id, ids(e.children as Menu)] : e.id)); + +describe('the menu edits (objectstack#36363)', () => { + it('move up / move down swap within the group, and stop at its ends', () => { + expect(ids(moveBy(MENU, 'opps', -1))).toEqual(['home', ['sales', ['opps', 'leads', 'mine']], ['insights', ['pipeline']]]); + expect(ids(moveBy(MENU, 'opps', 1))).toEqual(['home', ['sales', ['leads', 'mine', 'opps']], ['insights', ['pipeline']]]); + expect(moveBy(MENU, 'leads', -1)).toBe(MENU); + expect([canMoveBy(MENU, 'leads', -1), canMoveBy(MENU, 'leads', 1), canMoveBy(MENU, 'mine', 1)]).toEqual([false, true, false]); + expect(ids(MENU)).toEqual(['home', ['sales', ['leads', 'opps', 'mine']], ['insights', ['pipeline']]]); + }); + + it('move to a group appends there; to the top level too; never into itself', () => { + expect(ids(moveEntry(MENU, 'leads', 'insights', Infinity))).toEqual([ + 'home', + ['sales', ['opps', 'mine']], + ['insights', ['pipeline', 'leads']], + ]); + expect(ids(moveEntry(MENU, 'pipeline', null, Infinity))).toEqual(['home', ['sales', ['leads', 'opps', 'mine']], ['insights', []], 'pipeline']); + expect(moveEntry(MENU, 'sales', 'sales', 0)).toBe(MENU); + }); + + it('a drop in the same group lands after the entry below it and before the one above it', () => { + // `to.index` is read before the move, as the editor passes it. + expect(ids(moveEntry(MENU, 'leads', 'sales', placeOf(MENU, 'mine')!.index))).toEqual([ + 'home', + ['sales', ['opps', 'mine', 'leads']], + ['insights', ['pipeline']], + ]); + expect(ids(moveEntry(MENU, 'mine', 'sales', placeOf(MENU, 'leads')!.index))).toEqual([ + 'home', + ['sales', ['mine', 'leads', 'opps']], + ['insights', ['pipeline']], + ]); + }); + + it('insert puts an entry at a place, clamped to the group; remove takes it off', () => { + const added = insertEntry(MENU, 'insights', 0, { id: 'x', type: 'page', pageName: 'x' }); + expect(ids(added)).toEqual(['home', ['sales', ['leads', 'opps', 'mine']], ['insights', ['x', 'pipeline']]]); + expect(ids(insertEntry(MENU, null, 99, { id: 'y', type: 'url', url: 'https://e.x' }))).toEqual([ + 'home', + ['sales', ['leads', 'opps', 'mine']], + ['insights', ['pipeline']], + 'y', + ]); + expect(ids(removeEntry(added, 'x'))).toEqual(ids(MENU)); + }); + + it('rename and icon patch the entry; a key patched to undefined goes', () => { + const renamed = patchEntry(MENU, 'leads', { label: 'Prospects', icon: 'user-plus' }); + expect((renamed[1].children as Menu)[0]).toEqual({ id: 'leads', type: 'object', objectName: 'crm_lead', label: 'Prospects', icon: 'user-plus' }); + expect((patchEntry(renamed, 'leads', { label: undefined }) [1].children as Menu)[0]).not.toHaveProperty('label'); + }); + + it('what the menu opens, one key per thing; a picked thing makes the entry that opens it', () => { + expect([...menuTargets(MENU)].sort()).toEqual( + ['dashboard/home', 'object/crm_lead', 'object/crm_opportunity', 'report/pipeline', 'view/crm_opportunity.mine'].sort(), + ); + expect(targetKeyOf({ type: 'object', objectName: 'a', recordId: '1' })).toBeNull(); + expect(entryFor('view', 'crm_lead.hot', 'n1')).toEqual({ id: 'n1', type: 'object', objectName: 'crm_lead', viewName: 'crm_lead.hot' }); + expect(entryFor('url', 'https://e.x', 'n2', { label: 'Docs', url: 'https://e.x' })).toEqual({ + id: 'n2', + type: 'url', + label: 'Docs', + url: 'https://e.x', + }); + for (const kind of ['object', 'dashboard', 'report', 'page'] as const) { + expect(targetKeyOf(entryFor(kind, 'n', 'id'))).toBe(`${kind}/n`); + } + }); + + // S1 on review 7081253549: a view named short is its object's view. + it("a view named without its object is keyed as that object's view, as the picker keys it", () => { + expect(targetKeyOf({ type: 'object', objectName: 'crm_lead', viewName: 'hot' })).toBe('view/crm_lead.hot'); + expect(targetKeyOf({ type: 'object', objectName: 'crm_lead', viewName: 'crm_lead.hot' })).toBe('view/crm_lead.hot'); + expect(menuTargets([{ id: 'h', type: 'object', objectName: 'crm_lead', viewName: 'hot' }]).has(targetKeyFor('view', 'crm_lead.hot'))).toBe(true); + }); + + it('an entry without an id gets one no entry holds; groups are listed with their depth', () => { + const served: Menu = [{ type: 'object', objectName: 'a' }, { id: 'nav_item_1', type: 'group', children: [{ type: 'page', pageName: 'p' }] }]; + const withIds = withEntryIds(served); + expect(ids(withIds)).toEqual(['nav_item_2', ['nav_item_1', ['nav_item_3']]]); + expect(withEntryIds(MENU)).toBe(MENU); + expect(newEntryId(withIds)).toBe('nav_item_4'); + expect(groupsOf(MENU).map((g) => [g.id, g.depth])).toEqual([ + ['sales', 0], + ['insights', 0], + ]); + }); +}); + +describe('the edits replayed on the stored menu (objectstack#36363, review 7081226692)', () => { + const STORED: Menu = [ + { id: 'a', type: 'object', objectName: 'a', label: 'A' }, + { id: 'hidden', type: 'object', objectName: 'h', label: 'H' }, + { id: 'b', type: 'object', objectName: 'b', label: 'B' }, + { id: 'g', type: 'group', label: 'G', children: [{ id: 'c', type: 'object', objectName: 'c', label: 'C' }] }, + ]; + const SERVED: Menu = [ + { id: 'a', type: 'object', objectName: 'a', label: 'α' }, + { id: 'b', type: 'object', objectName: 'b', label: 'β' }, + { id: 'g', type: 'group', label: 'γ', children: [{ id: 'c', type: 'object', objectName: 'c', label: 'ς' }] }, + ]; + + it('no edit is the stored menu itself', () => { + expect(rebaseMenuEdits(SERVED, SERVED, STORED)).toBe(STORED); + }); + + it('a removal beside an entry does not move it', () => { + const out = rebaseMenuEdits(SERVED, removeEntry(SERVED, 'a'), STORED); + expect(out.map((e) => e.id)).toEqual(['hidden', 'b', 'g']); + expect(out[1]).toBe(STORED[2]); + }); + + it('a move to another group takes the stored entry there, after the entry before it', () => { + const out = rebaseMenuEdits(SERVED, moveEntry(SERVED, 'b', 'g', 0), STORED); + expect(out.map((e) => e.id)).toEqual(['a', 'hidden', 'g']); + expect(out[2].children).toEqual([STORED[2], (STORED[3].children as Menu)[0]]); + }); + + it('a group the stored menu lacks puts the entry at the top level', () => { + const stored = STORED.filter((e) => e.id !== 'g'); + const out = rebaseMenuEdits(SERVED, moveEntry(SERVED, 'a', 'g', 1), stored); + expect(out.map((e) => e.id)).toEqual(['hidden', 'b', 'a']); + }); + + it('the stored entry behind each served one, an id-less one matched by its target', () => { + const stored: Menu = [{ type: 'object', objectName: 'a', label: 'A' }, { type: 'object', objectName: 'h' }]; + const served = withEntryIds([{ type: 'object', objectName: 'a', label: 'α' }]); + const byId = storedEntriesById(served, stored); + expect(byId.get(String(served[0].id))).toBe(stored[0]); + expect(byId.size).toBe(1); + }); + + // M1 on review 7082970423: another package's entry is never written from its served copy. + it("a move beside another package's entry writes no entry of that package's", () => { + const stored: Menu = [ + { id: 'lead', type: 'object', objectName: 'crm_lead', label: 'Leads' }, + { id: 'account', type: 'object', objectName: 'crm_account', label: 'Accounts' }, + ]; + const served: Menu = [ + { id: 'lead', type: 'object', objectName: 'crm_lead', label: '线索' }, + { id: 'account', type: 'object', objectName: 'crm_account', label: '客户' }, + { id: 'quote', type: 'object', objectName: 'crm_quote', label: '报价' }, + ]; + expect(rebaseMenuEdits(served, moveBy(served, 'account', 1), stored)).toBe(stored); + expect(rebaseMenuEdits(served, moveBy(served, 'quote', -1), stored)).toBe(stored); + const swapped = rebaseMenuEdits(served, moveEntry(served, 'quote', null, 0), stored); + expect(swapped).toBe(stored); + }); + + it('an entry moved after it left the stored menu is not written back', () => { + const stored: Menu = [{ id: 'a', type: 'object', objectName: 'a', label: 'A' }]; + const served: Menu = [ + { id: 'a', type: 'object', objectName: 'a', label: 'α' }, + { id: 'b', type: 'object', objectName: 'b', label: 'β' }, + ]; + expect(rebaseMenuEdits(served, moveBy(served, 'b', -1), stored)).toEqual(stored); + }); + + // S2 on review 7082970423: ids the reader was shown are not ids the stored menu holds. + it('an added entry whose id a hidden stored entry holds is written under a fresh id', () => { + const hidden = { id: 'nav_item_1', type: 'object', objectName: 'hr_payroll', label: 'Payroll' }; + const stored: Menu = [{ id: 'lead', type: 'object', objectName: 'crm_lead', label: 'Leads' }, hidden]; + const served: Menu = [{ id: 'lead', type: 'object', objectName: 'crm_lead', label: '线索' }]; + const added = entryFor('object', 'crm_case', newEntryId(served)); + expect(added.id).toBe('nav_item_1'); + const out = rebaseMenuEdits(served, insertEntry(served, null, 1, added), stored); + expect(out).toEqual([stored[0], { ...added, id: 'nav_item_2' }, hidden]); + expect(out[2]).toBe(hidden); + }); + + it('a served entry given the id a hidden stored entry holds is matched by its target, not that id', () => { + const hidden = { id: 'nav_item_1', type: 'object', objectName: 'hr_payroll', label: 'Payroll' }; + const lead = { type: 'object', objectName: 'crm_lead', label: 'Leads' }; + const stored: Menu = [lead, hidden]; + const served = withEntryIds([{ type: 'object', objectName: 'crm_lead', label: '线索' }]); + expect(served[0].id).toBe('nav_item_1'); + expect(rebaseMenuEdits(served, removeEntry(served, 'nav_item_1'), stored)).toEqual([hidden]); + expect(storedEntriesById(served, stored).get('nav_item_1')).toBe(lead); + }); +}); 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 new file mode 100644 index 00000000000..8aeeddb2e4d --- /dev/null +++ b/ui/packages/app-shell/src/layout/__tests__/designModeMenuSave-36363.test.ts @@ -0,0 +1,235 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The write behind the design mode's 「Save」 for the app's menu + * (objectstack#36363): where Studio's menu editing writes it, published at + * once, never over somebody's pending draft, and composed from the app as + * STORED, never as served (review 7081226692): the served menu is translated + * for the reader and pruned of what the reader may not open. + */ + +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const emitMetadataRefresh = vi.hoisted(() => vi.fn()); +vi.mock('../../assistant/assistantBus', async (importOriginal) => ({ + ...(await importOriginal>()), + emitMetadataRefresh, +})); + +import { withEntryIds, moveBy, insertEntry, patchEntry, type Menu } from '../designModeMenu'; +import { isSameLanguage, saveAppMenu, type AppMenuSaveDoors } from '../designModeMenuSave'; + +const TEXTS = { notListed: 'not listed', pendingDraft: 'pending draft', noVersion: 'no version', notWritable: 'not writable' }; +const NAV = [{ id: 'leads', type: 'object', objectName: 'crm_lead' }]; + +function doors(opts: { + writable: boolean; + version?: string; + stored?: Menu; + pairWritable?: boolean; + save?: () => Promise; + publish?: () => Promise; +}) { + const calls: Array<[string, ...unknown[]]> = []; + const d: AppMenuSaveDoors = { + listPackages: async () => + new Map([ + ['com.acme.crm', { id: 'com.acme.crm', name: 'CRM', writable: opts.writable, manifest: opts.version ? { version: opts.version } : {} }], + ]), + ensureCustomization: async (base) => { + calls.push(['ensure', base]); + return { basePackageId: base, packageId: `${base}.custom`, namespace: 'crm_custom', created: false, writable: opts.pairWritable ?? true }; + }, + client: { + layered: async (...args) => { + calls.push(['layered', ...args]); + const code = { name: 'crm', label: 'CRM', navigation: opts.stored ?? [], _packageId: 'com.acme.crm', _diagnostics: [] }; + return { code, effective: code }; + }, + save: async (...args) => { + calls.push(['save', ...args]); + return opts.save ? opts.save() : {}; + }, + publish: async (...args) => { + calls.push(['publish', ...args]); + return opts.publish ? opts.publish() : {}; + }, + reset: async (...args) => { + calls.push(['reset', ...args]); + return {}; + }, + }, + }; + return { d, calls }; +} + +/** The navigation the save wrote. */ +const savedNav = (calls: Array<[string, ...unknown[]]>) => + (calls.find(([c]) => c === 'save')![3] as { navigation: Menu }).navigation; + +beforeEach(() => emitMetadataRefresh.mockReset()); + +describe('saving the app menu (objectstack#36363)', () => { + it('a writable package: the stored app with its new menu, saved there as a draft and published', async () => { + const { d, calls } = doors({ writable: true }); + await saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served: [], navigation: NAV }, TEXTS, d); + expect(calls).toEqual([ + ['layered', 'app', 'crm', { packageId: 'com.acme.crm' }], + ['save', 'app', 'crm', { name: 'crm', label: 'CRM', navigation: NAV }, { mode: 'draft', packageId: 'com.acme.crm', ifNoneMatch: '*' }], + ['publish', 'app', 'crm', { packageId: 'com.acme.crm' }], + ]); + expect(emitMetadataRefresh).toHaveBeenCalledTimes(1); + }); + + it("an installed (read-only) package: saved into its customization package, declaring the override at the base's version", async () => { + const { d, calls } = doors({ writable: false, version: '6.5.0' }); + await saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served: [], navigation: NAV }, TEXTS, d); + expect(calls).toEqual([ + ['layered', 'app', 'crm', { packageId: 'com.acme.crm' }], + ['ensure', 'com.acme.crm'], + [ + 'save', + 'app', + 'crm', + { name: 'crm', label: 'CRM', navigation: NAV, overrides: { package: 'com.acme.crm', basedOn: '6.5.0' } }, + { mode: 'draft', packageId: 'com.acme.crm.custom', ifNoneMatch: '*' }, + ], + ['publish', 'app', 'crm', { packageId: 'com.acme.crm.custom' }], + ]); + }); + + it('a read-only package that states no version is refused before anything is created or written', async () => { + const { d, calls } = doors({ writable: false }); + await expect(saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served: [], navigation: NAV }, TEXTS, d)).rejects.toThrow('no version'); + expect(calls.map(([c]) => c)).toEqual(['layered']); + }); + + it('a customization package the server answers not writable is refused before anything is written to it', async () => { + const { d, calls } = doors({ writable: false, version: '6.5.0', pairWritable: false }); + await expect(saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served: [], navigation: NAV }, TEXTS, d)).rejects.toThrow('not writable'); + expect(calls.map(([c]) => c)).toEqual(['layered', 'ensure']); + }); + + it('a package the server does not list is refused, before anything is read', async () => { + const { d, calls } = doors({ writable: true }); + await expect(saveAppMenu({ appName: 'crm', packageId: 'com.other', served: [], navigation: NAV }, TEXTS, d)).rejects.toThrow('not listed'); + expect(calls).toEqual([]); + }); + + it("a draft already pending is not overwritten nor published: the save says so", async () => { + const conflict = Object.assign(new Error('conflict'), { status: 409, code: 'METADATA_CONFLICT' }); + const { d, calls } = doors({ writable: true, save: () => Promise.reject(conflict) }); + await expect(saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served: [], navigation: NAV }, TEXTS, d)).rejects.toThrow('pending draft'); + expect(calls.map(([c]) => c)).toEqual(['layered', 'save']); + expect(emitMetadataRefresh).not.toHaveBeenCalled(); + }); + + it('a refused publish discards the draft this save wrote, and the refusal is passed on', async () => { + const { d, calls } = doors({ writable: true, publish: () => Promise.reject(new Error('Package is read-only')) }); + await expect(saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served: [], navigation: NAV }, TEXTS, d)).rejects.toThrow('Package is read-only'); + expect(calls.map(([c]) => c)).toEqual(['layered', 'save', 'publish', 'reset']); + expect(calls[3]).toEqual(['reset', 'app', 'crm', { state: 'draft', packageId: 'com.acme.crm' }]); + }); +}); + +describe('the save writes the stored menu with the edits, never the served one (review 7081226692)', () => { + // As stored: the source-language labels, and an entry this reader may not open. + const STORED: Menu = [ + { id: 'leads', type: 'object', objectName: 'crm_lead', label: 'Leads' }, + { id: 'payroll', type: 'object', objectName: 'hr_payroll', label: 'Payroll', requiredPermissions: ['hr.admin'] }, + { id: 'accounts', type: 'object', objectName: 'crm_account', label: 'Accounts' }, + { id: 'sales', type: 'group', label: 'Sales', children: [{ id: 'cases', type: 'object', objectName: 'crm_case', label: 'Cases' }] }, + ]; + // As served to a zh-CN reader without hr.admin: translated, payroll pruned. + const SERVED: Menu = [ + { id: 'leads', type: 'object', objectName: 'crm_lead', label: '线索' }, + { id: 'accounts', type: 'object', objectName: 'crm_account', label: '客户' }, + { id: 'sales', type: 'group', label: '销售', children: [{ id: 'cases', type: 'object', objectName: 'crm_case', label: '工单' }] }, + ]; + + it('a move under a translated menu writes the stored labels, every untouched entry byte for byte', async () => { + const { d, calls } = doors({ writable: true, stored: STORED }); + const edited = moveBy(SERVED, 'accounts', -1); + await saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served: SERVED, navigation: edited }, TEXTS, d); + const nav = savedNav(calls); + // The entry moved is put before the one it passed; the pruned one keeps its stored place. + expect(nav.map((e) => e.label)).toEqual(['Accounts', 'Leads', 'Payroll', 'Sales']); + expect(JSON.stringify(nav)).not.toMatch(/线索|客户|销售|工单/); + // Untouched: the same stored objects. + expect(nav[1]).toBe(STORED[0]); + expect(nav[3]).toBe(STORED[3]); + }); + + it('an entry pruned from the reader stays in the stored menu, where it was', async () => { + const { d, calls } = doors({ writable: true, stored: STORED }); + const added = { id: 'reports', type: 'report', reportName: 'pipeline', label: 'Pipeline' }; + const edited = insertEntry(SERVED, 'sales', 1, added); + await saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served: SERVED, navigation: edited }, TEXTS, d); + const nav = savedNav(calls); + expect(nav.slice(0, 3)).toEqual(STORED.slice(0, 3)); + expect(nav[1]).toBe(STORED[1]); + expect((nav[3].children as Menu).map((e) => e.id)).toEqual(['cases', 'reports']); + }); + + it('a rename writes the one key it changed; a removal removes only that entry', async () => { + const { d, calls } = doors({ writable: true, stored: STORED }); + let edited = patchEntry(SERVED, 'cases', { label: 'Tickets' }); + edited = edited.filter((e) => e.id !== 'leads'); + await saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served: SERVED, navigation: edited }, TEXTS, d); + const nav = savedNav(calls); + expect(nav.map((e) => e.id)).toEqual(['payroll', 'accounts', 'sales']); + expect(nav[2].children).toEqual([{ id: 'cases', type: 'object', objectName: 'crm_case', label: 'Tickets' }]); + }); + + it('stored entries without an id are matched by their target and written without one', async () => { + const idless: Menu = [ + { type: 'object', objectName: 'crm_lead', label: 'Leads' }, + { type: 'object', objectName: 'hr_payroll', label: 'Payroll' }, + { type: 'object', objectName: 'crm_account', label: 'Accounts' }, + ]; + // The served copy, payroll pruned, given ids as the editor gives them. + const served = withEntryIds([ + { type: 'object', objectName: 'crm_lead', label: '线索' }, + { type: 'object', objectName: 'crm_account', label: '客户' }, + ]); + const { d, calls } = doors({ writable: true, stored: idless }); + const edited = moveBy(served, String(served[1].id), -1); + await saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served, navigation: edited }, TEXTS, d); + expect(savedNav(calls)).toEqual([idless[2], idless[0], idless[1]]); + }); + + it("a move beside another package's entry writes none of that package's entries (M1)", async () => { + // The revenue module's Quotes, appended to Sales when the app is served; not stored. + const served: Menu = SERVED.map((e) => + e.id === 'sales' + ? { ...e, children: [...(e.children as Menu), { id: 'quote', type: 'object', objectName: 'crm_quote', label: '报价' }] } + : e, + ); + const { d, calls } = doors({ writable: true, stored: STORED }); + await saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served, navigation: moveBy(served, 'quote', -1) }, TEXTS, d); + expect(savedNav(calls)).toEqual(STORED); + expect(JSON.stringify(savedNav(calls))).not.toMatch(/quote|报价/); + }); + + it('an entry naming no target is left out of the save (N3)', async () => { + const { d, calls } = doors({ writable: true, stored: STORED }); + const edited = insertEntry(SERVED, null, 0, { id: 'blank', type: 'object' }); + await saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served: SERVED, navigation: edited }, TEXTS, d); + expect(savedNav(calls)).toEqual(STORED); + }); +}); + +describe('the session language against the default one', () => { + it.each([ + ['en', 'en', true], + ['EN-us', 'en-US', true], + ['en', 'en-US', true], + ['zh-CN', 'zh-CN', true], + ['zh_CN', 'zh-CN', true], + ['zh-CN', 'en', false], + ['zh-CN', 'zh-TW', false], + ['', 'en', false], + ])('%s against %s: %s', (language, locale, same) => { + expect(isSameLanguage(language, locale)).toBe(same); + }); +}); diff --git a/ui/packages/app-shell/src/layout/designMode.tsx b/ui/packages/app-shell/src/layout/designMode.tsx index 52e647e7724..67099e4e49e 100644 --- a/ui/packages/app-shell/src/layout/designMode.tsx +++ b/ui/packages/app-shell/src/layout/designMode.tsx @@ -37,8 +37,12 @@ * does not ask: the mode, and what it holds, go along. * * Who may enter is the header button's gate (`useAppStudioEntry`, a workspace - * administrator holding `manage_metadata` on a writable package), read where - * the button is drawn. The mode has no address: no URL enters it. Each + * administrator holding `manage_metadata`), read where the button is drawn + * (`ShellPageActions`). The app's package need not be writable: a read-only + * (installed) package's app enters too, and what the mode saves goes to that + * package's customization package, as Studio's edits do, except where the + * customization door is walled off for the caller. The mode has no address: + * no URL enters it. Each * change's `commit` is a write the server judges again. * * @module diff --git a/ui/packages/app-shell/src/layout/designModeMenu.ts b/ui/packages/app-shell/src/layout/designModeMenu.ts new file mode 100644 index 00000000000..ad45602e297 --- /dev/null +++ b/ui/packages/app-shell/src/layout/designModeMenu.ts @@ -0,0 +1,616 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The app's menu under the design mode (objectstack#36363): the edits the + * sidebar's menu editor (`DesignModeMenu.tsx`) makes to the app's + * `navigation`, as pure functions of the tree. Every function answers a new + * tree and leaves the one it was given untouched, so a staged menu is never + * changed in place. + * + * An entry is addressed by its `id`. The served tree may hold an entry + * without one (the spec makes it optional): {@link withEntryIds} gives each + * such entry an id by its place before the first edit, so an edit never + * addresses an entry by a place that a previous edit moved. + * + * A group is an entry of `type: 'group'` holding `children`. Groups are not + * added, removed or renamed here (out of the card); entries move within a + * group, between groups and to the menu's top level. + * + * @module + */ + +/** One menu entry, as the app document holds it. */ +export type MenuEntry = Readonly> & { readonly id?: unknown; readonly type?: unknown }; + +/** A menu: the app's `navigation`. */ +export type Menu = ReadonlyArray; + +/** Where an entry sits: the group holding it (`null` for the top level) and its index there. */ +export interface MenuPlace { + readonly parentId: string | null; + readonly index: number; +} + +/** The kinds of existing thing the picker adds (objectstack#36363 item 2). */ +export const MENU_TARGET_KINDS = ['object', 'view', 'dashboard', 'report', 'page', 'url'] as const; +export type MenuTargetKind = (typeof MENU_TARGET_KINDS)[number]; + +export function isGroup(entry: MenuEntry): boolean { + return entry.type === 'group'; +} + +function childrenOf(entry: MenuEntry): Menu { + return Array.isArray(entry.children) ? (entry.children as Menu) : []; +} + +function idOf(entry: MenuEntry): string | null { + return typeof entry.id === 'string' && entry.id ? entry.id : null; +} + +/** + * The tree with an id on every entry: an entry without one gets + * `nav_item_`, the first `n` from 1 that no entry of the tree holds. The + * answer is the tree given when every entry already has an id. + */ +export function withEntryIds(menu: Menu): Menu { + const taken = new Set(); + const collect = (entries: Menu) => { + for (const entry of entries) { + const id = idOf(entry); + if (id) taken.add(id); + collect(childrenOf(entry)); + } + }; + collect(menu); + let next = 1; + let changed = false; + const fresh = () => { + while (taken.has(`nav_item_${next}`)) next += 1; + const id = `nav_item_${next}`; + taken.add(id); + return id; + }; + const walk = (entries: Menu): Menu => { + const next = entries.map((entry) => { + const kids = Array.isArray(entry.children) ? walk(entry.children as Menu) : null; + const id = idOf(entry); + if (id && (kids === null || kids === entry.children)) return entry; + changed = true; + return { ...entry, ...(id ? {} : { id: fresh() }), ...(kids ? { children: kids } : {}) }; + }); + return next.every((entry, i) => entry === entries[i]) ? entries : next; + }; + const answer = walk(menu); + return changed ? answer : menu; +} + +/** A new entry id no entry of `menu` holds. */ +export function newEntryId(menu: Menu, stem = 'nav_item'): string { + const taken = new Set(); + const collect = (entries: Menu) => { + for (const entry of entries) { + const id = idOf(entry); + if (id) taken.add(id); + collect(childrenOf(entry)); + } + }; + collect(menu); + let n = 1; + while (taken.has(`${stem}_${n}`)) n += 1; + return `${stem}_${n}`; +} + +/** Where the entry `id` sits, or `null` when no entry has it. */ +export function placeOf(menu: Menu, id: string): MenuPlace | null { + const walk = (entries: Menu, parentId: string | null): MenuPlace | null => { + for (let i = 0; i < entries.length; i += 1) { + const entry = entries[i]; + if (idOf(entry) === id) return { parentId, index: i }; + if (isGroup(entry)) { + const found = walk(childrenOf(entry), idOf(entry)); + if (found) return found; + } + } + return null; + }; + return walk(menu, null); +} + +/** The entry `id`, or `null`. */ +export function entryOf(menu: Menu, id: string): MenuEntry | null { + const place = placeOf(menu, id); + return place ? siblingsAt(menu, place.parentId)?.[place.index] ?? null : null; +} + +/** The entries of the group `parentId` (the top level for `null`), or `null` when there is no such group. */ +export function siblingsAt(menu: Menu, parentId: string | null): Menu | null { + if (parentId === null) return menu; + const group = entryOf(menu, parentId); + return group && isGroup(group) ? childrenOf(group) : null; +} + +/** `menu` with the entries of the group `parentId` (the top level for `null`) replaced. */ +function withSiblings(menu: Menu, parentId: string | null, entries: Menu): Menu { + if (parentId === null) return entries; + const walk = (list: Menu): Menu => + list.map((entry) => { + if (!isGroup(entry)) return entry; + if (idOf(entry) === parentId) return { ...entry, children: entries }; + const kids = childrenOf(entry); + const next = walk(kids); + return next === kids || next.every((e, i) => e === kids[i]) ? entry : { ...entry, children: next }; + }); + return walk(menu); +} + +/** Every group of the menu, in reading order, with its depth (0 for a top-level group). */ +export function groupsOf(menu: Menu): Array<{ id: string; entry: MenuEntry; depth: number }> { + const out: Array<{ id: string; entry: MenuEntry; depth: number }> = []; + const walk = (entries: Menu, depth: number) => { + for (const entry of entries) { + const id = idOf(entry); + if (isGroup(entry) && id) { + out.push({ id, entry, depth }); + walk(childrenOf(entry), depth + 1); + } + } + }; + walk(menu, 0); + return out; +} + +/** `menu` without the entry `id` (and, for a group, what it holds). */ +export function removeEntry(menu: Menu, id: string): Menu { + const place = placeOf(menu, id); + if (!place) return menu; + const siblings = siblingsAt(menu, place.parentId) ?? []; + return withSiblings(menu, place.parentId, siblings.filter((_, i) => i !== place.index)); +} + +/** `menu` with `entry` put in the group `parentId` (the top level for `null`) at `index`, clamped to the group's ends. */ +export function insertEntry(menu: Menu, parentId: string | null, index: number, entry: MenuEntry): Menu { + const siblings = siblingsAt(menu, parentId); + if (!siblings) return menu; + const at = Math.max(0, Math.min(index, siblings.length)); + return withSiblings(menu, parentId, [...siblings.slice(0, at), entry, ...siblings.slice(at)]); +} + +/** `menu` with the entry `id` moved one place up (`-1`) or down (`1`) among its group's entries. */ +export function moveBy(menu: Menu, id: string, delta: -1 | 1): Menu { + const place = placeOf(menu, id); + if (!place) return menu; + const siblings = siblingsAt(menu, place.parentId) ?? []; + const to = place.index + delta; + if (to < 0 || to >= siblings.length) return menu; + const next = [...siblings]; + [next[place.index], next[to]] = [next[to], next[place.index]]; + return withSiblings(menu, place.parentId, next); +} + +/** Whether the entry `id` can move up (`-1`) or down (`1`) in its group. */ +export function canMoveBy(menu: Menu, id: string, delta: -1 | 1): boolean { + const place = placeOf(menu, id); + if (!place) return false; + const to = place.index + delta; + return to >= 0 && to < (siblingsAt(menu, place.parentId)?.length ?? 0); +} + +/** Whether `groupId` is `id` itself or a group inside it: an entry cannot move into itself. */ +function holds(menu: Menu, id: string, groupId: string): boolean { + if (id === groupId) return true; + const entry = entryOf(menu, id); + if (!entry || !isGroup(entry)) return false; + return placeOf(childrenOf(entry), groupId) !== null; +} + +/** + * `menu` with the entry `id` moved to the group `parentId` (the top level for + * `null`) at `index` of that group as it reads AFTER the entry has left its + * old place (`Infinity` for its end). A move into the entry itself is no move. + */ +export function moveEntry(menu: Menu, id: string, parentId: string | null, index: number): Menu { + const entry = entryOf(menu, id); + if (!entry) return menu; + if (parentId !== null && holds(menu, id, parentId)) return menu; + const without = removeEntry(menu, id); + if (!siblingsAt(without, parentId)) return menu; + return insertEntry(without, parentId, index, entry); +} + +/** `menu` with `patch` merged into the entry `id`; a key patched to `undefined` is removed. */ +export function patchEntry(menu: Menu, id: string, patch: Record): Menu { + const place = placeOf(menu, id); + if (!place) return menu; + const siblings = siblingsAt(menu, place.parentId) ?? []; + const next: Record = { ...siblings[place.index], ...patch }; + for (const [key, value] of Object.entries(patch)) if (value === undefined) delete next[key]; + return withSiblings( + menu, + place.parentId, + siblings.map((e, i) => (i === place.index ? next : e)), + ); +} + +/** + * What an entry opens, as one key per thing: `object/`, + * `view/` (an object entry that lands on a view), `dashboard/`, + * `report/`, `page/`, `url/`; `null` for a group, a separator or an entry + * that names no target. The picker compares these only with each other + * (`targetKeyFor`); they are no cache key, and are spelled with `/` so they + * never read as the data adapter's `view:` keys. + */ +export function targetKeyOf(entry: MenuEntry): string | null { + const str = (key: string) => (typeof entry[key] === 'string' && entry[key] ? (entry[key] as string) : null); + switch (entry.type) { + case 'object': { + const view = str('viewName'); + const object = str('objectName'); + // A view is named `.`; an entry may name it by its key + // alone (`viewName: 'my_projects'`, as HotCRM's menus do), which is + // the same view of its own object. + if (view) return `view/${view.includes('.') || !object ? view : `${object}.${view}`}`; + // An entry that opens a record or a form is not the object's list. + return object && !str('recordId') && !str('form') ? `object/${object}` : null; + } + case 'dashboard': + return str('dashboardName') ? `dashboard/${str('dashboardName')}` : null; + case 'report': + return str('reportName') ? `report/${str('reportName')}` : null; + case 'page': + return str('pageName') ? `page/${str('pageName')}` : null; + case 'url': + return str('url') ? `url/${str('url')}` : null; + default: + return null; + } +} + +/** Every target the menu opens ({@link targetKeyOf}), at every depth. */ +export function menuTargets(menu: Menu): Set { + const out = new Set(); + const walk = (entries: Menu) => { + for (const entry of entries) { + const key = targetKeyOf(entry); + if (key) out.add(key); + walk(childrenOf(entry)); + } + }; + walk(menu); + return out; +} + +/** The menu entry that opens `name` of `kind`, with `id`; a link takes its `label` and `url`. */ +export function entryFor( + kind: MenuTargetKind, + name: string, + id: string, + link?: { label: string; url: string }, +): MenuEntry { + switch (kind) { + case 'object': + return { id, type: 'object', objectName: name }; + case 'view': { + // A view item is named `.`. + const dot = name.indexOf('.'); + return { id, type: 'object', objectName: dot > 0 ? name.slice(0, dot) : name, viewName: name }; + } + case 'dashboard': + return { id, type: 'dashboard', dashboardName: name }; + case 'report': + return { id, type: 'report', reportName: name }; + case 'page': + return { id, type: 'page', pageName: name }; + case 'url': + return { id, type: 'url', label: link?.label ?? name, url: link?.url ?? name }; + } +} + +/** The {@link targetKeyOf} key the picker's row `name` of `kind` would add. */ +export function targetKeyFor(kind: MenuTargetKind, name: string): string { + return `${kind}/${name}`; +} + +/** An entry's own keys, its `children` left out: what a patch compares. */ +function ownKeys(entry: MenuEntry): Record { + const { children: _children, ...own } = entry as Record; + return own; +} + +interface Located { + readonly entry: MenuEntry; + readonly parentId: string | null; +} + +function locate(menu: Menu, keyOf: (entry: MenuEntry) => string | null): Map { + const out = new Map(); + const walk = (entries: Menu, parentId: string | null) => { + for (const entry of entries) { + const key = keyOf(entry); + if (key) out.set(key, { entry, parentId }); + if (isGroup(entry)) walk(childrenOf(entry), key); + } + }; + walk(menu, null); + return out; +} + +/** + * The key of each stored entry: the id of its served copy, or `null` for a + * stored entry the reader was never shown. + * + * A stored entry with an id is keyed by it only when the served entry of that + * id is the same thing (the same type and target): the editor gives served + * entries without an id the first free `nav_item_` of what the reader was + * shown (`withEntryIds`), which a stored entry pruned from the reader can + * already hold. A stored entry without an id is matched to an unmatched served + * entry by its group, type and target, in order. + */ +interface StoredKeyer { + (entry: MenuEntry): string | null; + /** Give `copy`, a rebuilt or inserted entry, the key `key`. */ + alias(copy: MenuEntry, key: string | null): MenuEntry; +} + +function sameThing(a: MenuEntry, b: MenuEntry): boolean { + return a.type === b.type && targetKeyOf(a) === targetKeyOf(b); +} + +function storedKeyer(served: Menu, stored: Menu): StoredKeyer { + const servedAt = locate(served, idOf); + const keys = new Map(); + const matched = new Set(); + const byId = (entries: Menu) => { + for (const entry of entries) { + const id = idOf(entry); + const copy = id ? servedAt.get(id) : undefined; + if (id && copy && !matched.has(id) && sameThing(copy.entry, entry)) { + keys.set(entry, id); + matched.add(id); + } + if (isGroup(entry)) byId(childrenOf(entry)); + } + }; + byId(stored); + const unclaimed = [...servedAt.entries()].filter(([id]) => !matched.has(id)); + const claim = (entry: MenuEntry, parentId: string | null): string | null => { + const at = unclaimed.findIndex(([, s]) => s.parentId === parentId && sameThing(s.entry, entry)); + if (at < 0) return null; + const [[id]] = unclaimed.splice(at, 1); + return id; + }; + // `undefined`: the group was never shown, so nothing in it can be claimed. + const adopt = (entries: Menu, parentId: string | null | undefined) => { + for (const entry of entries) { + let key = keys.get(entry) ?? null; + if (!key && !idOf(entry) && parentId !== undefined) { + key = claim(entry, parentId); + if (key) keys.set(entry, key); + } + if (isGroup(entry)) adopt(childrenOf(entry), key ?? undefined); + } + }; + adopt(stored, null); + const keyOf = ((entry: MenuEntry) => keys.get(entry) ?? null) as StoredKeyer; + keyOf.alias = (copy, key) => { + if (key) keys.set(copy, key); + return copy; + }; + return keyOf; +} + +/** The stored entry behind each served entry, by the served entry's id. */ +export function storedEntriesById(served: Menu, stored: Menu): Map { + const keyOf = storedKeyer(served, stored); + const out = new Map(); + locate(stored, keyOf).forEach((located, id) => out.set(id, located.entry)); + return out; +} + +/** + * The served entries that keep their place: in the same group, and in the + * longest run of that group's entries whose order the edits kept (so a + * removal or an addition beside an entry does not move it, and of two + * entries swapped one is moved, the later one in the served order). Only + * the entries `counted` holds take part: an entry of another package's is + * neither moved nor a reason to move one. + */ +function staysInOrder(served: Map, edited: Map, counted: (id: string) => boolean): Set { + const groups = new Map(); + const groupOf = (parentId: string | null) => { + let g = groups.get(parentId); + if (!g) groups.set(parentId, (g = { was: [], now: [] })); + return g; + }; + served.forEach((was, id) => { + if (counted(id) && edited.get(id)?.parentId === was.parentId) groupOf(was.parentId).was.push(id); + }); + edited.forEach((now, id) => { + if (counted(id) && served.get(id)?.parentId === now.parentId) groupOf(now.parentId).now.push(id); + }); + const out = new Set(); + groups.forEach(({ was, now }) => { + // The longest common subsequence of the two orders. + const n = was.length; + const m = now.length; + const len: number[][] = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0)); + for (let i = n - 1; i >= 0; i -= 1) { + for (let j = m - 1; j >= 0; j -= 1) { + len[i][j] = was[i] === now[j] ? len[i + 1][j + 1] + 1 : Math.max(len[i + 1][j], len[i][j + 1]); + } + } + for (let i = 0, j = 0; i < n && j < m; ) { + if (was[i] === now[j]) { + out.add(was[i]); + i += 1; + j += 1; + } else if (len[i + 1][j] > len[i][j + 1]) i += 1; + else j += 1; + } + }); + return out; +} + +/** + * The edits made to `served` (the tree the editor was seeded from, every + * entry with an id) that turned it into `edited`, applied by entry id to + * `stored`, the app's navigation as stored (objectstack#36363). + * + * The served tree is not what is stored: its labels are translated for the + * reader's language (`translateApp`), and entries the reader may not open + * are pruned from it (`filterNav`). So the save never writes it back. It + * writes `stored` with the edits replayed on it: + * + * - an entry `edited` no longer holds is removed; + * - an entry `edited` adds is put in its group after the entry before it; + * - an entry moved (to another group, or out of the order its group's other + * entries kept, `staysInOrder`) is taken out and put back after the entry + * before it in `edited`, its stored keys kept; + * - an entry whose own keys changed (a rename, an icon) has those keys + * written, and only those: a key it did not change keeps its stored value. + * + * Every other stored entry, one the reader was never shown included, stays + * where it was and is the same object. Stored entries are matched to their + * served copies by `storedKeyer`. + * + * Nothing the stored menu does not hold is ever written from its served + * copy: an entry another package puts into the menu (`navigationContributions`, + * appended when the app is served), or one that has left the stored menu + * since the editor read it, is not moved, patched or written, and takes no + * part in the order comparison. Only an entry `served` does not hold is an + * addition; one whose id a stored entry already holds is written under a + * fresh `nav_item_` that neither menu holds. + */ +export function rebaseMenuEdits(served: Menu, edited: Menu, stored: Menu): Menu { + const keyOf = storedKeyer(served, stored); + const s = locate(served, idOf); + const e = locate(edited, idOf); + const storedKeys = new Set(locate(stored, keyOf).keys()); + /** A served entry the stored menu does not hold: never written from its served copy. */ + const foreign = (id: string) => s.has(id) && !storedKeys.has(id); + const removed = new Set([...s.keys()].filter((id) => !e.has(id))); + const stays = staysInOrder(s, e, (id) => !foreign(id)); + const placed: string[] = []; + const patches = new Map>(); + e.forEach((now, id) => { + const was = s.get(id); + if (!was) { + placed.push(id); + return; + } + if (foreign(id)) return; + if (!stays.has(id)) placed.push(id); + const before = ownKeys(was.entry); + const after = ownKeys(now.entry); + const patch: Record = {}; + for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) { + if (JSON.stringify(before[key]) !== JSON.stringify(after[key])) patch[key] = after[key]; + } + if (Object.keys(patch).length > 0) patches.set(id, patch); + }); + const lifted = new Set(placed); + + // The stored entries a moved one takes along, by key, each with its patch. + const taken = new Map(); + const patched = (entry: MenuEntry, key: string | null): MenuEntry => { + const patch = key ? patches.get(key) : undefined; + if (!patch) return entry; + const next: Record = { ...entry, ...patch }; + for (const [k, v] of Object.entries(patch)) if (v === undefined) delete next[k]; + return keyOf.alias(next, key); + }; + const strip = (entries: Menu): Menu => { + const out: MenuEntry[] = []; + let changed = false; + for (const entry of entries) { + const key = keyOf(entry); + if (key && removed.has(key)) { + changed = true; + continue; + } + let next = entry; + if (isGroup(entry)) { + const kids = childrenOf(entry); + const kept = strip(kids); + if (kept !== kids) next = keyOf.alias({ ...entry, children: kept }, key); + } + next = patched(next, key); + if (key && lifted.has(key)) { + taken.set(key, next); + changed = true; + continue; + } + if (next !== entry) changed = true; + out.push(next); + } + return changed ? out : entries; + }; + let result = strip(stored); + + // Put each placed entry back, in the edited tree's reading order, after the + // nearest entry before it in `edited` that the result holds. + const holdsKey = (menu: Menu, key: string) => { + const walk = (entries: Menu): boolean => entries.some((x) => keyOf(x) === key || (isGroup(x) && walk(childrenOf(x)))); + return walk(menu); + }; + const indexIn = (entries: Menu, key: string) => entries.findIndex((x) => keyOf(x) === key); + const groupEntries = (menu: Menu, parentId: string | null): Menu | null => { + if (parentId === null) return menu; + let found: Menu | null = null; + const walk = (entries: Menu) => { + for (const x of entries) { + if (found) return; + if (keyOf(x) === parentId && isGroup(x)) found = childrenOf(x); + else if (isGroup(x)) walk(childrenOf(x)); + } + }; + walk(menu); + return found; + }; + const replaceGroup = (menu: Menu, parentId: string | null, entries: Menu): Menu => { + if (parentId === null) return entries; + return menu.map((x) => { + if (!isGroup(x)) return x; + if (keyOf(x) === parentId) return keyOf.alias({ ...x, children: entries }, parentId); + const kids = childrenOf(x); + const next = replaceGroup(kids, parentId, entries); + return next === kids || next.every((k, i) => k === kids[i]) ? x : keyOf.alias({ ...x, children: next }, keyOf(x)); + }); + }; + const editedSiblings = (parentId: string | null): string[] => { + const group = parentId === null ? edited : siblingsAt(edited, parentId) ?? []; + return group.map((x) => idOf(x)).filter((x): x is string => !!x); + }; + // The ids a written entry may not take: every id either menu holds. + const heldIds = new Set([...locate(stored, idOf).keys(), ...s.keys(), ...e.keys()]); + let fresh = 1; + const freshId = () => { + while (heldIds.has(`nav_item_${fresh}`)) fresh += 1; + const id = `nav_item_${fresh}`; + heldIds.add(id); + return id; + }; + const storedIds = new Set(locate(stored, idOf).keys()); + for (const id of placed) { + const now = e.get(id)!; + let entry: MenuEntry; + if (taken.has(id)) entry = taken.get(id)!; + else if (!s.has(id)) entry = keyOf.alias(storedIds.has(id) ? { ...now.entry, id: freshId() } : now.entry, id); + else continue; + // A group the stored menu lacks: the entry goes to the end of the top level. + const lost = now.parentId !== null && !groupEntries(result, now.parentId); + const parentId = lost ? null : now.parentId; + const siblings = groupEntries(result, parentId) ?? []; + const order = editedSiblings(now.parentId); + let at = lost ? siblings.length : 0; + for (let i = lost ? -1 : order.indexOf(id) - 1; i >= 0; i -= 1) { + const before = indexIn(siblings, order[i]); + if (before >= 0) { + at = before + 1; + break; + } + } + if (holdsKey(result, id)) continue; + result = replaceGroup(result, parentId, [...siblings.slice(0, at), entry, ...siblings.slice(at)]); + } + return result; +} diff --git a/ui/packages/app-shell/src/layout/designModeMenuSave.ts b/ui/packages/app-shell/src/layout/designModeMenuSave.ts new file mode 100644 index 00000000000..1a67c611f5a --- /dev/null +++ b/ui/packages/app-shell/src/layout/designModeMenuSave.ts @@ -0,0 +1,208 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The write behind the design mode's 「Save」 for the app's menu + * (objectstack#36363): the app document with its new `navigation`, written + * where Studio's menu editing writes it and published at once, so everyone + * sees it. + * + * Where it is written is Studio's rule (`StudioDesignSurface`'s nav save, + * objectstack#30059, ADR-0146 D2/D3): the app's own package when the server + * lists it writable, else the base's paired customization package, asked of + * the ensure door (which creates it on first use and names it), the body + * declaring the override of the base at the base's listed version + * (`overrideDraftBody`). An installed app's menu is thereby a customization + * of this environment, as Studio's is. + * + * What is written is the app as STORED, never as served (objectstack#36363, + * review 7081226692): the served app is translated for the reader's language + * (`translateApp`) and pruned of entries the reader may not open + * (`filterNav`), so writing it back would store the reader's language on + * every label and drop what the reader was not shown. The stored app is the + * layered read (`/layers`, which serves a caller who may write the app its + * stored version, unpruned and untranslated), and the menu edits are + * replayed on its navigation by entry id (`rebaseMenuEdits`); an entry + * naming no target is left out (`navPayloadOf`, as Studio's nav save). + * + * 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. + * + * How it is written is the runtime's confirmed-save rule + * (`saveAndPublishRuntimeMetadata`, objectstack#35955): the draft is written + * with the first-write pin, so a draft somebody left pending (in Studio, say) + * is refused, never overwritten nor published on its saver's behalf, and the + * refusal is said; a publish the server refuses discards the draft this save + * wrote. A landed publish announces itself (`emitMetadataRefresh`), and the + * console re-reads the app, its menu included. + * + * @module + */ + +import { stripReadDecorations } from '@objectstack/spec/kernel'; +import { emitMetadataRefresh } from '../assistant/assistantBus.js'; +import { isDraftVersionConflict } from '../views/metadata-admin/DraftConflictDialog.js'; +import { overrideDraftBody } from '../views/studio-design/StudioCustomizeControls.js'; +import { + ensureCustomizationPackage, + fetchListedPackageManifests, + listedPackageVersion, + type EnsuredCustomizationPackage, + type ListedPackageManifest, +} from '../views/studio-design/packages-io.js'; +import { navPayloadOf } from '../views/metadata-admin/previews/AppNavCanvas.js'; +import { rebaseMenuEdits, type Menu } from './designModeMenu.js'; + +/** The doors the save goes through; the defaults are the console's own. */ +export interface AppMenuSaveDoors { + readonly listPackages: () => Promise>; + readonly ensureCustomization: (basePackageId: string) => Promise; + readonly client: { + layered: (type: string, name: string, options: { packageId?: string }) => Promise; + save: (type: string, name: string, body: unknown, options: Record) => Promise; + publish: (type: string, name: string, options: { packageId?: string }) => Promise; + reset: (type: string, name: string, options: Record) => Promise; + }; +} + +/** The sentences a refused save is said with, in the viewer's language. */ +export interface AppMenuSaveTexts { + /** The app's package is not one the server lists. */ + readonly notListed: string; + /** A draft of the app is already pending. */ + readonly pendingDraft: string; + /** The base's listed manifest states no version to declare the override at. */ + readonly noVersion: string; + /** The customization package the server answered is not writable. */ + readonly notWritable: string; +} + +/** A document as stored, less what a read adds and what belongs to its package. */ +function documentOf(read: unknown): Record { + const body = stripReadDecorations((read ?? {}) as Record) as Record; + const doc: Record = {}; + for (const [key, value] of Object.entries(body)) if (!key.startsWith('_')) doc[key] = value; + return doc; +} + +/** The stored app of a layered read: its effective layer (the override folded over the base), else its code. */ +function storedApp(layers: unknown): Record { + const read = (layers ?? {}) as { effective?: unknown; code?: unknown }; + return documentOf(read.effective ?? read.code ?? {}); +} + +/** + * Save the menu edits that turned `served` (the menu the editor was seeded + * from) into `navigation`, as the menu of the app `appName` of the package + * `packageId`, and publish it. + */ +export async function saveAppMenu( + input: { appName: string; packageId: string; served: Menu; navigation: Menu }, + texts: AppMenuSaveTexts, + doors: AppMenuSaveDoors, +): Promise { + const { appName, packageId, served, navigation } = input; + const manifests = await doors.listPackages(); + const listed = manifests.get(packageId); + if (!listed) throw new Error(texts.notListed); + // 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[]); + let body: Record | null = { ...stored, name: appName, navigation: nextNav }; + let target = packageId; + if (!listed.writable) { + body = overrideDraftBody(body, packageId, listedPackageVersion(manifests, packageId)); + if (body === null) throw new Error(texts.noVersion); + const pair = await doors.ensureCustomization(packageId); + if (!pair.writable) throw new Error(texts.notWritable); + target = pair.packageId; + } + try { + await doors.client.save('app', appName, body, { mode: 'draft', packageId: target, ifNoneMatch: '*' }); + } catch (err) { + if (isDraftVersionConflict(err)) throw Object.assign(new Error(texts.pendingDraft), { cause: err }); + throw err; + } + try { + await doors.client.publish('app', appName, { packageId: target }); + } catch (err) { + try { + await doors.client.reset('app', appName, { state: 'draft', packageId: target }); + } catch (discardErr) { + console.error('[design-mode] a refused publish left the menu draft pending:', discardErr); + } + emitMetadataRefresh(); + throw err; + } + emitMetadataRefresh(); +} + +/** The console's doors, around `client` (`useMetadataClient()`). */ +export function consoleAppMenuDoors(client: AppMenuSaveDoors['client']): AppMenuSaveDoors { + return { listPackages: fetchListedPackageManifests, ensureCustomization: ensureCustomizationPackage, client }; +} + +/** + * The stored menu of the app `appName` of the package `packageId`: the + * navigation of its layered read (`storedApp`), `null` when the read fails. + * The editor compares an entry's shown label with it to tell a translated + * label from the stored one (objectstack#36363, ruling (4)). + */ +export async function readStoredMenu( + appName: string, + packageId: string, + client: Pick, +): Promise { + try { + const stored = storedApp(await client.layered('app', appName, packageId ? { packageId } : {})); + return Array.isArray(stored.navigation) ? (stored.navigation as Menu) : []; + } catch { + return null; + } +} + +let defaultLocaleRead: Promise | null = null; + +/** + * The deployment's default language, as `GET /api/v1/i18n/locales` marks it + * (`isDefault`), read once per page load; `null` when the read fails or marks + * none. The stored labels are taken to be in it: the server states no + * `sourceLocale` of its own yet (objectstack#36504). + */ +export function fetchDefaultLocale(): Promise { + if (defaultLocaleRead) return defaultLocaleRead; + defaultLocaleRead = (async () => { + try { + const res = await fetch('/api/v1/i18n/locales', { credentials: 'include' }); + if (!res.ok) return null; + const json = (await res.json()) as { data?: { locales?: unknown }; locales?: unknown }; + const locales = Array.isArray(json?.data?.locales) ? json.data.locales : Array.isArray(json?.locales) ? json.locales : []; + const marked = (locales as Array<{ code?: unknown; isDefault?: unknown }>).find((l) => l?.isDefault === true); + return typeof marked?.code === 'string' && marked.code ? marked.code : null; + } catch { + return null; + } + })(); + return defaultLocaleRead; +} + +/** Test seam: forget the default-language read. Not public. */ +export function __resetDefaultLocale(): void { + defaultLocaleRead = null; +} + +/** + * Whether the session language `language` is the language `locale`: the same + * tag, letter case aside, or the same base when either names no region + * (`en` is `en-US`; `zh-CN` is not `zh-TW`). + */ +export function isSameLanguage(language: string, locale: string): boolean { + const a = language.trim().toLowerCase().replace(/_/g, '-'); + const b = locale.trim().toLowerCase().replace(/_/g, '-'); + if (!a || !b) return false; + if (a === b) return true; + const [baseA, ...restA] = a.split('-'); + const [baseB, ...restB] = b.split('-'); + return baseA === baseB && (restA.length === 0 || restB.length === 0); +} 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 87708cf155c..8abffe74835 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 @@ -462,7 +462,10 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // 124 once objectstack-ai/objectstack#36286 added // `console.commandPalette.createAs`, the palette's row creating a record // from the typed words („{{query}}“) — one interpolated span, user input. - expect(okSpans, 'correctly paired spans').toBe(124); + // 125 once objectstack-ai/objectstack#36363 added `designMode.menu.iconHint`, + // the menu editor's icon field naming an example icon („briefcase“) — one + // literal span. + expect(okSpans, 'correctly paired spans').toBe(125); }); it('keeps the count identity that replaces the card’s count(„) === count(“)', () => { @@ -586,7 +589,9 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // more matched pairs. // 124 / 124 / 0 after objectstack-ai/objectstack#36286 added // `console.commandPalette.createAs`, one more matched pair. - expect({ open, close, rdq }).toEqual({ open: 124, close: 124, rdq: 0 }); + // 125 / 125 / 0 after objectstack-ai/objectstack#36363 added + // `designMode.menu.iconHint`, one more matched pair. + expect({ open, close, rdq }).toEqual({ open: 125, close: 125, 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/__tests__/ellipsis-glyph-3878.test.ts b/ui/packages/i18n/src/__tests__/ellipsis-glyph-3878.test.ts index 2a7b3af5e44..b510546e4d1 100644 --- a/ui/packages/i18n/src/__tests__/ellipsis-glyph-3878.test.ts +++ b/ui/packages/i18n/src/__tests__/ellipsis-glyph-3878.test.ts @@ -336,7 +336,8 @@ const LOADING_GROUP_EN = 'Loading…'; * The group as measured on `main` @ `22ba9271f`, plus `home.loading`, which * joined when objectui#12956 dropped the cloud noun from its `en` value * (`Loading environment…` became `Loading…`); every pack now renders it the - * way it renders the rest of the group. Pinned by name so the + * way it renders the rest of the group, and `designMode.menu.loading`, the + * design mode's menu picker (objectstack#36363). Pinned by name so the * uniformity rule below cannot go green by the group quietly emptying out — * a uniformity assertion over nothing passes, which is this pin's failure mode. */ @@ -345,6 +346,7 @@ const LOADING_GROUP = [ 'auth.device.loading', 'common.loading', 'dashboard.loading', + 'designMode.menu.loading', 'detail.loading', 'fields.recipient.loading', 'grid.bulk.loading', @@ -373,7 +375,7 @@ describe('objectui#5972 — each pack renders the merged `Loading…` group exac // this file reasons about is no longer the group it names, and the rule // below would be silently measuring something else. const derived = PACKS.en.filter(([, value]) => value === LOADING_GROUP_EN).map(([key]) => key); - expect(derived.length, 'the group emptied or changed size — re-measure before editing the list').toBe(11); + expect(derived.length, 'the group emptied or changed size — re-measure before editing the list').toBe(12); expect([...derived].sort()).toEqual([...LOADING_GROUP].sort()); // And every pack must actually define every member. An absent key is a key-set diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index c3010486d99..68da4f84319 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -3829,6 +3829,45 @@ const ar = { title: 'وضع التصميم', leaveUnsaved: 'هل تريد مغادرة وضع التصميم؟ ستفقد التغييرات غير المحفوظة.', saveFailed: 'لم يتم حفظ بعض التغييرات: {{reason}}', + menu: { + title: 'القائمة', + addItem: 'إضافة عنصر قائمة', + placeholder: 'اختر عنصر قائمة…', + actions: 'إجراءات {{name}}', + moveUp: 'نقل لأعلى', + moveDown: 'نقل لأسفل', + moveToGroup: 'نقل إلى مجموعة', + topLevel: 'المستوى الأعلى', + addBefore: 'إضافة عنصر قبله', + addAfter: 'إضافة عنصر بعده', + rename: 'إعادة التسمية والأيقونة', + renameSourceOnly: 'تُغيَّر أسماء القائمة بلغة التطبيق المصدر', + remove: 'إزالة من القائمة', + contributed: 'تضيف حزمة أخرى هذا العنصر. يُنقل أو يُعاد تسميته أو يُزال هناك.', + pickerTitle: 'إضافة عنصر قائمة', + search: 'بحث…', + kind: { + object: 'الكائنات', + view: 'طرق العرض', + dashboard: 'لوحات المعلومات', + report: 'التقارير', + page: 'الصفحات', + url: 'رابط', + }, + linkLabel: 'التسمية', + linkUrl: 'عنوان URL', + add: 'إضافة', + name: 'الاسم', + icon: 'الأيقونة', + iconHint: 'اسم أيقونة من Lucide، مثل "briefcase".', + done: 'تم', + none: 'لا شيء لإضافته هنا', + loading: 'جارٍ التحميل…', + notListed: 'حزمة هذا التطبيق غير مدرجة، لذا لا يمكن حفظ قائمته.', + pendingDraft: 'لهذا التطبيق تغييرات غير منشورة في Studio. انشرها أو تجاهلها هناك، ثم احفظ مرة أخرى.', + noVersion: 'حزمة هذا التطبيق لا تذكر إصدارًا، لذا لا يمكن تخصيص قائمته.', + notWritable: 'حزمة تخصيص هذا التطبيق غير قابلة للكتابة، لذا لا يمكن حفظ قائمته.', + }, }, topbar: { openAssistant: "فتح مساعد {{name}}", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index ffedd874ffd..f05beb01d63 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -3506,6 +3506,45 @@ const de = { title: 'Designmodus', leaveUnsaved: 'Designmodus verlassen? Nicht gespeicherte Änderungen gehen verloren.', saveFailed: 'Einige Änderungen wurden nicht gespeichert: {{reason}}', + menu: { + title: 'Menü', + addItem: 'Menüeintrag hinzufügen', + placeholder: 'Menüeintrag auswählen…', + actions: 'Aktionen für {{name}}', + moveUp: 'Nach oben', + moveDown: 'Nach unten', + moveToGroup: 'In Gruppe verschieben', + topLevel: 'Oberste Ebene', + addBefore: 'Eintrag davor einfügen', + addAfter: 'Eintrag danach einfügen', + rename: 'Umbenennen und Symbol', + renameSourceOnly: 'Menünamen werden in der Ausgangssprache der App geändert', + remove: 'Aus dem Menü entfernen', + contributed: 'Ein anderes Paket fügt diesen Eintrag hinzu. Er wird dort verschoben, umbenannt oder entfernt.', + pickerTitle: 'Menüeintrag hinzufügen', + search: 'Suchen…', + kind: { + object: 'Objekte', + view: 'Ansichten', + dashboard: 'Dashboards', + report: 'Berichte', + page: 'Seiten', + url: 'Link', + }, + linkLabel: 'Bezeichnung', + linkUrl: 'URL', + add: 'Hinzufügen', + name: 'Name', + icon: 'Symbol', + iconHint: 'Ein Lucide-Symbolname, z. B. „briefcase“.', + done: 'Fertig', + none: 'Nichts zum Hinzufügen', + loading: 'Wird geladen…', + notListed: 'Das Paket dieser App ist nicht gelistet, daher kann ihr Menü nicht gespeichert werden.', + pendingDraft: 'Diese App hat unveröffentlichte Änderungen in Studio. Veröffentlichen oder verwerfen Sie sie dort und speichern Sie dann erneut.', + noVersion: 'Das Paket dieser App nennt keine Version, daher kann ihr Menü nicht angepasst werden.', + notWritable: 'Das Anpassungspaket dieser App ist nicht beschreibbar, daher kann ihr Menü nicht gespeichert werden.', + }, }, topbar: { openAssistant: "Assistent {{name}} öffnen", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index bc51e535396..c249b74b18a 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -4181,6 +4181,45 @@ const en = { title: 'Design mode', leaveUnsaved: 'Leave design mode? Your unsaved changes will be lost.', saveFailed: 'Some changes were not saved: {{reason}}', + menu: { + title: 'Menu', + addItem: 'Add menu item', + placeholder: 'Choose a menu item…', + actions: 'Actions for {{name}}', + moveUp: 'Move up', + moveDown: 'Move down', + moveToGroup: 'Move to group', + topLevel: 'Top level', + addBefore: 'Add an item before', + addAfter: 'Add an item after', + rename: 'Rename and icon', + renameSourceOnly: 'Menu names are changed in the app\'s source language', + remove: 'Remove from menu', + contributed: 'Another package adds this item. It is moved, renamed or removed there.', + pickerTitle: 'Add menu item', + search: 'Search…', + kind: { + object: 'Objects', + view: 'Views', + dashboard: 'Dashboards', + report: 'Reports', + page: 'Pages', + url: 'Link', + }, + linkLabel: 'Label', + linkUrl: 'URL', + add: 'Add', + name: 'Name', + icon: 'Icon', + iconHint: 'A Lucide icon name, such as "briefcase".', + done: 'Done', + none: 'Nothing to add here', + loading: 'Loading…', + notListed: 'This app\'s package is not listed, so its menu cannot be saved.', + pendingDraft: 'This app has unpublished changes in Studio. Publish or discard them there, then save again.', + noVersion: 'This app\'s package states no version, so its menu cannot be customized.', + notWritable: 'This app\'s customization package cannot be written, so its menu cannot be saved.', + }, }, topbar: { aiAssistant: 'AI Assistant', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 4eb1416c2e9..a90e82ceeb8 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -3588,6 +3588,45 @@ const es = { title: 'Modo de diseño', leaveUnsaved: '¿Salir del modo de diseño? Se perderán los cambios no guardados.', saveFailed: 'Algunos cambios no se guardaron: {{reason}}', + menu: { + title: 'Menú', + addItem: 'Añadir elemento de menú', + placeholder: 'Elige un elemento de menú…', + actions: 'Acciones de {{name}}', + moveUp: 'Subir', + moveDown: 'Bajar', + moveToGroup: 'Mover a grupo', + topLevel: 'Nivel superior', + addBefore: 'Añadir un elemento antes', + addAfter: 'Añadir un elemento después', + rename: 'Cambiar nombre e icono', + renameSourceOnly: 'Los nombres del menú se cambian en el idioma de origen de la aplicación', + remove: 'Quitar del menú', + contributed: 'Otro paquete añade este elemento. Se mueve, se renombra o se quita allí.', + pickerTitle: 'Añadir elemento de menú', + search: 'Buscar…', + kind: { + object: 'Objetos', + view: 'Vistas', + dashboard: 'Paneles', + report: 'Informes', + page: 'Páginas', + url: 'Enlace', + }, + linkLabel: 'Etiqueta', + linkUrl: 'URL', + add: 'Añadir', + name: 'Nombre', + icon: 'Icono', + iconHint: 'Un nombre de icono de Lucide, como "briefcase".', + done: 'Listo', + none: 'No hay nada que añadir', + loading: 'Cargando…', + notListed: 'El paquete de esta aplicación no está en la lista, así que su menú no se puede guardar.', + pendingDraft: 'Esta aplicación tiene cambios sin publicar en Studio. Publícalos o descártalos allí y vuelve a guardar.', + noVersion: 'El paquete de esta aplicación no declara versión, así que su menú no se puede personalizar.', + notWritable: 'El paquete de personalización de esta aplicación no se puede escribir, así que su menú no se puede guardar.', + }, }, topbar: { openAssistant: "Abrir el asistente {{name}}", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 2897ba30a6d..0c20cd0ab88 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -3584,6 +3584,45 @@ const fr = { title: 'Mode conception', leaveUnsaved: 'Quitter le mode conception ? Les modifications non enregistrées seront perdues.', saveFailed: 'Certaines modifications n’ont pas été enregistrées : {{reason}}', + menu: { + title: 'Menu', + addItem: 'Ajouter un élément de menu', + placeholder: 'Choisir un élément de menu…', + actions: 'Actions pour {{name}}', + moveUp: 'Monter', + moveDown: 'Descendre', + moveToGroup: 'Déplacer vers un groupe', + topLevel: 'Niveau supérieur', + addBefore: 'Ajouter un élément avant', + addAfter: 'Ajouter un élément après', + rename: 'Renommer et icône', + renameSourceOnly: 'Les noms du menu se modifient dans la langue source de l’application', + remove: 'Retirer du menu', + contributed: 'Un autre package ajoute cet élément. Il se déplace, se renomme ou se retire là-bas.', + pickerTitle: 'Ajouter un élément de menu', + search: 'Rechercher…', + kind: { + object: 'Objets', + view: 'Vues', + dashboard: 'Tableaux de bord', + report: 'Rapports', + page: 'Pages', + url: 'Lien', + }, + linkLabel: 'Libellé', + linkUrl: 'URL', + add: 'Ajouter', + name: 'Nom', + icon: 'Icône', + iconHint: 'Un nom d’icône Lucide, par exemple "briefcase".', + done: 'Terminé', + none: 'Rien à ajouter ici', + loading: 'Chargement…', + notListed: 'Le package de cette application n’est pas listé : son menu ne peut pas être enregistré.', + pendingDraft: 'Cette application a des modifications non publiées dans Studio. Publiez-les ou annulez-les là-bas, puis enregistrez à nouveau.', + noVersion: 'Le package de cette application ne déclare aucune version : son menu ne peut pas être personnalisé.', + notWritable: 'Le package de personnalisation de cette application n’est pas modifiable : son menu ne peut pas être enregistré.', + }, }, topbar: { openAssistant: "Ouvrir l'assistant {{name}}", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 8e905217048..79f8acda064 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -3508,6 +3508,45 @@ const ja = { title: 'デザインモード', leaveUnsaved: 'デザインモードを終了しますか?保存されていない変更は失われます。', saveFailed: '一部の変更が保存されませんでした:{{reason}}', + menu: { + title: 'メニュー', + addItem: 'メニュー項目を追加', + placeholder: 'メニュー項目を選択…', + actions: '{{name}} の操作', + moveUp: '上へ移動', + moveDown: '下へ移動', + moveToGroup: 'グループへ移動', + topLevel: 'トップレベル', + addBefore: '前に項目を追加', + addAfter: '後ろに項目を追加', + rename: '名前とアイコンを変更', + renameSourceOnly: 'メニュー名はアプリのソース言語で変更します', + remove: 'メニューから削除', + contributed: 'この項目は別のパッケージが追加しています。移動・名前の変更・削除はそのパッケージで行います。', + pickerTitle: 'メニュー項目を追加', + search: '検索…', + kind: { + object: 'オブジェクト', + view: 'ビュー', + dashboard: 'ダッシュボード', + report: 'レポート', + page: 'ページ', + url: 'リンク', + }, + linkLabel: 'ラベル', + linkUrl: 'リンク先', + add: '追加', + name: '名前', + icon: 'アイコン', + iconHint: 'Lucide のアイコン名(例: "briefcase")。', + done: '完了', + none: '追加できるものはありません', + loading: '読み込み中…', + notListed: 'このアプリのパッケージが一覧にないため、メニューを保存できません。', + pendingDraft: 'このアプリには Studio に未公開の変更があります。そちらで公開または破棄してから、もう一度保存してください。', + noVersion: 'このアプリのパッケージにはバージョンがないため、メニューをカスタマイズできません。', + notWritable: 'このアプリのカスタマイズパッケージに書き込めないため、メニューを保存できません。', + }, }, topbar: { openAssistant: "{{name}} アシスタントを開く", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 0b863615fd9..7dc8d732034 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -3506,6 +3506,45 @@ const ko = { title: '디자인 모드', leaveUnsaved: '디자인 모드를 종료할까요? 저장하지 않은 변경 사항은 사라집니다.', saveFailed: '일부 변경 사항이 저장되지 않았습니다: {{reason}}', + menu: { + title: '메뉴', + addItem: '메뉴 항목 추가', + placeholder: '메뉴 항목 선택…', + actions: '{{name}} 작업', + moveUp: '위로 이동', + moveDown: '아래로 이동', + moveToGroup: '그룹으로 이동', + topLevel: '최상위', + addBefore: '앞에 항목 추가', + addAfter: '뒤에 항목 추가', + rename: '이름 및 아이콘 변경', + renameSourceOnly: '메뉴 이름은 앱의 원본 언어에서 변경합니다', + remove: '메뉴에서 제거', + contributed: '이 항목은 다른 패키지가 추가합니다. 이동, 이름 변경, 제거는 그 패키지에서 합니다.', + pickerTitle: '메뉴 항목 추가', + search: '검색…', + kind: { + object: '개체', + view: '보기', + dashboard: '대시보드', + report: '보고서', + page: '페이지', + url: '링크', + }, + linkLabel: '레이블', + linkUrl: '링크 주소', + add: '추가', + name: '이름', + icon: '아이콘', + iconHint: 'Lucide 아이콘 이름(예: "briefcase").', + done: '완료', + none: '추가할 항목이 없습니다', + loading: '로딩 중…', + notListed: '이 앱의 패키지가 목록에 없어 메뉴를 저장할 수 없습니다.', + pendingDraft: '이 앱에는 Studio에 게시되지 않은 변경 사항이 있습니다. 그곳에서 게시하거나 취소한 뒤 다시 저장하세요.', + noVersion: '이 앱의 패키지에 버전이 없어 메뉴를 사용자 지정할 수 없습니다.', + notWritable: '이 앱의 사용자 지정 패키지에 쓸 수 없어 메뉴를 저장할 수 없습니다.', + }, }, topbar: { openAssistant: "{{name}} 어시스턴트 열기", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index fa337da7bd4..ae8548b5739 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -3583,6 +3583,45 @@ const pt = { title: 'Modo de design', leaveUnsaved: 'Sair do modo de design? As alterações não salvas serão perdidas.', saveFailed: 'Algumas alterações não foram salvas: {{reason}}', + menu: { + title: 'Menu', + addItem: 'Adicionar item de menu', + placeholder: 'Escolha um item de menu…', + actions: 'Ações de {{name}}', + moveUp: 'Mover para cima', + moveDown: 'Mover para baixo', + moveToGroup: 'Mover para grupo', + topLevel: 'Nível superior', + addBefore: 'Adicionar um item antes', + addAfter: 'Adicionar um item depois', + rename: 'Renomear e ícone', + renameSourceOnly: 'Os nomes do menu são alterados no idioma de origem do aplicativo', + remove: 'Remover do menu', + contributed: 'Outro pacote adiciona este item. Ele é movido, renomeado ou removido lá.', + pickerTitle: 'Adicionar item de menu', + search: 'Pesquisar…', + kind: { + object: 'Objetos', + view: 'Visualizações', + dashboard: 'Painéis', + report: 'Relatórios', + page: 'Páginas', + url: 'Link', + }, + linkLabel: 'Rótulo', + linkUrl: 'URL', + add: 'Adicionar', + name: 'Nome', + icon: 'Ícone', + iconHint: 'Um nome de ícone do Lucide, como "briefcase".', + done: 'Concluído', + none: 'Nada para adicionar aqui', + loading: 'Carregando…', + notListed: 'O pacote deste aplicativo não está listado, então o menu não pode ser salvo.', + pendingDraft: 'Este aplicativo tem alterações não publicadas no Studio. Publique ou descarte-as lá e salve novamente.', + noVersion: 'O pacote deste aplicativo não declara versão, então o menu não pode ser personalizado.', + notWritable: 'O pacote de personalização deste aplicativo não pode ser gravado, então o menu não pode ser salvo.', + }, }, topbar: { openAssistant: "Abrir o assistente {{name}}", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 22a331c1f3b..855bc253b98 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -3675,6 +3675,45 @@ const ru = { title: 'Режим дизайна', leaveUnsaved: 'Выйти из режима дизайна? Несохранённые изменения будут потеряны.', saveFailed: 'Некоторые изменения не сохранены: {{reason}}', + menu: { + title: 'Меню', + addItem: 'Добавить пункт меню', + placeholder: 'Выберите пункт меню…', + actions: 'Действия для {{name}}', + moveUp: 'Переместить вверх', + moveDown: 'Переместить вниз', + moveToGroup: 'Переместить в группу', + topLevel: 'Верхний уровень', + addBefore: 'Добавить пункт перед', + addAfter: 'Добавить пункт после', + rename: 'Имя и значок', + renameSourceOnly: 'Названия пунктов меню меняются на исходном языке приложения', + remove: 'Убрать из меню', + contributed: 'Этот пункт добавляет другой пакет. Перемещайте, переименовывайте или удаляйте его там.', + pickerTitle: 'Добавить пункт меню', + search: 'Поиск…', + kind: { + object: 'Объекты', + view: 'Представления', + dashboard: 'Панели', + report: 'Отчёты', + page: 'Страницы', + url: 'Ссылка', + }, + linkLabel: 'Подпись', + linkUrl: 'Адрес', + add: 'Добавить', + name: 'Имя', + icon: 'Значок', + iconHint: 'Имя значка Lucide, например "briefcase".', + done: 'Готово', + none: 'Нечего добавить', + loading: 'Загрузка…', + notListed: 'Пакет этого приложения отсутствует в списке, поэтому меню нельзя сохранить.', + pendingDraft: 'В Studio есть неопубликованные изменения этого приложения. Опубликуйте или отмените их там и сохраните снова.', + noVersion: 'Пакет этого приложения не указывает версию, поэтому меню нельзя настроить.', + notWritable: 'Пакет настроек этого приложения недоступен для записи, поэтому меню нельзя сохранить.', + }, }, topbar: { openAssistant: "Открыть ассистента {{name}}", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 3937118eb1a..631d4578f9a 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -3587,6 +3587,45 @@ const zh = { title: '设计模式', leaveUnsaved: '离开设计模式?未保存的改动将会丢失。', saveFailed: '部分改动没有保存:{{reason}}', + menu: { + title: '菜单', + addItem: '添加菜单项', + placeholder: '选择一个菜单项…', + actions: '{{name}} 的操作', + moveUp: '上移', + moveDown: '下移', + moveToGroup: '移到分组', + topLevel: '顶层', + addBefore: '在前面加一项', + addAfter: '在后面加一项', + rename: '改名和图标', + renameSourceOnly: '菜单名称需在应用的源语言下修改', + remove: '从菜单移除', + contributed: '此菜单项由另一个包添加,请在那个包中移动、改名或移除。', + pickerTitle: '添加菜单项', + search: '搜索…', + kind: { + object: '对象', + view: '视图', + dashboard: '仪表盘', + report: '报表', + page: '页面', + url: '链接', + }, + linkLabel: '名称', + linkUrl: '网址', + add: '添加', + name: '名称', + icon: '图标', + iconHint: 'Lucide 图标名,例如 "briefcase"。', + done: '完成', + none: '没有可添加的内容', + loading: '加载中…', + notListed: '这个应用所在的包不在列表中,菜单无法保存。', + pendingDraft: '这个应用在 Studio 里有未发布的改动。请先在那里发布或丢弃,再保存。', + noVersion: '这个应用所在的包没有声明版本,菜单无法定制。', + notWritable: '这个应用的定制包不可写,菜单无法保存。', + }, }, topbar: { aiAssistant: 'AI 助手', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index e27f1bad492..bfd5dc07c17 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -3587,6 +3587,45 @@ const zhHant = { title: '設計模式', leaveUnsaved: '離開設計模式?未儲存的改動將會丟失。', saveFailed: '部分改動沒有儲存:{{reason}}', + menu: { + title: '選單', + addItem: '新增選單項', + placeholder: '選擇一個選單項…', + actions: '{{name}} 的操作', + moveUp: '上移', + moveDown: '下移', + moveToGroup: '移到分組', + topLevel: '頂層', + addBefore: '在前面加一項', + addAfter: '在後面加一項', + rename: '改名和圖示', + renameSourceOnly: '選單名稱需在應用的源語言下修改', + remove: '從選單移除', + contributed: '此選單項由另一個包新增,請在那個包中移動、改名或移除。', + pickerTitle: '新增選單項', + search: '搜尋…', + kind: { + object: '物件', + view: '檢視', + dashboard: '儀表盤', + report: '報表', + page: '頁面', + url: '連結', + }, + linkLabel: '名稱', + linkUrl: '網址', + add: '新增', + name: '名稱', + icon: '圖示', + iconHint: 'Lucide 圖示名,例如 "briefcase"。', + done: '完成', + none: '沒有可新增的內容', + loading: '載入中…', + notListed: '這個應用所在的包不在列表中,選單無法儲存。', + pendingDraft: '這個應用在 Studio 裡有未釋出的改動。請先在那裡釋出或丟棄,再儲存。', + noVersion: '這個應用所在的包沒有宣告版本,選單無法定製。', + notWritable: '這個應用的定製包不可寫,選單無法儲存。', + }, }, topbar: { aiAssistant: 'AI 助手',