From 5fa0bcd6d1422bccc6a20c03ae93b2f3bc387a40 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 03:18:35 +0000 Subject: [PATCH 1/2] feat(console): configure tabs on installed objects, into the paired .custom package (#36499) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On an installed (read-only) object, 「Configure tabs」 writes the relatedLists of the paired .custom package's object extension through one shared arrangement writer (saveObjectExtensionArrangement), created on first save by the ensure door; every tab moves, a related one hides, and each is marked with where it comes from. The entry leads the record's overflow menu, ahead of Refresh (a host entry's leadsMenu). Claude-Session: https://claude.ai/code/session_01ADHkmP8GZoB2rUETxwNEDv Co-authored-by: Claude --- .../app-shell/src/views/RecordDetailView.tsx | 8 +- .../app-shell/src/views/RecordTabsConfig.tsx | 166 ++++++++-- .../RecordTabsConfigInstalled-36499.test.tsx | 223 ++++++++++++++ ...jectExtensionArrangementSave-36499.test.ts | 178 +++++++++++ .../recordTabsConfigSave-36499.test.ts | 31 +- .../recordTabsInstalled-36499.test.ts | 147 +++++++++ .../views/objectExtensionArrangementSave.ts | 157 ++++++++++ .../app-shell/src/views/recordTabsConfig.ts | 29 +- .../src/views/recordTabsConfigIo.tsx | 32 +- .../src/views/recordTabsConfigSave.ts | 106 +++++-- .../src/views/recordTabsInstalled.ts | 291 ++++++++++++++++++ .../page-header-overflow-close-36499.test.tsx | 26 +- .../src/renderers/layout/containers.tsx | 24 +- ui/packages/i18n/src/locales/ar.ts | 5 + ui/packages/i18n/src/locales/de.ts | 5 + ui/packages/i18n/src/locales/en.ts | 5 + ui/packages/i18n/src/locales/es.ts | 5 + ui/packages/i18n/src/locales/fr.ts | 5 + ui/packages/i18n/src/locales/ja.ts | 5 + ui/packages/i18n/src/locales/ko.ts | 5 + ui/packages/i18n/src/locales/pt-BR.ts | 5 + ui/packages/i18n/src/locales/ru.ts | 5 + ui/packages/i18n/src/locales/zh-Hans.ts | 5 + ui/packages/i18n/src/locales/zh-Hant.ts | 5 + 24 files changed, 1396 insertions(+), 77 deletions(-) create mode 100644 ui/packages/app-shell/src/views/__tests__/RecordTabsConfigInstalled-36499.test.tsx create mode 100644 ui/packages/app-shell/src/views/__tests__/objectExtensionArrangementSave-36499.test.ts create mode 100644 ui/packages/app-shell/src/views/__tests__/recordTabsInstalled-36499.test.ts create mode 100644 ui/packages/app-shell/src/views/objectExtensionArrangementSave.ts create mode 100644 ui/packages/app-shell/src/views/recordTabsInstalled.ts diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 26450e0ef59..c32ea48482f 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -5331,12 +5331,14 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri : onEdit({ id: pureRecordId }, objectName)), } as any); } - // objectstack#36499 — 「Configure tabs」, the first of the host's entries - // in the `⋯`, for an administrator who may arrange this object's tabs - // (`useRecordTabsConfig`'s gate: never on a phone, a drawer or a pane). + // objectstack#36499 — 「Configure tabs」, the first item of the `⋯` + // (`leadsMenu`, ahead of Refresh), for an administrator who may arrange + // this object's tabs (`useRecordTabsConfig`'s gate: never on a phone, a + // drawer or a pane). if (tabsConfig.offered && !tabsConfig.active && !recordEditState) { items.push({ name: RECORD_TABS_CONFIG_ACTION, + leadsMenu: true, label: t('designMode.recordTabs.entry', { defaultValue: 'Configure tabs' }), icon: 'panels-top-left', type: 'script', diff --git a/ui/packages/app-shell/src/views/RecordTabsConfig.tsx b/ui/packages/app-shell/src/views/RecordTabsConfig.tsx index fc3cc2fcbd0..f37119e25da 100644 --- a/ui/packages/app-shell/src/views/RecordTabsConfig.tsx +++ b/ui/packages/app-shell/src/views/RecordTabsConfig.tsx @@ -5,10 +5,13 @@ * objectstack#36359): an administrator arranges the record page's tabs in * place, for everyone. * - * - The entry is the first of the record's own entries in its 「…」, drawn for - * a workspace administrator who may author metadata, on the desktop full - * page of an object whose package the server lists writable (the gate of - * Studio's design entries, `useStudioDesignGate`). Not on a phone, not in a + * - The entry opens the record's 「…」 (it leads the menu, ahead of Refresh), + * drawn for a workspace administrator who may author metadata, on the + * desktop full page of an object whose package Studio lists: writable (an + * object of a self-built app, the gate of Studio's design entries, + * `useStudioDesignGate`), or read-only (an installed app's object, Studio's + * view posture, `useStudioEntryGate`) where the customization door does not + * wall this caller off (`useCustomizeDoorWalled`). Not on a phone, not in a * drawer or pane, not on a page its author composed. * - Chosen, the page enters its edit state in place: a bar across the top of * the page — 「Configure tabs」 at its left, 「Cancel」 and 「Save」 at its @@ -20,7 +23,11 @@ * - 「Cancel」 drops the draft and writes nothing. With a change held, leaving * the page asks first (the shell's unsaved-edits seam). * - 「Save」 writes the object's `relatedLists` and publishes it - * (`saveRecordTabs`): the order everyone sees by default. A reader's own + * (`saveRecordTabs`): the order everyone sees by default. On an installed + * object it writes the `relatedLists` of the object extension of the base's + * paired `.custom` package instead (`recordTabsInstalled.ts`), where every + * tab can be moved, a related one hidden, and each is marked with where it + * comes from (the original package, another package, this environment). A reader's own * arrangement is a diff laid over that default (`relatedArrangement.ts`), * and 「Restore default order」 returns them to it. * - The field area is not changed here: 「Adjust field groups」 opens the @@ -51,9 +58,10 @@ import { CSS } from '@dnd-kit/utilities'; import { Eye, EyeOff, GripVertical, Lock, Pencil, PanelsTopLeft } from 'lucide-react'; import { Button, Input, cn } from '@object-ui/components'; import { useObjectTranslation } from '@object-ui/i18n'; -import { isRecordPageBuiltinTab, relatedListEntryName } from '@objectstack/spec/data'; +import { isRecordPageBuiltinTab, readRelatedListsArrangement, relatedListEntryName } from '@objectstack/spec/data'; import { registerUnsavedEdits } from '../chrome/unsavedEdits.js'; -import { useStudioDesignGate } from '../hooks/useStudioDesignGate.js'; +import { useStudioDesignGate, useStudioEntryGate } from '../hooks/useStudioDesignGate.js'; +import { useCustomizeDoorWalled } from './studio-design/StudioCustomizeControls.js'; import { relatedListEntryNames, type DerivedRelatedList } from '../utils/deriveRelatedLists.js'; import { studioPillarItemPath } from './studio-design/metadataArea.js'; import { entryDetails } from './studio-design/relatedListVocabulary.js'; @@ -69,6 +77,13 @@ import { type RecordTabsEdit, } from './recordTabsConfig.js'; import { consoleRecordTabsDoors, saveRecordTabs } from './recordTabsConfigSave.js'; +import { + initialInstalledTabsDraft, + previewInstalledTabsObject, + recordTabSource, + recordTabsPackageOf, + type RecordTabSource, +} from './recordTabsInstalled.js'; import type { RecordTabsIo } from './recordTabsConfigIo.js'; type RecordTabsObjectDef = Record & { name?: string }; @@ -81,10 +96,15 @@ export const RECORD_TABS_CONFIG_ACTION = 'sys_configure_tabs'; /** The package an object is kept in, as served (`_packageId`), or `null`. */ export function objectPackageId(objectDef: RecordTabsObjectDef | null | undefined): string | null { - const id = objectDef?._packageId; - return typeof id === 'string' && id && id !== 'sys_metadata' ? id : null; + return recordTabsPackageOf(objectDef); } +/** + * Where a save lands, as the editor knows it: `own`, the object's writable + * package; `pair`, the paired `.custom` package of the installed base. + */ +export type RecordTabsMode = 'own' | 'pair'; + /** Where 「Adjust field groups」 goes: the object in Studio's Data pillar. */ export function recordTabsStudioPath(objectDef: RecordTabsObjectDef | null | undefined): string | null { const packageId = objectPackageId(objectDef); @@ -94,6 +114,7 @@ export function recordTabsStudioPath(objectDef: RecordTabsObjectDef | null | und interface RecordTabsSession { readonly objectName: string; + readonly mode: RecordTabsMode; readonly initial: RecordTabsDraft; readonly draft: RecordTabsDraft; } @@ -128,11 +149,15 @@ export function useRecordTabsConfig({ objectDef, objects, enabled, canRead, titl const objectName = typeof objectDef?.name === 'string' ? objectDef.name : ''; const packageId = objectPackageId(objectDef); const studioPath = recordTabsStudioPath(objectDef); - const offered = useStudioDesignGate(enabled ? studioPath : null) !== null && !!packageId; + const own = useStudioDesignGate(enabled ? studioPath : null) !== null; + const entry = useStudioEntryGate(enabled && !own ? studioPath : null); + const walled = useCustomizeDoorWalled(); + const mode: RecordTabsMode | null = !packageId ? null : own ? 'own' : entry?.posture === 'view' && !walled ? 'pair' : null; + const offered = mode !== null; const [held, setHeld] = React.useState(null); const [saving, setSaving] = React.useState(false); - const session = held && held.objectName === objectName && offered ? held : null; + const session = held && held.objectName === objectName && held.mode === mode ? held : null; const active = session !== null; const catalog = React.useMemo( @@ -141,11 +166,14 @@ export function useRecordTabsConfig({ objectDef, objects, enabled, canRead, titl ); const enter = React.useCallback(() => { - if (!objectDef || !objectName) return; + if (!objectDef || !objectName || !mode) return; const opened = recordTabsCatalog(objectDef, objects, { canRead }); - const initial = initialRecordTabsDraft(objectDef, objects, opened, { canRead }); - setHeld({ objectName, initial, draft: initial }); - }, [objectDef, objectName, objects, canRead]); + const initial = + mode === 'pair' + ? initialInstalledTabsDraft(objectDef, objects, opened, { canRead }) + : initialRecordTabsDraft(objectDef, objects, opened, { canRead }); + setHeld({ objectName, mode, initial, draft: initial }); + }, [objectDef, objectName, objects, canRead, mode]); const cancel = React.useCallback(() => setHeld(null), []); const edit = React.useCallback((change: RecordTabsEdit) => { setHeld((prev) => (prev ? { ...prev, draft: editRecordTabsDraft(prev.draft, change) } : prev)); @@ -170,7 +198,7 @@ export function useRecordTabsConfig({ objectDef, objects, enabled, canRead, titl setSaving(true); try { await saveRecordTabs( - { objectName, packageId, draft: session.draft, catalog }, + { objectName, packageId, draft: session.draft, catalog, initial: session.initial }, { notListed: t('designMode.recordTabs.notListed', { defaultValue: "This object's package is not listed, so its tabs cannot be saved.", @@ -181,6 +209,9 @@ export function useRecordTabsConfig({ objectDef, objects, enabled, canRead, titl notWritable: t('designMode.recordTabs.notWritable', { defaultValue: "This object's package cannot be written, so its tabs cannot be saved here.", }), + pairNotWritable: t('designMode.recordTabs.pairNotWritable', { + defaultValue: "This app's customization package cannot be written, so its tabs cannot be saved.", + }), }, consoleRecordTabsDoors(client), ); @@ -198,9 +229,21 @@ export function useRecordTabsConfig({ objectDef, objects, enabled, canRead, titl }, [session, catalog, packageId, saving, objectName, client, t]); const previewObject = React.useMemo( - () => (session && catalog && objectDef ? previewRecordTabsObject(objectDef, session.draft, catalog) : undefined), + () => + session && catalog && objectDef + ? session.mode === 'pair' + ? previewInstalledTabsObject(objectDef, session.draft, catalog) + : previewRecordTabsObject(objectDef, session.draft, catalog) + : undefined, [session, catalog, objectDef], ); + const pairId = (objectDef && readRelatedListsArrangement(objectDef)?.packageId) ?? null; + const packageNames = io?.packageNames; + const sourceOf = React.useCallback( + (list: DerivedRelatedList): RecordTabSource | undefined => (objectDef ? recordTabSource(list, objectDef, objects) : undefined), + [objectDef, objects], + ); + const packageName = React.useCallback((id: string) => packageNames?.get(id) ?? id, [packageNames]); const storedLists = io?.stored?.objectName === objectName ? io.stored.lists : null; const sourceLanguage = io?.sourceLanguage ?? false; @@ -210,7 +253,13 @@ export function useRecordTabsConfig({ objectDef, objects, enabled, canRead, titl void save()} /> {packageId && ( - + )} @@ -227,6 +276,7 @@ export function useRecordTabsConfig({ objectDef, objects, enabled, canRead, titl studioPath={studioPath} disabled={saving} onEdit={edit} + {...(session.mode === 'pair' ? { installed: { sourceOf, packageName } } : {})} /> ) : null; @@ -301,10 +351,12 @@ interface ChipProps { fixedReason?: string; rename?: { open: boolean; hint?: string; onRename: (label: string | undefined) => void }; hide?: { label: string; onHide: () => void }; + /** Where the tab comes from, on an installed object (card item 7). */ + source?: { kind: RecordTabSource['kind']; text: string }; disabled: boolean; } -function TabChipBody({ label, fixedReason, rename, hide, disabled, handle }: ChipProps & { handle?: React.ReactNode }) { +function TabChipBody({ label, fixedReason, rename, hide, source, disabled, handle }: ChipProps & { handle?: React.ReactNode }) { const { t } = useObjectTranslation(); const [editing, setEditing] = React.useState(false); const [value, setValue] = React.useState(label); @@ -340,6 +392,15 @@ function TabChipBody({ label, fixedReason, rename, hide, disabled, handle }: Chi {label} )} + {source && !editing && ( + + {source.text} + + )} {rename && !editing && ( + )} + {config.bar} + {config.editor} + + ); +} + +const flush = () => + act(async () => { + await new Promise((r) => setTimeout(r, 0)); + }); + +beforeEach(() => { + written.length = 0; + session.view = true; + session.walled = false; + __resetDefaultLocale(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => ({ ok: true, json: async () => ({ data: { locales: [{ code: 'en', isDefault: true }] } }) })), + ); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +async function open() { + render(); + fireEvent.click(screen.getByText('enter')); + await waitFor(() => expect(screen.getByTestId('record-tabs-config-bar')).toHaveAttribute('data-ready', 'true')); + await flush(); +} + +const shownTabs = () => + Array.from(screen.getByTestId('record-tabs-editor').querySelectorAll('[data-record-tabs-tab]')).map((el) => + el.getAttribute('data-record-tabs-tab'), + ); + +describe('「Configure tabs」 on an installed object (objectstack#36499)', () => { + it('is offered where Studio opens the base read-only, and not where the customization door walls this caller off', () => { + render(); + expect(screen.getByTestId('offered')).toHaveTextContent('true'); + cleanup(); + session.walled = true; + render(); + expect(screen.getByTestId('offered')).toHaveTextContent('false'); + cleanup(); + session.walled = false; + session.view = false; + render(); + expect(screen.getByTestId('offered')).toHaveTextContent('false'); + }); + + it("every tab moves, another package's and the built-in ones too; a related tab hides, a built-in one does not; each related tab names its source", async () => { + await open(); + expect(shownTabs()).toEqual(['contact.lead', 'campaign_member.lead', 'survey.lead', 'sys_approval_request', 'sys_activity']); + const editor = screen.getByTestId('record-tabs-editor'); + for (const id of ['contact.lead', 'campaign_member.lead', 'sys_activity']) { + expect(editor.querySelector(`[data-record-tabs-tab="${id}"] [data-record-tabs-handle]`)).not.toBeNull(); + } + const tab = (id: string) => editor.querySelector(`[data-record-tabs-tab="${id}"]`) as HTMLElement; + expect(within(tab('campaign_member.lead')).getByRole('button', { name: 'Hide Campaign members' })).toBeEnabled(); + expect(tab('sys_activity').querySelector('[data-record-tabs-hide]')).toBeNull(); + expect(tab('contact.lead').querySelector('[data-record-tabs-source="base"]')).toHaveTextContent('Original package'); + expect(tab('campaign_member.lead').querySelector('[data-record-tabs-source="package"]')).toHaveTextContent('From Marketing'); + expect(tab('survey.lead').querySelector('[data-record-tabs-source="environment"]')).toHaveTextContent('This environment'); + }); + + it("Save writes the pair's extension of the object, through the ensure door's answer, and publishes it", async () => { + await open(); + fireEvent.click(screen.getByRole('button', { name: 'Hide Campaign members' })); + act(() => dragEnd.current?.({ active: { id: 'sys_activity' }, over: { id: 'contact.lead' } })); + expect(shownTabs()).toEqual(['sys_activity', 'contact.lead', 'survey.lead', 'sys_approval_request']); + fireEvent.click(screen.getByTestId('record-tabs-config-save')); + await flush(); + await flush(); + expect(written).toEqual([ + ['ensure', BASE], + [ + 'save', + 'object_extension', + 'lead', + { + extend: 'lead', + relatedLists: [ + 'sys_activity', + { list: 'contact', label: 'Contacts' }, + 'survey', + 'sys_approval_request', + { list: 'campaign_member', hidden: true }, + ], + }, + { mode: 'draft', packageId: PAIR, ifNoneMatch: '*' }, + ], + ['publish', 'object_extension', 'lead', { packageId: PAIR }], + ]); + expect(screen.queryByTestId('record-tabs-config-bar')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/__tests__/objectExtensionArrangementSave-36499.test.ts b/ui/packages/app-shell/src/views/__tests__/objectExtensionArrangementSave-36499.test.ts new file mode 100644 index 00000000000..89a7e887601 --- /dev/null +++ b/ui/packages/app-shell/src/views/__tests__/objectExtensionArrangementSave-36499.test.ts @@ -0,0 +1,178 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The one writer of an installed object's arrangement (objectstack#36499, + * ADR-0146 D10): the pair the ensure door answers, the pair's STORED + * extension with only the caller's keys replaced (`fields`, `fieldPatches`, + * `place` and the other arrangement key kept), a pinned draft, a publish; a + * refused publish discards the draft; a pair the server lists read-only is + * refused before anything is written. + */ + +import { describe, expect, it, vi } from 'vitest'; +import { + extensionWithArrangement, + saveObjectExtensionArrangement, + type ExtensionArrangementDoors, +} from '../objectExtensionArrangementSave'; + +const BASE = 'app.hotcrm'; +const PAIR = 'app.hotcrm.custom'; +const TEXTS = { notListed: 'not listed', pendingDraft: 'pending draft', notWritable: 'pair not writable' }; + +const STORED_EXTENSION = { + extend: 'lead', + fields: { region__c: { type: 'text', label: 'Region' } }, + fieldPatches: { status: { label: 'Stage' } }, + place: [{ field: 'region__c', after: 'status' }], + fieldGroups: [{ key: 'basic', label: 'Basics', fields: ['name'] }], + relatedLists: ['task'], + _packageId: PAIR, +}; + +function doors(opts: { + extension?: unknown; + pairWritable?: boolean; + listed?: boolean; + save?: () => Promise; + publish?: () => Promise; +}) { + const calls: Array<[string, ...unknown[]]> = []; + const refreshed = vi.fn(); + const d: ExtensionArrangementDoors = { + listPackages: async () => (opts.listed === false ? new Map() : new Map([[BASE, { writable: false }]])), + ensureCustomization: async (base) => { + calls.push(['ensure', base]); + return { packageId: PAIR, writable: opts.pairWritable ?? true }; + }, + client: { + get: async (...args) => { + calls.push(['get', ...args]); + return opts.extension === undefined ? null : opts.extension; + }, + layered: async (...args) => { + calls.push(['layered', ...args]); + const code = { name: 'lead', relatedLists: [{ list: 'contact', label: 'People' }] }; + 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 {}; + }, + }, + refreshed, + }; + return { d, calls, refreshed }; +} + +describe("writing an installed object's arrangement into its pair (objectstack#36499)", () => { + it('replaces only the returned key over the STORED extension, every other key kept, pinned draft then publish', async () => { + const { d, calls, refreshed } = doors({ extension: STORED_EXTENSION }); + const seen: unknown[] = []; + const pair = await saveObjectExtensionArrangement( + { + objectName: 'lead', + basePackageId: BASE, + arrange: (stored) => { + seen.push(stored); + return { relatedLists: ['contact', { list: 'task', hidden: true }] }; + }, + }, + TEXTS, + d, + ); + expect(pair).toBe(PAIR); + // The caller composes over what is stored: the extension without its read + // envelope, the object of the layered read. + const { _packageId: _envelope, ...storedBody } = STORED_EXTENSION; + expect(seen).toEqual([{ extension: storedBody, object: { name: 'lead', relatedLists: [{ list: 'contact', label: 'People' }] } }]); + expect(calls).toEqual([ + ['ensure', BASE], + ['get', 'object_extension', 'lead', { packageId: PAIR }], + ['layered', 'object', 'lead', { packageId: BASE }], + [ + 'save', + 'object_extension', + 'lead', + { + extend: 'lead', + fields: STORED_EXTENSION.fields, + fieldPatches: STORED_EXTENSION.fieldPatches, + place: STORED_EXTENSION.place, + fieldGroups: STORED_EXTENSION.fieldGroups, + relatedLists: ['contact', { list: 'task', hidden: true }], + }, + { mode: 'draft', packageId: PAIR, ifNoneMatch: '*' }, + ], + ['publish', 'object_extension', 'lead', { packageId: PAIR }], + ]); + expect(refreshed).toHaveBeenCalledTimes(1); + }); + + it('a second caller writes fieldGroups through the same writer, the tab list kept', async () => { + const { d, calls } = doors({ extension: STORED_EXTENSION }); + await saveObjectExtensionArrangement( + { objectName: 'lead', basePackageId: BASE, arrange: () => ({ fieldGroups: [{ key: 'all', label: 'All' }] }) }, + TEXTS, + d, + ); + const body = calls.find(([c]) => c === 'save')?.[3] as Record; + expect(body.fieldGroups).toEqual([{ key: 'all', label: 'All' }]); + expect(body.relatedLists).toEqual(['task']); + expect(body.fields).toEqual(STORED_EXTENSION.fields); + }); + + it('no extension stored yet: the body is the object it extends and the returned key', async () => { + const { d, calls } = doors({}); + await saveObjectExtensionArrangement( + { objectName: 'lead', basePackageId: BASE, arrange: () => ({ relatedLists: ['task'] }) }, + TEXTS, + d, + ); + expect(calls.find(([c]) => c === 'save')?.[3]).toEqual({ extend: 'lead', relatedLists: ['task'] }); + }); + + it('a key returned undefined is taken off (the base arrangement is served again)', () => { + expect(extensionWithArrangement({ extend: 'lead', relatedLists: ['task'], place: [] }, 'lead', { relatedLists: undefined })).toEqual({ + extend: 'lead', + place: [], + }); + }); + + it('a pair the server answers read-only, or an unlisted base: refused before anything is written', async () => { + for (const [opts, sentence, expected] of [ + [{ pairWritable: false }, 'pair not writable', ['ensure']], + [{ listed: false }, 'not listed', []], + ] as const) { + const { d, calls } = doors(opts); + await expect( + saveObjectExtensionArrangement({ objectName: 'lead', basePackageId: BASE, arrange: () => ({ relatedLists: [] }) }, TEXTS, d), + ).rejects.toThrow(sentence); + expect(calls.map(([c]) => c)).toEqual(expected); + } + }); + + it('a draft already pending is refused with its sentence; a refused publish discards the draft this save wrote', async () => { + const conflict = Object.assign(new Error('conflict'), { status: 409, code: 'METADATA_CONFLICT' }); + const pending = doors({ save: () => Promise.reject(conflict) }); + await expect( + saveObjectExtensionArrangement({ objectName: 'lead', basePackageId: BASE, arrange: () => ({ relatedLists: [] }) }, TEXTS, pending.d), + ).rejects.toThrow('pending draft'); + expect(pending.calls.map(([c]) => c)).not.toContain('publish'); + + const refused = doors({ publish: () => Promise.reject(new Error('refused')) }); + await expect( + saveObjectExtensionArrangement({ objectName: 'lead', basePackageId: BASE, arrange: () => ({ relatedLists: [] }) }, TEXTS, refused.d), + ).rejects.toThrow('refused'); + expect(refused.calls.at(-1)).toEqual(['reset', 'object_extension', 'lead', { state: 'draft', packageId: PAIR }]); + expect(refused.refreshed).toHaveBeenCalledTimes(1); + }); +}); diff --git a/ui/packages/app-shell/src/views/__tests__/recordTabsConfigSave-36499.test.ts b/ui/packages/app-shell/src/views/__tests__/recordTabsConfigSave-36499.test.ts index 4706e027845..5b63e3264f2 100644 --- a/ui/packages/app-shell/src/views/__tests__/recordTabsConfigSave-36499.test.ts +++ b/ui/packages/app-shell/src/views/__tests__/recordTabsConfigSave-36499.test.ts @@ -19,7 +19,7 @@ const emitMetadataRefresh = vi.fn(); import { recordTabsCatalog, type RecordTabsDraft } from '../recordTabsConfig'; import { resolveRecordTabsSaveTarget, saveRecordTabs, type RecordTabsSaveDoors } from '../recordTabsConfigSave'; -const TEXTS = { notListed: 'not listed', pendingDraft: 'pending draft', notWritable: 'not writable' }; +const TEXTS = { notListed: 'not listed', pendingDraft: 'pending draft', notWritable: 'not writable', pairNotWritable: 'pair not writable' }; const PKG = 'app.crm'; const served = { name: 'account', @@ -40,7 +40,15 @@ function doors(opts: { writable?: boolean; listed?: boolean; save?: () => Promis const calls: Array<[string, ...unknown[]]> = []; const d: RecordTabsSaveDoors = { listPackages: async () => (opts.listed === false ? new Map() : new Map([[PKG, { writable: opts.writable ?? true }]])), + ensureCustomization: async (base) => { + calls.push(['ensure', base]); + return { packageId: `${base}.custom`, writable: false }; + }, client: { + get: async (...args) => { + calls.push(['get', ...args]); + return null; + }, layered: async (...args) => { calls.push(['layered', ...args]); const code = { name: 'account', label: 'Account', fields: {}, relatedLists: [{ list: 'contact', columns: ['name'] }], _packageId: PKG }; @@ -105,22 +113,17 @@ describe("saving the record page's tabs (objectstack#36499)", () => { expect(calls[3]).toEqual(['reset', 'object', 'account', { state: 'draft', packageId: PKG }]); }); - it('a read-only (installed) package or an unlisted one: refused before anything is read or written', async () => { - for (const [opts, sentence] of [ - [{ writable: false }, 'not writable'], - [{ listed: false }, 'not listed'], - ] as const) { - const { d, calls } = doors(opts); - await expect(saveRecordTabs({ objectName: 'account', packageId: PKG, draft: DRAFT, catalog }, TEXTS, d)).rejects.toThrow( - sentence, - ); - expect(calls).toEqual([]); - } + it('an unlisted package: refused before anything is read or written', async () => { + const { d, calls } = doors({ listed: false }); + await expect(saveRecordTabs({ objectName: 'account', packageId: PKG, draft: DRAFT, catalog }, TEXTS, d)).rejects.toThrow( + 'not listed', + ); + expect(calls).toEqual([]); }); - it('the one seam: a writable package is the target; anything else has none yet', () => { + it('the one seam: a writable package is the target, a read-only one its pair, an unlisted one none', () => { expect(resolveRecordTabsSaveTarget(PKG, new Map([[PKG, { writable: true }]]))).toEqual({ kind: 'package', packageId: PKG }); - expect(resolveRecordTabsSaveTarget(PKG, new Map([[PKG, { writable: false }]]))).toBeNull(); + expect(resolveRecordTabsSaveTarget(PKG, new Map([[PKG, { writable: false }]]))).toEqual({ kind: 'pair', basePackageId: PKG }); expect(resolveRecordTabsSaveTarget(PKG, new Map())).toBeNull(); }); }); diff --git a/ui/packages/app-shell/src/views/__tests__/recordTabsInstalled-36499.test.ts b/ui/packages/app-shell/src/views/__tests__/recordTabsInstalled-36499.test.ts new file mode 100644 index 00000000000..289be13ca25 --- /dev/null +++ b/ui/packages/app-shell/src/views/__tests__/recordTabsInstalled-36499.test.ts @@ -0,0 +1,147 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * 「Configure tabs」 on an installed object (objectstack#36499, card items 4 + * and 7): the draft opens on what the page draws (another package's list and + * the built-in tabs in their places), every tab moves, a related one hides; + * a save writes the paired `.custom` extension's `relatedLists` in the spec's + * shape (the shown tabs in order, a built-in bare, every hidden related tab + * written hidden) with the STORED names and columns; the preview draws the + * draft; each tab names where it comes from. + */ + +import { describe, expect, it } from 'vitest'; +import { RECORD_PAGE_BUILTIN_TABS } from '@objectstack/spec/data'; +import { deriveRelatedLists } from '../../utils/deriveRelatedLists'; +import { editRecordTabsDraft, recordTabsCatalog } from '../recordTabsConfig'; +import { + initialInstalledTabsDraft, + installedTabsEntries, + previewInstalledTabsObject, + recordTabSource, +} from '../recordTabsInstalled'; + +const BASE = 'app.hotcrm'; +const PAIR = 'app.hotcrm.custom'; +const toLead = { type: 'lookup', reference: 'lead' }; + +const lead = { + name: 'lead', + _packageId: BASE, + enable: { files: true }, + // Served: the owner's declared list, its title translated for the reader. + relatedLists: [{ list: 'contact', label: 'Kontakte', columns: ['name'] }, 'task'], +}; +const OBJECTS = [ + lead, + { name: 'contact', _packageId: BASE, fields: { lead: toLead } }, + { name: 'task', _packageId: BASE, fields: { lead: toLead } }, + { name: 'meeting', _packageId: BASE, fields: { lead__c: toLead } }, + { name: 'campaign_member', _packageId: 'com.marketing', fields: { lead: toLead } }, + { name: 'survey', _packageId: PAIR, fields: { lead: toLead } }, +]; +const OWNER_STORED = [{ list: 'contact', label: 'Contacts', columns: ['name'] }, 'task']; + +const catalog = recordTabsCatalog(lead, OBJECTS); + +describe('the draft an installed object opens on (objectstack#36499)', () => { + it("what the page draws: the owner's tabs, another package's and the environment's after them, then 审批 and 动态; unlisted attachments hidden", () => { + const draft = initialInstalledTabsDraft(lead, OBJECTS, catalog); + expect(draft.order).toEqual([ + 'contact.lead', + 'task.lead', + 'campaign_member.lead', + 'survey.lead', + 'sys_approval_request', + 'sys_activity', + ]); + expect(draft.hidden).toEqual(['meeting.lead__c', 'sys_attachment']); + expect(draft.labels).toEqual({ 'contact.lead': 'Kontakte' }); + }); + + it("the environment's arrangement as served: its order, its hidden names hidden, a built-in at its place", () => { + const arranged = { + ...lead, + relatedLists: ['sys_activity', 'campaign_member', { list: 'contact', label: 'People' }, 'sys_attachment'], + _relatedListsArrangement: { packageId: PAIR, hidden: ['task'], unlisted: 'hidden' }, + }; + const draft = initialInstalledTabsDraft(arranged, OBJECTS, recordTabsCatalog(arranged, OBJECTS)); + expect(draft.order).toEqual([ + 'sys_activity', + 'campaign_member.lead', + 'contact.lead', + 'sys_attachment', + 'survey.lead', + 'sys_approval_request', + ]); + expect(draft.hidden).toEqual(['task.lead', 'meeting.lead__c']); + }); +}); + +describe('what a save writes into the pair', () => { + const initial = initialInstalledTabsDraft(lead, OBJECTS, catalog); + + it('every shown tab in order (a built-in bare), every hidden related tab written hidden; stored title and columns, not the served translation', () => { + let draft = editRecordTabsDraft(initial, { kind: 'move', id: 'sys_activity', to: 0 }); + draft = editRecordTabsDraft(draft, { kind: 'hide', id: 'task.lead' }); + draft = editRecordTabsDraft(draft, { kind: 'hide', id: 'campaign_member.lead' }); + expect(installedTabsEntries(draft, catalog, { extension: undefined, owner: OWNER_STORED }, initial)).toEqual([ + 'sys_activity', + { list: 'contact', label: 'Contacts', columns: ['name'] }, + 'survey', + 'sys_approval_request', + { list: 'meeting', hidden: true }, + { list: 'task', hidden: true }, + { list: 'campaign_member', hidden: true }, + ]); + }); + + it("a rename is written; the pair's own stored entry wins over the owner's; restoring the attachments tab names it", () => { + let draft = editRecordTabsDraft(initial, { kind: 'rename', id: 'contact.lead', label: 'People' }); + draft = editRecordTabsDraft(draft, { kind: 'restore', id: 'sys_attachment' }); + const entries = installedTabsEntries( + draft, + catalog, + { extension: [{ list: 'task', label: 'To-dos', columns: ['subject'] }], owner: OWNER_STORED }, + initial, + ); + expect(entries.slice(0, 3)).toEqual([ + { list: 'contact', label: 'People', columns: ['name'] }, + { list: 'task', label: 'To-dos', columns: ['subject'] }, + 'campaign_member', + ]); + expect(entries).toContain('sys_attachment'); + }); + + it('a stored entry naming no list the editor offers is kept as it was', () => { + const entries = installedTabsEntries(initial, catalog, { extension: ['ghost', { list: 'phantom', hidden: true }], owner: OWNER_STORED }, initial); + expect(entries).toContain('ghost'); + expect(entries.at(-1)).toEqual({ list: 'phantom', hidden: true }); + }); + + it('the preview draws the draft: the shown related tabs in its order, the hidden ones gone', () => { + let draft = editRecordTabsDraft(initial, { kind: 'hide', id: 'task.lead' }); + draft = editRecordTabsDraft(draft, { kind: 'move', id: 'survey.lead', to: 0 }); + const preview = previewInstalledTabsObject(lead, draft, catalog); + const shown = deriveRelatedLists(preview as never, OBJECTS as never[]).map((l) => `${l.childObject}.${l.referenceField}`); + expect(shown).toEqual(['survey.lead', 'contact.lead', 'campaign_member.lead']); + expect((preview.relatedLists as unknown[]).filter((e) => (RECORD_PAGE_BUILTIN_TABS as readonly unknown[]).includes(e))).toEqual([ + 'sys_approval_request', + 'sys_activity', + ]); + }); +}); + +describe('where each tab comes from (card item 7)', () => { + it('the original package, another package, or this environment (no package, the .custom package, a __c field)', () => { + const source = (childObject: string, referenceField = 'lead') => recordTabSource({ childObject, referenceField }, lead, [ + ...OBJECTS, + { name: 'note_env', _packageId: 'sys_metadata', fields: { lead: toLead } }, + ]); + expect(source('contact')).toEqual({ kind: 'base' }); + expect(source('campaign_member')).toEqual({ kind: 'package', packageId: 'com.marketing' }); + expect(source('survey')).toEqual({ kind: 'environment' }); + expect(source('note_env')).toEqual({ kind: 'environment' }); + expect(source('meeting', 'lead__c')).toEqual({ kind: 'environment' }); + }); +}); diff --git a/ui/packages/app-shell/src/views/objectExtensionArrangementSave.ts b/ui/packages/app-shell/src/views/objectExtensionArrangementSave.ts new file mode 100644 index 00000000000..d0b27016c7c --- /dev/null +++ b/ui/packages/app-shell/src/views/objectExtensionArrangementSave.ts @@ -0,0 +1,157 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The ONE write of an installed object's arrangement (ADR-0146 D2/D3/D10): the + * keys `CUSTOM_ARRANGEMENT_KEYS` names (`fieldGroups`, `relatedLists`), written + * into the object extension of the base's paired `.custom` package and + * published at once, so everyone sees it. + * + * Every arrangement editor of an installed object is a caller of this one + * writer, never a second writer: the record page's 「Configure tabs」 hands it + * `relatedLists` (objectstack#36499); a field-layout editor hands it + * `fieldGroups` the same way. + * + * - Where: the pair the ensure door answers for the object's package + * (`ensureCustomizationPackage`, which creates it on first use and names + * it). The pair's id is never spelled here. A pair the server does not list + * writable is refused before anything is written to it. + * - What: the pair's stored extension of the object (`object_extension`, + * filed under the object's name), every key it holds kept (`fields`, + * `fieldPatches`, `place`, the other arrangement key, …), with ONLY the keys + * the caller returns replaced. A key returned `undefined` is taken off (the + * base's arrangement is served again). With no stored extension yet, the + * body is `{ extend: }` plus those keys. + * - From what: the caller composes its keys over what is STORED, never over + * what is served (`arrange` receives the stored extension and the stored + * object of the layered read): the served object carries read decorations + * and translated labels, and the folded result of every package. + * - How: the runtime's confirmed-save rule (objectstack#35955), as the record + * page's own save and the design mode's menu save: 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; + * a publish the server refuses discards the draft this save wrote; a landed + * publish announces itself and the console reads the object again. + * + * @module + */ + +import { stripReadDecorations } from '@objectstack/spec/kernel'; +import type { CustomArrangementKey } from '@objectstack/spec/data'; +import { isDraftVersionConflict } from './metadata-admin/DraftConflictDialog.js'; +import { OBJECT_EXTENSION_TYPE, objectExtensionBodyOf, type ObjectExtensionBody } from './studio-design/StudioCustomizeControls.js'; +import type { EnsuredCustomizationPackage, ListedPackageManifest } from './studio-design/packages-io.js'; + +/** The doors the write goes through; the defaults are the console's own (`consoleExtensionArrangementDoors`). */ +export interface ExtensionArrangementDoors { + readonly listPackages: () => Promise>>; + readonly ensureCustomization: (basePackageId: string) => Promise>; + readonly client: { + get: (type: string, name: string, options: { packageId?: string }) => Promise; + 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; + }; + /** Announces the object changed, so the console reads it again. */ + readonly refreshed: () => void; +} + +/** The sentences a refused write is said with, in the viewer's language. */ +export interface ExtensionArrangementTexts { + /** The object's package is not one the server lists. */ + readonly notListed: string; + /** A draft of the pair's extension is already pending. */ + readonly pendingDraft: string; + /** The customization package the server answered is not writable. */ + readonly notWritable: string; +} + +/** What a caller composes its keys over: both as STORED. */ +export interface StoredArrangement { + /** The pair's stored extension of the object, `null` when it has none yet. */ + readonly extension: ObjectExtensionBody | null; + /** The object as its own package stores it (the layered read), never as served. */ + readonly object: Record; +} + +/** The arrangement keys to write: a key present replaces the stored one; `undefined` takes it off. */ +export type ExtensionArrangementPatch = Partial>; + +/** 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 object of a layered read: its effective layer, else its code. */ +function storedObjectOf(layers: unknown): Record { + const read = (layers ?? {}) as { effective?: unknown; code?: unknown }; + return documentOf(read.effective ?? read.code ?? {}); +} + +/** `stored` with `patch`'s keys replaced (or taken off), every other key kept. */ +export function extensionWithArrangement( + stored: ObjectExtensionBody | null, + objectName: string, + patch: ExtensionArrangementPatch, +): ObjectExtensionBody { + const body: ObjectExtensionBody = { ...(stored ?? {}), extend: objectName }; + for (const [key, value] of Object.entries(patch)) { + if (value === undefined) delete body[key]; + else body[key] = value; + } + return body; +} + +/** + * Write `arrange`'s keys into the pair's extension of the object `objectName` + * of the read-only package `basePackageId`, and publish it. Answers the pair's + * id. + */ +export async function saveObjectExtensionArrangement( + input: { + objectName: string; + basePackageId: string; + arrange: (stored: StoredArrangement) => ExtensionArrangementPatch; + }, + texts: ExtensionArrangementTexts, + doors: ExtensionArrangementDoors, +): Promise { + const { objectName, basePackageId, arrange } = input; + const manifests = await doors.listPackages(); + if (!manifests.has(basePackageId)) throw new Error(texts.notListed); + const pair = await doors.ensureCustomization(basePackageId); + if (!pair.writable) throw new Error(texts.notWritable); + const target = pair.packageId; + const [extensionRead, objectRead] = await Promise.all([ + doors.client.get(OBJECT_EXTENSION_TYPE, objectName, { packageId: target }), + doors.client.layered('object', objectName, { packageId: basePackageId }), + ]); + const extension = objectExtensionBodyOf(extensionRead, objectName); + const body = extensionWithArrangement( + extension, + objectName, + arrange({ extension, object: storedObjectOf(objectRead) }), + ); + try { + await doors.client.save(OBJECT_EXTENSION_TYPE, objectName, 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(OBJECT_EXTENSION_TYPE, objectName, { packageId: target }); + } catch (err) { + try { + await doors.client.reset(OBJECT_EXTENSION_TYPE, objectName, { state: 'draft', packageId: target }); + } catch (discardErr) { + console.error('[object-extension] a refused publish left the extension draft pending:', discardErr); + } + doors.refreshed(); + throw err; + } + doors.refreshed(); + return target; +} diff --git a/ui/packages/app-shell/src/views/recordTabsConfig.ts b/ui/packages/app-shell/src/views/recordTabsConfig.ts index f19f6a88b42..51accb2948e 100644 --- a/ui/packages/app-shell/src/views/recordTabsConfig.ts +++ b/ui/packages/app-shell/src/views/recordTabsConfig.ts @@ -230,6 +230,22 @@ export function editRecordTabsDraft(draft: RecordTabsDraft, edit: RecordTabsEdit } } +/** + * The `label` a save writes for the tab `id`: the draft's name where the + * editor renamed it (`initial` given and the name moved), else `stored`, the + * label the stored entry naming the list already carries. With no `initial`, + * the draft's name. + */ +export function recordTabLabelToWrite( + id: RecordTabId, + draft: RecordTabsDraft, + initial: RecordTabsDraft | undefined, + stored: string | undefined, +): string | undefined { + if (initial === undefined || draft.labels[id] !== initial.labels[id]) return draft.labels[id]; + return stored; +} + /** * The object's `relatedLists` the draft makes, written over `base` (the * object's stored `relatedLists`): `undefined` when nothing is to be declared @@ -238,7 +254,12 @@ export function editRecordTabsDraft(draft: RecordTabsDraft, edit: RecordTabsEdit * - Each shown related tab the editor arranges, in its order, as Studio * spells an entry (`relationshipEntry`: the child, or `child.field` where * the child points here more than once), with the `columns` of the base - * entry that named it and the draft's name for it. + * entry that named it and the draft's name for it. Given `initial` (the + * draft the editor opened on), a tab the editor did not rename keeps the + * base entry's own `label`: the name the editor shows is the served one, + * which the read translates for the reader's language + * (`objects.OBJECT._relatedLists.LIST.label`), so writing it back would + * store a translation as the source. * - The attachments tab where the object enables files and it is shown: * at the base entry's place, else after the related tabs. * - Every other base entry: the built-in 审批 / 动态 names, and an entry @@ -254,6 +275,7 @@ export function recordTabsEntries( draft: RecordTabsDraft, base: readonly unknown[] | undefined, catalog: RecordTabsCatalog, + initial?: RecordTabsDraft, ): RelatedListEntryInput[] | undefined { const baseEntries = Array.isArray(base) ? base : []; const arranged = catalog.candidates.filter((c) => c.fromPackage === undefined); @@ -278,9 +300,10 @@ export function recordTabsEntries( const candidate = arrangedById.get(id); if (!candidate) continue; const at = baseIndexOf(candidate.list); - const { columns } = entryDetails(at >= 0 ? baseEntries[at] : undefined); + const stored = entryDetails(at >= 0 ? baseEntries[at] : undefined); + const label = recordTabLabelToWrite(id, draft, initial, stored.label); const name = relationshipEntry(candidate.list, catalog.relationships); - out.push({ entry: entryWithDetails(name, { label: draft.labels[id], columns }), baseIndex: at }); + out.push({ entry: entryWithDetails(name, { label, columns: stored.columns }), baseIndex: at }); } // Each base entry kept: one past the last related entry the editor // arranges stays at the end; any other after the entry that followed the diff --git a/ui/packages/app-shell/src/views/recordTabsConfigIo.tsx b/ui/packages/app-shell/src/views/recordTabsConfigIo.tsx index fe4343c38fc..9162c4ca887 100644 --- a/ui/packages/app-shell/src/views/recordTabsConfigIo.tsx +++ b/ui/packages/app-shell/src/views/recordTabsConfigIo.tsx @@ -4,8 +4,10 @@ * What 「Configure tabs」 reads and writes through, loaded only once its edit * state opens (objectstack#36499): the console's metadata client (the one * every app-shell write takes, `useMetadataClient`), the object's stored - * `relatedLists`, and whether the reader's language is the deployment's - * default (the rename gate's precedent). + * `relatedLists` (on an installed object whose tabs the paired `.custom` + * package arranges, its extension's entries first), the listed packages' + * names (a tab's source, card item 7), and whether the reader's language is + * the deployment's default (the rename gate's precedent). * * It sits behind `React.lazy` so the record page's own module graph does not * gain the metadata client's module (it mints its authenticated fetch when it @@ -18,7 +20,8 @@ import * as React from 'react'; import { fetchDefaultLocale, isSameLanguage } from '../layout/designModeMenuSave.js'; import { useMetadataClient } from './metadata-admin/useMetadata.js'; -import { readStoredRelatedLists, type RecordTabsSaveDoors } from './recordTabsConfigSave.js'; +import { fetchListedPackageManifests } from './studio-design/packages-io.js'; +import { readStoredTabEntries, type RecordTabsSaveDoors } from './recordTabsConfigSave.js'; export interface RecordTabsIo { readonly client: RecordTabsSaveDoors['client']; @@ -26,36 +29,49 @@ export interface RecordTabsIo { readonly stored: { readonly objectName: string; readonly lists: unknown[] | null } | null; /** The reader's language is the deployment's default. */ readonly sourceLanguage: boolean; + /** The listed packages' names, by id (empty until read, or when the read failed). */ + readonly packageNames: ReadonlyMap; } export interface RecordTabsConfigIoProps { readonly objectName: string; readonly packageId: string; + /** The `.custom` package that arranges the object's tabs now (`_relatedListsArrangement`), else `null`. */ + readonly pairId: string | null; readonly language: string; readonly onIo: (io: RecordTabsIo) => void; } -export default function RecordTabsConfigIo({ objectName, packageId, language, onIo }: RecordTabsConfigIoProps) { +const NO_NAMES: ReadonlyMap = new Map(); + +export default function RecordTabsConfigIo({ objectName, packageId, pairId, language, onIo }: RecordTabsConfigIoProps) { const client = useMetadataClient() as unknown as RecordTabsSaveDoors['client']; const [stored, setStored] = React.useState(null); const [defaultLocale, setDefaultLocale] = React.useState(null); + const [packageNames, setPackageNames] = React.useState>(NO_NAMES); React.useEffect(() => { let cancelled = false; - void readStoredRelatedLists(objectName, packageId, client).then((lists) => { + void readStoredTabEntries(objectName, packageId, pairId, client).then((lists) => { if (!cancelled) setStored({ objectName, lists }); }); + void fetchListedPackageManifests().then( + (listed) => { + if (!cancelled) setPackageNames(new Map([...listed].map(([id, entry]) => [id, entry.name || id] as const))); + }, + () => undefined, + ); void fetchDefaultLocale().then((code) => { if (!cancelled) setDefaultLocale(code); }); return () => { cancelled = true; }; - }, [objectName, packageId, client]); + }, [objectName, packageId, pairId, client]); const sourceLanguage = !!defaultLocale && isSameLanguage(language, defaultLocale); React.useEffect(() => { - onIo({ client, stored, sourceLanguage }); - }, [onIo, client, stored, sourceLanguage]); + onIo({ client, stored, sourceLanguage, packageNames }); + }, [onIo, client, stored, sourceLanguage, packageNames]); return null; } diff --git a/ui/packages/app-shell/src/views/recordTabsConfigSave.ts b/ui/packages/app-shell/src/views/recordTabsConfigSave.ts index 0b6c604e246..dd68791acb7 100644 --- a/ui/packages/app-shell/src/views/recordTabsConfigSave.ts +++ b/ui/packages/app-shell/src/views/recordTabsConfigSave.ts @@ -7,12 +7,13 @@ * * Where it is written is decided once, here ({@link resolveRecordTabsSaveTarget}): * the object's own package, when the server lists it writable (an object of a - * self-built app). An object of a package the server lists read-only (an - * installed app) is not offered the entry yet: its arrangement belongs in the - * base's paired `.custom` package (ADR-0146 D10), a second target of this one - * seam, never a second editor. + * self-built app); else, for a package the server lists read-only (an + * installed app), the object extension of the base's paired `.custom` + * package (ADR-0146 D10), written by the one arrangement writer + * (`saveObjectExtensionArrangement`) in the extension's own shape + * (`installedTabsEntries`). * - * What is written is the object as STORED, never as served — the precedent of + * What is written is composed over what is STORED, never what is served — the precedent of * the design mode's menu save (`saveAppMenu`, objectstack#36363, review * 7081226692): the served object carries read decorations and may carry * another package's `place` spliced into its `relatedLists`, so writing it @@ -34,15 +35,22 @@ import { stripReadDecorations } from '@objectstack/spec/kernel'; import { emitMetadataRefresh } from '../assistant/assistantBus.js'; import { isDraftVersionConflict } from './metadata-admin/DraftConflictDialog.js'; import { + ensureCustomizationPackage, fetchListedPackageManifests, type ListedPackageManifest, } from './studio-design/packages-io.js'; import { recordTabsEntries, type RecordTabsCatalog, type RecordTabsDraft } from './recordTabsConfig.js'; +import { saveObjectExtensionArrangement, type ExtensionArrangementDoors } from './objectExtensionArrangementSave.js'; +import { installedTabsEntries } from './recordTabsInstalled.js'; +import { OBJECT_EXTENSION_TYPE, objectExtensionBodyOf } from './studio-design/StudioCustomizeControls.js'; /** The doors the save goes through; the defaults are the console's own. */ export interface RecordTabsSaveDoors { readonly listPackages: () => Promise>>; + /** The ensure door: the base's paired `.custom` package, created on first use. */ + readonly ensureCustomization: ExtensionArrangementDoors['ensureCustomization']; readonly client: { + get: (type: string, name: string, options: { packageId?: string }) => Promise; 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; @@ -60,25 +68,31 @@ export interface RecordTabsSaveTexts { readonly pendingDraft: string; /** The object's package is not writable. */ readonly notWritable: string; + /** The customization package the server answered for an installed object is not writable. */ + readonly pairNotWritable: string; } /** - * Where a save of an object's tabs lands. One kind today: the object's own - * package. The installed-object arrangement (the paired `.custom` package's - * object extension) is the second kind this union grows. + * Where a save of an object's tabs lands: the object's own package, or the + * paired `.custom` package of the read-only base it belongs to (its object + * extension, through the ensure door). */ -export type RecordTabsSaveTarget = { readonly kind: 'package'; readonly packageId: string }; +export type RecordTabsSaveTarget = + | { readonly kind: 'package'; readonly packageId: string } + | { readonly kind: 'pair'; readonly basePackageId: string }; /** * The target for an object of `packageId`, from the package list: its own - * package when listed writable, else `null` (not offered here). + * package when listed writable, the base's pair when listed read-only, else + * `null` (a package the server does not list). */ export function resolveRecordTabsSaveTarget( packageId: string, manifests: ReadonlyMap>, ): RecordTabsSaveTarget | null { const listed = manifests.get(packageId); - return listed?.writable ? { kind: 'package', packageId } : null; + if (!listed) return null; + return listed.writable ? { kind: 'package', packageId } : { kind: 'pair', basePackageId: packageId }; } /** A document as stored, less what a read adds and what belongs to its package. */ @@ -97,21 +111,49 @@ export function storedObjectOf(layers: unknown): Record { /** * Save `draft` as the record-page tabs of the object `objectName` of the - * package `packageId`, and publish it. + * package `packageId`, and publish it. `initial` is the draft the editor + * opened on: a tab it did not rename keeps its stored name. */ export async function saveRecordTabs( - input: { objectName: string; packageId: string; draft: RecordTabsDraft; catalog: RecordTabsCatalog }, + input: { + objectName: string; + packageId: string; + draft: RecordTabsDraft; + catalog: RecordTabsCatalog; + initial?: RecordTabsDraft; + }, texts: RecordTabsSaveTexts, doors: RecordTabsSaveDoors, ): Promise { - const { objectName, packageId, draft, catalog } = input; + const { objectName, packageId, draft, catalog, initial } = input; const manifests = await doors.listPackages(); - if (!manifests.has(packageId)) throw new Error(texts.notListed); const target = resolveRecordTabsSaveTarget(packageId, manifests); - if (!target) throw new Error(texts.notWritable); + if (!target) throw new Error(texts.notListed); + if (target.kind === 'pair') { + await saveObjectExtensionArrangement( + { + objectName, + basePackageId: target.basePackageId, + arrange: ({ extension, object }) => ({ + relatedLists: installedTabsEntries( + draft, + catalog, + { + extension: Array.isArray(extension?.relatedLists) ? (extension.relatedLists as unknown[]) : undefined, + owner: Array.isArray(object.relatedLists) ? (object.relatedLists as unknown[]) : undefined, + }, + initial, + ), + }), + }, + { notListed: texts.notListed, pendingDraft: texts.pendingDraft, notWritable: texts.pairNotWritable }, + { ...doors, listPackages: async () => manifests }, + ); + return; + } const stored = storedObjectOf(await doors.client.layered('object', objectName, { packageId: target.packageId })); const base = Array.isArray(stored.relatedLists) ? (stored.relatedLists as unknown[]) : undefined; - const entries = recordTabsEntries(draft, base, catalog); + const entries = recordTabsEntries(draft, base, catalog, initial); const { relatedLists: _previous, ...rest } = stored; const body: Record = { ...rest, name: objectName, ...(entries ? { relatedLists: entries } : {}) }; try { @@ -136,7 +178,12 @@ export async function saveRecordTabs( /** The console's doors, around `client` (`useMetadataClient()`). */ export function consoleRecordTabsDoors(client: RecordTabsSaveDoors['client']): RecordTabsSaveDoors { - return { listPackages: fetchListedPackageManifests, client, refreshed: emitMetadataRefresh }; + return { + listPackages: fetchListedPackageManifests, + ensureCustomization: ensureCustomizationPackage, + client, + refreshed: emitMetadataRefresh, + }; } /** @@ -156,3 +203,26 @@ export async function readStoredRelatedLists( return null; } } + +/** + * The stored entries a tab's shown name is compared with (the rename gate) on + * an object of `packageId`: on an installed object whose tabs the pair + * `pairId` arranges, the pair's stored extension entries first, then the + * owner's (the first entry naming a list is the stored one); else the owner's + * alone. `null` when a read fails. + */ +export async function readStoredTabEntries( + objectName: string, + packageId: string, + pairId: string | null, + client: Pick, +): Promise { + const owner = await readStoredRelatedLists(objectName, packageId, client); + if (owner === null || pairId === null) return owner; + try { + const extension = objectExtensionBodyOf(await client.get(OBJECT_EXTENSION_TYPE, objectName, { packageId: pairId }), objectName); + return [...(Array.isArray(extension?.relatedLists) ? (extension.relatedLists as unknown[]) : []), ...owner]; + } catch { + return null; + } +} diff --git a/ui/packages/app-shell/src/views/recordTabsInstalled.ts b/ui/packages/app-shell/src/views/recordTabsInstalled.ts new file mode 100644 index 00000000000..631b5cf4eae --- /dev/null +++ b/ui/packages/app-shell/src/views/recordTabsInstalled.ts @@ -0,0 +1,291 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * 「Configure tabs」 on an INSTALLED object (objectstack#36499, ADR-0146 + * D10): the record page's tab list the environment arranges, written as the + * `relatedLists` of the object extension of the base's paired `.custom` + * package (`saveObjectExtensionArrangement`), as a pure model. + * + * ## What the environment may arrange (the spec's `.custom` `relatedLists`) + * + * Every tab, whoever brings it: the object's own lists, a list another + * package brings, and the three built-in tabs (附件, 审批, 动态), each moved to + * any place. A related tab is hidden by writing it (`{ list, hidden: true }`); + * a tab the list does not name still shows, after the listed ones. A built-in + * tab is written only as its bare name and cannot be hidden there: the editor + * moves it and offers no hide. The attachments tab shows where it shows now; + * where the base hides it (a declared list that leaves it out), it waits in + * the 「Hidden」 area, and naming it shows it. + * + * ## What is written (the whole list, explicitly) + * + * Every shown tab in the editor's order (a built-in by its bare name), then + * every hidden related tab as `{ list, hidden: true }`. Nothing the editor + * offers is left to the unlisted rule, so the page shows exactly what the + * editor showed. An entry of the stored extension naming a list the editor + * does not offer (a child this reader may not read) is kept as it was. A + * tab's `label` is the stored one unless the editor renamed it: the shown + * name is the served one, which the read translates for the reader's + * language; its `columns` are the stored ones. "Stored" is the extension's + * entry naming the list, else the owner's (the object's layered read): the + * extension's list replaces the owner's whole, so an owner's title the + * extension does not repeat would be lost. + * + * ## Where each tab comes from (card item 7) + * + * The served read does not carry a tab's source (`_relatedListsArrangement` + * carries the arrangement's package, its hidden names and its unlisted rule, + * nothing per tab). It is read from the child object's package as served + * (`_packageId`) and the relationship field's name: the base's own package, + * another package, or this environment (no package, a `.custom` package, or a + * customer `__c` field). + * + * @module + */ + +import { + RELATED_LISTS_ARRANGEMENT_DECORATION, + RECORD_PAGE_BUILTIN_TABS, + isExtensionFieldName, + isRecordPageBuiltinTab, + readRelatedListsArrangement, + relatedListEntryHidden, + relatedListEntryName, + type ObjectExtensionRelatedListEntryObject, + type RelatedListsArrangement, +} from '@objectstack/spec/data'; +import { isCustomizationPackage } from '@objectstack/spec/kernel'; +import { deriveRelatedLists, relatedListEntryNames, type DerivedRelatedList } from '../utils/deriveRelatedLists.js'; +import { entryDetails, entryWithDetails, relationshipEntry } from './studio-design/relatedListVocabulary.js'; +import { + RECORD_TABS_ATTACHMENTS, + recordTabId, + recordTabLabelToWrite, + type RecordTabId, + type RecordTabsCatalog, + type RecordTabsDraft, +} from './recordTabsConfig.js'; + +type RecordTabsObjectDef = Record & { name?: string }; + +/** The `_packageId` the server stamps on a definition bound to no package. */ +const NO_PACKAGE = 'sys_metadata'; + +/** The package an object belongs to, as served (`_packageId`), or `null` for none. */ +export function recordTabsPackageOf(objectDef: Readonly> | null | undefined): string | null { + const id = objectDef?._packageId; + return typeof id === 'string' && id && id !== NO_PACKAGE ? id : null; +} + +/** Where one tab of an installed object comes from (card item 7). */ +export type RecordTabSource = + | { readonly kind: 'base' } + | { readonly kind: 'package'; readonly packageId: string } + | { readonly kind: 'environment' }; + +/** + * Where the related tab `list` of `objectDef` comes from: this environment + * when the child is bound to no package or to a `.custom` package, or the + * relationship is a customer `__c` field; the base's own package when the + * child is in the object's package; else the child's package. + */ +export function recordTabSource( + list: Pick, + objectDef: RecordTabsObjectDef, + objects: readonly RecordTabsObjectDef[], +): RecordTabSource { + if (isExtensionFieldName(list.referenceField)) return { kind: 'environment' }; + const child = objects.find((o) => o.name === list.childObject); + const childPackage = recordTabsPackageOf(child); + if (childPackage === null || isCustomizationPackage(childPackage)) return { kind: 'environment' }; + if (childPackage === recordTabsPackageOf(objectDef)) return { kind: 'base' }; + return { kind: 'package', packageId: childPackage }; +} + +/** The built-in tabs the editor draws for `catalog`, in the page's default order. */ +export function installedBuiltinTabs(catalog: RecordTabsCatalog): RecordTabId[] { + return RECORD_PAGE_BUILTIN_TABS.filter((name) => name !== RECORD_TABS_ATTACHMENTS || catalog.files); +} + +/** The first entry of `entries` naming the related list `list`, or `undefined`. */ +function namingEntry(entries: readonly unknown[] | undefined, list: DerivedRelatedList): unknown { + return (entries ?? []).find((entry) => { + const name = relatedListEntryName(entry); + return name !== undefined && !isRecordPageBuiltinTab(name) && relatedListEntryNames(name, list); + }); +} + +/** + * The tabs `ids` (related ids and built-in names, in the page's built order: + * related, then attachments, approvals, the stream) in the order the page + * draws them under the served `entries`, and the ones it does not draw — the + * synthesized page's own ranking (`arrangeDeclaredTabs` in + * `@object-ui/plugin-detail`), over ids. + */ +function arrangeTabIds( + ids: readonly RecordTabId[], + entries: readonly unknown[], + unlistedTabs: RelatedListsArrangement['unlisted'] | undefined, + listOf: (id: RecordTabId) => DerivedRelatedList | undefined, +): { shown: RecordTabId[]; dropped: RecordTabId[] } { + if (entries.length === 0 && unlistedTabs !== 'hidden') return { shown: [...ids], dropped: [] }; + const names = entries.map((entry) => relatedListEntryName(entry)); + const unlisted = names.length; + let tail = names.length; + while (tail > 0 && (names[tail - 1] === 'sys_approval_request' || names[tail - 1] === 'sys_activity')) tail -= 1; + const unlistedRelated = tail < names.length ? tail - 0.5 : unlisted; + const rank = (id: RecordTabId): number | null => { + if (isRecordPageBuiltinTab(id)) { + const at = names.indexOf(id); + if (at !== -1) return at; + if (id === RECORD_TABS_ATTACHMENTS) return unlistedTabs === 'shown' ? unlistedRelated : null; + return id === 'sys_activity' ? unlisted + 1 : unlisted; + } + const list = listOf(id); + if (!list) return unlistedRelated; + const at = names.findIndex((name) => name !== undefined && !isRecordPageBuiltinTab(name) && relatedListEntryNames(name, list)); + return at === -1 ? unlistedRelated : at; + }; + const ranked = ids.map((id, index) => ({ id, index, rank: rank(id) })); + const shown = ranked + .filter((entry): entry is { id: RecordTabId; index: number; rank: number } => entry.rank !== null) + .sort((a, b) => a.rank - b.rank || a.index - b.index) + .map((entry) => entry.id); + return { shown, dropped: ranked.filter((entry) => entry.rank === null).map((entry) => entry.id) }; +} + +/** + * The draft the editor opens on for an installed object: what the page shows + * now. The shown related tabs are the page's own derivation of the served + * object (the environment's arrangement applied); the built-in tabs sit where + * the page draws them; every other related list of the catalog, and an + * attachments tab the page does not draw, is hidden. A tab's name is the + * served `label` of the entry naming it. + */ +export function initialInstalledTabsDraft( + objectDef: RecordTabsObjectDef, + objects: readonly RecordTabsObjectDef[], + catalog: RecordTabsCatalog, + options: { canRead?: (objectName: string) => boolean } = {}, +): RecordTabsDraft { + const derived = deriveRelatedLists(objectDef as never, objects as never[], { + ...(options.canRead ? { canRead: options.canRead } : {}), + }); + const byId = new Map(catalog.candidates.map((c) => [c.id, c] as const)); + const related: RecordTabId[] = []; + for (const list of derived) { + if (list.isPrimary && list.keepsTab !== true) continue; + const id = recordTabId(list); + if (byId.has(id) && !related.includes(id)) related.push(id); + } + const served = Array.isArray(objectDef.relatedLists) ? (objectDef.relatedLists as unknown[]) : []; + const { shown, dropped } = arrangeTabIds( + [...related, ...installedBuiltinTabs(catalog)], + served, + readRelatedListsArrangement(objectDef)?.unlisted, + (id) => byId.get(id)?.list, + ); + const hidden = [...catalog.candidates.map((c) => c.id).filter((id) => !related.includes(id)), ...dropped]; + const labels: Record = {}; + for (const candidate of catalog.candidates) { + const { label } = entryDetails(namingEntry(served, candidate.list)); + if (label?.trim()) labels[candidate.id] = label; + } + return { order: shown, hidden, attachmentsHidden: false, labels }; +} + +/** One entry of the `.custom` extension's `relatedLists`: a bare name, or the object form (`hidden` included). */ +export type InstalledTabEntry = string | ObjectExtensionRelatedListEntryObject; + +/** What a save of an installed object's tabs composes over: both as stored. */ +export interface InstalledTabsStored { + /** The pair's stored extension's `relatedLists`, `undefined` when it declares none. */ + readonly extension: readonly unknown[] | undefined; + /** The owner's stored `relatedLists` (the object's layered read), `undefined` when it declares none. */ + readonly owner: readonly unknown[] | undefined; +} + +/** + * The `.custom` extension's `relatedLists` the draft makes (see the module + * header): the shown tabs in order, then the hidden related tabs written + * hidden, with the stored extension's entries naming no offered list kept. + */ +export function installedTabsEntries( + draft: RecordTabsDraft, + catalog: RecordTabsCatalog, + stored: InstalledTabsStored, + initial?: RecordTabsDraft, +): InstalledTabEntry[] { + const byId = new Map(catalog.candidates.map((c) => [c.id, c] as const)); + const storedEntry = (list: DerivedRelatedList) => namingEntry(stored.extension, list) ?? namingEntry(stored.owner, list); + const shown: InstalledTabEntry[] = []; + for (const id of draft.order) { + if (isRecordPageBuiltinTab(id)) { + if (!shown.includes(id)) shown.push(id); + continue; + } + const candidate = byId.get(id); + if (!candidate) continue; + const details = entryDetails(storedEntry(candidate.list)); + const label = recordTabLabelToWrite(id, draft, initial, details.label); + shown.push(entryWithDetails(relationshipEntry(candidate.list, catalog.relationships), { label, columns: details.columns })); + } + const hidden: InstalledTabEntry[] = []; + for (const id of draft.hidden) { + const candidate = byId.get(id); + if (!candidate) continue; + hidden.push({ list: relationshipEntry(candidate.list, catalog.relationships), hidden: true }); + } + // A stored entry naming no list the editor offers: kept as it was. + const kept = (stored.extension ?? []).filter((entry) => { + const name = relatedListEntryName(entry); + if (name === undefined || isRecordPageBuiltinTab(name)) return false; + return !catalog.relationships.some((list) => relatedListEntryNames(name, list)); + }) as InstalledTabEntry[]; + return [ + ...shown, + ...kept.filter((entry) => !relatedListEntryHidden(entry)), + ...hidden, + ...kept.filter((entry) => relatedListEntryHidden(entry)), + ]; +} + +/** + * The object as the page previews it while the editor is open on an installed + * object: `objectDef` with the draft's shown tabs as its `relatedLists` and + * the draft's hidden related tabs as the environment arrangement's hidden + * names, a declared list (`unlisted: 'hidden'`), so the page draws exactly + * the draft. + */ +export function previewInstalledTabsObject( + objectDef: T, + draft: RecordTabsDraft, + catalog: RecordTabsCatalog, +): T { + const { [RELATED_LISTS_ARRANGEMENT_DECORATION]: _arrangement, relatedLists: served, ...rest } = objectDef; + const servedEntries = Array.isArray(served) ? (served as unknown[]) : []; + const byId = new Map(catalog.candidates.map((c) => [c.id, c] as const)); + const relatedLists: unknown[] = []; + for (const id of draft.order) { + if (isRecordPageBuiltinTab(id)) { + relatedLists.push(id); + continue; + } + const candidate = byId.get(id); + if (!candidate) continue; + const { columns } = entryDetails(namingEntry(servedEntries, candidate.list)); + relatedLists.push( + entryWithDetails(relationshipEntry(candidate.list, catalog.relationships), { label: draft.labels[id], columns }), + ); + } + const hidden = draft.hidden + .map((id) => byId.get(id)) + .filter((c): c is NonNullable => c !== undefined) + .map((c) => relationshipEntry(c.list, catalog.relationships)); + const arrangement: RelatedListsArrangement = { + packageId: readRelatedListsArrangement(objectDef)?.packageId ?? `${recordTabsPackageOf(objectDef) ?? 'object'}.custom`, + hidden, + unlisted: 'hidden', + }; + return { ...rest, relatedLists, [RELATED_LISTS_ARRANGEMENT_DECORATION]: arrangement } as unknown as T; +} diff --git a/ui/packages/components/src/__tests__/page-header-overflow-close-36499.test.tsx b/ui/packages/components/src/__tests__/page-header-overflow-close-36499.test.tsx index 3c7986fd3da..2cb76f9577c 100644 --- a/ui/packages/components/src/__tests__/page-header-overflow-close-36499.test.tsx +++ b/ui/packages/components/src/__tests__/page-header-overflow-close-36499.test.tsx @@ -32,7 +32,7 @@ function PageHeader({ schema }: { schema: any }) { return ; } -function renderHeader(actions: any[]) { +function renderHeader(actions: any[], headerSystemActions?: any[]) { return render( @@ -42,6 +42,7 @@ function renderHeader(actions: any[]) { data={{ id: 'WO-1', name: 'WO-0001' }} objectSchema={{ name: 'mes_work_order', label: 'Work Order' }} refresh={vi.fn()} + headerSystemActions={headerSystemActions} > @@ -83,3 +84,26 @@ describe('page:header — a ⋯ entry that finished on the click closes the menu await waitFor(() => expect(screen.getByRole('menuitem', { name: 'Recompute' })).not.toHaveAttribute('aria-busy')); }); }); + +describe('page:header — a host entry declaring leadsMenu opens the ⋯, ahead of Refresh (objectstack#36499)', () => { + const host = (name: string, label: string, extra: Record = {}) => ({ + name, + label, + locations: ['record_header'], + component: 'action:menu', + onClick: vi.fn(), + ...extra, + }); + + it('the host entry is the first item; Refresh and the other entries follow in their bands', async () => { + renderHeader([], [host('sys_share', 'Share'), host('sys_configure_tabs', 'Configure tabs', { leadsMenu: true }), host('sys_delete', 'Delete')]); + await openMore(); + expect(screen.getAllByRole('menuitem').map((item) => item.textContent)).toEqual(['Configure tabs', 'Refresh', 'Share', 'Delete']); + }); + + it('an authored action cannot claim the place: it stays in its band, after Refresh', async () => { + renderHeader([{ name: 'approve', label: 'Approve', locations: ['record_more'], leadsMenu: true }], [host('sys_share', 'Share')]); + await openMore(); + expect(screen.getAllByRole('menuitem').map((item) => item.textContent)).toEqual(['Refresh', 'Approve', 'Share']); + }); +}); diff --git a/ui/packages/components/src/renderers/layout/containers.tsx b/ui/packages/components/src/renderers/layout/containers.tsx index 966685005ef..31fdfa9a1e7 100644 --- a/ui/packages/components/src/renderers/layout/containers.tsx +++ b/ui/packages/components/src/renderers/layout/containers.tsx @@ -1975,7 +1975,8 @@ export interface PageHeaderActionsProps { /** * The host's manual refresh (`RecordContext.refresh`), drawn as the first * item of the `⋯` menu (objectstack#27055, the v3 header: 「1 主 + 2 次 + ⋯ - * (刷新收进 ⋯)」). With a refresh and no action, the row is the `⋯` alone. + * (刷新收进 ⋯)」), after only a host entry that declares `leadsMenu: true` + * (objectstack#36499). With a refresh and no action, the row is the `⋯` alone. */ refresh?: PageHeaderRefreshItem; /** @@ -2813,16 +2814,24 @@ export const PageHeaderActions: React.FC = ({ // authored actions first, then the host's menu chrome (favorites / // Share), then every destructive entry last, set apart by a separator. // Each band keeps the `order` sort the memo above gave it. + // + // A host entry declaring `leadsMenu: true` opens the menu instead, ahead + // of the host's refresh (objectstack#36499: the record page's 「Configure + // tabs」 is the first item of its `⋯`). Only the host's own entries lead: + // an authored action's key is never a host key, so metadata cannot claim + // the place. + const leadsMenu = (a: any): boolean => isHostAction(a) && !isDestructiveAction(a) && a?.leadsMenu === true; const overflowPool = [...foldedButtons, ...menuOnly, ...moreOnlyActions]; + const leadingActions = overflowPool.filter(leadsMenu); const overflowActions = [ ...overflowPool.filter((a) => !isDestructiveAction(a) && !isHostAction(a)), - ...overflowPool.filter((a) => !isDestructiveAction(a) && isHostAction(a)), + ...overflowPool.filter((a) => !isDestructiveAction(a) && isHostAction(a) && !leadsMenu(a)), ...overflowPool.filter(isDestructiveAction), ]; // The first destructive entry gets a separator above it, unless it opens // the menu (a separator under nothing sets nothing apart). const firstDestructiveIdx = overflowActions.findIndex(isDestructiveAction); - const useOverflow = overflowActions.length > 0 || !!refresh; + const useOverflow = overflowActions.length > 0 || leadingActions.length > 0 || !!refresh; // The trailing segment (objectstack#27241): the host's chrome after the // actions, a hairline between the two so the switches do not read as one // more action. `ml-auto`: when the row wraps (a narrow header), the @@ -3080,6 +3089,8 @@ export const PageHeaderActions: React.FC = ({ + {leadingActions.map((action, idx) => renderMenuItem(action, idx, 'lead', -1))} + {leadingActions.length > 0 && (refreshItem || overflowActions.length > 0) && } {refreshItem && ( <> {refreshItem} @@ -3106,19 +3117,22 @@ export const PageHeaderActions: React.FC = ({ const pool = [...ranked, ...menuOnly, ...moreOnlyActions]; return [ ...pool.filter((a) => !isDestructiveAction(a) && !isHostAction(a)), - ...pool.filter((a) => !isDestructiveAction(a) && isHostAction(a)), + ...pool.filter((a) => !isDestructiveAction(a) && isHostAction(a) && !leadsMenu(a)), ...pool.filter(isDestructiveAction), ]; })() : []; const stateFirstDestructiveIdx = stateMenuActions.findIndex(isDestructiveAction); + const stateLeading = stateGroup ? [...ranked, ...menuOnly, ...moreOnlyActions].filter(leadsMenu) : []; const toolbarItems = ( <> {stateGroup ? stateGroup({ recordRow: recordRowItems, - recordMenuItems: stateMenuActions.length > 0 || refreshItem ? ( + recordMenuItems: stateMenuActions.length > 0 || stateLeading.length > 0 || refreshItem ? ( <> + {stateLeading.map((action, idx) => renderMenuItem(action, idx, 'state-lead', -1))} + {stateLeading.length > 0 && (refreshItem || stateMenuActions.length > 0) && } {refreshItem} {refreshItem && stateMenuActions.length > 0 && } {stateMenuActions.map((action, idx) => renderMenuItem(action, idx, 'state', stateFirstDestructiveIdx))} diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 08a0a1ae790..8b0aee37407 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -3926,6 +3926,11 @@ const ar = { renameSourceOnly: 'تُغيَّر أسماء علامات التبويب بلغة المصدر للتطبيق', builtinFixed: 'تعرض المنصة علامة التبويب هذه أخيرًا باسمها الخاص.', adjustFieldGroups: 'ضبط مجموعات الحقول', + pairNotWritable: 'لا يمكن الكتابة في حزمة التخصيص لهذا التطبيق، لذا لا يمكن حفظ علاماته.', + builtinMoves: 'يمكن نقل علامة التبويب المضمنة، لكن لا يمكن إخفاؤها أو إعادة تسميتها.', + sourceBase: 'الحزمة الأصلية', + sourcePackage: 'من {{name}}', + sourceEnvironment: 'هذه البيئة', }, }, topbar: { diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 53765d7bd96..1e01805a962 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -3603,6 +3603,11 @@ const de = { renameSourceOnly: 'Tab-Namen werden in der Quellsprache der App geändert', builtinFixed: 'Die Plattform zeigt diesen Tab zuletzt und unter eigenem Namen.', adjustFieldGroups: 'Feldgruppen anpassen', + pairNotWritable: 'Das Anpassungspaket dieser App ist nicht beschreibbar, daher können die Tabs nicht gespeichert werden.', + builtinMoves: 'Ein integrierter Tab kann verschoben, aber nicht ausgeblendet oder umbenannt werden.', + sourceBase: 'Ursprüngliches Paket', + sourcePackage: 'Aus {{name}}', + sourceEnvironment: 'Diese Umgebung', }, }, topbar: { diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index f80bfdf5227..27bd1b9fcaa 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -4284,6 +4284,11 @@ const en = { renameSourceOnly: 'Tab names are changed in the app\'s source language', builtinFixed: 'The platform draws this tab last, under its own name.', adjustFieldGroups: 'Adjust field groups', + pairNotWritable: 'This app\'s customization package cannot be written, so its tabs cannot be saved.', + builtinMoves: 'A built-in tab can be moved, not hidden or renamed.', + sourceBase: 'Original package', + sourcePackage: 'From {{name}}', + sourceEnvironment: 'This environment', }, }, topbar: { diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 4abc7273401..9b9935fd3e2 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -3685,6 +3685,11 @@ const es = { renameSourceOnly: 'Los nombres de las pestañas se cambian en el idioma de origen de la app', builtinFixed: 'La plataforma muestra esta pestaña al final, con su propio nombre.', adjustFieldGroups: 'Ajustar grupos de campos', + pairNotWritable: 'No se puede escribir en el paquete de personalización de esta app, así que sus pestañas no se pueden guardar.', + builtinMoves: 'Una pestaña integrada se puede mover, pero no ocultar ni renombrar.', + sourceBase: 'Paquete original', + sourcePackage: 'De {{name}}', + sourceEnvironment: 'Este entorno', }, }, topbar: { diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 51ef152ad93..f02ccaffd67 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -3681,6 +3681,11 @@ const fr = { renameSourceOnly: 'Les noms d\'onglet se modifient dans la langue source de l\'application', builtinFixed: 'La plateforme affiche cet onglet en dernier, sous son propre nom.', adjustFieldGroups: 'Ajuster les groupes de champs', + pairNotWritable: 'Le package de personnalisation de cette app n\'est pas modifiable : ses onglets ne peuvent pas être enregistrés.', + builtinMoves: 'Un onglet intégré peut être déplacé, mais pas masqué ni renommé.', + sourceBase: 'Package d\'origine', + sourcePackage: 'De {{name}}', + sourceEnvironment: 'Cet environnement', }, }, topbar: { diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index bc43f7e990c..7d9690a34c6 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -3605,6 +3605,11 @@ const ja = { renameSourceOnly: 'タブ名はアプリのソース言語でのみ変更できます', builtinFixed: 'このタブはプラットフォームが最後に固有の名前で表示します。', adjustFieldGroups: 'フィールドグループを調整', + pairNotWritable: 'このアプリのカスタマイズパッケージは書き込めないため、タブを保存できません。', + builtinMoves: '組み込みタブは移動できますが、非表示や名前の変更はできません。', + sourceBase: '元のパッケージ', + sourcePackage: '{{name}} から', + sourceEnvironment: 'この環境', }, }, topbar: { diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 825f64da97d..833e1eaa50f 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -3603,6 +3603,11 @@ const ko = { renameSourceOnly: '탭 이름은 앱의 원본 언어에서만 변경할 수 있습니다', builtinFixed: '이 탭은 플랫폼이 고유한 이름으로 마지막에 표시합니다.', adjustFieldGroups: '필드 그룹 조정', + pairNotWritable: '이 앱의 사용자 지정 패키지에 쓸 수 없어 탭을 저장할 수 없습니다.', + builtinMoves: '기본 제공 탭은 이동할 수 있지만 숨기거나 이름을 바꿀 수 없습니다.', + sourceBase: '원본 패키지', + sourcePackage: '{{name}}에서', + sourceEnvironment: '이 환경', }, }, topbar: { diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index aa398d8f7b0..d3bef294458 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -3680,6 +3680,11 @@ const pt = { renameSourceOnly: 'Os nomes das abas são alterados no idioma de origem do app', builtinFixed: 'A plataforma exibe esta aba por último, com o próprio nome.', adjustFieldGroups: 'Ajustar grupos de campos', + pairNotWritable: 'O pacote de personalização deste app não pode ser gravado, então suas abas não podem ser salvas.', + builtinMoves: 'Uma aba integrada pode ser movida, mas não ocultada nem renomeada.', + sourceBase: 'Pacote original', + sourcePackage: 'De {{name}}', + sourceEnvironment: 'Este ambiente', }, }, topbar: { diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index f80ce3d48fe..343bf2715b8 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -3772,6 +3772,11 @@ const ru = { renameSourceOnly: 'Названия вкладок меняются на исходном языке приложения', builtinFixed: 'Платформа показывает эту вкладку последней, под её собственным названием.', adjustFieldGroups: 'Настроить группы полей', + pairNotWritable: 'Пакет настроек этого приложения недоступен для записи, поэтому вкладки нельзя сохранить.', + builtinMoves: 'Встроенную вкладку можно переместить, но нельзя скрыть или переименовать.', + sourceBase: 'Исходный пакет', + sourcePackage: 'Из {{name}}', + sourceEnvironment: 'Эта среда', }, }, topbar: { diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 1a58e3f7177..c3c55f7d014 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -3684,6 +3684,11 @@ const zh = { renameSourceOnly: '页签名称只能在应用的源语言下修改', builtinFixed: '此页签由平台绘制,固定在最后,名称不可改。', adjustFieldGroups: '调整字段分组', + pairNotWritable: '这个应用的定制包不可写,页签无法保存。', + builtinMoves: '内置页签可以移动,不能隐藏或改名。', + sourceBase: '原始包', + sourcePackage: '来自{{name}}', + sourceEnvironment: '本环境', }, }, topbar: { diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 6cc4700f42f..a362c6cd6dc 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -3684,6 +3684,11 @@ const zhHant = { renameSourceOnly: '頁簽名稱只能在應用的源語言下修改', builtinFixed: '此頁籤由平台繪製,固定在最後,名稱不可改。', adjustFieldGroups: '調整欄位分組', + pairNotWritable: '這個應用的定製包不可寫,頁籤無法儲存。', + builtinMoves: '內建頁籤可以移動,不能隱藏或改名。', + sourceBase: '原始包', + sourcePackage: '來自{{name}}', + sourceEnvironment: '本環境', }, }, topbar: { From 0aacc5aad66dddc2763397bbc07e3ac1bc4b0358 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 03:18:48 +0000 Subject: [PATCH 2/2] chore(changeset): installed-object tab configuration (#36499) Claude-Session: https://claude.ai/code/session_01ADHkmP8GZoB2rUETxwNEDv Co-authored-by: Claude --- .../36499-record-tab-config-installed.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 .changeset/36499-record-tab-config-installed.md diff --git a/.changeset/36499-record-tab-config-installed.md b/.changeset/36499-record-tab-config-installed.md new file mode 100644 index 00000000000..c8971c27468 --- /dev/null +++ b/.changeset/36499-record-tab-config-installed.md @@ -0,0 +1,22 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +'@object-ui/components': patch +--- + +feat(console): 「Configure tabs」 on an installed object writes its paired `.custom` package, marks where each tab comes from, and opens the record's 「…」 + +Clause-②: yes (widening) +Metadata-protocol: none + +On the record page of an object of an installed (read-only) package, a workspace administrator who may author metadata now finds 「Configure tabs」 too, where the customization door does not wall them off (the walled `group` / `isolated` postures leave it to the platform operator). Its 「Save」 writes the `relatedLists` of the object extension of the base's paired `.custom` package in the spec's shape (ADR-0146 D10): every shown tab in order, a built-in tab by its bare name, and every hidden related tab written `{ list, hidden: true }`; the pair is created on the first save by the ensure door, as Studio creates it. The extension is written over what the pair stores, with only its `relatedLists` replaced (`fields`, `fieldPatches`, `place` and `fieldGroups` kept), as a draft with the first-write pin, then published; a refused publish discards that draft. The original package is not written. + +On an installed object every tab can be moved: the object's own lists, a list another package brings, and the built-in 附件 / 审批 / 动态. A related tab can be hidden and shown again; a built-in tab cannot be hidden there (the `.custom` list cannot hide it), and an attachments tab the base hides waits in 「Hidden」, from which it can be shown. Each related tab is marked 「Original package」, 「From 」 or 「This environment」, read from the child object's package and the relationship field. + +A tab's stored title is kept when the administrator did not rename it, on self-built and installed objects alike: the name the editor shows is the served one, which the read translates for the reader's language. + +The write is one shared helper, `saveObjectExtensionArrangement`, which replaces only the arrangement keys a caller returns (`relatedLists` here; `fieldGroups` for a field-layout editor). + +`page:header`: a host `⋯` entry declaring `leadsMenu: true` is drawn first, ahead of Refresh; an authored action cannot claim the place. The record page's 「Configure tabs」 declares it, so it is the first item of the record's 「…」. + +New language-pack keys under `designMode.recordTabs` (`pairNotWritable`, `builtinMoves`, `sourceBase`, `sourcePackage`, `sourceEnvironment`) in all eleven console locales.