From b6438f6fcb24129c5c953e57ed36583225bfad63 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 07:36:03 +0000 Subject: [PATCH 1/2] fix(studio): retire Studio's Interfaces column (objectstack#36502) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Studio keeps Data, Automations, Access and All metadata. Menus, header actions, list views, dashboards, reports and record pages are designed in the running app. - /studio//interfaces, with or without ?surface=, lands on the Data pillar with a one-line notice (「界面的修改已经搬到应用里」) and a link back to the app; ?changes=review travels with it. - The MCP authoring tools and `os meta register --draft` print /studio//data?changes=review; the console's Edit-in-Studio links for a dashboard, page, report or view open its All-metadata item page. - On a read-only base, a view, dashboard, report or page is customized on its All-metadata item page (AREA_CUSTOMIZE_EDITOR_TYPES), into the pair, with the override mark and Restore: the door the Interfaces header was. - Code and tests that served only the column are deleted; parts other surfaces (and PR #36784) use are kept. - The live customize journey and the checklist item move to the new door. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzj9RY8jKV57hUTNEYg --- .changeset/36502-retire-studio-interfaces.md | 20 + .../platform-checklist/areas/dashboards.json | 7 +- .../areas/studio-authoring.json | 106 +- .../areas/ux-conventions.json | 9 +- docs/qa/platform-checklist/coverage.json | 3 - .../src/commands/meta/register-draft.test.ts | 4 +- packages/cli/src/commands/meta/register.ts | 2 +- .../runtime/src/domains/mcp-authoring.test.ts | 4 +- packages/runtime/src/domains/mcp-authoring.ts | 4 +- .../evals/draft-door-procedure.json | 10 +- ui/e2e/live/studio-customize-journey.spec.ts | 32 +- ui/packages/app-shell/README.md | 36 +- ...eryRedirectsFollowDeclaration-7373.test.ts | 2 - .../openPathObjectReaders-12811.test.ts | 9 - .../app-shell/src/console/ai/AiChatPage.tsx | 8 +- ...AiChatPage.appliedCardDoors-12894.test.tsx | 4 +- ...Page.noNavigationAfterBuild-12724.test.tsx | 7 +- .../ai/__tests__/artifactStudioPath.test.ts | 17 +- .../src/console/ai/artifactStudioPath.ts | 33 +- ...eNavTargetLabel.draftLabels-11862.test.tsx | 104 + .../app-shell/src/layout/AppHeader.tsx | 4 +- ...ditAppFollowsPackagePosture-12615.test.tsx | 4 +- ...pageRouteNoAuthoringHandles-12198.test.tsx | 2 +- .../__tests__/SidebarAppMenu-36112.test.tsx | 2 +- .../src/services/componentRegistry.ts | 8 - .../src/utils/__tests__/appRoute.test.ts | 25 +- ui/packages/app-shell/src/utils/appRoute.ts | 37 +- ui/packages/app-shell/src/views/PageView.tsx | 8 +- ...StudioFollowsPackagePosture-12615.test.tsx | 2 +- ...iew.editInStudioOpensStudio-12540.test.tsx | 9 +- ...rmattingEditor.listEquality-36459.test.tsx | 39 +- ...rectoryPage.stateVocabulary-29705.test.tsx | 9 +- .../src/views/metadata-admin/PageShell.tsx | 7 +- .../src/views/metadata-admin/draftVerdict.ts | 23 - .../AppNavCanvas.menuOrder-26979.test.tsx | 165 + .../previews/SourcePageProperties.test.tsx | 81 - .../previews/SourcePageProperties.tsx | 127 - ...dgets.filterBuilderMultiple-36169.test.tsx | 77 - ...InterfacesNavRail.editKinds-34796.test.tsx | 106 - ...esNavRail.internalFormHidden-36425.test.ts | 55 - .../views/studio-design/InterfacesNavRail.tsx | 702 ---- ...facesPillar.canvasDraftOnly-12508.test.tsx | 178 - ...r.componentListServedTitles-12688.test.tsx | 254 -- .../InterfacesPillar.customize-28562.test.tsx | 1079 ----- ...ar.customizePackagelessView-35600.test.tsx | 340 -- ...erfacesPillar.editRailWidth-12519.test.tsx | 151 - ...acesPillar.formViewWarnings-29311.test.tsx | 206 - ...terfacesPillar.heldListItem-27459.test.tsx | 207 - ...InterfacesPillar.heldWidget-11910.test.tsx | 448 -- ...sPillar.navActionServedRows-36725.test.tsx | 135 - ...rfacesPillar.offNavDeepLink-28561.test.tsx | 175 - ...nterfacesPillar.offNavItems-26889.test.tsx | 263 -- ...facesPillar.offNavListViews-30046.test.tsx | 463 --- ...InterfacesPillar.reportHeld-27785.test.tsx | 295 -- ...terfacesPillar.reportJoined-29022.test.tsx | 218 - ...facesPillar.saveErrorClears-11950.test.tsx | 250 -- ...nterfacesPillar.showMeFocus-26730.test.tsx | 190 - ...InterfacesPillar.slotGutter-12611.test.tsx | 178 - ...InterfacesPillar.sourcePage-12522.test.tsx | 267 -- .../ListViewBulkActionsSection.tsx | 633 --- .../studio-design/ListViewChartSection.tsx | 355 -- .../studio-design/ListViewMoreSection.tsx | 161 - .../studio-design/ListViewTypeSection.tsx | 189 - ...ctListViewInspector.addView-27836.test.tsx | 287 -- ...stViewInspector.bulkActions-30089.test.tsx | 454 -- ...tViewInspector.chartBinding-27933.test.tsx | 404 -- ...tViewInspector.copilotMarks-12725.test.tsx | 287 -- ...ViewInspector.dateSortLabel-27520.test.tsx | 162 - ...tViewInspector.displayTitle-13151.test.tsx | 206 - ...ewInspector.draftObjectSeed-30317.test.tsx | 212 - ...ewInspector.draftOnlyObject-12508.test.tsx | 309 -- ...ewInspector.draftUnreadable-29148.test.tsx | 259 -- ...wInspector.fallbackNoLayers-36750.test.tsx | 252 -- ...ewInspector.firstSavePinned-11773.test.tsx | 202 - ...nspector.hiddenSystemFields-13152.test.tsx | 182 - ...ViewInspector.layersUnsaved-11799.test.tsx | 254 -- ...tViewInspector.namesOnHover-34796.test.tsx | 159 - ...ector.picklistFilterOptions-27515.test.tsx | 230 - .../ObjectListViewInspector.target.test.tsx | 90 - .../studio-design/ObjectListViewInspector.tsx | 1702 -------- ...istViewInspector.twoHolders-28584.test.tsx | 160 - ...tViewInspector.typeSettings-27895.test.tsx | 290 -- .../studio-design/ObjectListViewTitle.tsx | 209 - .../studio-design/StudioBundleItemEditor.tsx | 11 +- .../studio-design/StudioCustomizeControls.tsx | 31 +- ...DesignSurface.accessSegment-12452.test.tsx | 123 +- ...tudioDesignSurface.aiApplyRefresh.test.tsx | 31 +- .../StudioDesignSurface.aiChipLabel.test.tsx | 33 +- ...ignSurface.autosaveInFlight-11204.test.tsx | 101 +- ...esignSurface.autosaveSwitch-11232.test.tsx | 275 +- ...DesignSurface.cancelledLoad-11331.test.tsx | 47 +- .../StudioDesignSurface.canvasFrame.test.tsx | 130 - .../StudioDesignSurface.canvasMode.test.tsx | 128 - ...face.canvasStripServedLabel-36480.test.tsx | 85 +- ...oDesignSurface.copilotDoors-12894.test.tsx | 17 +- ...ce.createAppOpensInterfaces-11794.test.tsx | 234 -- ...ignSurface.customizePublish-28562.test.tsx | 106 +- ...gnSurface.designerRegistryMissing.test.tsx | 53 +- ...gnSurface.designerRegistryPartial.test.tsx | 129 - ...signSurface.draftUnreadable-29015.test.tsx | 373 -- ...signSurface.draftUnreadable-29148.test.tsx | 136 +- ...esignSurface.expectedMisses-11799.test.tsx | 87 +- ...oDesignSurface.flowAutosave-34818.test.tsx | 24 +- ...ignSurface.heldWidgetCreate-26845.test.tsx | 213 - ...signSurface.heldWidgetLeave-26705.test.tsx | 259 -- ...gnSurface.heldWidgetPublish-11910.test.tsx | 268 -- ...udioDesignSurface.interfacePolish.test.tsx | 183 - ...dioDesignSurface.interfacesAction.test.tsx | 128 - ...ignSurface.interfacesCreate-11823.test.tsx | 390 -- ...urface.interfacesCreatePage-11823.test.tsx | 341 -- ...gnSurface.interfacesNavTree-12455.test.tsx | 339 -- ...nSurface.interfacesReadOnly-11136.test.tsx | 422 -- ...gnSurface.interfacesRetired-36502.test.tsx | 272 ++ ...signSurface.itemHeaderLabel-26746.test.tsx | 209 - ...udioDesignSurface.itemTools-28239.test.tsx | 126 - ...Surface.kanbanCardSelection-12725.test.tsx | 663 --- ...esignSurface.kernelReadOnly-29567.test.tsx | 47 +- ...ignSurface.lateRegistration-11939.test.tsx | 41 +- ...Surface.leafColumnSelection-12725.test.tsx | 386 -- ...gnSurface.listViewInspector-11823.test.tsx | 328 -- ...esignSurface.listViewSwitch-27896.test.tsx | 393 -- ...ignSurface.listViewTypeHeld-27895.test.tsx | 218 - ...oDesignSurface.metadataArea-28561.test.tsx | 2 +- ...oDesignSurface.narrowHeader-12509.test.tsx | 46 +- ...ignSurface.navAutosaveFlush-11189.test.tsx | 430 -- ...ioDesignSurface.navDeepLink-11153.test.tsx | 294 -- ...esignSurface.navDraftLabels-11862.test.tsx | 307 -- ...ace.navEditClosesOnReadOnly-11167.test.tsx | 332 -- ...dioDesignSurface.navItemInspector.test.tsx | 111 - ...urface.navItemInspectorKeys-26740.test.tsx | 344 -- ...rface.navItemInspectorLabel-11196.test.tsx | 148 - ...e.navItemInspectorLabelMaps-11148.test.tsx | 178 - ...rface.navItemInspectorNames-26732.test.tsx | 58 - ...oDesignSurface.navItemTypes-11790.test.tsx | 558 --- ...DesignSurface.navPageDrafts-26743.test.tsx | 199 - ...nSurface.navPlaceholderSave-11776.test.tsx | 416 -- ...DesignSurface.navRenameHeld-27464.test.tsx | 59 +- ...gnSurface.noAppPackageLabel-12718.test.tsx | 187 - ...tudioDesignSurface.notFound-26708.test.tsx | 18 +- ...dioDesignSurface.oneSurface-28572.test.tsx | 345 +- ...gnSurface.packageListErrorPosture.test.tsx | 4 +- ...tudioDesignSurface.pillarNavGuard.test.tsx | 25 +- .../StudioDesignSurface.railLabels.test.tsx | 1868 --------- ...nSurface.refusedLeafUnsaved-29113.test.tsx | 414 -- ...oDesignSurface.restoreMarks-30238.test.tsx | 258 -- ...udioDesignSurface.rightSlot-12725.test.tsx | 255 +- ...oDesignSurface.selectionLeafScope.test.tsx | 392 -- ...urface.servedDraftTakenAsIs-10765.test.tsx | 51 +- ...oDesignSurface.sharedSelect-11865.test.tsx | 347 +- ...nSurface.standardNavEntries-11201.test.tsx | 216 - ...dioDesignSurface.studioCanvasLeaf.test.tsx | 349 -- .../studio-design/StudioDesignSurface.tsx | 3690 +---------------- ...dioDesignSurface.twoHolders-28584.test.tsx | 29 +- .../StudioInterfacesRetiredNotice.tsx | 70 + ...tudioItemHeader.statusPlace-12524.test.tsx | 47 +- .../StudioMetadataArea.routes-28561.test.tsx | 20 +- .../studio-design/StudioNavItemInspector.tsx | 1069 ----- .../src/views/studio-design/StudioPicker.tsx | 86 + .../views/studio-design/StudioPillarKit.tsx | 31 - .../StudioRailCustomizations.tsx | 83 +- .../studio-design/datasetCreate.test.tsx | 105 +- ...nterfaceCreate.sharedSelect-11865.test.tsx | 310 -- .../studio-design/interfaceCreate.test.tsx | 308 -- .../views/studio-design/interfaceCreate.tsx | 388 -- .../views/studio-design/metadataArea.test.ts | 20 +- .../src/views/studio-design/metadataArea.ts | 30 +- ...tadataError.heldNestedInput-29006.test.tsx | 74 +- .../studio-design/servedDashboardText.ts | 20 - .../views/studio-design/studioChangesLink.ts | 8 +- .../studioInterfacesRetired.test.ts | 61 + .../studio-design/studioInterfacesRetired.ts | 55 + .../studioZhPillarNames-11801.test.ts | 50 + ui/packages/i18n/src/namespaces/studio/en.ts | 4 + ui/packages/i18n/src/namespaces/studio/zh.ts | 4 + .../plugin-chatbot/src/ChatbotEnhanced.tsx | 2 +- ...banRenderer.cardOpensRecord-12725.test.tsx | 81 + 176 files changed, 1489 insertions(+), 35605 deletions(-) create mode 100644 .changeset/36502-retire-studio-interfaces.md create mode 100644 ui/packages/app-shell/src/hooks/useNavTargetLabel.draftLabels-11862.test.tsx create mode 100644 ui/packages/app-shell/src/views/metadata-admin/previews/AppNavCanvas.menuOrder-26979.test.tsx delete mode 100644 ui/packages/app-shell/src/views/metadata-admin/previews/SourcePageProperties.test.tsx delete mode 100644 ui/packages/app-shell/src/views/metadata-admin/previews/SourcePageProperties.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesNavRail.editKinds-34796.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesNavRail.internalFormHidden-36425.test.ts delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesNavRail.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesPillar.canvasDraftOnly-12508.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesPillar.componentListServedTitles-12688.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesPillar.customize-28562.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesPillar.customizePackagelessView-35600.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesPillar.editRailWidth-12519.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesPillar.formViewWarnings-29311.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesPillar.heldListItem-27459.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesPillar.heldWidget-11910.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesPillar.navActionServedRows-36725.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesPillar.offNavDeepLink-28561.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesPillar.offNavItems-26889.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesPillar.offNavListViews-30046.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesPillar.reportHeld-27785.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesPillar.reportJoined-29022.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesPillar.saveErrorClears-11950.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesPillar.showMeFocus-26730.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesPillar.slotGutter-12611.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/InterfacesPillar.sourcePage-12522.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ListViewBulkActionsSection.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ListViewChartSection.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ListViewMoreSection.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ListViewTypeSection.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.addView-27836.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.bulkActions-30089.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.chartBinding-27933.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.copilotMarks-12725.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.dateSortLabel-27520.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.displayTitle-13151.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.draftObjectSeed-30317.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.draftOnlyObject-12508.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.draftUnreadable-29148.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.fallbackNoLayers-36750.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.firstSavePinned-11773.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.hiddenSystemFields-13152.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.layersUnsaved-11799.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.namesOnHover-34796.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.picklistFilterOptions-27515.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.target.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.twoHolders-28584.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.typeSettings-27895.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectListViewTitle.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.canvasFrame.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.canvasMode.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.createAppOpensInterfaces-11794.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.designerRegistryPartial.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.draftUnreadable-29015.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldWidgetCreate-26845.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldWidgetLeave-26705.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldWidgetPublish-11910.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.interfacePolish.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.interfacesAction.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.interfacesCreate-11823.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.interfacesCreatePage-11823.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.interfacesNavTree-12455.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.interfacesReadOnly-11136.test.tsx create mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.interfacesRetired-36502.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemHeaderLabel-26746.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.kanbanCardSelection-12725.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.leafColumnSelection-12725.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.listViewInspector-11823.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.listViewSwitch-27896.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.listViewTypeHeld-27895.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.navAutosaveFlush-11189.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.navDeepLink-11153.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.navDraftLabels-11862.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.navEditClosesOnReadOnly-11167.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.navItemInspector.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.navItemInspectorKeys-26740.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.navItemInspectorLabel-11196.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.navItemInspectorLabelMaps-11148.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.navItemInspectorNames-26732.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.navItemTypes-11790.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.navPageDrafts-26743.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.navPlaceholderSave-11776.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.noAppPackageLabel-12718.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.railLabels.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.refusedLeafUnsaved-29113.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.restoreMarks-30238.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.selectionLeafScope.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.standardNavEntries-11201.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.studioCanvasLeaf.test.tsx create mode 100644 ui/packages/app-shell/src/views/studio-design/StudioInterfacesRetiredNotice.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioNavItemInspector.tsx create mode 100644 ui/packages/app-shell/src/views/studio-design/StudioPicker.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/interfaceCreate.sharedSelect-11865.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/interfaceCreate.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/interfaceCreate.tsx create mode 100644 ui/packages/app-shell/src/views/studio-design/studioInterfacesRetired.test.ts create mode 100644 ui/packages/app-shell/src/views/studio-design/studioInterfacesRetired.ts create mode 100644 ui/packages/app-shell/src/views/studio-design/studioZhPillarNames-11801.test.ts create mode 100644 ui/packages/plugin-kanban/src/__tests__/KanbanRenderer.cardOpensRecord-12725.test.tsx diff --git a/.changeset/36502-retire-studio-interfaces.md b/.changeset/36502-retire-studio-interfaces.md new file mode 100644 index 00000000000..a2a21a519b8 --- /dev/null +++ b/.changeset/36502-retire-studio-interfaces.md @@ -0,0 +1,20 @@ +--- +'@objectstack/runtime': patch +'@objectstack/cli': patch +'@object-ui/i18n': patch +'@object-ui/plugin-chatbot': patch +--- + +fix(studio): Studio's Interfaces column is retired; its old links land on the Studio home and its Changes links open from the Data pillar + +Clause-②: no +Metadata-protocol: none + +objectstack#36502. Menus, header actions, list views, dashboards, reports and record pages are designed in the running app. Studio keeps Data, Automations, Access and All metadata, and every view, dashboard, report and page stays readable and editable as metadata on its All-metadata item page. No metadata type, key or stored shape changes. + +- **Old links still open.** `/studio//interfaces`, with or without a `?surface=` deep link, lands on the package's Data pillar and says once, there, "Interface edits have moved into the app" (「界面的修改已经搬到应用里」) with a link back to the app. A `?changes=review` request travels with it. +- **`@objectstack/runtime`, `@objectstack/cli`.** The review link the MCP authoring tools and `os meta register --draft` print is `/studio//data?changes=review` (it was `/studio//interfaces?changes=review`, which still works through the redirect). +- **`@object-ui/i18n`.** Adds `engine.studio.interfacesRetired.sentence`, `.backToApp` and `.dismiss` (en, zh). +- **`@object-ui/plugin-chatbot`.** The `onDesignBuiltApp` doc example names the Data route. +- The console's "Edit in Studio" links for a dashboard, page, report or view open its All-metadata item page. +- **Customize moves with them.** On a read-only base, a view, dashboard, report or page is customized on its All-metadata item page, in the type's designer, into the base's pair (`.custom`), with the override mark and "Restore package original" as before. It was the Interfaces column's header. diff --git a/docs/qa/platform-checklist/areas/dashboards.json b/docs/qa/platform-checklist/areas/dashboards.json index 169c3e01547..3a4a21b2c11 100644 --- a/docs/qa/platform-checklist/areas/dashboards.json +++ b/docs/qa/platform-checklist/areas/dashboards.json @@ -700,7 +700,7 @@ "title": "Dashboard-level dateRange + global filters re-scope every bound widget through its OWN field mapping; opted-out widgets stay fixed; and the Studio widget inspector AUTHORS those filterBindings", "since": "v16", "status": "active", - "revision": 6, + "revision": 7, "priority": "P1", "surface": "browser", "personas": [ @@ -711,7 +711,7 @@ "requires": [ "the Revenue Pulse dashboard (showcase_revenue_pulse) — the framework#2501 acceptance fixture: one dateRange (default field issued_on) + one region filter (default field region) driving invoice AND account widgets, account widgets re-mapping via filterBindings (dateRange→signed_on, region→sales_region), one KPI opted out of both (filterBindings false) as the all-time reference", "seeded accounts spread across sales_region amer/emea/apac with signed_on dates (src/data/seed/index.ts)", - "for D2 and D3 a SCRATCH dashboard, because no stock dashboard serves either leg (QA run #23163 scored both on runtime scratch dashboards): D2's Studio authoring round-trip needs a dashboard in a WRITABLE package to publish into — create a scratch package (POST /api/v1/packages with the body {id, name, version: '0.1.0', type: 'app'}: the manifest is strict, so a `label` key is refused as unrecognized, and `type` is required) and author the dashboard there, since the showcase package is read-only in Studio — AND author an app in that package whose navigation carries the dashboard (PUT /api/v1/meta/app/NAME?package=PKG): the Studio Interfaces pillar IS the app navigation tree (objectui app-shell StudioDesignSurface.tsx: \"Interfaces: the real App navigation tree\"), so a package with no app shows no dashboard to select (QA run #24573); D3's dataset-sourced option half needs a globalFilter whose options come from `optionsFrom` ({object, valueField, labelField} — GlobalFilterOptionsFromSchema in packages/spec/src/ui/dashboard.zod.ts), which NO stock dashboard declares (Revenue Pulse's region filter lists static options). D3's {value,label} render half still reads on Revenue Pulse. A scratch dashboard that carries Revenue Pulse's global filters gives each account-bound widget a filterBindings for them (e.g. dateRange→signed_on, region: false) before its first save: a widget the issued_on / region defaults cannot reach is refused 422 dashboard-filter-field-unknown. Delete the scratch package at teardown" + "for D2 and D3 a SCRATCH dashboard, because no stock dashboard serves either leg (QA run #23163 scored both on runtime scratch dashboards): D2's Studio authoring round-trip needs a dashboard in a WRITABLE package to publish into — create a scratch package (POST /api/v1/packages with the body {id, name, version: '0.1.0', type: 'app'}: the manifest is strict, so a `label` key is refused as unrecognized, and `type` is required) and author the dashboard there, since the showcase package is read-only in Studio — AND author an app in that package whose navigation carries the dashboard (PUT /api/v1/meta/app/NAME?package=PKG), so the dashboard opens in the running app, where its design mode is the authoring door since Studio's Interfaces pillar (which reached a dashboard only through an app's navigation, QA run #24573) retired with #36502; D3's dataset-sourced option half needs a globalFilter whose options come from `optionsFrom` ({object, valueField, labelField} — GlobalFilterOptionsFromSchema in packages/spec/src/ui/dashboard.zod.ts), which NO stock dashboard declares (Revenue Pulse's region filter lists static options). D3's {value,label} render half still reads on Revenue Pulse. A scratch dashboard that carries Revenue Pulse's global filters gives each account-bound widget a filterBindings for them (e.g. dateRange→signed_on, region: false) before its first save: a widget the issued_on / region defaults cannot reach is refused 422 dashboard-filter-field-unknown. Delete the scratch package at teardown" ] }, "steps": [ @@ -840,7 +840,8 @@ "date": "2026-11-15", "change": "fixtures.requires[2] names the scratch package body POST /api/v1/packages takes ({id, name, version, type}; 'label' is refused) and the filterBindings a scratch dashboard needs before its first save (else 422 dashboard-filter-field-unknown) (QA run #33853, comment 6894307378; ledger 6896511848 of #33761 row 71). No clause changed. Read at base bc6b7ffd", "ref": "#34016" - } + }, + { "revision": 7, "date": "2026-11-24", "change": "fixtures.requires[2]: D2's authoring door is the running app's design mode, since Studio's Interfaces pillar retired with #36502; the app that carries the dashboard stays, now to open it in the app. No clause changed", "ref": "#36502" } ] }, { diff --git a/docs/qa/platform-checklist/areas/studio-authoring.json b/docs/qa/platform-checklist/areas/studio-authoring.json index f7ac81581b4..a9459485b67 100644 --- a/docs/qa/platform-checklist/areas/studio-authoring.json +++ b/docs/qa/platform-checklist/areas/studio-authoring.json @@ -9,7 +9,7 @@ "title": "The first-run authoring loop closes: package → object → record → app → publish → end-user, zero code, zero restarts", "since": "v16", "status": "active", - "revision": 13, + "revision": 14, "priority": "P0", "surface": "mixed", "personas": ["admin (seeded admin@objectos.ai)", "end user (same account driving the published app)"], @@ -20,7 +20,7 @@ ], "knownGaps": [ "SUPERSEDED (QA run #24571): publish is no longer one click with no confirmation. Publish opens the 'Pending changes' review sheet — every pending draft listed as New or Update, each expanding into the keys it changes, and a separate 'Publish all' confirm (objectui app-shell preview/DraftChangesPanel.tsx, mounted by StudioDesignSurface.tsx; the audit's finding 3 / ADR-0016 §3.6 step 4). A review step now exists; do not score its presence or absence here — this item scores the loop", - "SUPERSEDED (QA run #21056): a new app no longer scaffolds zero nav items — the Create-app dialog seeds the app's navigation from the package's objects behind a checkbox that defaults ON (objectui StudioDesignSurface appAddObjects, objectui#2262). With it on, step 5's nav item already exists and the Interfaces step confirms it rather than builds it; only with it unticked does the manual wiring remain the contract. Do not expect zero items", + "SUPERSEDED (QA run #21056): a new app no longer scaffolds zero nav items — the Create-app dialog seeds the app's navigation from the package's objects behind a checkbox that defaults ON (objectui StudioDesignSurface appAddObjects, objectui#2262). With it on, step 5's nav item already exists; with it unticked, the entry is wired by hand in the running app's design mode (the menu editor), since Studio's Interfaces pillar, where it was wired before, retired with #36502. Do not expect zero items", "mixed-language Studio chrome (audit finding 4) is asserted by i18n.studio-follows-app-locale — locale consistency is that item's business, not this one's", "FIXED, regression row, expected PASS on the zh-CN leg (#29673, closed by PR #29790, merged as 589049b0; pins packages/metadata-protocol/src/protocol-translated-echo.test.ts and packages/qa/dogfood/test/studio-zh-cn-echo-publish.dogfood.test.ts): an object saved back from a translated /meta read now stores its source labels, so an object first published from Studio in zh-CN reaches the data plane. QA run #29877 (W5-P0, at 589049b0) read the zh-CN leg passing acceptance[2] and [3]: publish answered published, the list served, the overlay carried no queue / owner_id, and an en read showed Owner / Queue. Score both legs normally; a zh-CN publish that answers published while the data read answers 404 OBJECT_NOT_FOUND is a regression of #29673. The failure as it was: The draft read serves the injected queue column with its translated label (队列), the autosave echoes it, the registry judges the echo byte for byte against the platform's definition (isInjectedColumnDefinition, packages/spec/src/data/injected-system-column-provenance.ts) and refuses it as an author's field named queue, and the failed registration is only a console.warn (the registerObject catch in packages/metadata-protocol/src/protocol.ts). Publish answers published while GET /api/v1/data/repairs_repair_ticket answers 404 OBJECT_NOT_FOUND. Re-read unchanged at base 339f63da30, before the fix" ] @@ -31,7 +31,7 @@ "Data pillar → new object 'Repair Ticket' (the identifier auto-suggests repair_ticket from the display name, and the dialog PREFIXES it with the package namespace, so the object is named repairs_repair_ticket — the name every later step and clause uses (framework#2694, objectui StudioDesignSurface prefixObjectName). The dialog also carries an OWD (sharing model) choice, pre-selected to the platform's recommended baseline: confirm or change it, then click 'Save as draft', the dialog's confirm button (engine.studio.createDraft; no Studio create dialog has a button named Create)) → add a picklist field Status with 3 values. After a navigation the object surface opens on its Records tab (the Data pillar's default view, ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx); Add field is the Form tab's button (where QA run #28545 found it; the Records grid's add-column header carries it too). Each option's stored value derives from its label as you type it — 'In Repair' stores in_repair (ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx OptionsEditor) — so overwrite the value wherever the run wants a different one (a short code such as wip), and note the three stored values: acceptance[1] and acceptance[2] read them. There is no Save draft button: the designer autosaves, and a picklist field is held unsaved until it has at least one option (the status line reads 'Not saved yet: the field “Status” needs at least one option'), so add the field and fill its options, and the draft save fires", "open the Changes panel and Publish, then confirm with 'Publish all' in the review sheet; the toast names the count — 'Published N items in this package' (N = the drafts promoted), 'Published 1 item in this package' for one (engine.studio.publishedAllCount / publishedAllCountOne, objectui#11807; 'Published all drafts in this package' is the fallback when the count is unknown) — and, because the publish puts an object live, it adds 'Members can use it once a permission set grants them access.' with an 'Open Access' action (StudioDesignSurface.tsx)", "create a record in the runtime-faithful Records grid with a Status value chosen", - "Create app 'Repair Center' (identifier auto-suggested) → Interfaces pillar → add a nav item bound to repairs_repair_ticket → Publish", + "Create app 'Repair Center' (identifier auto-suggested), leaving 'Add this package's objects as menu items' on, so the app's navigation holds an entry bound to repairs_repair_ticket; the dialog stays on the Data pillar → Publish", "return to the console Home (/_console/home — the Studio header's house icon goes to the Studio landing, 'Studio home', and from the landing the console Home is its top bar's product mark, the link named 'PRODUCT home' (e.g. 'ObjectOS home'; data-testid app-bar-product-home, ui/packages/app-shell/src/layout/AppHeader.tsx ProductHomeMark), which goes to the deployment's home path, /_console/home on stock; no control on that bar is named plain 'Home'): the launcher must show Repair Center; open it and drive the end-user list", "verify server truth after each publish: GET /api/v1/meta/object/repairs_repair_ticket, GET /api/v1/data/repairs_repair_ticket, GET /api/v1/meta/app?id= — ?id= matches the App document name, NOT the package id com.example.repairs; fetch /api/v1/meta/app with no query first to read the name the wizard actually minted", "negative probe: on the READ-ONLY com.example.showcase package there is no gesture to drive — the console HIDES New object and Add field there (objectui StudioDesignSurface gates them on !readOnly) — so the probe is a FORGED request: send the authoring write the gesture would have made straight to the metadata write door against that package, and capture the server response (QA run #21056 read 422 WRITABLE_PACKAGE_REQUIRED and 403 ITEM_LOCKED)" @@ -99,7 +99,8 @@ { "revision": 10, "date": "2026-11-01", "change": "QA run #28545 (W3-C1R) finding on steps[2]: the object surface opens on Records after a navigation, Add field is on the Form tab, and an option's stored value derives from its label ('In Repair' gives in_repair), so a run that wants wip must overwrite it. steps[2] now says so, read from source (StudioDesignSurface.tsx viewMode default 'grid'; OptionsEditor derives a new row's value with toFieldNameOrEmpty). The same card's steps[3] finding, the stale publish toast, was fixed upstream by revision 9 (#28526, after eeec88d1). No clause changed. Read from source at base 6b9c1ca991. Wave anchor #27377, wave-3 accuracy slice S9 (#28641); finding parked in anchor comment 6554042054", "ref": "#28545" }, { "revision": 11, "date": "2026-11-03", "change": "fixtures.requires[0], steps[0] and a new negative[2] name two locale legs, en and zh-CN, and a clause holds only on both; a new fixtures.knownGaps[3] records the zh-CN leg's open failure; steps[1]'s identifier note follows pinyin derivation. QA run #29672 found the item named no locale while steps[1] uses a Chinese display name: its en leg passed and its zh-CN leg failed acceptance[2] (#29673, extracted by the run), so a run that drove one locale could score the loop either way. Read at base 339f63da30: the registry judge and the swallowed registration are unchanged and #29673 is open; and since #29734 (11c4eb59dd) a Chinese display name derives a pinyin package id (deriveCreatePackageId), so steps[1]'s 'derives no package id' no longer held, while its instruction to type com.example.repairs stands. No clause text changed; each now holds per leg. Card #29679, from QA run #29672", "ref": "#29679" }, { "revision": 12, "date": "2026-11-04", "change": "acceptance[0].verify re-pointed: the Studio package switcher, which declares the studio-pkg-chip testid, moved unchanged from ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx to PackageSwitcher.tsx beside it (#29988 slice 2, a move-only split). Re-read at base f7aab8958. No clause changed", "ref": "#29988" }, - { "revision": 13, "date": "2026-11-04", "change": "fixtures.knownGaps[3] corrected from QA run #29877 (W5-P0, at 589049b0; the list of record is comment 6600018008 on #27377): the zh-CN leg's acceptance[2] failure is fixed by PR #29790 (#29673 closed), and the run read that leg passing acceptance[2] and [3], so the instruction to score it FAIL citing #29673 is withdrawn and the row is a regression row. Read at base f68b47ca", "ref": "#29906" } + { "revision": 13, "date": "2026-11-04", "change": "fixtures.knownGaps[3] corrected from QA run #29877 (W5-P0, at 589049b0; the list of record is comment 6600018008 on #27377): the zh-CN leg's acceptance[2] failure is fixed by PR #29790 (#29673 closed), and the run read that leg passing acceptance[2] and [3], so the instruction to score it FAIL citing #29673 is withdrawn and the row is a regression row. Read at base f68b47ca", "ref": "#29906" }, + { "revision": 14, "date": "2026-11-24", "change": "steps[5] and knownGaps[1] no longer route through Studio's Interfaces pillar, retired by #36502: the Create-app scaffold (box on) is the nav item, the dialog stays on the Data pillar, and a hand-wired entry is the running app's design-mode menu editor. No clause changed", "ref": "#36502" } ] }, { @@ -439,7 +440,7 @@ "title": "Metadata draft→publish lifecycle: drafts staged not served, publish flips visibility atomically, conflicts and invalid drafts refused, and the history/audit/diff/rollback forensics tell the truth", "since": "v16", "status": "active", - "revision": 14, + "revision": 15, "priority": "P1", "surface": "mixed", "personas": ["admin (authors drafts)", "end user (must not see drafts)"], @@ -456,7 +457,7 @@ "steps": [ "author a dashboard draft: PUT /api/v1/meta/dashboard/qa_lifecycle_probe?mode=draft with one dataset-bound widget (dataset: showcase_task_metrics, dimensions: ['status'], values: ['task_count']) — the same door areas/dashboards.json exercises. The writable package of steps[2] must declare the showcase as a dependency to query that dataset: create it with dependencies: { 'com.example.showcase': '^0' } on POST /api/v1/packages. Without it the widget renders its title over 'Dataset query failed: 409 Conflict — The dataset \"showcase_task_metrics\" is held outside the declared dependency closure of package …' (ADR-0141, ADR-0150 D3; QA runs #33861 and #33914)", "record the receipt: { success, version, seq, state: 'draft' }", - "BOTH sides pre-publish: GET /api/v1/meta/dashboard/qa_lifecycle_probe as the runtime read → 404 (never published) — the draft body must not be served; in Studio the item header shows the draft line 'Draft · N unpublished' (objectui#12725, studioItemDraftStatus.ts; N is the package's pending count) and a numbered pill on the Changes button (objectui#12459). The chip is per item: it shows only while the selected item itself has a draft (N still counts the package), so after the dashboard's own publish the chip goes while the pill keeps counting the app draft. A gone chip does not mean the package is clean; read the pill or GET /api/v1/meta/_drafts?package=PKG for that (QA run #33914). For the Studio half stage the draft in a WRITABLE package (?package=PKG on the draft PUT): the pill counts the pending drafts of the package in scope, and an env-wide, package-less draft is counted in no package scope, so it shows no pill. Open the item in Studio through that package: stage, in the same package, an app draft whose navigation names the dashboard (e.g. an entry of type dashboard, dashboardName qa_lifecycle_probe) and select that entry in the Interfaces pillar — a package with no app shows 'This package has no app yet' and no dashboard to select, so no chip can render; the pill then counts both drafts", + "BOTH sides pre-publish: GET /api/v1/meta/dashboard/qa_lifecycle_probe as the runtime read → 404 (never published) — the draft body must not be served; in Studio the item header shows the draft line 'Draft · N unpublished' (objectui#12725, studioItemDraftStatus.ts; N is the package's pending count) and a numbered pill on the Changes button (objectui#12459). The chip is per item: it shows only while the selected item itself has a draft (N still counts the package), so after the dashboard's own publish the chip goes while the pill keeps counting the app draft. A gone chip does not mean the package is clean; read the pill or GET /api/v1/meta/_drafts?package=PKG for that (QA run #33914). For the Studio half stage the draft in a WRITABLE package (?package=PKG on the draft PUT): the pill counts the pending drafts of the package in scope, and an env-wide, package-less draft is counted in no package scope, so it shows no pill. Open the item in Studio through that package: open its item page in the \"All metadata\" area, /_console/studio/PKG/metadata/dashboard/qa_lifecycle_probe (Studio's Interfaces pillar, which opened it through an app's navigation, retired with #36502; re-measure on the first run whether that page draws the item-header chip, and record what it draws instead if not); stage, in the same package, an app draft whose navigation names the dashboard (e.g. an entry of type dashboard, dashboardName qa_lifecycle_probe), so the pill counts both drafts", "publish per-ref: POST /api/v1/meta/dashboard/qa_lifecycle_probe/publish → 200; GET now serves the authored body", "author a SECOND draft revision on the same name and confirm the live read keeps serving revision 1 until that draft is published", "concurrency guard: re-PUT with the STALE version as If-Match and capture the 409", @@ -574,7 +575,8 @@ { "revision": 11, "date": "2026-11-02", "change": "acceptance[10] (clause, verify) re-pointed to #28355: revision 10 said a 422 INVALID_METADATA spec refusal writes no row, and #28355 now stamps one denied row per catalogued refusal at the four single-item doors (protocol-refusal-audit.ts, REFUSAL_AUDIT_CODES = NOT_OVERRIDABLE, NOT_CREATABLE, INVALID_METADATA, DESTRUCTIVE_CHANGE, stored lower-case). The clause names those four beside item_locked, metadata_conflict and the batch codes, and keeps NO_DRAFT, INVALID_REQUEST and 5xx as writing none; the verify asks for steps[7]'s 422 as exactly one denied invalid_metadata save row with the actor, and for no row from steps[12]'s 400 or a NO_DRAFT publish. acceptance[3] spells the wire code METADATA_CONFLICT and says the stale If-Match must be sent while a draft row exists. Measured at base 0a41075a through the real protocol doors with a throwaway probe (deleted): the stray-key dashboard draft save answered 422 INVALID_METADATA with one denied invalid_metadata row carrying the actor; a publish with no draft answered 404 NO_DRAFT and a rollback with no toVersion 400 INVALID_REQUEST, neither writing a row; a draft save carrying the published version as If-Match with no draft row answered 409 METADATA_CONFLICT (current is null). Stronger, not weaker: the 422 that scored a row as a FAIL now owes one. QA run #29002 clause FAIL", "ref": "#29013" }, { "revision": 12, "date": "2026-11-04", "change": "acceptance[3].verify corrected from QA run #29890 (W5-FAIL, at 589049b0): a GET with ?mode=draft answers 400 (the read's parameters are closed; the draft read is ?state=draft), so the no-overwrite proof is the next publish serving the newer draft. Read at base f68b47ca", "ref": "#29906" }, { "revision": 13, "date": "2026-11-13", "change": "acceptance[6].verify drops the expectation that a publish made outside Studio shows only after a reload: phase 1 of the #32592 ruling (6844196863) has usePendingDrafts read the ledger again when the tab becomes visible or gains focus, and on a poll while it stays visible, sending the tab's metadata-refresh pulse when the answer moved, so the item header line and the Changes pill follow an outside publish or draft without a reload. A hidden tab sends nothing (hiddenTabPollStop.ts). No other clause changed", "ref": "#32592" }, - { "revision": 14, "date": "2026-11-15", "change": "steps[0] and steps[2] and fixtures.requires[1] re-pointed: the writable package needs a dependency on com.example.showcase to query showcase_task_metrics (else 409, dependency closure); the Draft chip is per item, so its absence does not mean a clean package; and a draft-only name is discarded through discard-drafts, not DELETE (QA run #33861, comment 6894395705, and QA run #33914, comment 6895723718; ledger 6896511848 of #33761 rows 163, 226 and 227; the record numbers the chip step 3). The clauses are unchanged. Read at base 895783a1", "ref": "#33981" } + { "revision": 14, "date": "2026-11-15", "change": "steps[0] and steps[2] and fixtures.requires[1] re-pointed: the writable package needs a dependency on com.example.showcase to query showcase_task_metrics (else 409, dependency closure); the Draft chip is per item, so its absence does not mean a clean package; and a draft-only name is discarded through discard-drafts, not DELETE (QA run #33861, comment 6894395705, and QA run #33914, comment 6895723718; ledger 6896511848 of #33761 rows 163, 226 and 227; the record numbers the chip step 3). The clauses are unchanged. Read at base 895783a1", "ref": "#33981" }, + { "revision": 15, "date": "2026-11-24", "change": "steps[2] opens the dashboard's draft on its All-metadata item page instead of selecting it in Studio's Interfaces pillar, retired by #36502; the app draft stays, for the pill's two-draft count. Whether the generic item page draws the per-item chip is marked for re-measure on the first run. No clause changed", "ref": "#36502" } ] }, { @@ -1306,7 +1308,7 @@ "title": "Source-authored page tiers render by the RIGHT path: kind:'html' source is PARSED-never-executed (static, in-browser sdui-parser compile), kind:'react' source is EXECUTED behind its capability gate (live data + interactivity) — command-center-jsx / capability-map (html) vs crm-workbench (react)", "since": "v16", "status": "active", - "revision": 6, + "revision": 7, "priority": "P2", "surface": "mixed", "personas": ["admin (seeded admin@objectos.ai) driving the published showcase app as an end user"], @@ -1329,7 +1331,7 @@ "prove the react tier is EXECUTED against LIVE data: the 'Total projects' KPI equals GET /api/v1/data/showcase_project's count (the page computes it via useAdapter().find('showcase_project'), reading the QueryResult .data envelope), and a showcase_project find query fires on the network — the number is computed at render, not authored", "prove react interactivity (executed handlers, not a parsed tree): click a ListView row → the ObjectForm binds THAT record (React useState); click '+ New project' → the form switches to create mode", "both-sides gate: boot the launch entry showcase-react-pages-off-3779 (OS_PAGE_REACT_ENABLED=false), sign in as the seeded admin and re-open crm-workbench — it must render the NAMED 'React pages are disabled on this deployment' notice (CapabilityDisabledNotice), never a blank and never an executed page; the html pages still render (html is not gated). If that entry cannot boot, record this clause blocked(environment)", - "degradation: (a) html — save a faulting html source at the ACTIVE door (or publish one) and capture the 422 INVALID_METADATA with its compile diagnostics; then save the same source as a ?mode=draft draft IN A WRITABLE PACKAGE (?package=PKG) that also holds an app whose navigation references the page, and open it in Studio at /_console/studio/PKG/interfaces?surface=page:NAME, where the draft preview's 'HTML page failed to compile (N)' panel renders with the diagnostic messages. An env-wide (package-less) draft has no Studio surface, and the save gate keeps a faulting html page off the rendered route, so the panel cannot be met anywhere else (knownGaps[0]); (b) react — a react runtime error shows the 'React page error' fallback on the rendered page. Neither may be a blank page" + "degradation: (a) html — save a faulting html source at the ACTIVE door (or publish one) and capture the 422 INVALID_METADATA with its compile diagnostics; then save the same source as a ?mode=draft draft IN A WRITABLE PACKAGE (?package=PKG) and open its item page in Studio's \"All metadata\" area, /_console/studio/PKG/metadata/page/NAME (Studio's Interfaces pillar, which opened it at /interfaces?surface=page:NAME through an app's navigation, retired with #36502), where the draft preview's 'HTML page failed to compile (N)' panel renders with the diagnostic messages. An env-wide (package-less) draft has no Studio surface, and the save gate keeps a faulting html page off the rendered route, so the panel cannot be met anywhere else (knownGaps[0]); (b) react — a react runtime error shows the 'React page error' fallback on the rendered page. Neither may be a blank page" ], "acceptance": [ { @@ -1394,7 +1396,8 @@ { "revision": 3, "date": "2026-10-16", "change": "steps[7](a) names how to reach the draft preview (checklist-accuracy finding 8 of QA run #23942, wave #23878). The compile panel is reachable only for a page staged in a writable package that an app's navigation references, opened at /_console/studio/PKG/interfaces?surface=page:NAME; an env-wide draft has no Studio surface, which is what #23942 met. The clause is unchanged", "ref": "#24036" }, { "revision": 4, "date": "2026-10-25", "change": "the react-pages tier defaults OFF (ADR-0081 amendment): fixtures.requires names the showcase's committed .env opt-in OS_PAGE_REACT_ENABLED=true, and the both-sides gate's off-state is a boot with OS_PAGE_REACT_ENABLED=false (steps[6], acceptance[4], negative[1], source rows). The clauses are unchanged", "ref": "claude/project-thread-80dotk" }, { "revision": 5, "date": "2026-10-28", "change": "knownGaps/source re-pointed from ui/e2e/live/showcase-smoke.spec.ts, deleted by the triage of the live specs that ran in no CI lane (ruling Q3 B) as a duplicate: every surface it swept and each of its four assertions are in examples/app-showcase/e2e/showcase-smoke.spec.ts, which Nightly Tiers runs, with a wider surface list and stricter waits. That sweep includes the three html/react pages, which the old note said it did not; it pins render-clean only, so the item stays browser-driven. No clause changed", "ref": "#25914" }, - { "revision": 6, "date": "2026-11-04", "change": "fixtures.requires[1] and steps[6] name the .claude/launch.json entry showcase-react-pages-off-3779 as the off-state boot of the both-sides gate. QA run #29672 could not flip the env, because a runner that starts servers only from launch.json had no such entry. No clause changed", "ref": "#29819" } + { "revision": 6, "date": "2026-11-04", "change": "fixtures.requires[1] and steps[6] name the .claude/launch.json entry showcase-react-pages-off-3779 as the off-state boot of the both-sides gate. QA run #29672 could not flip the env, because a runner that starts servers only from launch.json had no such entry. No clause changed", "ref": "#29819" }, + { "revision": 7, "date": "2026-11-24", "change": "steps[7](a) opens the faulting draft on its All-metadata item page instead of Studio's Interfaces pillar, retired by #36502; the app that referenced the page is no longer needed to reach it. No clause changed", "ref": "#36502" } ] }, { @@ -3515,8 +3518,9 @@ "id": "studio-authoring.interfaces-create-dialogs", "title": "The Interfaces create dialogs work end to end: Create app derives its identifier and scaffolds one menu entry per package object (none when the box is cleared), New dashboard / report / page write spec-valid drafts linked from the menu, a report without a dataset or a measure and an identifier already taken are refused in the dialog, and everything opens in the published app", "since": "v18", - "status": "active", - "revision": 4, + "status": "retired", + "retiredReason": "The surface this item proved was removed by #36502: Studio's Interfaces pillar retired, and with it the dialogs this item drove from it — the 'Add to navigation' menu's New dashboard, New report and New page (doCreateSurface, interfaceCreate.tsx) and Create app's landing on that pillar. What stays is carried elsewhere: Create app's identifier derivation and its menu scaffold (box on and off) are studio-authoring.first-run-loop's (Create app still opens from Studio, and now stays on the Data pillar); a dashboard, report or page is created in the running app or through the API (studio-authoring.report-authoring-options, studio-authoring.authored-page-slots-and-variables), and the identifier-taken refusal is the create door's own. No single successor covers every clause, so no supersededBy.", + "revision": 5, "priority": "P1", "surface": "mixed", "personas": [ @@ -3615,7 +3619,8 @@ "date": "2026-11-14", "change": "steps[3] and steps[5] name where the create entries live (QA run #33048, comment 6846028996): the Interfaces rail's 'Add to navigation' menu (if-create-menu → if-create-dashboard / -report / -page, StudioDesignSurface.tsx) and the page dialog's 'Written in' select (ui/packages/i18n/src/namespaces/studio/en.ts). No clause changed. Read at base 87330e89", "ref": "#33329" - } + }, + { "revision": 5, "date": "2026-11-24", "change": "Retired by #36502, which retired Studio's Interfaces pillar and the create dialogs it opened (New dashboard / report / page, interfaceCreate.tsx) together with their jsdom pins (StudioDesignSurface.interfacesCreate-11823, interfacesCreatePage-11823, createAppOpensInterfaces-11794). The clauses that outlive the pillar are carried as retiredReason lists. A retired item is not run. No clause text changed", "ref": "#36502" } ] }, { @@ -3623,7 +3628,7 @@ "title": "A package dashboard renders every widget type the spec declares — those Studio offers and those written through the API — and every global-filter type renders its control and re-scopes the widgets bound to it; Studio's two widget-type entries offer the same set", "since": "v18", "status": "active", - "revision": 7, + "revision": 8, "priority": "P2", "surface": "mixed", "personas": [ @@ -3638,7 +3643,7 @@ ] }, "steps": [ - "open the dashboard in /_console/studio/PKG/interfaces; read the Add-widget menu's type list and, on one widget, the Type picker's list", + "open the dashboard in the running app's design mode (DashboardInPageEditor; Studio's Interfaces pillar, where this was read before, retired with #36502); read the Add-widget menu's type list and, on one widget, the Type picker's list. Re-measure on the first run whether the in-app editor offers the same lists, and record the difference if not", "add one widget of every type the Add menu offers, bound to the dataset (a dimension and a measure each); the menu offers every ChartTypeSchema member since #26967, so for any type it does not list, record the missing type and write that widget into the same dashboard draft with PUT /api/v1/meta/dashboard/NAME?mode=draft&package=PKG (keep the Studio-authored widgets in the body)", "global filters: add one filter of each type — text, select (with options or optionsFrom), date, number, lookup (with optionsFrom {object, valueField, labelField}: a lookup filter draws the same select control and, with no options or optionsFrom, offers no choices — ui/packages/plugin-dashboard/src/DashboardFilterBar.tsx) — and bind each to at least one widget through that widget's filter mapping; leave one widget unbound, which means filterBindings { NAME: false } for EVERY filter on it. A widget with no filterBindings entry is not unbound: it inherits each filter on that filter's own field (ui/packages/core/src/utils/dashboard-filters.ts resolveBoundField: an explicit binding, then targetWidgets, then the filter's field; read from source, not driven live)", "publish; open the board in the app; screenshot it settled", @@ -3673,7 +3678,7 @@ { "clause": "Studio's global-filter editor never autosaves an incomplete filter: the item is held until complete, and no other edit is lost", "oracle": "network", - "verify": "no dashboard PUT carries the incomplete filter. Four cases, each judged: (a) the edits made BEFORE Add item survive a reload; (b) an edit made while the item is held is carried by the PUT that completes the item, answered 200 (ui/packages/app-shell/src/views/studio-design/InterfacesPillar.heldListItem-27459.test.tsx); (c) a reload while the item is held raises the browser's leave-site prompt, and Leave then discards the held item and the edits kept with it, by design (studio-authoring.held-edit-leave-guard) — a reload with no prompt that loses an edit is a FAIL; (d) the wave-4 shape, a Field filled with Options From begun, is held like any incomplete item: no PUT carries it and a later edit still saves (#29006, fixed by #29300)", + "verify": "no dashboard PUT carries the incomplete filter. Four cases, each judged: (a) the edits made BEFORE Add item survive a reload; (b) an edit made while the item is held is carried by the PUT that completes the item, answered 200 (its jsdom pin, InterfacesPillar.heldListItem-27459.test.tsx, retired with the Interfaces pillar in #36502: the held-item judgement itself stays pinned in metadataError.heldListItem-27459.test.ts); (c) a reload while the item is held raises the browser's leave-site prompt, and Leave then discards the held item and the edits kept with it, by design (studio-authoring.held-edit-leave-guard) — a reload with no prompt that loses an edit is a FAIL; (d) the wave-4 shape, a Field filled with Options From begun, is held like any incomplete item: no PUT carries it and a later edit still saves (#29006, fixed by #29300)", "evidence": "the trace + the post-reload read" } ], @@ -3743,7 +3748,8 @@ "date": "2026-11-04", "change": "fixtures.requires[2]: the 'Studio has no dataset editor' parenthetical is stale, as #29906 found for interfaces-create-dialogs and report-authoring-options. Studio's New dataset entry (datasetCreate.tsx DatasetCreateEntry, objectstack#27518) sits beside the widget inspector's dataset picker (DashboardWidgetInspector.tsx) and the New report dialog's. The fixture stays API-written for a known shape. No clause changed. Read at base 232d3bb5ef", "ref": "#30129" - } + }, + { "revision": 8, "date": "2026-11-24", "change": "steps[0] reads the widget lists in the running app's design mode, since Studio's Interfaces pillar retired with #36502 (marked for re-measure); acceptance[4](b)'s jsdom ref names the pin that retired with the pillar and the helper pin that stays. No clause changed", "ref": "#36502" } ] }, { @@ -3751,7 +3757,7 @@ "title": "Reports authored in Studio render every report type from the same dataset — tabular, summary, matrix and joined — and their runtimeFilter, order and chart take effect in the published app, while a joined report refuses a chart and a block with no dataset", "since": "v18", "status": "active", - "revision": 4, + "revision": 5, "priority": "P2", "surface": "mixed", "personas": [ @@ -3766,7 +3772,7 @@ ] }, "steps": [ - "in /_console/studio/PKG/interfaces create a report (New report: the dataset and a measure); on its canvas set the type to tabular, then summary with a row dimension, then matrix with a row and a column dimension; keep a copy of each as its own report", + "create a report in the running app (its New report page, ReportNewPage; Studio's Interfaces pillar and its New report dialog retired with #36502), or write it through the API (PUT /api/v1/meta/report/NAME?mode=draft&package=PKG), with the dataset and a measure; on its editor set the type to tabular, then summary with a row dimension, then matrix with a row and a column dimension; keep a copy of each as its own report", "on the summary report set runtimeFilter to narrow the rows (e.g. one category value), order by the measure descending, and an embedded chart", "author a joined report with two blocks, each bound to the dataset with its own rows and values (switching the Report type to Joined is held, and nothing saves, until the first block is added, #29022: a runner who switches the type and reloads before adding a block sees the previous type again)", "refusals: PUT a joined report carrying a chart, and one whose block has no dataset, with ?mode=draft&package=PKG; capture both", @@ -3840,7 +3846,8 @@ "date": "2026-11-04", "change": "fixtures.requires[2] and steps[2] corrected from QA run #29893 (W5-STUDIO, at 589049b0): the 'no dataset editor' parenthetical is stale (New dataset, datasetCreate.tsx), and a switch to Joined is held until a block is added (#29022). steps[0] names no Joined switch and is unchanged. Read at base f68b47ca", "ref": "#29906" - } + }, + { "revision": 5, "date": "2026-11-24", "change": "steps[0] creates the report in the running app or through the API: Studio's Interfaces pillar and its New report dialog retired with #36502. No clause changed", "ref": "#36502" } ] }, { @@ -3848,7 +3855,7 @@ "title": "App and menu-entry keys reach the running app: branding, areas and context selectors render; an entry's viewName, recordId / recordMode, filters, badge, requiresObject and visible each change what the entry does or who sees it; hidden takes an app off the switcher and nothing else — and Studio's menu-entry inspector edits them", "since": "v18", "status": "active", - "revision": 8, + "revision": 9, "priority": "P2", "surface": "mixed", "personas": [ @@ -3871,7 +3878,7 @@ "as admin and as the member (each in its own context, identity proved with GET /api/v1/auth/get-session), open the app (no dialog opens over it: a fresh organization's first-run checklist is a non-modal card on Home only, RUNNER environment facts) and read the chrome colours and logo, the areas switcher, the context selector, and click each entry", "GET /api/v1/meta/app?id=APP as each persona and list the entries each receives", "set hidden: true on a second app of the package (through the API) and publish; as the member read the App Switcher, the Home launcher, the avatar menu and GET /api/v1/meta/app?id=SECOND; open its URL directly", - "open the app in /_console/studio/PKG/interfaces, select each entry and read its inspector. Studio's Interfaces pillar opens only the package's FIRST app (the first app the package lists, else its first app draft) and draws only that app's top-level `navigation`: an entry that lives only inside `areas` has no rail row (ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx, the Interfaces pillar's app load). So the app steps[0] writes must be the package's first, and its top-level navigation must hold at least one entry carrying each key acceptance[5] names; the area entries' runtime effect is read in acceptance[0]–[3], not here" + "open the app in the running console, turn on design mode, and open each entry in the menu editor (DesignModeMenu; Studio's Interfaces pillar and its nav-item inspector, where this was read before, retired with #36502). The app's top-level navigation must hold at least one entry carrying each key acceptance[5] names; re-measure on the first run which of those keys the in-app menu editor offers a control for, and record the rest as metadata-only (editable on the app's All-metadata item page, /_console/studio/PKG/metadata/app/NAME); the area entries' runtime effect is read in acceptance[0]–[3], not here" ], "acceptance": [ { @@ -3907,7 +3914,7 @@ { "clause": "Studio's menu-entry inspector edits these keys — visible, viewName, recordId / recordMode, filters, badge / badgeVariant, requiresObject, order — as the metadata admin's app editor does", "oracle": "dom", - "verify": "each key has an editable control in the Studio inspector, and an edit there autosaves it into the app draft. The View picker offers the package's view items of the bound object and writes the qualified 'OBJECT.KEY' name (StudioNavItemInspector.tsx, e.g. gsixn_project.closed_projects), while steps[0]'s API write may name the bare list-view key the runtime also accepts: record which spelling each entry carries, and whether an entry carrying the qualified name opens that view (QA run #29893 did not drive it)", + "verify": "each key has an editable control in the running app's design-mode menu editor or, where it has none, on the app's All-metadata item page, and an edit there saves it into the app draft (the Studio nav-item inspector this read before, StudioNavItemInspector.tsx, retired with the Interfaces pillar in #36502; its View picker wrote the qualified 'OBJECT.KEY' name, e.g. gsixn_project.closed_projects); while steps[0]'s API write may name the bare list-view key the runtime also accepts: record which spelling each entry carries, and whether an entry carrying the qualified name opens that view (QA run #29893 did not drive it)", "evidence": "the inspector DOM per key + one autosave PUT" } ], @@ -3923,7 +3930,7 @@ "source": [ "packages/spec/src/ui/app.zod.ts (branding: primaryColor / accentColor / logo / favicon; areas; contextSelectors; hidden — 'navigation only, never an access gate'; the nav item keys viewName, recordId, recordMode, filters, badge, badgeVariant, requiresObject, visible, order)", "packages/metadata-core/src/artifact-forward-conversion.ts (where the retired app-hidden-to-unpublished conversion stood; dbf7e04a removed it from packages/spec/src/conversions/registry.ts, so a stored hidden: true round-trips — #26712, closed as fixed)", - "ui/packages/app-shell/src/views/studio-design/StudioNavItemInspector.tsx (the Studio menu-entry inspector)", + "ui/packages/app-shell/src/layout/DesignModeMenu.tsx (the running app's design-mode menu editor; the Studio menu-entry inspector, StudioNavItemInspector.tsx, retired with the Interfaces pillar in #36502)", "cross-ref: the doc-type menu entry is studio-authoring.doc-on-app-menu; nav rendering on the stock showcase is platform-core.nav-surfaces-render" ], "history": [ @@ -3974,7 +3981,8 @@ "date": "2026-11-06", "change": "steps[1] no longer tells the runner to dismiss the 'Set the default currency' prompt: PR #30868 (#30206) retired that boot-time dialog for a non-modal first-run checklist card on Home, which does not cover the app (RUNNER environment facts). No clause changed. Read at base 0e882086", "ref": "#30876" - } + }, + { "revision": 9, "date": "2026-11-24", "change": "steps[4], acceptance[5] and source[2] read the menu-entry keys in the running app's design-mode menu editor (or the app's All-metadata item page where it offers no control): Studio's Interfaces pillar and its nav-item inspector retired with #36502. Which keys the in-app editor offers is marked for re-measure. The clause's subject (an editable control per key, saved into the app draft) is unchanged", "ref": "#36502" } ] }, { @@ -3982,7 +3990,7 @@ "title": "Pages authored in a package take the page model's full shape: a slotted record page renders its slot overrides on the object's records, and page variables of all six types drive visibleWhen on the rendered page — at first render and live as a writer changes them", "since": "v18", "status": "active", - "revision": 3, + "revision": 4, "priority": "P2", "surface": "mixed", "personas": [ @@ -3997,7 +4005,7 @@ }, "steps": [ "slotted page: PUT /api/v1/meta/page/NAME?mode=draft&package=PKG with type 'record', object OBJ, kind 'slotted', isDefault true and slots overriding highlights, details and discussion (not tabs: `slots.tabs` is retired by ADR-0085, and the save door refuses it with its tombstone, '`page.slots.tabs` was removed in @objectstack/spec 18.3.0 (ADR-0085) …', packages/spec/src/ui/page.zod.ts; the slot keys are header, actions, alerts, highlights, details and discussion); publish; open a record of OBJ in the app", - "variables: on an app page of the package (created in Studio's Interfaces, New page, or written through the API) declare six variables, one per type — string, number, boolean, object, array, record_id — each with a default; add one element:text per variable whose visibleWhen reads it (e.g. page.flag == true, page.count > 2, size(page.items) > 0, page.obj.k == 'v', page.name == '', page.rec == ''), plus an element:text_input writing the string variable and an element:record_picker writing the record_id one", + "variables: on an app page of the package (written through the API, or created in the running app; Studio's Interfaces pillar and its New page retired with #36502) declare six variables, one per type — string, number, boolean, object, array, record_id — each with a default; add one element:text per variable whose visibleWhen reads it (e.g. page.flag == true, page.count > 2, size(page.items) > 0, page.obj.k == 'v', page.name == '', page.rec == ''), plus an element:text_input writing the string variable and an element:record_picker writing the record_id one", "publish; open the page; screenshot the first render; then type into the text input and pick a record, re-reading after each without reloading" ], "acceptance": [ @@ -4060,7 +4068,8 @@ "date": "2026-11-01", "change": "negative[1] moved to source[3]: it was a scope note naming the items that own the neighbouring surfaces, which no run can decide, so it could only score skipped. Its text is unchanged except the SCOPE: label, which now reads cross-ref:, the spelling the sibling source rows use. Ruling 6545938831 item ① on #28345 (scope notes leave negative[], which keeps only decidable entries; the #27651 precedent). No clause changed. Wave anchor #27377", "ref": "#28345" - } + }, + { "revision": 4, "date": "2026-11-24", "change": "steps[1] no longer names Studio's Interfaces New page, retired with #36502, as a way to create the page. No clause changed", "ref": "#36502" } ] }, { @@ -4730,7 +4739,7 @@ "title": "A write that names a package nobody installed is refused, for every metadata type as it already is for flows: the save door answers WRITABLE_PACKAGE_REQUIRED and stores nothing, publish-drafts on that id promotes nothing, and Studio opened on it says the package does not exist instead of rendering a writable builder", "since": "v18", "status": "active", - "revision": 3, + "revision": 4, "priority": "P1", "surface": "mixed", "personas": [ @@ -4773,7 +4782,7 @@ { "clause": "Studio opened on a package that does not exist shows that it does not exist, with a way back — never a writable builder; an unknown pillar segment does not silently render another pillar", "oracle": "screenshot", - "verify": "the not-found state for both URLs (no New object, no Create app); the bogus pillar URL is not shown as the Interfaces pillar with the bogus URL kept", + "verify": "the not-found state for both URLs (no New object, no Create app); the bogus pillar URL is not shown as another pillar with the bogus URL kept (it was the Interfaces pillar until #36502 retired it; an old /interfaces URL now lands on the Data pillar by design, so it is not a bogus pillar URL)", "evidence": "the screenshots described" } ], @@ -4809,7 +4818,8 @@ "date": "2026-11-01", "change": "negative[1] moved to source[3]: it was a scope note naming the items that own the neighbouring surfaces, which no run can decide, so it could only score skipped. Its text is unchanged except the SCOPE: label, which now reads cross-ref:, the spelling the sibling source rows use. Ruling 6545938831 item ① on #28345 (scope notes leave negative[], which keeps only decidable entries; the #27651 precedent). No clause changed. Wave anchor #27377", "ref": "#28345" - } + }, + { "revision": 4, "date": "2026-11-24", "change": "acceptance[3]'s FAIL shape no longer names the Interfaces pillar, retired by #36502, whose old URL now redirects to the Data pillar by design. No clause changed", "ref": "#36502" } ] }, { @@ -4817,7 +4827,7 @@ "title": "Customize a read-only base's view, dashboard or report in Studio: the edit lands in .custom as a declared override, every read serves it, the pair's export carries the declaration, and 'Restore package original' brings the base back", "since": "v18", "status": "active", - "revision": 6, + "revision": 7, "priority": "P1", "surface": "mixed", "personas": [ @@ -4839,31 +4849,31 @@ }, "steps": [ "record the shipped base first, for each variant: GET /api/v1/meta/TYPE/NAME, the same with ?package=com.example.showcase, GET /api/v1/meta/TYPE/NAME/layers, and GET /api/v1/packages/com.example.showcase/export — the restore clause diffs against these", - "dashboard leg: open /_console/studio/com.example.showcase/interfaces and select showcase_ops_dashboard. Read the header: the editors are read-only and a Customize button (data-testid studio-customize) is offered, titled with the base. Press it with the network panel recording: no write is sent (the dashboard canvas re-runs its analytics dataset query on the unlock re-render, POST /api/v1/analytics/dataset/query/batch, a read; QA run #33861)", - "edit a widget title, blur the input, and let the autosave run: capture POST /api/v1/packages/com.example.showcase/ensure-customization and the PUT /api/v1/meta/dashboard/showcase_ops_dashboard?mode=draft&package=com.example.showcase.custom that follows; GET /api/v1/meta/dashboard/showcase_ops_dashboard?state=draft&package=com.example.showcase.custom", - "publish through the surface's Pending / Publish, which act on the pair (POST /api/v1/packages/com.example.showcase.custom/publish-drafts); reload the pillar and read the header badge (data-testid studio-override-chip)", + "dashboard leg: open showcase_ops_dashboard's All metadata item page, /_console/studio/com.example.showcase/metadata/dashboard/showcase_ops_dashboard (the door since #36502 retired the Interfaces pillar; StudioBundleItemEditor with the type's registered designer). Read the header: the designer is read-only and a Customize button (data-testid studio-customize) is offered, titled with the base. Press it with the network panel recording: no write is sent (the dashboard preview may re-run its analytics dataset query on the unlock re-render, POST /api/v1/analytics/dataset/query/batch, a read; QA run #33861)", + "edit the dashboard's Description in its designer, blur the input, and let the autosave run: capture POST /api/v1/packages/com.example.showcase/ensure-customization and the PUT /api/v1/meta/dashboard/showcase_ops_dashboard?mode=draft&package=com.example.showcase.custom that follows; GET /api/v1/meta/dashboard/showcase_ops_dashboard?state=draft&package=com.example.showcase.custom", + "publish through the surface's Pending / Publish, which act on the pair (POST /api/v1/packages/com.example.showcase.custom/publish-drafts); reload the item page and read the header badge (data-testid studio-override-chip)", "the reads after publish: GET /api/v1/meta/dashboard/showcase_ops_dashboard with no package, with ?package=com.example.showcase, its /layers, and the list GET /api/v1/meta/dashboard; then open the dashboard in the showcase app as the end user (client reload only, no server restart)", "export: GET /api/v1/packages/com.example.showcase.custom/export and GET /api/v1/packages/com.example.showcase/export. A standalone view sits in the export's `viewItems` collection, not `views` (packages/metadata-protocol/src/package-unmanaged-install.ts, the assembled viewItems channel)", "Restore: open the override chip's popover and press its Restore (data-testid studio-override-restore), read the confirmation (studio-restore-original-dialog) and confirm with studio-restore-original-confirm (StudioCustomizeControls.tsx); capture DELETE /api/v1/meta/dashboard/showcase_ops_dashboard?state=draft&package=com.example.showcase.custom then DELETE …?package=com.example.showcase.custom; repeat step 5's reads and render", - "view leg: in the same Interfaces pillar open the showcase_task object leaf's list-view inspector (ObjectListViewInspector) on a packaged list view; Customize, change a setting or the column set, publish, and run steps 5–7 for the view (GET /api/v1/meta/view/VIEW, ?package=com.example.showcase, /layers, the list GET /api/v1/meta/view?object=showcase_task, and the view's end-user render at /apps/com.example.showcase/showcase_task/view/VIEW, e.g. …/view/in_progress — not the 'In-Progress Tasks' nav entry, which is a filtered object entry, nav_slice_in_progress in examples/app-showcase/src/ui/apps/index.ts, and never renders the view). Report leg: the same for the picked report from the Interfaces pillar" + "view leg: open a packaged list view's All metadata item page, e.g. /_console/studio/com.example.showcase/metadata/view/showcase_task.in_progress; Customize, change a setting or remove a column in the view's designer (Remove ), publish, and run steps 5–7 for the view (GET /api/v1/meta/view/VIEW, ?package=com.example.showcase, /layers, the list GET /api/v1/meta/view?object=showcase_task, and the view's end-user render at /apps/com.example.showcase/showcase_task/view/VIEW, e.g. …/view/in_progress — not the 'In-Progress Tasks' nav entry, which is a filtered object entry, nav_slice_in_progress in examples/app-showcase/src/ui/apps/index.ts, and never renders the view). Report leg: the same for the picked report on its item page, /_console/studio/com.example.showcase/metadata/report/NAME" ], "acceptance": [ { "clause": "Customize unlocks the item and writes nothing; the first saved edit asks the ensure door once and writes the item's draft into com.example.showcase.custom, declaring overrides: { package: 'com.example.showcase', basedOn: '0.1.0' }, while the base's own item is untouched", "oracle": "network", - "verify": "step 2 sends no request; step 3 sends exactly one ensure POST (201 on the run's first customization, 200 after), once per editing session: the surface keeps the door's answer only while it is mounted (ensurePairPackage, StudioDesignSurface.tsx), so a fresh page load of the same item asks the ensure door again (200) on its first edit and then the draft PUT naming package=com.example.showcase.custom whose body carries the overrides block and none of the read's `_` keys (overrideDraftBody, StudioCustomizeControls.tsx). No write names com.example.showcase. A draft written into com.example.showcase, or a package-less write, is the FAIL", + "verify": "step 2 sends no request; step 3 sends exactly one ensure POST (201 on the run's first customization, 200 after), once per editing session: the editor keeps the door's answer only while it is mounted (StudioBundleItemEditor.tsx), so a fresh page load of the same item asks the ensure door again (200) on its first edit and then the draft PUT naming package=com.example.showcase.custom whose body carries the overrides block and none of the read's `_` keys (overrideDraftBody, StudioCustomizeControls.tsx). No write names com.example.showcase. A draft written into com.example.showcase, or a package-less write, is the FAIL", "evidence": "the network trace of steps 2–3 + the pair's draft read" }, { "clause": "after publish every read of the base's name serves the override — the read naming no package, the read naming the base, the layered read (code = the base's document, overlay and effective = the override) and the list — so the three reads the epic names show one column set", "oracle": "api", - "verify": "step 5's reads carry the edited title (dashboard) or column set (view) on all four; the package-less read reports _packageId com.example.showcase and carries the overrides block; /layers' code is byte-identical to step 1's base. Re-fetch each read fresh (cache-staleness). A read that still serves the base, or two reads that disagree, is the FAIL ADR-0146 D8 forbids", + "verify": "step 5's reads carry the edited description (dashboard) or column set (view) on all four; the package-less read reports _packageId com.example.showcase and carries the overrides block; /layers' code is byte-identical to step 1's base. Re-fetch each read fresh (cache-staleness). A read that still serves the base, or two reads that disagree, is the FAIL ADR-0146 D8 forbids", "evidence": "the four reads per variant, beside step 1's baseline" }, { "clause": "the end user sees the customization after publish with no server restart", "oracle": "screenshot", - "verify": "the showcase dashboard (and, on the view leg, the task list) renders the edited title or columns after a client reload; the server log shows no restart across the sequence", + "verify": "the showcase dashboard (and, on the view leg, the task list) renders the edited description or columns after a client reload; the server log shows no restart across the sequence", "evidence": "before/after end-user screenshots + the server log excerpt" }, { @@ -4881,7 +4891,7 @@ { "clause": "'Restore package original' deletes the pair's draft and row at the pair, and every read and the end user's render serve the base again", "oracle": "api", - "verify": "step 7's two DELETEs name package=com.example.showcase.custom and answer 200; the four reads equal step 1's baseline and the render shows the shipped title or columns. Cancel on the dialog deletes nothing (a separate attempt before the confirm). A restore that answers 200 while any read still serves the override is the FAIL", + "verify": "step 7's two DELETEs name package=com.example.showcase.custom and answer 200; the four reads equal step 1's baseline and the render shows the shipped description or columns. Cancel on the dialog deletes nothing (a separate attempt before the confirm). A restore that answers 200 while any read still serves the override is the FAIL", "evidence": "the DELETE trace + the post-restore reads diffed against step 1 + the reverted render" }, { @@ -4896,9 +4906,9 @@ "a customization that carries no overrides block, or declares a package other than com.example.showcase, is served over the base — FAIL: only the base's pair declares, and only a declared item is served at the base's name (ADR-0146 D2, D8)" ], "variants": [ - "dashboard (showcase_ops_dashboard, Interfaces pillar)", - "view (a showcase_task list view, the Interfaces pillar's object leaf and its list-view inspector)", - "report (a packaged showcase report, Interfaces pillar)" + "dashboard (showcase_ops_dashboard, its All metadata item page)", + "view (a showcase_task list view, its All metadata item page and the view's designer)", + "report (a packaged showcase report, its All metadata item page)" ], "traps": [ "stale-console-bundle", @@ -4908,11 +4918,11 @@ ], "automated": { "kind": "e2e", - "ref": "ui/e2e/live/studio-customize-journey.spec.ts (live Playwright against a booted showcase and a built console, in the required Live E2E UI job's test:e2e:live:ci allowlist; the VIEW variant only, on showcase_task.in_progress: acceptance[0] at the network layer — Customize, one ensure answering 200 or 201, the draft PUT naming package=com.example.showcase.custom with overrides { package: 'com.example.showcase', basedOn } and the edited column set; acceptance[1]'s read naming no package, the read naming the base and the list, at HTTP — not /layers; acceptance[3]'s studio-override-chip drawn — not its sentence or title; acceptance[5]'s two DELETEs at the pair answering 200 and the three reads back to the shipped columns — not Cancel and not the end user's render. It drives neither the dashboard nor the report variant, acceptance[2] or acceptance[4]) + ui/packages/app-shell/src/views/studio-design/InterfacesPillar.customize-28562.test.tsx + StudioCustomizeControls.customize-28562.test.tsx + StudioDesignSurface.customizePublish-28562.test.tsx (jsdom, the console's calls and states for acceptance[0], [3] and [5]'s client half) + packages/objectql/src/protocol-custom-override-effective-read.test.ts (protocol layer: the five reads agree and the pair's per-package read carries the declaration — corroborates acceptance[1] and [4], drives no HTTP door). The dashboard and report variants, the end user's render and both exports remain the run's live leg" + "ref": "ui/e2e/live/studio-customize-journey.spec.ts (live Playwright against a booted showcase and a built console, in the required Live E2E UI job's test:e2e:live:ci allowlist; the VIEW variant only, on showcase_task.in_progress: acceptance[0] at the network layer — Customize on the view's All metadata item page (/studio/com.example.showcase/metadata/view/showcase_task.in_progress, objectstack#36502), one ensure answering 200 or 201, the draft PUT naming package=com.example.showcase.custom with overrides { package: 'com.example.showcase', basedOn } and the edited column set; acceptance[1]'s read naming no package, the read naming the base and the list, at HTTP — not /layers; acceptance[3]'s studio-override-chip drawn — not its sentence or title; acceptance[5]'s two DELETEs at the pair answering 200 and the three reads back to the shipped columns — not Cancel and not the end user's render. It drives neither the dashboard nor the report variant, acceptance[2] or acceptance[4]) + ui/packages/app-shell/src/views/studio-design/StudioBundleItemEditor.customize-28569.test.tsx + StudioCustomizeControls.customize-28562.test.tsx + StudioDesignSurface.customizePublish-28562.test.tsx + metadataArea.test.ts (areaItemOpensFormEditor: a read-only base's view, dashboard, report and page open that editor) (jsdom, the console's calls and states for acceptance[0], [3] and [5]'s client half) + packages/objectql/src/protocol-custom-override-effective-read.test.ts (protocol layer: the five reads agree and the pair's per-package read carries the declaration — corroborates acceptance[1] and [4], drives no HTTP door). The dashboard and report variants, the end user's render and both exports remain the run's live leg" }, "source": [ "ui/packages/app-shell/src/views/studio-design/StudioCustomizeControls.tsx#STUDIO_CUSTOMIZE_TYPES (view, dashboard, report), ui/packages/app-shell/src/views/studio-design/StudioCustomizeControls.tsx#overrideDraftBody (the pair's draft body and its declaration), ui/packages/app-shell/src/views/studio-design/StudioCustomizeControls.tsx#StudioCustomizeButton, ui/packages/app-shell/src/views/studio-design/StudioCustomizeControls.tsx#StudioOverrideChip, ui/packages/app-shell/src/views/studio-design/StudioCustomizeControls.tsx#StudioRestoreOriginalDialog", - "ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx (the Interfaces pillar's save into the pair and restoreOriginal: two client.reset calls at the pair, the draft then the row) + ui/packages/app-shell/src/views/studio-design/packages-io.ts#ensureCustomizationPackage", + "ui/packages/app-shell/src/views/studio-design/StudioBundleItemEditor.tsx (the All metadata item page's Customize editor: the save into the pair and its Restore, the draft then the row; the door since #36502 retired the Interfaces pillar) + ui/packages/app-shell/src/views/studio-design/metadataArea.ts#AREA_CUSTOMIZE_EDITOR_TYPES + ui/packages/app-shell/src/views/studio-design/packages-io.ts#ensureCustomizationPackage", "packages/spec/src/kernel/override-declaration.zod.ts#OverrideDeclarationSchema (overrides: { package, basedOn })", "docs/adr/0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md D2, D3, D8 (the five reads agree; export carries the declaration; the epic's two-minute check 「HotCRM 视图「定制」→ 三处读取同一列集、导出带声明、「恢复包原版」回原样」)", "#28562 (N-17) landed by PR #28711; the one effective read #28409 (N-10) by PR #28507; the pair's Pending and Publish by PR #28747 (#28572)", @@ -4955,6 +4965,12 @@ "date": "2026-11-15", "change": "steps[1] says Customize sends no write (the canvas re-runs a read), and steps[7] names the view's own end-user route instead of the task list, since the 'In-Progress Tasks' nav entry is a filtered slice, not the view (QA run #33861, comment 6894395705; ledger 6896511848 of #33761 row 174; the record numbers the Customize step 2). The clauses are unchanged. Read at base 895783a1", "ref": "#33981" + }, + { + "revision": 7, + "date": "2026-11-24", + "change": "RE-POINTED: the Customize door for a read-only base's dashboard, view and report moves from the retired Interfaces pillar to each item's All metadata item page (StudioBundleItemEditor, metadataArea.ts#AREA_CUSTOMIZE_EDITOR_TYPES), so steps[1], [2], [3] and [7], the wording of acceptance[0]-[2] and [5], the variants, automated.ref and source name that page and its designer. The dashboard edit is its Description, since the designer edits a widget title only through the widget's own inspector. The clauses are unchanged. The live spec's view leg drives the new door (test:e2e:live:ci 23/23 green on a local CI-shaped boot). Read at base 47ed85d2", + "ref": "#36502" } ] }, diff --git a/docs/qa/platform-checklist/areas/ux-conventions.json b/docs/qa/platform-checklist/areas/ux-conventions.json index 9d7a9d400f0..77f587c0699 100644 --- a/docs/qa/platform-checklist/areas/ux-conventions.json +++ b/docs/qa/platform-checklist/areas/ux-conventions.json @@ -329,7 +329,7 @@ "title": "Where a label exists users see the label — machine names, raw ids and spec paths appear only as secondary text", "since": "v17.7", "status": "active", - "revision": 5, + "revision": 6, "priority": "P1", "surface": "browser", "personas": [ @@ -343,7 +343,7 @@ "read access to the served metadata of every sampled surface — labels are read from metadata, never assumed" ], "knownGaps": [ - "objectui#11862 is FIXED for the rows that still failed at 1fb1ced36243 (QA run #23953 at objectui daeb77fc84dd): the Access permission-set list, the Changes panel and the Lookup inspector's Display-field picker now lead with the label, as do Explain access's principal line (pin AccessExplainPanel.principalPerson-11862.test.tsx) and the nav editor's items — regression rows, expected PASS. Explain's server-built Principal resolution prose names the person too — 'Principal NAME (EMAIL; id USER_ID)' (packages/plugins/plugin-security/src/explain-engine.ts; #23157, closed). Regression rows, expected PASS since QA run #24570 (objectui 4016370a, two fresh loads each): (a) Explain access's principal card draws its position and permission-set chips by label and the result banner names the object by its label; (b) Studio Interfaces' list-view 'Columns' rows draw each field's label, its api name on the row's title (objectstack-ai/objectui#12693, closed by objectui PR #12834, cda4076b, in the console pin 4016370a and on objectui main). ⚠️ Explain's Principal resolution 'Contributed by' chips are a different surface from (a): QA run #24570 found them on machine names at 4016370a and extracted objectstack-ai/objectui#13056, since FIXED: each layer's 'Contributed by' line draws the item's label (ui/packages/app-shell/src/views/metadata-admin/AccessExplainPanel.tsx; pin AccessExplainPanel.contributorLabels-13056.test.tsx), and QA run #33094 did not reproduce it — a regression row, expected PASS", + "objectui#11862 is FIXED for the rows that still failed at 1fb1ced36243 (QA run #23953 at objectui daeb77fc84dd): the Access permission-set list, the Changes panel and the Lookup inspector's Display-field picker now lead with the label, as do Explain access's principal line (pin AccessExplainPanel.principalPerson-11862.test.tsx) and the nav editor's items — regression rows, expected PASS. Explain's server-built Principal resolution prose names the person too — 'Principal NAME (EMAIL; id USER_ID)' (packages/plugins/plugin-security/src/explain-engine.ts; #23157, closed). Regression rows, expected PASS since QA run #24570 (objectui 4016370a, two fresh loads each): (a) Explain access's principal card draws its position and permission-set chips by label and the result banner names the object by its label; (b) Studio Interfaces' list-view 'Columns' rows (retired with that pillar in #36502; not a row any more) drew each field's label, its api name on the row's title (objectstack-ai/objectui#12693, closed by objectui PR #12834, cda4076b, in the console pin 4016370a and on objectui main). ⚠️ Explain's Principal resolution 'Contributed by' chips are a different surface from (a): QA run #24570 found them on machine names at 4016370a and extracted objectstack-ai/objectui#13056, since FIXED: each layer's 'Contributed by' line draws the item's label (ui/packages/app-shell/src/views/metadata-admin/AccessExplainPanel.tsx; pin AccessExplainPanel.contributorLabels-13056.test.tsx), and QA run #33094 did not reproduce it — a regression row, expected PASS", "FIXED, regression row, expected PASS (objectui#11866): Profile states the access the console resolves rather than the auth library's raw user.role ('user') (objectui apps/console/src/pages/system/ProfilePage.tsx; pin ProfilePage.access.test.tsx)", "FIXED, regression row, expected PASS (objectui#11778): the flow inspector's Node Type select offers the add-node palette's display names instead of raw snake_case types such as connector_action and try_catch (http_request, the old example, is a retired callout name the flow schema refuses since spec 18, use 'http': packages/spec/src/automation/flow-reserved-node-types.ts) (pin FlowNodeInspector.nodeTypeOptions-11778.test.tsx); QA run #23163 read the Node Type value as its label", "Regression rows, expected PASS: the audit-log actor and composite field values render as people and labels since objectstack-ai/objectui#11697." @@ -352,7 +352,7 @@ "variants": [ "Studio → Access → Explain access result (the principal line)", "Studio → Access → permission-set list (scratch package)", - "Studio → Interfaces → nav editor items (scratch package)", + "the running app's design-mode menu editor items (scratch package; this variant read Studio → Interfaces → nav editor items until that pillar retired with #36502)", "Studio → Changes panel (pending items)", "Studio → flow inspector Node Type select", "Studio → field type picker and the object pickers (Lookup related object, flow trigger object)", @@ -436,7 +436,8 @@ "date": "2026-11-14", "change": "acceptance[0].verify, knownGaps[0] and knownGaps[2] re-pointed (ledger rows 11 and 267 of #32908: QA run #32949 card body, and QA run #33094, comment 6852480973). acceptance[0] carves out the position half of a security-assignment title per #32106 ruling A, which keeps the catalog machine name. knownGaps[0]: objectui#13056 is fixed (AccessExplainPanel.tsx and its pin) and did not reproduce. knownGaps[2] no longer cites http_request, which spec 18 retired (flow-reserved-node-types.ts). Read at base 82838e83", "ref": "#33328" - } + }, + { "revision": 6, "date": "2026-11-24", "change": "variants[2] reads the running app's design-mode menu editor, and knownGaps[0](b) marks Studio Interfaces' list-view Columns rows as retired with that pillar (#36502). No clause changed", "ref": "#36502" } ] } ] diff --git a/docs/qa/platform-checklist/coverage.json b/docs/qa/platform-checklist/coverage.json index fbf0ec19728..414f56e6743 100644 --- a/docs/qa/platform-checklist/coverage.json +++ b/docs/qa/platform-checklist/coverage.json @@ -48,7 +48,6 @@ "search.command-palette-navigation", "platform-core.marketplace-install-local-lifecycle", "platform-core.marketplace-console-honesty", - "studio-authoring.interfaces-create-dialogs", "studio-authoring.app-and-nav-properties" ] }, @@ -276,7 +275,6 @@ "platform-core.nav-surfaces-render", "search.command-palette-navigation", "platform-core.marketplace-console-honesty", - "studio-authoring.interfaces-create-dialogs", "studio-authoring.authored-page-slots-and-variables", "studio-authoring.uninstalled-package-refused", "api-backend.meta-qualified-item-read", @@ -353,7 +351,6 @@ "dashboards.dataset-report-authoring", "dashboards.drill-through-range", "search.command-palette-navigation", - "studio-authoring.interfaces-create-dialogs", "studio-authoring.report-authoring-options", "studio-authoring.package-customize-restore-display", "dashboards.report-measure-drill-scope" diff --git a/packages/cli/src/commands/meta/register-draft.test.ts b/packages/cli/src/commands/meta/register-draft.test.ts index 9ffd53b0757..256293f7954 100644 --- a/packages/cli/src/commands/meta/register-draft.test.ts +++ b/packages/cli/src/commands/meta/register-draft.test.ts @@ -344,7 +344,7 @@ describe('[#34777] the `--mode` flag `os meta register` declares', () => { expect(head).toContain('view/v'); expect(head).toContain('not published'); expect(head).toContain('hmac-sha256:ab'); - expect(review).toContain(`/studio/${PKG}/interfaces?changes=review`); + expect(review).toContain(`/studio/${PKG}/data?changes=review`); }); it('[ruling D4] `--mode draft` naming no package is refused, and the refusal names `--package `', () => { @@ -386,7 +386,7 @@ describe('[#34777] `os meta register --mode draft` against the real save door', expect(run.exitCode).toBe(0); expect(run.out).toContain('Draft saved: view/draft_view'); - expect(run.out).toContain(`/studio/${PKG}/interfaces?changes=review`); + expect(run.out).toContain(`/studio/${PKG}/data?changes=review`); expect(run.out).not.toContain('Metadata registered'); // The save, then the strict draft read of the same package, and nothing else. expect(requests(wire)).toEqual([ diff --git a/packages/cli/src/commands/meta/register.ts b/packages/cli/src/commands/meta/register.ts index b470fca8609..2e524e5b24b 100644 --- a/packages/cli/src/commands/meta/register.ts +++ b/packages/cli/src/commands/meta/register.ts @@ -210,7 +210,7 @@ export function draftSaveLines(args: { if (args.packageId) { lines.push( `Review and publish it in Studio's Changes for package ${args.packageId} ` - + `(/studio/${encodeURIComponent(args.packageId)}/interfaces?changes=review).`, + + `(/studio/${encodeURIComponent(args.packageId)}/data?changes=review).`, ); } return lines; diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index f45eab10fd7..43cf1f47bcd 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -749,7 +749,7 @@ describe('save_metadata_draft saves a draft and answers with its publish verdict saved: { type: 'flow', name: 'lead_intake', package: 'com.acme.crm', state: 'draft', version: 'v8' }, verdict: { publishable: false, refusals: [UNROUTABLE_ISSUE], advisories: [] }, review: { - changes: '/studio/com.acme.crm/interfaces?changes=review', + changes: '/studio/com.acme.crm/data?changes=review', item: '/studio/com.acme.crm/metadata/flow/lead_intake?review=1', note: expect.any(String), }, @@ -1026,7 +1026,7 @@ describe('done when: an OAuth author saves an app-crm flow draft with no routabl expect(finding.path).toBe('flows[0].nodes[0].config.triggerType'); expect(typeof finding.hint === 'string' && finding.hint.length > 0).toBe(true); expect(saved.body.verdict.publishable).toBe(false); - expect(saved.body.review.changes).toBe(`/studio/${STUDIO_BASE}/interfaces?changes=review`); + expect(saved.body.review.changes).toBe(`/studio/${STUDIO_BASE}/data?changes=review`); // The Studio Changes source: the package's pending drafts. const listed = await call(authoring, 'list_drafts', { package: STUDIO_BASE }); diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts index 7c9cc9da70e..2fe455f181a 100644 --- a/packages/runtime/src/domains/mcp-authoring.ts +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -1284,13 +1284,13 @@ function verdictOf(judgement: OpenAuthoringDraftJudgement): { /** * Where a person reviews the draft, as Console routes: the package's Changes - * drawer (`?changes=review` on its Interfaces pillar, `studioChangesLink.ts`) + * drawer (`?changes=review` on its Studio home, the Data pillar, `studioChangesLink.ts`) * and the item's draft review on Studio's metadata area (`?review=1`). */ function reviewRoutes(packageId: string, type: string, name: string): { changes: string; item: string; note: string } { const pkg = encodeURIComponent(packageId); return { - changes: `/studio/${pkg}/interfaces?changes=review`, + changes: `/studio/${pkg}/data?changes=review`, item: `/studio/${pkg}/metadata/${encodeURIComponent(type)}/${encodeURIComponent(name)}?review=1`, note: 'Console routes. A person reviews and publishes the draft there; this server cannot publish.', }; diff --git a/skills/objectstack-mcp-build/evals/draft-door-procedure.json b/skills/objectstack-mcp-build/evals/draft-door-procedure.json index 070150cf912..6cfcd3c1801 100644 --- a/skills/objectstack-mcp-build/evals/draft-door-procedure.json +++ b/skills/objectstack-mcp-build/evals/draft-door-procedure.json @@ -3,8 +3,8 @@ "evals": [ { "id": 1, - "prompt": "You build through an ObjectStack environment's MCP draft door, in the package `com.acme.crm`. The user asked: \"After a lead is created, notify the regional sales manager.\" You saved the flow `crm_lead_created_notify` with `save_metadata_draft`: its `type` is `record_change`, and its start node's `config` names the object and no `triggerType`. The reply: `saved: { type: 'flow', name: 'crm_lead_created_notify', package: 'com.acme.crm', state: 'draft' }`, `verdict: { publishable: false, refusals: [{ rule: 'flow-trigger-unroutable', path: 'flows[0].nodes[0].config.triggerType', message: \"declares type: 'record_change' but its start node has no triggerType at all, so the engine routes it to no trigger, so the flow is demoted to a manual one and never fires\", hint: \"Set triggerType to record-{before,after}-{create,update,delete,write}, or declare type: 'autolaunched' or 'screen' if the flow is launched by hand or from a screen\", severity: 'error' }], advisories: [] }`, `review: { changes: '/studio/com.acme.crm/interfaces?changes=review', item: '/studio/com.acme.crm/metadata/flow/crm_lead_created_notify?review=1' }`. What do you do next, and what do you tell the user when you are done?", - "expected_output": "The draft is saved, and a publish would refuse it: `verdict.refusals` holds `flow-trigger-unroutable`. It reads the refusal's `path` and `hint` and repairs the item as the hint says: the user asked for a flow that runs after a lead is created, so the start node's `triggerType` becomes `record-after-create` (it does not turn the flow into an `autolaunched` one, which would drop what the user asked for). It sends the whole flow again with `save_metadata_draft` and reads the new reply's verdict before saying anything about the flow. Once `verdict.refusals` is empty, it tells the user that the flow `crm_lead_created_notify` is saved as a draft in `com.acme.crm` and would publish, that nothing is live yet, and that a person reviews and publishes it in Studio, giving the `review` routes as the reply wrote them (`/studio/com.acme.crm/interfaces?changes=review` for the package's changes, and the flow's own route). It never says the flow is published, live or already notifying anyone.", + "prompt": "You build through an ObjectStack environment's MCP draft door, in the package `com.acme.crm`. The user asked: \"After a lead is created, notify the regional sales manager.\" You saved the flow `crm_lead_created_notify` with `save_metadata_draft`: its `type` is `record_change`, and its start node's `config` names the object and no `triggerType`. The reply: `saved: { type: 'flow', name: 'crm_lead_created_notify', package: 'com.acme.crm', state: 'draft' }`, `verdict: { publishable: false, refusals: [{ rule: 'flow-trigger-unroutable', path: 'flows[0].nodes[0].config.triggerType', message: \"declares type: 'record_change' but its start node has no triggerType at all, so the engine routes it to no trigger, so the flow is demoted to a manual one and never fires\", hint: \"Set triggerType to record-{before,after}-{create,update,delete,write}, or declare type: 'autolaunched' or 'screen' if the flow is launched by hand or from a screen\", severity: 'error' }], advisories: [] }`, `review: { changes: '/studio/com.acme.crm/data?changes=review', item: '/studio/com.acme.crm/metadata/flow/crm_lead_created_notify?review=1' }`. What do you do next, and what do you tell the user when you are done?", + "expected_output": "The draft is saved, and a publish would refuse it: `verdict.refusals` holds `flow-trigger-unroutable`. It reads the refusal's `path` and `hint` and repairs the item as the hint says: the user asked for a flow that runs after a lead is created, so the start node's `triggerType` becomes `record-after-create` (it does not turn the flow into an `autolaunched` one, which would drop what the user asked for). It sends the whole flow again with `save_metadata_draft` and reads the new reply's verdict before saying anything about the flow. Once `verdict.refusals` is empty, it tells the user that the flow `crm_lead_created_notify` is saved as a draft in `com.acme.crm` and would publish, that nothing is live yet, and that a person reviews and publishes it in Studio, giving the `review` routes as the reply wrote them (`/studio/com.acme.crm/data?changes=review` for the package's changes, and the flow's own route). It never says the flow is published, live or already notifying anyone.", "files": [], "assertions": { "must_contain": ["save_metadata_draft", "record-after-create", "changes=review", "Studio"], @@ -23,11 +23,11 @@ }, { "id": 3, - "prompt": "Through an ObjectStack environment's MCP draft door you saved the dataset `crm_sales_metrics` in the package `com.acme.crm`. The reply: `saved: { type: 'dataset', name: 'crm_sales_metrics', package: 'com.acme.crm', state: 'draft' }`, `verdict: { publishable: true, refusals: [], advisories: [{ rule: 'dataset-member-no-vocabulary', path: 'datasets.crm_sales_metrics.measures[0]', message: 'declares neither `synonyms` nor a `description`, so it answers only to its own name and label', hint: 'Add `synonyms`, the words a person types for it, and a one-sentence `description`', severity: 'warning' }] }`, `review: { changes: '/studio/com.acme.crm/interfaces?changes=review', item: '/studio/com.acme.crm/metadata/dataset/crm_sales_metrics?review=1' }`. It was the only item the user asked for. What is your reply to the user?", - "expected_output": "The verdict is publishable, so the item is done, and the reply is the hand-over. It says the dataset `crm_sales_metrics` is saved as a draft in `com.acme.crm` and that a publish would accept it. It tells the user what the advisory says: the first measure has neither synonyms nor a description, so a question in a user's own words will not find it; it offers to add them, and does not treat the advisory as a refusal. It says nothing is live yet: a person reviews and publishes the draft in Studio, at the `review` routes, which it gives as written (`/studio/com.acme.crm/interfaces?changes=review` for the package's changes and the item's own route). It never says the dataset is published, live or ready to query.", + "prompt": "Through an ObjectStack environment's MCP draft door you saved the dataset `crm_sales_metrics` in the package `com.acme.crm`. The reply: `saved: { type: 'dataset', name: 'crm_sales_metrics', package: 'com.acme.crm', state: 'draft' }`, `verdict: { publishable: true, refusals: [], advisories: [{ rule: 'dataset-member-no-vocabulary', path: 'datasets.crm_sales_metrics.measures[0]', message: 'declares neither `synonyms` nor a `description`, so it answers only to its own name and label', hint: 'Add `synonyms`, the words a person types for it, and a one-sentence `description`', severity: 'warning' }] }`, `review: { changes: '/studio/com.acme.crm/data?changes=review', item: '/studio/com.acme.crm/metadata/dataset/crm_sales_metrics?review=1' }`. It was the only item the user asked for. What is your reply to the user?", + "expected_output": "The verdict is publishable, so the item is done, and the reply is the hand-over. It says the dataset `crm_sales_metrics` is saved as a draft in `com.acme.crm` and that a publish would accept it. It tells the user what the advisory says: the first measure has neither synonyms nor a description, so a question in a user's own words will not find it; it offers to add them, and does not treat the advisory as a refusal. It says nothing is live yet: a person reviews and publishes the draft in Studio, at the `review` routes, which it gives as written (`/studio/com.acme.crm/data?changes=review` for the package's changes and the item's own route). It never says the dataset is published, live or ready to query.", "files": [], "assertions": { - "must_contain": ["draft", "synonyms", "/studio/com.acme.crm/interfaces?changes=review"], + "must_contain": ["draft", "synonyms", "/studio/com.acme.crm/data?changes=review"], "must_not_contain": ["dataset is now live", "dataset is now published", "`crm_sales_metrics` is now live", "`crm_sales_metrics` is now published", "now available to query", "successfully published"] } }, diff --git a/ui/e2e/live/studio-customize-journey.spec.ts b/ui/e2e/live/studio-customize-journey.spec.ts index 063023dac65..5943215f5b5 100644 --- a/ui/e2e/live/studio-customize-journey.spec.ts +++ b/ui/e2e/live/studio-customize-journey.spec.ts @@ -6,10 +6,12 @@ import { test as base, expect, type APIRequestContext, type Page, type Request, * the deployment boots from code, so Studio reads it as read-only and every * change goes into its paired customization package `com.example.showcase.custom`. * - * 1. Customize a list view: Customize on `showcase_task.in_progress`, drop a - * column, publish the pair, and read the columns the SERVER serves at the - * base's name (the read naming no package, the read naming the base, the - * type's list) — not what the canvas draws. + * 1. Customize a list view: Customize on `showcase_task.in_progress`'s + * All metadata item page (`/studio//metadata/view/`, the + * door since objectstack#36502 retired the Interfaces pillar), drop a + * column in the view's designer, publish the pair, and read the columns + * the SERVER serves at the base's name (the read naming no package, the + * read naming the base, the type's list) — not what the preview draws. * 2. Restore package original: the pair's draft and row are deleted at the * pair, and the three reads serve the shipped column set again. * 3. Add `region__c`: Add field on the base object's Form, then the top @@ -86,6 +88,8 @@ const OBJECT = 'showcase_task'; /** The column the customization drops, by its field name and its label in the inspector. */ const DROPPED = { field: 'due_date', label: 'Due Date' }; const FIELD = { label: 'Region', name: 'region__c' }; +/** The item header's ⋯ menu on the All metadata item page (`StudioBundleItemEditor`). */ +const ITEM_MORE = 'studio-bundle-editor-more'; type Column = string | { field?: string }; const columnNames = (columns: Column[] | undefined): string[] => @@ -132,9 +136,8 @@ async function publishPair(page: Page) { /** * The override chip is reachable on the item header once the pair is published. - * When the row has room it is in the row. On a narrower content column (the - * job's 1280 px window with the inspector open) the header folds its identity - * chips into the item's ⋯ menu first, so the item's name stays readable + * When the row has room it is in the row. On a narrower header the identity + * chips fold into the item's ⋯ menu first, so the item's name stays readable * (objectstack#29693), and there the chip sits in the menu's chips entry. The * menu is closed again so the next step opens it fresh. */ @@ -143,7 +146,7 @@ async function expectOverrideChip(page: Page) { const entry = page.getByTestId('studio-item-header-folded-chips'); await expect(async () => { if (await chip.isVisible()) return; - await page.getByTestId('if-item-more').click(); + await page.getByTestId(ITEM_MORE).click(); try { await expect(entry.getByTestId('studio-override-chip')).toBeVisible({ timeout: 1_000 }); } finally { @@ -165,9 +168,10 @@ test('a read-only base is customized, restored and extended through Studio, and try { await test.step('Customize a view: the edit lands in the pair, and the server serves its columns', async () => { - await page.goto(`/studio/${BASE}/interfaces?surface=${encodeURIComponent(`view:${VIEW}`)}`); - // The read-only base offers Customize (the top bar's read-only chip left - // with the package switcher, objectstack#36501). + // objectstack#36502 — a read-only base's view is customized on its All + // metadata item page, in the view's designer. + await page.goto(`/studio/${BASE}/metadata/view/${encodeURIComponent(VIEW)}`); + // The read-only base offers Customize. await expect(page.getByTestId('studio-customize')).toBeVisible(); await page.getByTestId('studio-customize').click(); @@ -178,7 +182,7 @@ test('a read-only base is customized, restored and extended through Studio, and (r) => r.request().method() === 'PUT' && r.url().includes(`/api/v1/meta/view/${VIEW}?`), ); await page - .getByTestId('if-inspector') + .getByTestId('studio-bundle-editor-form') .getByRole('button', { name: `Remove ${DROPPED.label}`, exact: true }) .click(); const ensure = await ensured; @@ -205,11 +209,11 @@ test('a read-only base is customized, restored and extended through Studio, and page.on('response', onResponse); // objectstack#29692 — Restore is on the override chip's popover: the chip in // the row, or in the item's ⋯ menu while the header is folded. - const rowChip = page.getByTestId('if-item-header').getByTestId('studio-override-chip'); + const rowChip = page.getByTestId('studio-bundle-editor').getByTestId('studio-override-chip').first(); if (await rowChip.isVisible()) { await rowChip.click(); } else { - await page.getByTestId('if-item-more').click(); + await page.getByTestId(ITEM_MORE).click(); await page.getByTestId('studio-item-header-folded-chips').getByTestId('studio-override-chip').click(); } await page.getByTestId('studio-override-popover').getByTestId('studio-override-restore').click(); diff --git a/ui/packages/app-shell/README.md b/ui/packages/app-shell/README.md index 5990134d8f2..ddab6aa11e8 100644 --- a/ui/packages/app-shell/README.md +++ b/ui/packages/app-shell/README.md @@ -597,18 +597,18 @@ trip is required to edit a draft. ### New dataset beside the Studio's dataset pickers (objectstack#27518) -The Interfaces pillar provides `StudioDatasetAuthoringContext` -(`src/views/studio-design/datasetCreate.tsx`): the package being edited and the -pillar's draft-saved signal. A dataset picker that finds it (the New report -dialog's `ReportCreateFields` and the dashboard widget inspector) reads the -draft-overlaid dataset catalog (`useDatasetCatalog(…, { previewDrafts: true })`), -lists the package's datasets first, and renders `DatasetCreateEntry`: a **New -dataset** button whose dialog saves a `dataset` draft in the package through -the draft door (the spec's create seed, the picked object, a dimension per -group-by field and a `sum` measure per total), re-reads the catalog and binds -the new name. While no dataset reads one of the package's objects, the entry -says so. Outside the Studio there is no context: Setup's editors keep the -published catalog and offer no entry. +`StudioDatasetAuthoringContext` (`src/views/studio-design/datasetCreate.tsx`) +carries the package being edited and a draft-saved signal. A dataset picker +that finds it (the dashboard widget inspector) reads the draft-overlaid dataset +catalog (`useDatasetCatalog(…, { previewDrafts: true })`), lists the package's +datasets first, and renders `DatasetCreateEntry`: a **New dataset** button +whose dialog saves a `dataset` draft in the package through the draft door +(the spec's create seed, the picked object, a dimension per group-by field and +a `sum` measure per total), re-reads the catalog and binds the new name. While +no dataset reads one of the package's objects, the entry says so. Without the +context there is no entry and the catalog is the published one. Its provider +was Studio's Interfaces pillar, retired by objectstack#36502, so no surface +provides it today. ### AI chat conversation key (ADR-0057) @@ -631,11 +631,15 @@ Inside a running app, workspace admins get an "Edit app" button in the top bar (`AppHeader`) — and, at the end of the app switcher's dropdown, an "Edit APP in Studio" row to the same target — that deep-links to the app's owning package on the Studio design surface. When the current route names a specific interface — a -dashboard, page, or report — it opens straight to that surface in the Interfaces -pillar (`/studio/:packageId/interfaces?surface=:`); on an object -route it opens that object in the Data pillar +dashboard, page, or report — it opens that item's page in Studio's "All +metadata" area (`/studio/:packageId/metadata//`), where it is read +and edited as metadata; interfaces themselves are designed in the running app, +since objectstack#36502 retired Studio's Interfaces pillar. On an object route +it opens that object in the Data pillar (`/studio/:packageId/data?surface=object:`), and at the app root the -package's Data tab (`/studio/:packageId/data`). +package's Data tab (`/studio/:packageId/data`). An old +`/studio/:packageId/interfaces` link lands on the Data tab with a one-line +notice that interface editing moved into the app. The route-type → surface-type decision lives in `appStudioRoutePath`. It is the reverse of the builder's "Open app" bridge (ADR-0080): the entry only renders for admins and only when the app has an owning package (`_packageId`), and diff --git a/ui/packages/app-shell/src/__tests__/homeRecoveryRedirectsFollowDeclaration-7373.test.ts b/ui/packages/app-shell/src/__tests__/homeRecoveryRedirectsFollowDeclaration-7373.test.ts index 2d1fe0917f3..52b9c018a79 100644 --- a/ui/packages/app-shell/src/__tests__/homeRecoveryRedirectsFollowDeclaration-7373.test.ts +++ b/ui/packages/app-shell/src/__tests__/homeRecoveryRedirectsFollowDeclaration-7373.test.ts @@ -137,10 +137,8 @@ const RECOVERY_SITES: ReadonlyArray<{ { file: 'packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx', alsoReads: [ - 'packages/app-shell/src/views/studio-design/StudioNavItemInspector.tsx', 'packages/app-shell/src/views/studio-design/PackageSwitcher.tsx', 'packages/app-shell/src/views/studio-design/StudioBackToApp.tsx', - 'packages/app-shell/src/views/studio-design/InterfacesNavRail.tsx', 'packages/app-shell/src/views/studio-design/AutomationsFlowRail.tsx', 'packages/app-shell/src/views/studio-design/StudioPillarKit.tsx', 'packages/app-shell/src/views/studio-design/DataPillarHelpers.tsx', diff --git a/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts b/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts index fef866e0d03..a4d0d766f5d 100644 --- a/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts +++ b/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts @@ -123,16 +123,7 @@ const OBJECTS_READERS: Record = { 'packages/app-shell/src/views/setup/RecycleBinPage.tsx': { kind: 'off', why: 'Setup → Recycle Bin, not mounted on an app object-list open' }, 'packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx': { kind: 'off', why: 'Setup → Public forms, not mounted on an app object-list open (objectstack#36444)' }, 'packages/app-shell/src/views/metadata-admin/previews/ScreenPreview.tsx': { kind: 'off', why: "the metadata admin's form-screen preview" }, - 'packages/app-shell/src/views/studio-design/ObjectListViewInspector.tsx': { kind: 'off', why: 'Studio' }, - 'packages/app-shell/src/views/studio-design/ObjectListViewTitle.tsx': { - kind: 'off', - why: "Studio: the object's view labels New view refuses to reuse, the read the list-view panel made before the switcher moved into the header (objectstack#30046)", - }, 'packages/app-shell/src/views/studio-design/studio-object-records-canvas.tsx': { kind: 'off', why: 'Studio' }, - 'packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx': { - kind: 'off', - why: "Studio: an object's label as the shell serves it in this locale, for the page of an object no entry opens (objectstack#30046); the Form tab no longer reads the served form view (objectstack#36425)", - }, 'packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.tsx': { kind: 'byName', why: "Studio's record-sharing table: a controlled-by-parent row's master outside the package, its label by name (objectstack#33864)", diff --git a/ui/packages/app-shell/src/console/ai/AiChatPage.tsx b/ui/packages/app-shell/src/console/ai/AiChatPage.tsx index 0c5b2896893..a1b77730fb5 100644 --- a/ui/packages/app-shell/src/console/ai/AiChatPage.tsx +++ b/ui/packages/app-shell/src/console/ai/AiChatPage.tsx @@ -3139,16 +3139,18 @@ export function ChatPane({ // The secondary door (在 Studio 中查看): Studio is the built app's // iteration home (direct edit + the same copilot conversation in the // dock, which the build's binding resumes). The package id is the - // canvas segment (one package = one app). + // canvas segment (one package = one app). objectstack#36502 — it opens + // the package's Studio home; the app's interfaces are designed in the + // running app, which the primary door opens. onDesignBuiltApp={(_appName, appSegment) => { const pkg = appSegment ?? boundPackageId; if (!pkg) return; - navigate(`/studio/${encodeURIComponent(pkg)}/interfaces`); + navigate(`/studio/${encodeURIComponent(pkg)}/data`); }} designBuiltAppLabel={t('console.ai.viewBuiltAppInStudio', { defaultValue: 'View in Studio' })} // Artifact deep links: every artifact the agent built gets a one-click // path to where it can be edited BY HAND (object → Data, flow → - // Automations, dashboard/page/view/app → Interfaces). Returns null for + // Automations, dashboard/page/view/app → its All metadata item page). Returns null for // types with no direct-edit home (seed/dataset) → rendered as text. getArtifactAction={(artifact, appSegment) => { const path = artifactStudioPath(appSegment ?? boundPackageId, artifact); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.appliedCardDoors-12894.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.appliedCardDoors-12894.test.tsx index 373286aff9c..d5a675cd6ba 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.appliedCardDoors-12894.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.appliedCardDoors-12894.test.tsx @@ -172,7 +172,7 @@ describe('objectui#12894 — 查看变更并发布 opens Studio\'s 变更 drawer const onReviewDrafts = props.onReviewDrafts as (packageId: string) => void; expect(typeof onReviewDrafts).toBe('function'); act(() => onReviewDrafts('app.hcpl')); - expect(screen.getByTestId('location').textContent).toBe('/studio/app.hcpl/interfaces?changes=review'); + expect(screen.getByTestId('location').textContent).toBe('/studio/app.hcpl/data?changes=review'); }); it('on one of the package\'s Studio pillars: the same pillar and selection, with the param added', () => { @@ -186,7 +186,7 @@ describe('objectui#12894 — 查看变更并发布 opens Studio\'s 变更 drawer it('CONTROL: on ANOTHER package\'s Studio, the card\'s own package opens', () => { const props = renderPane('/studio/app.other/data', 'app.other'); act(() => (props.onReviewDrafts as (packageId: string) => void)('app.hcpl')); - expect(screen.getByTestId('location').textContent).toBe('/studio/app.hcpl/interfaces?changes=review'); + expect(screen.getByTestId('location').textContent).toBe('/studio/app.hcpl/data?changes=review'); }); }); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.noNavigationAfterBuild-12724.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.noNavigationAfterBuild-12724.test.tsx index 5f6706cf6e1..65af4069974 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.noNavigationAfterBuild-12724.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.noNavigationAfterBuild-12724.test.tsx @@ -19,7 +19,8 @@ * it), so pin 1 is not vacuous. * 3. The two doors are SPA navigations the user chooses: 打开应用 to * `/apps/APP` (the app's first navigation item), 在 Studio 中查看 to - * `/studio/PKG/interfaces` with no landing state. + * `/studio/PKG/data` with no landing state (the Interfaces pillar it + * opened before retired with objectstack#36502). * * Same faked-chat harness the retired files used: the hook instance owns the * thread; hydration (the REAL AiChatPage path) derives the envelopes. @@ -330,13 +331,13 @@ describe('AiChatPage — no automatic navigation after a build (objectui#12724)' expect(assignSpy).not.toHaveBeenCalled(); }); - it('在 Studio 中查看 is an SPA navigation to the Interfaces pillar with no landing state', async () => { + it('在 Studio 中查看 is an SPA navigation to the Studio home (the Data pillar) with no landing state', async () => { serverTurns = UNBUILT_TURNS; renderPage(); await waitFor(() => expect(screen.getByTestId('pane')).toBeInTheDocument(), { timeout: 4000 }); fireEvent.click(screen.getByTestId('studio-door')); expect(await screen.findByTestId('studio-page', {}, { timeout: 4000 })).toBeInTheDocument(); - expect(screen.getByTestId('where')).toHaveAttribute('data-path', '/studio/app.k9/interfaces'); + expect(screen.getByTestId('where')).toHaveAttribute('data-path', '/studio/app.k9/data'); expect(screen.getByTestId('where')).toHaveAttribute('data-state', 'null'); expect(assignSpy).not.toHaveBeenCalled(); }); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/artifactStudioPath.test.ts b/ui/packages/app-shell/src/console/ai/__tests__/artifactStudioPath.test.ts index c49e1367e1d..5673fa67ed9 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/artifactStudioPath.test.ts +++ b/ui/packages/app-shell/src/console/ai/__tests__/artifactStudioPath.test.ts @@ -22,24 +22,23 @@ describe('artifactStudioPath', () => { ); }); - it('dashboard / page → Interfaces pillar with their own surface', () => { + // objectstack#36502 — the Interfaces pillar is retired: these open their All-metadata item page. + it('dashboard / page → their All-metadata item page', () => { expect(artifactStudioPath(pkg, { type: 'dashboard', name: 'home_dashboard' })).toBe( - '/studio/app.rmpe/interfaces?surface=dashboard%3Ahome_dashboard', - ); - expect(artifactStudioPath(pkg, { type: 'page', name: 'welcome' })).toBe( - '/studio/app.rmpe/interfaces?surface=page%3Awelcome', + '/studio/app.rmpe/metadata/dashboard/home_dashboard', ); + expect(artifactStudioPath(pkg, { type: 'page', name: 'welcome' })).toBe('/studio/app.rmpe/metadata/page/welcome'); }); - it('view → the OWNING OBJECT leaf on Interfaces (views are not nav leaves)', () => { + it('view → its own All-metadata item page, by its qualified name', () => { expect(artifactStudioPath(pkg, { type: 'view', name: 'rmpe_customer.customer_list' })).toBe( - '/studio/app.rmpe/interfaces?surface=object%3Armpe_customer', + '/studio/app.rmpe/metadata/view/rmpe_customer.customer_list', ); }); - it('app → Interfaces pillar home (no surface)', () => { + it('app → its All-metadata item page', () => { expect(artifactStudioPath(pkg, { type: 'app', name: 'customer_management' })).toBe( - '/studio/app.rmpe/interfaces', + '/studio/app.rmpe/metadata/app/customer_management', ); }); diff --git a/ui/packages/app-shell/src/console/ai/artifactStudioPath.ts b/ui/packages/app-shell/src/console/ai/artifactStudioPath.ts index 73be4bc1091..98d567f7d19 100644 --- a/ui/packages/app-shell/src/console/ai/artifactStudioPath.ts +++ b/ui/packages/app-shell/src/console/ai/artifactStudioPath.ts @@ -1,20 +1,19 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. /** - * Map an AI-built artifact to its direct-edit home — the Studio pillar route - * where that artifact can be changed by hand. Every AI-built artifact gets an - * edit path that needs no AI: the finished build card links each artifact to - * its pillar (objectui#2623). + * Map an AI-built artifact to its direct-edit home in Studio — the route where + * that artifact can be changed by hand. Every AI-built artifact gets an edit + * path that needs no AI: the finished build card links each artifact there + * (objectui#2623). * * object → Data pillar, the object's schema/records surface * flow → Automations pillar (the `?surface=flow:` consumer was reserved * for exactly this bridge — this is its first producer) - * dashboard → Interfaces pillar, that dashboard's canvas - * page → Interfaces pillar, that page's canvas - * view → Interfaces pillar, the OWNING OBJECT's canvas — views are not - * nav leaves; their name is `.`, so land on the - * object leaf the view hangs off - * app → Interfaces pillar home (the app's nav is the surface) + * dashboard, page, view, app + * → the item's page in the "All metadata" area. objectstack#36502: + * the Interfaces pillar that designed them is retired; they are + * designed in the running app, and the item page is where they + * are read and edited as metadata. * * Returns null for artifacts with no direct-edit home (seed / dataset / …) — * callers render those as plain text, not dead links. @@ -24,6 +23,7 @@ import { DESIGNER_SURFACE_PARAM, formatSurfaceParam, } from '../../views/metadata-admin/nav-selection.js'; +import { studioMetadataItemPath } from '../../views/studio-design/metadataArea.js'; export interface BuiltArtifact { type: string; @@ -32,7 +32,7 @@ export interface BuiltArtifact { function pillarPath( packageId: string, - pillar: 'data' | 'automations' | 'interfaces', + pillar: 'data' | 'automations', surface?: BuiltArtifact, ): string { const base = `/studio/${encodeURIComponent(packageId)}/${pillar}`; @@ -53,17 +53,10 @@ export function artifactStudioPath( case 'flow': return pillarPath(packageId, 'automations', { type: 'flow', name }); case 'dashboard': - return pillarPath(packageId, 'interfaces', { type: 'dashboard', name }); case 'page': - return pillarPath(packageId, 'interfaces', { type: 'page', name }); - case 'view': { - // `.` — land on the owning object's canvas leaf. - const dot = name.indexOf('.'); - const owner = dot > 0 ? name.slice(0, dot) : name; - return pillarPath(packageId, 'interfaces', { type: 'object', name: owner }); - } + case 'view': case 'app': - return pillarPath(packageId, 'interfaces'); + return studioMetadataItemPath(packageId, { type: artifact.type, name }); default: return null; } diff --git a/ui/packages/app-shell/src/hooks/useNavTargetLabel.draftLabels-11862.test.tsx b/ui/packages/app-shell/src/hooks/useNavTargetLabel.draftLabels-11862.test.tsx new file mode 100644 index 00000000000..09d7b75db58 --- /dev/null +++ b/ui/packages/app-shell/src/hooks/useNavTargetLabel.draftLabels-11862.test.tsx @@ -0,0 +1,104 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectui#11862 (the remainder) — the nav-target label resolver names a + * draft-only target by the label its `_drafts` row carries. + * + * On the maintainer's word 「所有地方以标签为主,机器名只作为次要信息」, and the seat + * ruling `6053526025` question 1 (A, at the producer): each `_drafts` row + * carries the draft body's own label, or `null` (objectstack-ai/objectstack#22200). + * A label-less nav entry inherits its target's CURRENT label (the runtime's + * rule, `useNavTargetLabel`), and a host that holds the pending drafts hands + * them to that resolver as its last rung through `DraftTargetLabels`. + * + * Moved out of `StudioDesignSurface.navDraftLabels-11862.test.tsx` when + * objectstack#36502 retired the Interfaces pillar: its whole-surface and + * nav-item inspector pins went with the pillar, and the resolver's pins stay. + * + * - a draft-only object answers its `_drafts` row's label; + * - the published label still wins where the console's metadata has one; + * - a row stored under a plural type spelling is folded, as every `/meta` + * reader folds it; + * - CONTROL: with no provider the resolver answers as it did. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, describe, expect, it } from 'vitest'; +import { cleanup, render, screen } from '@testing-library/react'; +import { MetadataCtx } from '@object-ui/react'; +import { DraftTargetLabels, useNavTargetLabel } from './useNavTargetLabel'; + +/** The package's `_drafts` rows, as objectstack serves them since #22200. */ +const DRAFT_ROWS = [ + { type: 'object', name: 'repairs_ticket', packageId: 'com.acme.app', label: 'Repair Ticket', updatedAt: null, updatedBy: null }, + { type: 'dashboard', name: 'ops_board', packageId: 'com.acme.app', label: 'Ops board', updatedAt: null, updatedBy: null }, + { type: 'object', name: 'b2r4_bare', packageId: 'com.acme.app', label: null, updatedAt: null, updatedBy: null }, +]; + +/** The host's metadata cache: published only, so no draft-only target is in it. */ +const METADATA = { + apps: [], + objects: [{ name: 'b2r4_customer', label: 'Customers' }], + dashboards: [], + reports: [], + pages: [], + loading: false, + error: null, + refresh: async () => {}, + invalidate: () => {}, + ensureType: async () => [], + getItem: async () => null, + getItemsByType: () => [], + getTypeStatus: () => 'ready' as const, +}; + +afterEach(() => { + cleanup(); +}); + +describe('objectui#11862 — the resolver the nav editor asks: the draft label is the last rung', () => { + function Probe({ target }: { target: Parameters>[0] }) { + const resolve = useNavTargetLabel(); + return {resolve(target) ?? '(none)'}; + } + + function probe(target: Parameters>[0], drafts: unknown[]) { + render( + + + + + , + ); + return screen.getByTestId('probe').textContent; + } + + it("a draft-only object answers its `_drafts` row's label", () => { + expect(probe({ kind: 'object', objectName: 'repairs_ticket' }, DRAFT_ROWS)).toBe('Repair Ticket'); + }); + + it('the published label still wins over a pending draft of the same object', () => { + const drafts = [{ type: 'object', name: 'b2r4_customer', label: 'Draft customers' }]; + expect(probe({ kind: 'object', objectName: 'b2r4_customer' }, drafts)).toBe('Customers'); + }); + + it('a row stored under a plural type spelling is folded to its singular type', () => { + const drafts = [{ type: 'objects', name: 'repairs_ticket', label: 'Repair Ticket' }]; + expect(probe({ kind: 'object', objectName: 'repairs_ticket' }, drafts)).toBe('Repair Ticket'); + }); + + it("a draft of another type does not name the target", () => { + const drafts = [{ type: 'dashboard', name: 'repairs_ticket', label: 'Not this one' }]; + expect(probe({ kind: 'object', objectName: 'repairs_ticket' }, drafts)).toBe('(none)'); + }); + + it('CONTROL: with no provider the resolver answers as it did — nothing for a target the metadata lacks', () => { + render( + + + , + ); + expect(screen.getByTestId('probe').textContent).toBe('(none)'); + }); +}); diff --git a/ui/packages/app-shell/src/layout/AppHeader.tsx b/ui/packages/app-shell/src/layout/AppHeader.tsx index 28a82c9f145..3ef08bae3c7 100644 --- a/ui/packages/app-shell/src/layout/AppHeader.tsx +++ b/ui/packages/app-shell/src/layout/AppHeader.tsx @@ -921,8 +921,8 @@ export function AppHeader({ left edge of this utility cluster (objectui#12201 item 6). Admins jump from the running app to its owning package's design surface; on a dashboard route it deep-links to that dashboard's - design page in the Interfaces pillar - (/studio/:packageId/interfaces?surface=dashboard:NAME), otherwise + item in Studio's All metadata area + (/studio/:packageId/metadata/dashboard/NAME), otherwise the package's Data tab. Hidden for everyone else, for apps with no owning package and for a package that is not writable (objectui#12615): not rendered, never disabled. An icon button diff --git a/ui/packages/app-shell/src/layout/__tests__/AppHeader.editAppFollowsPackagePosture-12615.test.tsx b/ui/packages/app-shell/src/layout/__tests__/AppHeader.editAppFollowsPackagePosture-12615.test.tsx index f945c5f8063..fa7c37488b7 100644 --- a/ui/packages/app-shell/src/layout/__tests__/AppHeader.editAppFollowsPackagePosture-12615.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/AppHeader.editAppFollowsPackagePosture-12615.test.tsx @@ -262,8 +262,8 @@ async function editAppOn( const SETUP_ROUTE = '/apps/com.objectstack.setup/dashboard/system_overview'; const HOTCRM_ROUTE = '/apps/app.objectstack.hotcrm/dashboard/pipeline'; const BASE_ROUTE = '/apps/com.example.my_base/dashboard/pipeline'; -const BASE_PENCIL = '/studio/com.example.my_base/interfaces?surface=dashboard:pipeline'; -const HOTCRM_VIEW = '/studio/app.objectstack.hotcrm/interfaces?surface=dashboard:pipeline'; +const BASE_PENCIL = '/studio/com.example.my_base/metadata/dashboard/pipeline'; +const HOTCRM_VIEW = '/studio/app.objectstack.hotcrm/metadata/dashboard/pipeline'; let fetchMock: ReturnType; diff --git a/ui/packages/app-shell/src/layout/__tests__/AppHeader.pageRouteNoAuthoringHandles-12198.test.tsx b/ui/packages/app-shell/src/layout/__tests__/AppHeader.pageRouteNoAuthoringHandles-12198.test.tsx index ec36102478e..916c05c3f03 100644 --- a/ui/packages/app-shell/src/layout/__tests__/AppHeader.pageRouteNoAuthoringHandles-12198.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/AppHeader.pageRouteNoAuthoringHandles-12198.test.tsx @@ -339,7 +339,7 @@ describe('a page offers no Studio entry to a caller without `manage_metadata` (o it('CONTROL — a workspace admin holding `manage_metadata` sees all three, all three to one target', async () => { const seen = await studioEntriesOnPageRoute(AUTHOR); - expect(seen['app-design-in-studio-button']).toBe('/studio/com.objectstack.cloud/interfaces?surface=page:welcome'); + expect(seen['app-design-in-studio-button']).toBe('/studio/com.objectstack.cloud/metadata/page/welcome'); // The page's pencil opened the metadata-admin page until objectui#12540. expect(seen['page-edit-in-studio-button']).toBe(seen['app-design-in-studio-button']); expect(seen['app-switcher-edit-in-studio']).toBe(seen['app-design-in-studio-button']); diff --git a/ui/packages/app-shell/src/layout/__tests__/SidebarAppMenu-36112.test.tsx b/ui/packages/app-shell/src/layout/__tests__/SidebarAppMenu-36112.test.tsx index 161c5b1ac43..3f60bf4e2dc 100644 --- a/ui/packages/app-shell/src/layout/__tests__/SidebarAppMenu-36112.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/SidebarAppMenu-36112.test.tsx @@ -346,7 +346,7 @@ describe('「Edit app」 in the app menu opens this app in Studio (objectstack#3 it('it follows the route the way the app switcher\'s Studio row does: a dashboard opens its design surface', async () => { await mountMenu({ route: '/apps/crm/dashboard/pipeline' }); - expect(editInStudio()).toHaveAttribute('href', '/studio/com.acme.crm/interfaces?surface=dashboard:pipeline'); + expect(editInStudio()).toHaveAttribute('href', '/studio/com.acme.crm/metadata/dashboard/pipeline'); }); it('an installed (read-only) package\'s app: 「View in Studio」 behind an eye, never the pencil', async () => { diff --git a/ui/packages/app-shell/src/services/componentRegistry.ts b/ui/packages/app-shell/src/services/componentRegistry.ts index 78937b00dc2..808a9525167 100644 --- a/ui/packages/app-shell/src/services/componentRegistry.ts +++ b/ui/packages/app-shell/src/services/componentRegistry.ts @@ -62,14 +62,6 @@ export function getAppComponent(ref: string): AppComponentRegistryEntry | undefi return REGISTRY.get(ref); } -/** - * Snapshot of all registered components — used by diagnostics surfaces - * (e.g. a future "Installed UI Components" admin page). - */ -export function listAppComponents(): AppComponentRegistryEntry[] { - return Array.from(REGISTRY.values()); -} - /** * Convert `metadata:resource` ↔ URL segments `['metadata', 'resource']`. * Component refs are restricted to one colon in MVP, but the helper is diff --git a/ui/packages/app-shell/src/utils/__tests__/appRoute.test.ts b/ui/packages/app-shell/src/utils/__tests__/appRoute.test.ts index ade3aeedb45..e2969b4b13c 100644 --- a/ui/packages/app-shell/src/utils/__tests__/appRoute.test.ts +++ b/ui/packages/app-shell/src/utils/__tests__/appRoute.test.ts @@ -281,20 +281,21 @@ describe('appStudioDesignPath', () => { }); /** - * App → Studio interface deep-link (dashboard design page). + * App → Studio interface deep-link: the item's page in the All-metadata area + * (objectstack#36502 retired the Interfaces pillar it opened before). */ describe('appStudioSurfacePath', () => { const crm = { name: 'crm', _packageId: 'com.acme.crm' }; - it('deep-links to the interface surface in the Interfaces pillar', () => { + it('deep-links to the interface\'s item page in the All-metadata area (objectstack#36502)', () => { expect(appStudioSurfacePath(crm, true, { type: 'dashboard', name: 'executive_dashboard' })).toBe( - '/studio/com.acme.crm/interfaces?surface=dashboard:executive_dashboard', + '/studio/com.acme.crm/metadata/dashboard/executive_dashboard', ); }); it('URL-encodes the package id and the surface name', () => { expect( appStudioSurfacePath({ _packageId: 'com.acme/crm' }, true, { type: 'dashboard', name: 'sales dash' }), - ).toBe('/studio/com.acme%2Fcrm/interfaces?surface=dashboard:sales%20dash'); + ).toBe('/studio/com.acme%2Fcrm/metadata/dashboard/sales%20dash'); }); it('returns null for non-admins', () => { expect(appStudioSurfacePath(crm, false, { type: 'dashboard', name: 'd' })).toBeNull(); @@ -341,28 +342,28 @@ describe('appStudioObjectPath', () => { /** * App → Studio route bridge — maps a running-app route to its Studio target: - * an interface surface (dashboard / page / report) deep-links into the - * Interfaces pillar; an object record page deep-links that object in the Data + * an interface surface (dashboard / page / report) deep-links to its + * All-metadata item page (objectstack#36502); an object record page deep-links that object in the Data * pillar; everything else opens the package's Data tab. */ describe('appStudioRoutePath', () => { const crm = { name: 'crm', _packageId: 'com.acme.crm' }; - it('deep-links a dashboard route to its Interfaces surface', () => { + it('deep-links a dashboard route to its All-metadata item page', () => { expect(appStudioRoutePath(crm, true, { type: 'dashboard', name: 'executive_dashboard' })).toBe( - '/studio/com.acme.crm/interfaces?surface=dashboard:executive_dashboard', + '/studio/com.acme.crm/metadata/dashboard/executive_dashboard', ); }); - it('deep-links a page route to its Interfaces surface (the fix — was the Data tab)', () => { + it('deep-links a page route to its All-metadata item page (the fix — was the Data tab)', () => { expect(appStudioRoutePath(crm, true, { type: 'page', name: 'showcase_crm_workbench' })).toBe( - '/studio/com.acme.crm/interfaces?surface=page:showcase_crm_workbench', + '/studio/com.acme.crm/metadata/page/showcase_crm_workbench', ); }); - it('deep-links a report route to its Interfaces surface', () => { + it('deep-links a report route to its All-metadata item page', () => { expect(appStudioRoutePath(crm, true, { type: 'report', name: 'pipeline_report' })).toBe( - '/studio/com.acme.crm/interfaces?surface=report:pipeline_report', + '/studio/com.acme.crm/metadata/report/pipeline_report', ); }); diff --git a/ui/packages/app-shell/src/utils/appRoute.ts b/ui/packages/app-shell/src/utils/appRoute.ts index e98cf4fabc4..f726d3ecb83 100644 --- a/ui/packages/app-shell/src/utils/appRoute.ts +++ b/ui/packages/app-shell/src/utils/appRoute.ts @@ -264,16 +264,14 @@ export function appStudioDesignPath( } /** - * Deep-link from a running app straight to a specific interface's design - * surface in Studio's Interfaces pillar — e.g. viewing a dashboard opens - * `/studio/:packageId/interfaces?surface=dashboard:`, which the pillar's - * `?surface=` restore honors (see `nav-selection.ts`). Same admin/package - * guards as {@link appStudioDesignPath}; returns null when the surface identity - * is incomplete so the caller can fall back to the plain design path. - * - * The `surface` param value is `type:name`; types never contain `:`, so the - * pillar splits on the first colon. Only the name is percent-encoded — the - * type is a fixed keyword (`dashboard`/`report`/…). + * Deep-link from a running app straight to a specific interface's metadata in + * Studio's "All metadata" area — e.g. viewing a dashboard opens + * `/studio/:packageId/metadata/dashboard/`, the item's page there. + * objectstack#36502: the Interfaces pillar it used to open is retired; an + * interface is designed in the running app, and this item page is where it is + * read and, as a fallback, edited as metadata. Same admin/package guards as + * {@link appStudioDesignPath}; returns null when the surface identity is + * incomplete so the caller can fall back to the plain design path. */ export function appStudioSurfacePath( app: AppRouteLike | null | undefined, @@ -286,8 +284,7 @@ export function appStudioSurfacePath( const type = surface?.type; const name = surface?.name; if (!type || !name) return null; - const value = `${type}:${encodeURIComponent(name)}`; - return `/studio/${encodeURIComponent(packageId)}/interfaces?surface=${value}`; + return `/studio/${encodeURIComponent(packageId)}/metadata/${encodeURIComponent(type)}/${encodeURIComponent(name)}`; } /** @@ -299,9 +296,8 @@ export function appStudioSurfacePath( * {@link appStudioDesignPath}; returns null when the object name is missing so * the caller can fall back to the plain Data tab. * - * The `surface` param value is `object:` — the same `type:name` shape the - * Interfaces pillar uses; only the name is percent-encoded (`object` is a fixed - * keyword). + * The `surface` param value is `object:`; only the name is + * percent-encoded (`object` is a fixed keyword). */ export function appStudioObjectPath( app: AppRouteLike | null | undefined, @@ -317,10 +313,9 @@ export function appStudioObjectPath( } /** - * Route types that correspond to a designable **interface** surface in Studio's - * Interfaces pillar. The console route type (`/apps/:pkg//`) doubles - * as the Studio surface type — the keywords match `resolveSurface` in - * `StudioDesignSurface` (`dashboard` / `page` / `report`). + * Route types that correspond to an **interface** item. The console route type + * (`/apps/:pkg//`) doubles as the metadata type + * (`dashboard` / `page` / `report`). */ const INTERFACE_SURFACE_ROUTE_TYPES = new Set(['dashboard', 'page', 'report']); @@ -336,8 +331,8 @@ const NON_OBJECT_ROUTE_TYPES = new Set([...INTERFACE_SURFACE_ROUTE_TYPES, 'syste /** * App → Studio bridge target for a running-app route (ADR-0080). When the route * names a specific interface (a dashboard, page, or report — see - * {@link INTERFACE_SURFACE_ROUTE_TYPES}), deep-link straight to THAT surface in - * the Interfaces pillar via {@link appStudioSurfacePath}. When it names an + * {@link INTERFACE_SURFACE_ROUTE_TYPES}), deep-link straight to THAT item in + * Studio's "All metadata" area via {@link appStudioSurfacePath}. When it names an * object record page (the route type IS the object name), deep-link that object * in the Data pillar via {@link appStudioObjectPath}. Otherwise (bare app root, * a `system` route, or an interface list route with no surface name) fall back diff --git a/ui/packages/app-shell/src/views/PageView.tsx b/ui/packages/app-shell/src/views/PageView.tsx index 34a0d563d6b..e831567e23b 100644 --- a/ui/packages/app-shell/src/views/PageView.tsx +++ b/ui/packages/app-shell/src/views/PageView.tsx @@ -5,9 +5,11 @@ * happens in the metadata studio (canvas + inspector), not here — runtime is * pure rendering. For parity with the view/report/dashboard runtime editors, * metadata authors get a lightweight "Edit in studio" affordance that - * deep-links to the page's design surface in Studio's Interfaces pillar - * (`/studio/PACKAGE/interfaces?surface=page:NAME`) rather than embedding the - * heavyweight page canvas in the runtime. It is the path the app bar's pencil, + * deep-links to the page's item in Studio's "All metadata" area + * (`/studio/PACKAGE/metadata/page/NAME`) rather than embedding the + * heavyweight page canvas in the runtime: a custom page has no visual editor + * since the Interfaces pillar retired (objectstack#36502), and is edited there + * as metadata. It is the path the app bar's pencil, * the app switcher's Studio row and the sidebar's Design open for the same * page, built by the same `appStudioRoutePath` (objectui#12540). * diff --git a/ui/packages/app-shell/src/views/__tests__/PageView.editInStudioFollowsPackagePosture-12615.test.tsx b/ui/packages/app-shell/src/views/__tests__/PageView.editInStudioFollowsPackagePosture-12615.test.tsx index 84a53d51055..3cc77d3ed6e 100644 --- a/ui/packages/app-shell/src/views/__tests__/PageView.editInStudioFollowsPackagePosture-12615.test.tsx +++ b/ui/packages/app-shell/src/views/__tests__/PageView.editInStudioFollowsPackagePosture-12615.test.tsx @@ -105,7 +105,7 @@ const PACKAGES = { }, }; -const BASE_TARGET = '/studio/com.example.my_base/interfaces?surface=page:welcome'; +const BASE_TARGET = '/studio/com.example.my_base/metadata/page/welcome'; function serve(answer: () => Promise<{ ok: boolean; status: number; body: unknown }>) { vi.stubGlobal( diff --git a/ui/packages/app-shell/src/views/__tests__/PageView.editInStudioOpensStudio-12540.test.tsx b/ui/packages/app-shell/src/views/__tests__/PageView.editInStudioOpensStudio-12540.test.tsx index 365ae9ff032..f8fb479927f 100644 --- a/ui/packages/app-shell/src/views/__tests__/PageView.editInStudioOpensStudio-12540.test.tsx +++ b/ui/packages/app-shell/src/views/__tests__/PageView.editInStudioOpensStudio-12540.test.tsx @@ -5,8 +5,9 @@ * Studio handle on the same route opens (objectui#12540). * * On a console page route the app bar's pencil, the app switcher's Studio row - * and the sidebar's Design (objectui#12520) all open the page's surface in - * Studio's Interfaces pillar, `/studio/PACKAGE/interfaces?surface=page:NAME`, + * and the sidebar's Design (objectui#12520) all open the page in Studio, at + * its All-metadata item page `/studio/PACKAGE/metadata/page/NAME` since + * objectstack#36502 retired the Interfaces pillar, * through `appStudioRoutePath`. The page's own button opened the * metadata-admin page instead, so the one handle labelled "Edit in studio" was * the one that did not open Studio. It now goes through the same derivation: @@ -140,12 +141,12 @@ afterEach(() => { }); describe('Edit in studio opens the page in Studio, as the app bar pencil does (objectui#12540)', () => { - it('lands on the page surface in Studio\'s Interfaces pillar — the pencil\'s derivation, for the same app and page', async () => { + it('lands on the page\'s All-metadata item page in Studio (objectstack#36502) — the pencil\'s derivation, for the same app and page', async () => { await mountUnder(OWNED); fireEvent.click(screen.getByTestId('page-edit-in-studio-button')); expect(navigateSpy).toHaveBeenCalledTimes(1); const target = navigateSpy.mock.calls[0][0]; - expect(target).toBe('/studio/com.objectstack.cloud/interfaces?surface=page:welcome'); + expect(target).toBe('/studio/com.objectstack.cloud/metadata/page/welcome'); // The app bar's inputs on this route: the app, the author gate, the route type and name. expect(target).toBe(appStudioRoutePath(OWNED, true, { type: 'page', name: 'welcome' })); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ConditionalFormattingEditor.listEquality-36459.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ConditionalFormattingEditor.listEquality-36459.test.tsx index d711a74adeb..a2e7270da15 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ConditionalFormattingEditor.listEquality-36459.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ConditionalFormattingEditor.listEquality-36459.test.tsx @@ -11,9 +11,10 @@ * - the editor itself: `tags` (a `select` declared `multiple: true`) is the * list subject; `stage` (a plain `select`) is the scalar CONTROL; `'vip' in * record.tags` is the shape that does match; - * - both mount sites hand the object's field definitions through: the view - * variant inspector (metadata admin) and the Studio list-view panel's - * "more" section. + * - the mount site hands the object's field definitions through: the view + * variant inspector (metadata admin). The Studio list-view panel's "more" + * section was the second, until objectstack#36502 retired it with the + * Interfaces pillar. * * Direction: without `fieldDefs` reaching the editor no field is judged a list, * `record.tags == 'vip'` lints clean and the refusing cases are red; the @@ -59,9 +60,7 @@ vi.mock('./useMetadata', async (importOriginal) => { import { ConditionalFormattingEditor, type ConditionalFormattingRuleDraft } from './ConditionalFormattingEditor'; import { ViewVariantInspector } from './inspectors/ViewVariantInspector'; -import { ListViewMoreSection } from '../studio-design/ListViewMoreSection'; import { mapObjectFields } from '../ViewConfigPanel'; -import { loaded } from './loadState'; afterEach(cleanup); @@ -135,7 +134,7 @@ describe('ConditionalFormattingEditor — list-equality while typing (#36459)', }); }); -describe('both mount sites hand the editor the object’s field definitions (#36459)', () => { +describe('the mount site hands the editor the object’s field definitions (#36459)', () => { it('the view variant inspector refuses == on a list field in a formatting rule', async () => { function Harness() { const [draft, setDraft] = React.useState>({ @@ -170,32 +169,4 @@ describe('both mount sites hand the editor the object’s field definitions (#36 typeCondition("record.tags == 'vip'", editor); expect(await within(editor).findByText(LIST_FINDING, {}, { timeout: 5000 })).toBeInTheDocument(); }); - - it('the Studio list-view panel refuses == on a list field, and holds the autosave', async () => { - const report = vi.fn(); - function Harness() { - const [body, setBody] = React.useState>({ - type: 'grid', - columns: ['name'], - conditionalFormatting: [{ condition: '', style: {} }], - }); - return ( - ({ ...f, multiple: f.multiple === true || undefined })))} - readOnly={false} - locale={'en-US'} - onBlockingIssuesChange={report} - /> - ); - } - render(); - const editor = screen.getByTestId('cf-editor'); - typeCondition("record.tags == 'vip'", editor); - await waitFor(() => expect(report.mock.calls.at(-1)?.[0]).toBe(1), { timeout: 5000 }); - expect(within(editor).getByText(LIST_FINDING)).toBeInTheDocument(); - }); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/DirectoryPage.stateVocabulary-29705.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/DirectoryPage.stateVocabulary-29705.test.tsx index d52e5d3dd79..5fc6c96bad4 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/DirectoryPage.stateVocabulary-29705.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/DirectoryPage.stateVocabulary-29705.test.tsx @@ -408,10 +408,11 @@ describe('one word per state, the second pass (objectstack#29729)', () => { /** * objectstack#30062 — the tile and the door agree for every type: on a * read-only package a type's tile (and its list header) reads 可定制 exactly - * when Studio offers Customize on its items — the Interfaces pillar's header - * (`STUDIO_CUSTOMIZE_TYPES`, a page since objectstack#30063), the All metadata - * area's form editor (`AREA_FORM_EDITOR_TYPES`) or customize editor - * (`AREA_CUSTOMIZE_EDITOR_TYPES`, a dataset since objectstack#30064), or the + * when Studio offers Customize on its items — `STUDIO_CUSTOMIZE_TYPES` (a page + * since objectstack#30063), the All metadata area's form editor + * (`AREA_FORM_EDITOR_TYPES`) or customize editor (`AREA_CUSTOMIZE_EDITOR_TYPES`, + * a dataset since objectstack#30064, a view, dashboard, report and page since + * objectstack#36502 retired the Interfaces pillar that was their door), or the * flow header — whatever the type's overlay flag says. Before, a tile read * `allowEnvironmentOverlay`, false for a flow, an app, a page and a dataset, * so their tiles read 只读 while their doors offered 定制. diff --git a/ui/packages/app-shell/src/views/metadata-admin/PageShell.tsx b/ui/packages/app-shell/src/views/metadata-admin/PageShell.tsx index 0d3d0440e47..6370e795c60 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PageShell.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PageShell.tsx @@ -98,10 +98,11 @@ export const TYPE_STATE_WORD_KEY: Readonly> = Obje /** * objectstack#30062 — whether Studio offers Customize on a read-only base's * item of `type`, read from the doors that offer it, never from the type's - * overlay flag: the Interfaces pillar's header ({@link isStudioCustomizeType}), + * overlay flag: the app's navigation customize ({@link isStudioCustomizeType}), * the All metadata area's form editor ({@link AREA_FORM_EDITOR_TYPES}) and - * its customize editor on a read-only package ({@link AREA_CUSTOMIZE_EDITOR_TYPES}, - * a dataset, objectstack#30064), and the Automations pillar's flow header + * its customize editor on a read-only package ({@link AREA_CUSTOMIZE_EDITOR_TYPES}: + * a dataset, objectstack#30064; a view, dashboard, report or page since + * objectstack#36502 retired the Interfaces pillar), and the Automations pillar's flow header * (objectstack#28570). A door added to one of those lists moves its type's * tile with it. * diff --git a/ui/packages/app-shell/src/views/metadata-admin/draftVerdict.ts b/ui/packages/app-shell/src/views/metadata-admin/draftVerdict.ts index 51b652f27b4..26fa9d5b639 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/draftVerdict.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/draftVerdict.ts @@ -180,29 +180,6 @@ export function serverHoldAt( return (valueAtPath(judged, path) ?? '') === text ? hits : NO_ERRORS; } -/** - * objectstack#29311 — {@link verdictPreviewEntries} for a canvas whose page - * does not read the item again after an autosave (the Studio Interfaces - * pillar): an entry is kept while the body on screen still holds, at the - * entry's path, the value the verdict judged there, and dropped once the - * author has edited that value (a field reference renamed or removed). The - * verdict describes the judged body and no other, as {@link serverHoldAt} - * says; the next read brings the next one. An entry with no path describes - * the whole body and is kept. ⛔ No rule is restated: the entries are the - * server's, taken whole. - */ -export function verdictEntriesStillShown( - diagnostics: ServerDiagnostics | undefined, - judged: unknown, - shown: unknown, -): Array<{ path?: string; message: string; severity: 'error' | 'warning'; code?: string }> { - return verdictPreviewEntries(diagnostics).filter( - (entry) => - !entry.path || - JSON.stringify(valueAtPath(judged, entry.path)) === JSON.stringify(valueAtPath(shown, entry.path)), - ); -} - /** {@link serverHoldAt} against the verdict and judged body the enclosing page provides. */ export function useServerHoldAt(path: string | undefined, text: string): readonly ServerDiagnosticEntry[] { return serverHoldAt(React.useContext(DraftVerdictContext), React.useContext(DraftVerdictBodyContext), path, text); diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/AppNavCanvas.menuOrder-26979.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/AppNavCanvas.menuOrder-26979.test.tsx new file mode 100644 index 00000000000..54849820a57 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/AppNavCanvas.menuOrder-26979.test.tsx @@ -0,0 +1,165 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#26979 — the nav canvas shows an app's nav entries in the order + * the running menu draws them. + * + * The menu sorts every level by `order` (`byNavOrder` in + * `packages/layout/src/navOrder.ts`: lower first, an absent `order` as `0`, + * ties in authored order), at the top level and inside each group. The nav + * canvas (`AppNavCanvas`, which Setup's app editor mounts) lists a level + * through `inMenuOrder`, which states the menu's rule; `byNavOrder` is + * internal to its package, so these pins are what hold the two rules + * together: each renders the menu (`NavigationRenderer`) beside the canvas + * over the same entries. + * + * Moved out of `StudioDesignSurface.railLabels.test.tsx` when objectstack#36502 + * retired the Interfaces pillar; its rail, the third surface these pins read, + * went with the pillar. + * + * - entries with `order` [3, 1, 2] (and a group whose children carry + * [2, 1]) read in one order on both surfaces; + * - a drag in the canvas leaves both agreeing, writing `order` on the moved + * entry only; + * - CONTROL: entries with no `order` keep their array order, and a drag + * among them writes no `order` at all. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { NavigationItemSchema } from '@objectstack/spec/ui'; +import { SidebarProvider } from '@object-ui/components'; +import { NavigationRenderer } from '@object-ui/layout'; +import type { NavigationItem } from '@object-ui/types'; +import { AppNavCanvas } from './AppNavCanvas'; + +describe('AppNavCanvas.menuOrder-26979', () => { + const page = (label: string, order?: number) => ({ + id: `nav_${label.toLowerCase()}`, + type: 'page', + label, + pageName: label.toLowerCase(), + ...(order === undefined ? {} : { order }), + }); + + /** Authored out of menu order: the menu reads Bravo, Charlie, Alpha, Folder (Yankee, Xray). */ + const ORDERED = [ + page('Alpha', 3), + page('Bravo', 1), + page('Charlie', 2), + { id: 'nav_folder', type: 'group', label: 'Folder', order: 4, expanded: true, children: [page('Xray', 2), page('Yankee', 1)] }, + ]; + + /** No `order` anywhere: the menu reads the array as authored. */ + const UNORDERED = [page('Alpha'), page('Bravo'), page('Charlie')]; + + const LABELS = ['Alpha', 'Bravo', 'Charlie', 'Folder', 'Xray', 'Yankee']; + + afterEach(cleanup); + + /** The labels `el` shows, in the order it shows them; each must show once. */ + function orderIn(el: HTMLElement): string[] { + const text = el.textContent ?? ''; + const shown = LABELS.filter((l) => text.includes(l)); + for (const l of shown) expect(text.indexOf(l)).toBe(text.lastIndexOf(l)); + return shown.sort((a, b) => text.indexOf(a) - text.indexOf(b)); + } + + /** The running app's sidebar over `nav`. */ + function menuOrder(nav: unknown[]): string[] { + const { container, unmount } = render( + + + + + , + ); + const order = orderIn(container); + unmount(); + return order; + } + + /** The nav canvas over `nav`, holding its patches as the host's draft does. */ + function renderCanvas(nav: unknown[]) { + const patches: unknown[][] = []; + function Host() { + const [draft, setDraft] = React.useState>({ navigation: nav }); + return ( +
+ { + patches.push(patch.navigation as unknown[]); + setDraft((d) => ({ ...d, ...patch })); + }} + /> +
+ ); + } + render(); + return { canvas: screen.getByTestId('nav-canvas'), patches }; + } + + /** The canvas card for `label`: the row button whose text starts with it. */ + const card = (label: string) => + screen.getAllByRole('button').find((b) => b.getAttribute('aria-pressed') !== null && b.textContent?.startsWith(label))!; + + /** Drag the card `label` and drop it before the card `before`, as a pointer does. */ + function dragBefore(label: string, before: string) { + // The canvas's own drag type (`DND_MIME` in `AppNavCanvas.tsx`); a drop of any other type is ignored. + const dataTransfer = { types: ['text/x-objectui-nav'], setData: vi.fn(), getData: vi.fn(), effectAllowed: '', dropEffect: '' }; + fireEvent.dragStart(card(label), { dataTransfer }); + fireEvent.dragOver(card(before), { dataTransfer }); + fireEvent.drop(card(before), { dataTransfer }); + } + + it('the fixtures are what the spec accepts', () => { + for (const item of [...ORDERED, ...UNORDERED]) expect(NavigationItemSchema.safeParse(item).success).toBe(true); + }); + + it('entries with order [3, 1, 2] read in the menu order on the canvas and the menu', () => { + const menu = menuOrder(ORDERED); + // Measured on the menu first: it sorts the top level and the group's children. + expect(menu).toEqual(['Bravo', 'Charlie', 'Alpha', 'Folder', 'Yankee', 'Xray']); + const { canvas } = renderCanvas(ORDERED); + expect(orderIn(canvas)).toEqual(menu); + }); + + it('a drag in the canvas leaves the canvas and the menu agreeing, and writes order on the moved entry only', () => { + const { canvas, patches } = renderCanvas(ORDERED); + // Alpha (order 3, shown third) to the top, before Bravo (order 1). + dragBefore('Alpha', 'Bravo'); + expect(patches).toHaveLength(1); + const next = patches[0] as Array>; + expect(orderIn(canvas)).toEqual(['Alpha', 'Bravo', 'Charlie', 'Folder', 'Yankee', 'Xray']); + // One `order` write: Alpha takes the weight of the entry it now precedes. + // Every other entry is the object it was. + const before = new Map(ORDERED.map((it) => [it.id, it])); + for (const it of next) { + if (it.id === 'nav_alpha') expect(it).toEqual({ ...before.get('nav_alpha'), order: 1 }); + else expect(it).toBe(before.get(it.id as string)); + } + cleanup(); + const menu = menuOrder(next); + expect(menu).toEqual(['Alpha', 'Bravo', 'Charlie', 'Folder', 'Yankee', 'Xray']); + }); + + it('CONTROL: entries with no order keep their array order, and a drag among them writes no order', () => { + const menu = menuOrder(UNORDERED); + expect(menu).toEqual(['Alpha', 'Bravo', 'Charlie']); + const { canvas, patches } = renderCanvas(UNORDERED); + expect(orderIn(canvas)).toEqual(menu); + dragBefore('Charlie', 'Alpha'); + const next = patches[0] as Array>; + expect(next.map((it) => it.id)).toEqual(['nav_charlie', 'nav_alpha', 'nav_bravo']); + for (const it of next) expect(it).not.toHaveProperty('order'); + expect(orderIn(canvas)).toEqual(['Charlie', 'Alpha', 'Bravo']); + cleanup(); + expect(menuOrder(next)).toEqual(['Charlie', 'Alpha', 'Bravo']); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/SourcePageProperties.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/SourcePageProperties.test.tsx deleted file mode 100644 index 4c2db45790f..00000000000 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/SourcePageProperties.test.tsx +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#12522 — `SourcePageProperties`, the Properties tab of an html / - * react page: what it shows, and that it writes only the page's `label`. - * - * - label, identifier and kind are shown, the kind in the create dialog's words; - * - a label edit patches `label` alone: a plain string is replaced, a - * per-language map changes only the designer locale's entry; - * - read-only (no `onPatch`), the label is text, not an input; - * - no navigation entry opens the page → it says so. - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'; -import { SourcePageProperties } from './SourcePageProperties'; -import { t } from '../i18n'; - -afterEach(cleanup); - -const LABEL = t('engine.studio.if.pageProps.label', 'en'); - -describe('SourcePageProperties (objectui#12522)', () => { - it('shows the label, the identifier, the kind and the entries that open the page', () => { - render( - {}} - locale="en" - />, - ); - expect(screen.getByLabelText(LABEL)).toHaveValue('Guide'); - expect(screen.getByTestId('source-page-identifier')).toHaveTextContent('guide'); - expect(screen.getByTestId('source-page-kind')).toHaveTextContent(t('engine.studio.interfaces.create.pageKindReact', 'en')); - const items = within(screen.getByTestId('source-page-nav-entries')).getAllByRole('listitem'); - expect(items.map((li) => li.textContent)).toEqual(['Guide', 'Docs › Start › Read me']); - }); - - it('a label edit patches `label` alone, replacing a plain string', () => { - const onPatch = vi.fn(); - render(); - fireEvent.change(screen.getByLabelText(LABEL), { target: { value: 'Handbook' } }); - expect(onPatch).toHaveBeenCalledWith({ label: 'Handbook' }); - }); - - it('a label edit on a per-language map changes only the designer locale entry', () => { - const onPatch = vi.fn(); - render( - , - ); - const input = screen.getByLabelText(t('engine.studio.if.pageProps.label', 'zh-CN')); - expect(input).toHaveValue('指南'); - fireEvent.change(input, { target: { value: '手册' } }); - expect(onPatch).toHaveBeenCalledWith({ label: { en: 'Guide', 'zh-CN': '手册' } }); - }); - - it('read-only, the label is text and nothing is editable', () => { - render(); - expect(screen.getByTestId('source-page-label').tagName).toBe('SPAN'); - expect(screen.getByTestId('source-page-label')).toHaveTextContent('Guide'); - expect(screen.queryByRole('textbox')).toBeNull(); - }); - - it('says so when no navigation entry opens the page', () => { - render(); - expect(screen.getByTestId('source-page-nav-none')).toHaveTextContent(t('engine.studio.if.pageProps.noNavEntries', 'en')); - }); -}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/SourcePageProperties.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/SourcePageProperties.tsx deleted file mode 100644 index 2d2b3979328..00000000000 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/SourcePageProperties.tsx +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * SourcePageProperties — the Properties tab of a `kind: 'html'` / `'react'` - * page in the Studio (objectui#12522). Such a page has no block tree, so the - * tab says what the page IS: its label, its identifier, the language it is - * written in, and the navigation entries that open it. - * - * It edits only what the page schema lets the Studio edit: - * - `label` (`I18nLabel`) is edited in the designer locale: a plain string is - * replaced, and a per-language map changes only that locale's entry - * (`renamedLabel`, objectui#11128), so no other language's text is lost. - * - `name` is the page's identity, which every save addresses - * (`PAGE_FIELDS_OWNED_ELSEWHERE`): read-only. - * - `kind` is chosen in the create dialog and is not changed in the Studio - * (`PageCreateFields`): read-only, worded as that dialog words it. - * - The navigation entries are the app's, not the page's: listed, never - * written from here. - */ - -import * as React from 'react'; -import { Input, Label } from '@object-ui/components'; -import type { I18nLabel } from '@objectstack/spec/ui'; -import { t } from '../i18n.js'; -import { navItemLabelText, renamedLabel } from './navItemLabel.js'; - -/** A navigation entry that opens the page, as the host resolved it. */ -export interface SourcePageNavEntry { - /** The entry's spec `id`. */ - id: string; - /** The entry's label in the designer locale. */ - label: string; - /** The labels of the groups the entry sits in, outermost first. */ - trail: string[]; -} - -export interface SourcePagePropertiesProps { - draft: Record; - /** The page's identifier: the name the Studio opened and saves it under. */ - name: string; - /** The navigation entries whose target is this page. */ - navEntries: SourcePageNavEntry[]; - /** Patch the draft; undefined in read-only mode. */ - onPatch?: (patch: Record) => void; - readOnly?: boolean; - /** The designer locale: the words, and the entry a label edit writes. */ - locale: string; -} - -const ROW = 'flex flex-col gap-1'; -const LABEL = 'text-[11px] font-medium uppercase tracking-wide text-muted-foreground'; -const VALUE = 'text-[13px] text-foreground'; -const HINT = 'text-[11px] text-muted-foreground'; - -export function SourcePageProperties({ - draft, - name, - navEntries, - onPatch, - readOnly, - locale, -}: SourcePagePropertiesProps) { - const idBase = React.useId(); - const label = draft.label as I18nLabel | undefined; - const labelEditable = !readOnly && !!onPatch; - const kind = (draft as { kind?: string }).kind === 'react' ? 'react' : 'html'; - - return ( -
-
- - {labelEditable ? ( - onPatch!({ label: renamedLabel(label, e.target.value, locale) })} - className="h-8 text-[13px]" - data-testid="source-page-label" - /> - ) : ( - - {navItemLabelText(label, locale) || name} - - )} -
- -
- {t('engine.studio.if.pageProps.identifier', locale)} - - {name} - -
- -
- {t('engine.studio.interfaces.create.pageKind', locale)} - - {kind === 'react' - ? t('engine.studio.interfaces.create.pageKindReact', locale) - : t('engine.studio.interfaces.create.pageKindHtml', locale)} - - {t('engine.studio.if.pageProps.kindFixed', locale)} -
- -
- {t('engine.studio.if.pageProps.navEntries', locale)} - {navEntries.length === 0 ? ( - - {t('engine.studio.if.pageProps.noNavEntries', locale)} - - ) : ( -
    - {navEntries.map((entry) => ( -
  • - {entry.trail.length > 0 && ( - {entry.trail.join(' › ')} › - )} - {entry.label} -
  • - ))} -
- )} -
-
- ); -} diff --git a/ui/packages/app-shell/src/views/metadata-admin/widgets.filterBuilderMultiple-36169.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/widgets.filterBuilderMultiple-36169.test.tsx index 9cfe3dab210..f422934e921 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/widgets.filterBuilderMultiple-36169.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/widgets.filterBuilderMultiple-36169.test.tsx @@ -79,16 +79,12 @@ vi.mock('./useMetadata', async (importOriginal) => { return { ...mod, useMetadataClient: () => clients.current }; }); -import { MetadataCtx, type MetadataContextValue } from '@object-ui/react'; -import { MetadataClient } from '@object-ui/data-objectstack'; import { WIDGETS } from './widgets'; import { loaded } from './loadState'; import { objectCatalogOf } from './ResourceEditPage'; import { mapObjectFields } from '../ViewConfigPanel'; import { ViewVariantInspector } from './inspectors/ViewVariantInspector'; import { PageBlockInspector } from './inspectors/PageBlockInspector'; -import { ObjectListViewInspector, useObjectListViewDraft } from '../studio-design/ObjectListViewInspector'; -import type { Surface } from '../studio-design/navSurface'; afterEach(() => { cleanup(); @@ -275,76 +271,3 @@ describe('every host that builds the filter-builder field list carries `multiple expect(await offeredFor(block, 'Regions')).toEqual(labelsFor('select', true)); }); }); - -/* The Studio list-view inspector, over a REAL `MetadataClient` whose transport - * serves the object and its default list view as the platform does - * (`ObjectListViewInspector.hiddenSystemFields-13152.test.tsx`'s harness). */ - -const VIEW = 'deal.default'; -const json = (status: number, body: unknown) => - new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); -const GRID_VIEW = { - name: VIEW, - object: 'deal', - viewKind: 'list', - isDefault: true, - config: { type: 'grid', data: { provider: 'object', object: 'deal' }, columns: ['name'] }, -}; - -async function serve(input: RequestInfo | URL, init?: RequestInit): Promise { - const method = (init?.method ?? 'GET').toUpperCase(); - const url = new URL(String(input), 'http://studio.test'); - const meta = url.pathname.match(/^\/api\/v1\/meta\/(.+)$/); - if (!meta) return json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); - const seg = meta[1].split('/').map(decodeURIComponent); - if (seg[0] === '_drafts') return json(200, { drafts: [] }); - if (method === 'PUT') return json(200, { success: true, version: 'v2', state: 'draft' }); - if (seg[0] === 'object' && seg.length === 2) return json(200, { type: 'object', name: seg[1], item: DEAL }); - const isView = seg[0] === 'view' && seg[1] === VIEW; - if (seg.length === 3 && seg[2] === 'layers') { - return isView - ? json(200, { code: null, overlay: GRID_VIEW, overlayScope: 'env', effective: GRID_VIEW }) - : json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); - } - if (seg.length === 2 && url.searchParams.get('state') === 'draft') { - return json(404, { error: { code: 'NO_DRAFT', message: 'absent' } }); - } - return isView ? json(200, { type: 'view', name: VIEW, item: GRID_VIEW }) : json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); -} - -const METADATA: MetadataContextValue = { - apps: [], - objects: [DEAL], - dashboards: [], - reports: [], - pages: [], - loading: false, - error: null, - refresh: async () => {}, - invalidate: () => {}, - ensureType: async () => [], - getItem: async () => null, - getItemsByType: () => [], -}; - -describe('the Studio list-view inspector’s filter carries `multiple` (objectstack#36169)', () => { - it('offers a multiple: true column membership only, and keeps Equals on a single-value control', async () => { - const real = new MetadataClient({ baseUrl: '', fetch: vi.fn(serve) as unknown as typeof fetch }); - clients.current = real; - const LEAF: Surface = { type: 'object', name: 'deal', label: 'Deals' }; - function Host() { - const listView = useObjectListViewDraft({ client: real, packageId: 'com.acme.app', leaf: LEAF, publishNonce: 0 }); - return ; - } - render( - - - , - ); - const filter = await screen.findByTestId('list-view-filter', {}, { timeout: 5000 }); - await waitFor(() => expect(within(filter).getByRole('button', { name: 'Add filter' })).toBeInTheDocument()); - expect(await offeredFor(filter, 'Accounts')).toEqual(labelsFor('lookup', true)); - await pickFrom(filter, 0, 'Owner'); - expect(await optionsOf(filter, 1)).toContain('Equals'); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesNavRail.editKinds-34796.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesNavRail.editKinds-34796.test.tsx deleted file mode 100644 index 9b0bc1d383a..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesNavRail.editKinds-34796.test.tsx +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#34796 — in Studio's navigation edit mode each entry's kind badge - * reads the kind the navigation list tags it with (`navKindName`), not the raw - * `type`: an object, a view (an object entry naming a kanban view), a - * dashboard and a page. The Setup designer passes no kind names, so its badges - * keep the raw type (the CONTROL). - */ - -// Paid at collection, not inside a clocked case (check:test-source-alias). -import '@objectstack/lint'; -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render, screen } from '@testing-library/react'; -import { I18nProvider } from '@object-ui/i18n'; -import { MetadataCtx } from '@object-ui/react'; - -import { AppNavCanvas } from '../metadata-admin/previews/AppNavCanvas'; -import { navKindName } from './InterfacesNavRail'; -// The zh rows live in the lazy `studio` namespace; resident before any case. -import { loadStudioCatalogue } from '@object-ui/i18n/namespaces/studio'; -await loadStudioCatalogue('zh'); - -afterEach(cleanup); - -const METADATA = { - apps: [], - objects: [{ name: 'meeting', label: 'Meeting' }], - dashboards: [], - reports: [], - pages: [], - loading: false, - error: null, - refresh: async () => {}, - invalidate: () => {}, - ensureType: async () => [], - getItem: async () => null, - getItemsByType: () => [], - getTypeStatus: () => 'ready' as const, -}; - -const NAV = [ - { id: 'nav_meeting', type: 'object', label: 'Meetings', objectName: 'meeting' }, - { id: 'nav_board', type: 'object', label: 'Todo board', objectName: 'meeting', viewName: 'kanban' }, - { id: 'nav_dash', type: 'dashboard', label: 'Overview', dashboardName: 'overview' }, - { id: 'nav_home', type: 'page', label: 'Home', pageName: 'home' }, -]; - -function renderCanvas(language: 'en' | 'zh', locale: string, withKindNames: boolean) { - render( - - - navKindName({ type: item.type, viewName: typeof item.viewName === 'string' ? item.viewName : undefined }, locale) - : undefined - } - /> - - , - ); -} - -/** The kind badge on the card whose label is `label`. */ -function badgeOf(label: string): string { - const card = screen.getByText(label).closest('[draggable], [role="button"], li, div[class*="rounded"]') as HTMLElement; - const badge = [...card.querySelectorAll('div, span')].find((el) => el.className.includes('h-5') && el.className.includes('px-1.5')); - return badge?.textContent ?? ''; -} - -describe("Studio's navigation edit mode names each kind as the navigation list does (objectstack#34796)", () => { - it('zh: object, view (a kanban entry), dashboard and page read 对象 / 视图 / 仪表盘 / 页面, and no badge reads `object`', () => { - renderCanvas('zh', 'zh-CN', true); - expect(badgeOf('Meetings')).toBe(navKindName(NAV[0], 'zh-CN')); - expect(badgeOf('Todo board')).toBe(navKindName(NAV[1], 'zh-CN')); - expect(badgeOf('Overview')).toBe(navKindName(NAV[2], 'zh-CN')); - expect(badgeOf('Home')).toBe(navKindName(NAV[3], 'zh-CN')); - expect([badgeOf('Meetings'), badgeOf('Todo board'), badgeOf('Overview'), badgeOf('Home')]).toEqual([ - '对象', - '视图', - '仪表盘', - '页面', - ]); - expect(screen.queryByText('object', { exact: true })).toBeNull(); - }); - - it('en reads the same kinds in English words', () => { - renderCanvas('en', 'en-US', true); - expect(badgeOf('Todo board')).toBe(navKindName(NAV[1], 'en-US')); - expect(badgeOf('Todo board')).not.toBe('object'); - }); - - it('CONTROL: without kind names (the Setup designer) the badge keeps the raw type', () => { - renderCanvas('en', 'en-US', false); - expect(badgeOf('Meetings')).toBe('object'); - expect(badgeOf('Todo board')).toBe('object'); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesNavRail.internalFormHidden-36425.test.ts b/ui/packages/app-shell/src/views/studio-design/InterfacesNavRail.internalFormHidden-36425.test.ts deleted file mode 100644 index 79fe82a613f..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesNavRail.internalFormHidden-36425.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack-ai/objectstack#36425 — the Studio Interfaces 视图 group no - * longer lists an internal create / edit form (the object's default form or - * its `OBJECT.create` form), which the console no longer loads. A public form - * (`sharing.enabled === true`) stays listed, and so does a named form an - * action of type `form` opens. The same test as the lint rule - * `form-view-internal-not-loaded`. - * - * Reads the published rows through the real `loadPackageSurfaces`, the merge - * the Interfaces pillar draws its rail from. - */ -import { describe, expect, it, vi } from 'vitest'; -// Paid at collection, not inside a case's clock (check:test-source-alias). -import '@objectstack/lint'; -import { loadPackageSurfaces, viewBindingOf, type PackageSurfaceClient } from './packageSurfaces'; -import { offNavViewIsInternalForm } from './InterfacesNavRail'; - -const sections = [{ label: 'Main', fields: ['name'] }]; -const ROWS: Array> = [ - { name: 'account.form', object: 'account', viewKind: 'form', isDefault: true, config: { sections } }, - { name: 'account.create', object: 'account', viewKind: 'form', config: { sections } }, - { name: 'lead.contact_us', object: 'lead', viewKind: 'form', isDefault: true, config: { sections, sharing: { enabled: true, publicLink: 'contact-us' } } }, - { name: 'lead.qualify', object: 'lead', viewKind: 'form', config: { sections } }, - { name: 'account.all', object: 'account', viewKind: 'list', isDefault: true, config: {} }, -]; - -function client(): PackageSurfaceClient { - return { - list: vi.fn(async () => ROWS), - listDrafts: vi.fn(async () => []) as unknown as PackageSurfaceClient['listDrafts'], - }; -} - -describe('Studio Interfaces leaves out internal forms, keeps public and named ones (#36425)', () => { - it('the default and the create form of an object are internal; nothing else is', async () => { - const rail = await loadPackageSurfaces(client(), 'view', 'com.qa.app'); - const hidden = rail.filter(offNavViewIsInternalForm).map((s) => s.name); - const listed = rail.filter((s) => !offNavViewIsInternalForm(s)).map((s) => s.name); - expect(hidden).toEqual(['account.form', 'account.create']); - expect(listed).toEqual(['lead.contact_us', 'lead.qualify', 'account.all']); - }); - - it('CONTROL: a public form is listed wherever it sits; sharing turned off makes it internal', () => { - const publicDefault = viewBindingOf({ name: 'x.form', object: 'x', viewKind: 'form', isDefault: true, sharing: { enabled: true } }); - expect(offNavViewIsInternalForm(publicDefault)).toBe(false); - const sharingOff = viewBindingOf({ name: 'x.form', object: 'x', viewKind: 'form', isDefault: true, config: { sharing: { enabled: false } } }); - expect(offNavViewIsInternalForm(sharingOff)).toBe(true); - }); - - it('CONTROL: a draft-only view (no body) stays listed', () => { - expect(offNavViewIsInternalForm({})).toBe(false); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesNavRail.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesNavRail.tsx deleted file mode 100644 index 4bb30cd2e31..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesNavRail.tsx +++ /dev/null @@ -1,702 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * The Interfaces pillar's navigation rail: the app's nav tree, its contributed - * rows and off-nav sections, the two rail contexts and the kind icons, moved - * out of `StudioDesignSurface.tsx` unchanged by objectstack#29988 (slice 3 of - * the move-only split). - */ - -import * as React from 'react'; -import { StudioRailGroup, StudioRailRow } from './StudioRail.js'; -import { Badge, ObjectIconTile, Popover, PopoverContent, PopoverTrigger, Separator, cn } from '@object-ui/components'; -import { - FileText, - Database, - LayoutDashboard, - BarChart3, - Table2, - Folder, - Compass, - Link as LinkIcon, - Puzzle, - BookOpen, - MousePointer2, - Minus, - RotateCcw, - type LucideIcon, -} from 'lucide-react'; -import { listViewTargetOf } from './ObjectListViewInspector.js'; -import type { PackageSurface } from './packageSurfaces.js'; -import { resolveSurface, isSameSurface, type NavNode, type Surface } from './navSurface.js'; -import { t, tFormat, translateMetadataType, useMetadataLocale } from '../metadata-admin/i18n.js'; -import { inMenuOrder, isIncompleteNavEntry } from '../metadata-admin/previews/AppNavCanvas.js'; -import { navEntryLabelText } from '../metadata-admin/previews/navItemLabel.js'; -import { useNavTargetLabel } from '../../hooks/useNavTargetLabel.js'; -import { isNavEntryType } from '../metadata-admin/inspectors/nav-target.js'; -import type { NavTargetLabelResolver } from '@object-ui/layout'; -import { getIcon } from '../../utils/getIcon.js'; -import { - ContributedRailRow, - RailCustomizationMark, - contributedItemTitle, - useOpenContributor, - type RailCustomizations, -} from './StudioRailCustomizations.js'; -import { CustomizationMark } from './CustomizationMark.js'; -import { - NO_SERVED_CONTRIBUTED_NAV, - servedEntryOf, - type NavContributionPlacement, - type ServedContributedNav, - type TopLevelContributedNav, -} from './contributionRows.js'; - -const KIND_ICON: Record = { - group: Folder, - page: FileText, - object: Database, - dashboard: LayoutDashboard, - report: BarChart3, - view: Table2, - action: MousePointer2, - // objectui#11790 — the types the nav editor can now add. A url / component / - // doc row opens no design surface (`resolveSurface`), so it renders disabled, - // under its own glyph rather than the generic compass. - url: LinkIcon, - component: Puzzle, - doc: BookOpen, - separator: Minus, -}; -export const navIcon = (type?: string): LucideIcon => KIND_ICON[type ?? ''] ?? Compass; - -/** - * The kind tag a nav entry carries at the right of its rail row, and the kind - * an entry is named by in the header chip and the inspector's eyebrow - * (objectui#12455). A type the console also names as a metadata type (object, - * page, dashboard, report) is translated by that one helper, so the rail, the - * breadcrumb and the canvas caption say the same word; an `object` entry bound - * to a named view reads "View"; the types that open no design surface (url, - * action, component, doc) and the two structural ones are named from the - * Studio's own table. `''` for an entry with no type the spec declares. - */ -export function navKindName(node: Pick, locale: string): string { - const type = node.type ?? ''; - if (type === 'object' && typeof node.viewName === 'string' && node.viewName) { - return t('engine.studio.if.kind.view', locale); - } - if (type === 'object' || type === 'page' || type === 'dashboard' || type === 'report') { - return translateMetadataType(type, locale); - } - if (isNavEntryType(type)) return t(`engine.studio.if.kind.${type}`, locale); - return ''; -} - -/** - * Whether `nodes` hold, at any depth, the entry that opens `active` — so a - * group the sidebar would collapse opens when the open leaf is inside it. - */ -function navTreeHoldsActive( - nodes: NavNode[] | undefined, - active: Surface | null, - locale: string, - targetLabel: NavTargetLabelResolver, -): boolean { - if (!active || !nodes) return false; - return nodes.some((node) => { - if (Array.isArray(node.children) && node.children.length) { - return navTreeHoldsActive(node.children, active, locale, targetLabel); - } - const surface = resolveSurface(node, locale, targetLabel); - return !!surface && isSameSurface(active, surface); - }); -} - -/** - * One group header and its children (objectui#12455). Open or closed as the - * running app's sidebar opens it (`NavigationRenderer` in `@object-ui/layout`): - * always open when the open leaf is inside it, else the spec's `expanded` when - * the author set it, else open — however many children it holds - * (objectui#13336). Collapsible by its - * header, as the sidebar's is. A group with nothing in it says so in its place - * instead of drawing a bare header. - */ -function NavTreeGroup({ - node, - labelText, - active, - onPick, - objectIcons, - objectColors, - depth, -}: { - node: NavNode; - labelText: string; - active: Surface | null; - onPick: (s: Surface) => void; - objectIcons?: Record; - objectColors?: Record; - depth: number; -}): React.ReactElement { - const locale = useMetadataLocale(); - const targetLabel = useNavTargetLabel(); - const children = node.children ?? []; - // objectstack#29786 — a declared group (`type: 'group'`) also holds the - // entries other packages contribute to it; a group with only those is no - // longer empty. - const placement = React.useContext(InterfacesNavContributionsContext); - const contributed = node.type === 'group' && typeof node.id === 'string' ? (placement.byGroup.get(node.id) ?? []) : []; - const holdsActive = navTreeHoldsActive(children, active, locale, targetLabel); - const [open, setOpen] = React.useState(() => { - if (holdsActive) return true; - if (typeof node.expanded === 'boolean') return node.expanded; - return true; - }); - // A leaf opened from elsewhere (a deep link, a create) inside a closed - // group opens the group, as the sidebar does for the route it is on. - // Adjusted while rendering, on the change, so no effect re-renders it. - const [heldActive, setHeldActive] = React.useState(holdsActive); - if (holdsActive !== heldActive) { - setHeldActive(holdsActive); - if (holdsActive) setOpen(true); - } - return ( - setOpen((v) => !v)}> - {children.length === 0 && contributed.length === 0 ? ( -

- {t('engine.studio.if.emptyGroup', locale)} -

- ) : ( - <> - {children.length > 0 && ( - - )} - {/* objectstack#29786 — what other packages add to this group, after - the group's own entries, as the served navigation appends them. */} - ({ entry, undeclaredGroup: null }))} indent /> - - )} -
- ); -} - -/** - * Recursive App-navigation tree: groups, separators and typed leaves. - * - * objectui#12455 (epic objectui#12446, decision 5) — the rail shows the app's - * navigation as the shipped sidebar renders it: the same order, the same - * groups (collapsible, opened as the sidebar opens them, see `NavTreeGroup`), - * the same icons. Each leaf is one 32 px row: its icon, its label, and its - * kind as a tag at the right (`navKindName`). The internal `type · name` pair - * lives on the row's tooltip (objectui#7254), which is also its accessible - * description; the visible text is what an author reads. - * - * objectui#11791 — the rail draws a `separator` and a leaf's `badge` / - * `badgeVariant` with the decisions the running app's sidebar makes - * (`NavigationRenderer` in `@object-ui/layout`, which `UnifiedSidebar` mounts), - * so the design surface agrees with the app it designs. Mirrored, not - * imported: the sidebar draws both inline in its row renderer, and its rows - * are `SidebarMenu` items this rail does not use. The pin that holds the two - * together renders both: the `StudioDesignSurface.railSeparatorBadge-11791` - * block of `StudioDesignSurface.railLabels.test.tsx`. - */ -/** - * objectstack#28572 — the Interfaces rail's customization marks, read by its - * tree rows and its off-nav rows alike (`railCustomizationsOf`); `null` on a - * package with nothing to mark. - */ -export const InterfacesRailMarksContext = React.createContext(null); - -/** - * objectstack#29786 — where the open app's contributed nav entries go - * (`placeNavContributions`), read by the tree's groups and its top level. - * Empty on a package with none. - */ -export const InterfacesNavContributionsContext = React.createContext({ byGroup: new Map(), top: [] }); - -/** - * objectstack#29851 — the open app's served entries its published layer does - * not hold, by id (`servedContributedNavOf`): what a contributed row reads - * its label from. Empty for a never-published app. - */ -export const InterfacesServedContributedNavContext = React.createContext(NO_SERVED_CONTRIBUTED_NAV); - -/** - * objectstack#29786 — contributed nav entries as rail rows: greyed, with the - * contributing package, and opening that package's Interfaces pillar. Not - * nav entries of this app: never in its edit buffer, never dragged, renamed - * or deleted here. - */ -export function ContributedNavRows({ - rows, - indent = false, -}: { - rows: readonly TopLevelContributedNav[]; - indent?: boolean; -}): React.ReactElement | null { - const locale = useMetadataLocale(); - const openContributor = useOpenContributor(); - const served = React.useContext(InterfacesServedContributedNavContext); - // objectstack#29851 — the label-less entry inherits as the live sidebar's does. - const targetLabel = useNavTargetLabel(); - if (rows.length === 0) return null; - return ( - <> - {rows.map(({ entry, undeclaredGroup }) => ( - } - title={contributedItemTitle(entry, locale, undeclaredGroup)} - onOpen={() => openContributor(`/studio/${encodeURIComponent(entry.packageId)}/interfaces`)} - locale={locale} - /> - ))} - - ); -} - -/** - * objectstack#29851 — the text the live app shows for a contributed entry: the - * served entry read with the rail's own resolver, or `undefined` when no served - * entry is known for it (the row then keeps its id). - */ -function contributedNavLabel( - node: Record | undefined, - locale: string, - targetLabel: NavTargetLabelResolver, -): string | undefined { - if (!node) return undefined; - const text = navEntryLabelText(node as NavNode, locale, targetLabel).trim(); - return text || undefined; -} - -export function NavTree({ - nodes, - active, - onPick, - objectIcons, - objectColors, - depth = 0, -}: { - nodes: NavNode[]; - active: Surface | null; - onPick: (s: Surface) => void; - /** object name → its metadata icon, so object nav items show their own glyph. */ - objectIcons?: Record; - /** object name → its palette colour: an object nav item draws its object's tile (objectstack#35985). */ - objectColors?: Record; - /** Nesting depth: a row under a group header is indented one step. */ - depth?: number; -}): React.ReactElement { - const locale = useMetadataLocale(); - // What a label-less row inherits is asked of the console's own resolver, so - // the rail names it as the console's sidebar does (objectui#11196). - const targetLabel = useNavTargetLabel(); - const railMarks = React.useContext(InterfacesRailMarksContext); - // objectstack#26979 — a level is listed in the order the running menu draws - // it, through the canvas's `inMenuOrder` (the menu's `byNavOrder` rule). `i` - // stays the entry's position in the authored array, which the canvas numbers - // an untitled entry by too. - const ordered = inMenuOrder(nodes); - return ( - <> - {ordered.map(([node, i]) => { - // objectui#11158 — the spec types a nav item's `label` as `I18nLabel`, - // so a locale map rendered raw threw ("Objects are not valid as a - // React child") and took the whole rail down. Every read below goes - // through the family's one helper, in the designer locale. - // objectui#11196 — an ABSENT label shows the text the entry inherits: - // the runtime's own rule, never a second copy of it. - // objectui#11791 — a `separator` is a rule between rows, not an entry. - // The sidebar's decision, mirrored: a decorative `Separator` - // (`role="none"`), so it is no row to click, no stop for the keyboard, - // and nothing a screen reader announces. The spec's separator carries - // `type`, `id` and `order` only, so there is no label or badge to draw. - if (node.type === 'separator') { - return ; - } - const labelText = navEntryLabelText(node, locale, targetLabel); - if (node.type === 'group' || (Array.isArray(node.children) && node.children.length)) { - return ( - - ); - } - // The same resolver names the Surface a click opens, so the caption, - // the breadcrumb and the copilot chip read what this row reads. - const surface = resolveSurface(node, locale, targetLabel); - // objectui#11862 — an entry that names no target yet ("Add nav item" - // left unbound, which the editor keeps showing in its place) inherits - // only its minted `id`. It reads as the editor's untitled wording - // instead, never `nav_item_N`. "No target" is the save's own rule - // (`navPayloadOf` leaves exactly these entries out), and an authored - // label still renders verbatim. - const incomplete = isIncompleteNavEntry(node); - const untitled = node.label === undefined && incomplete; - // objectui#7254 — a nav item with no declared label used to render an - // EMPTY row. It shows what it inherits (objectui#11196): its target's - // current label, else the target's internal name, which is the - // fallback #7254 chose. `surface?.name` stays for a label that is - // present but resolves to nothing (an empty map). - const rowText = untitled ? tFormat('engine.appNav.item', locale, { n: i + 1 }) : labelText || surface?.name || ''; - // Icon precedence: the nav item's own `icon`, then an object surface's - // own metadata icon, then the type-generic fallback. - const objIcon = surface?.type === 'object' ? objectIcons?.[surface.name] : undefined; - const Icon: React.ElementType = node.icon ? getIcon(node.icon) : objIcon ? getIcon(objIcon) : navIcon(node.type); - // objectui#11774 — the ENTRY is active, not every entry of its target: - // compared by nav id when both carry one (see `isSameSurface`). - const isActive = !!surface && !!active && isSameSurface(active, surface); - const kind = navKindName(node, locale); - return ( - surface && onPick(surface)} - disabled={!surface} - active={isActive} - indent={depth > 0} - // objectui#11862 — the label is what the row says; the machine - // name is the secondary information, on the tooltip with the type. - title={ - surface - ? `${surface.type} · ${surface.name}` - : incomplete - ? t('engine.appNav.incompleteHint', locale) - : rowText || undefined - } - className="disabled:opacity-40" - // objectstack#35985 — an object entry draws its object's tile: the - // glyph as above, the colour always the object's (as the menu). - icon={ - surface?.type === 'object' ? ( - - ) : ( - - ) - } - trailing={ - <> - {/* objectui#11791 — the spec's `badge` / `badgeVariant`, drawn - when the sidebar row draws them (a present `badge`, a count - `0` included) with the same `Badge` and the same variant: an - absent `badgeVariant` is `Badge`'s own default, which is the - sidebar's. On every leaf, a disabled one too; never on a - group heading, where the sidebar draws none. Before the kind - tag, so the pill sits beside the text it qualifies. */} - {node.badge != null && ( - - {node.badge} - - )} - {kind && ( - - {kind} - - )} - {/* An entry with no target yet (`isIncompleteNavEntry`): the - editor keeps it, marked, until it is bound or removed. */} - {incomplete && ( - - {t('engine.appNav.incomplete', locale)} - - )} - {surface && } - - } - > - {rowText} - - ); - })} - - ); -} - -/** - * objectstack#26889 — the item types the Interfaces pillar lists under the - * navigation tree, in the order of their sections: the three a nav entry can - * open by name, in the "+" menu's order, then views, which a package ships by - * the dozen and so sit last. - */ -export const OFF_NAV_TYPES = ['page', 'dashboard', 'report', 'view'] as const; -export type OffNavType = (typeof OFF_NAV_TYPES)[number]; - -/** An item's identity in {@link navOpenedItems}' set. Not a cache key. */ -export const itemKeyOf = (type: string, name: string): string => `${type}:${name}`; - -/** - * The `type:name` of every item a nav entry in `nodes` opens, at any depth — - * what the sections under the tree leave out, so no item is listed twice. The - * binding is the tree's own (`resolveSurface`): a page / dashboard / report - * entry opens the item it names, and an `object` entry with a `viewName` opens - * that view, under the name its view item carries (`.`, the - * spelling the entry's list-view panel edits, `listViewTargetOf`). A plain - * `object` entry opens its object, so the object's views stay listed. - */ -export function navOpenedItems(nodes: readonly NavNode[], locale: string): Set { - const opened = new Set(); - const walk = (list: readonly NavNode[]) => { - for (const node of list) { - if (Array.isArray(node.children) && node.children.length) { - walk(node.children); - continue; - } - const surface = resolveSurface(node, locale); - if (!surface) continue; - opened.add(itemKeyOf(surface.type, surface.name)); - if (surface.type === 'object' && typeof node.viewName === 'string' && node.viewName) { - opened.add(itemKeyOf('view', listViewTargetOf(surface.name, node.viewName, {}).viewId)); - } - } - }; - walk(nodes); - return opened; -} - -/** - * objectstack#30046 — whether the 视图 group leaves `item` out: a list view - * whose object a nav entry opens (`opened`, {@link navOpenedItems}), which the - * entry's header dropdown reaches. A form view, a list view of an object no - * entry opens, and a view whose family or object is unknown stay listed, as - * does a view a read-only base's pair adds (`addedIn`), which opens at that - * pair. - */ -export function offNavViewReachedByEntry( - item: Pick & { addedIn?: string }, - opened: ReadonlySet, -): boolean { - return item.viewKind === 'list' && !!item.object && !item.addedIn && opened.has(itemKeyOf('object', item.object)); -} - -/** - * objectstack-ai/objectstack#36425 — whether the 视图 group leaves `item` out - * as an internal create / edit form (`internalForm`: the object's default or - * `OBJECT.create` form, not shared publicly). The console no longer loads one, - * so the Studio does not list it. A public form stays listed, as do a named - * form an action opens and a view whose body is unknown (a draft-only row). - */ -export function offNavViewIsInternalForm(item: Pick): boolean { - return item.internalForm === true; -} - -/** - * objectstack#30046 — the 视图 group's heading, saying what it holds once - * the list views the dropdowns reach are gone: form views, list views (of - * objects no entry opens), or both. - */ -export function offNavViewHeading(items: ReadonlyArray>, locale: string): string { - const forms = items.filter((item) => item.viewKind === 'form').length; - if (forms === 0) return t('engine.studio.if.offNav.view', locale); - return t(forms === items.length ? 'engine.studio.if.offNav.viewForms' : 'engine.studio.if.offNav.viewMixed', locale); -} - -/** - * objectstack#30046 — what a 视图 row reads: the view's label, else, for a - * form view, its object's name and the word for a form ("Lead form"; a named - * form adds its key), never the item name (`crm_lead.form`). `objectLabel` is - * the object's name as the Studio shows it. A list view without a label keeps - * its item name, as before. - */ -export function offNavViewLabel(item: PackageSurface, objectLabel: string, locale: string): string { - const own = item.label && item.label !== item.name ? item.label : ''; - if (own || item.viewKind !== 'form') return own || item.name; - const form = tFormat('engine.studio.if.offNav.formName', locale, { object: objectLabel }); - const prefix = item.object ? `${item.object}.` : ''; - const key = prefix && item.name.startsWith(prefix) ? item.name.slice(prefix.length) : item.name; - return key === 'form' ? form : `${form} · ${key}`; -} - -/** - * objectstack#26889 — the package's pages, dashboards, reports and views that - * no nav entry opens (`navOpenedItems`), one collapsible section per type, - * under the navigation tree. A package with no app lists everything it ships - * here, under its "no app yet" notice. A row opens its item in the pillar's - * canvas and inspector as a tree row does, so a read-only package shows it - * read-only. Listing writes nothing: no nav entry is added for a row. - */ -export function OffNavSections({ - sections, - active, - activeViewId = null, - onPick, - onlyCustomized = false, -}: { - /** - * objectstack#30046 — a section may name itself (`label`): the 视图 group - * says what it holds. Without one, the type's own heading. - */ - sections: ReadonlyArray<{ type: OffNavType; label?: string; items: ReadonlyArray }>; - active: Surface | null; - /** - * objectstack#30046 — the list view the open object page shows, when that - * page was opened from here (an object no entry opens): its row is the - * active one, as a tree row is for its entry. - */ - activeViewId?: string | null; - onPick: (s: Surface) => void; - /** objectstack#28572 — "only customizations" is on: the sections list the marked items, and head nothing. */ - onlyCustomized?: boolean; -}): React.ReactElement | null { - const locale = useMetadataLocale(); - const shown = sections.filter((s) => s.items.length > 0); - if (shown.length === 0) return null; - return ( -
- {!onlyCustomized && ( -

{t('engine.studio.if.offNav.heading', locale)}

- )} - {shown.map((s) => ( - - ))} -
- ); -} - -/** One type's section: its rows, open until the author closes it. */ -function OffNavSection({ - type, - label, - items, - active, - activeViewId, - onPick, -}: { - type: OffNavType; - label?: string; - items: ReadonlyArray; - active: Surface | null; - activeViewId: string | null; - onPick: (s: Surface) => void; -}): React.ReactElement { - const locale = useMetadataLocale(); - const railMarks = React.useContext(InterfacesRailMarksContext); - const [open, setOpen] = React.useState(true); - const Icon = navIcon(type); - return ( - setOpen((v) => !v)} - > - {items.map((item) => { - // objectstack#28572 — an item the pair adds opens at that pair. - const surface: Surface = { - type: item.type, - name: item.name, - label: item.label, - ...(item.addedIn ? { addedIn: item.addedIn } : {}), - }; - return ( - onPick(surface)} - active={(!!active && isSameSurface(active, surface)) || (type === 'view' && item.name === activeViewId)} - indent - // The label is what the row says; the machine name rides on the - // tooltip with the type, as on a tree row (objectui#11862). - title={`${item.type} · ${item.name}`} - icon={} - trailing={} - > - {item.label || item.name} - - ); - })} - - ); -} - -/** - * objectstack#30059 (ADR-0146 D2, D3) — the Interfaces rail's mark for an app - * whose navigation a read-only base's pair overrides. The override is the - * app's, a whole copy, never one entry's, so the mark sits beside the rail's - * heading rather than on a row: the compact "customized" glyph every rail row - * carries ({@link CustomizationMark}), never a text label. - * - * Pressing it opens a small popover that says what the app overrides and the - * version it was taken from and, for an override the pair holds - * (`onRestore`), offers "Restore package original". That button only asks: - * the host opens its confirmation (`StudioRestoreOriginalDialog`), as the item - * header's override mark does (`StudioOverrideChip`). - * - * Drawn from a served declaration (`useServedOverride`), ⛔ never a - * computation: no diff against the base's navigation. - */ -export function InterfacesNavOverrideMark({ - baseLabel, - pairId, - basedOn, - locale, - onRestore, - restoreDisabled = false, -}: { - baseLabel: string; - /** The pair, named in the mark's tooltip; empty while it is not known. */ - pairId: string; - basedOn: string; - locale: string; - /** Opens the host's Restore confirmation; omitted, the popover states the facts alone. */ - onRestore?: () => void; - restoreDisabled?: boolean; -}): React.ReactElement { - const [open, setOpen] = React.useState(false); - return ( - - - - - -

- {tFormat('engine.studio.customize.overrides', locale, { package: baseLabel })} -

-

- {tFormat('engine.studio.customize.overridesTitle', locale, { package: baseLabel, basedOn })} -

- {onRestore && ( - - )} -
-
- ); -} diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.canvasDraftOnly-12508.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.canvasDraftOnly-12508.test.tsx deleted file mode 100644 index 6c25a6a02a2..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.canvasDraftOnly-12508.test.tsx +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#12508 — the Interfaces canvas does not mount the runtime records - * grid for an object that has only a draft. - * - * Measured on the card's session (HotCRM, a writable package): New object - * (saved as a draft), Create app, and the canvas of the object's entry sent - * `GET /api/v1/meta/object/st_ticket` → 404, logged - * `[useSettledSchema] getObjectSchema failed … MetadataNotFoundError` twice, - * and showed "Error loading grid". The default object canvas renders - * `object-view`, whose `ObjectView` asks the object's schema on mount; its - * records read (`/data/st_ticket`) answers 404 `OBJECT_NOT_FOUND` too. Preview - * = runtime, and a draft-only object has no runtime yet. - * - * The pillar already reads the package's published objects and drafts - * (stamped with the `publishNonce` the read ran under). It hands the canvas - * those names through `StudioCanvasDraftOnlyObjectsContext`; the default - * canvas shows an empty state for a draft-only object. - * - * The REAL `InterfacesPillar` and the REAL default canvas. `object-view` is a - * recorder registered in the component registry: its mount stands for - * `ObjectView`'s schema read, so "no mount" is "no `/meta/object` request". - * - * Pinned: - * - a draft-only object: the empty state, and no `object-view` mount; - * - CONTROL: a published object mounts `object-view`, as before; - * - a publish (`publishNonce` bumped): the answer read under the earlier - * publish is not used, so the just-published object is never shown as - * unpublished, and the grid mounts once the re-read answers, no reload. - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; -import { ComponentRegistry } from '@object-ui/core'; - -const PKG = 'com.default.studio-test'; -const DRAFT_ONLY = 'st_ticket'; -const PUBLISHED = 'st_case'; - -const NAV = [ - { id: 'nav_ticket', type: 'object', label: 'Tickets', objectName: DRAFT_ONLY }, - { id: 'nav_case', type: 'object', label: 'Cases', objectName: PUBLISHED }, -]; - -const defOf = (name: string) => ({ name, label: name, fields: { title: { name: 'title', type: 'text' } } }); - -const state = { - published: [PUBLISHED] as string[], - /** Set to hold the package's published-objects read until released. */ - holdObjectList: null as Promise | null, -}; - -const mockClient = { - save: vi.fn(async () => ({})), - list: vi.fn(async (type: string) => { - if (type === 'app') return [{ name: 'tickets', label: 'Tickets' }]; - if (type === 'object') { - if (state.holdObjectList) await state.holdObjectList; - return state.published.map((name) => ({ name, label: name })); - } - return []; - }), - listDrafts: vi.fn(async (opts?: { type?: string }) => - opts?.type === 'object' && !state.published.includes(DRAFT_ONLY) ? [{ name: DRAFT_ONLY, label: 'Ticket' }] : [], - ), - layered: vi.fn(async (type: string, name: string) => { - if (type === 'app') return { effective: { name: 'tickets', label: 'Tickets', navigation: NAV } }; - if (type === 'object' && state.published.includes(name)) return { effective: defOf(name), code: defOf(name) }; - return { effective: null, code: null }; - }), - getDraft: vi.fn(async (type: string, name: string) => - type === 'object' && name === DRAFT_ONLY && !state.published.includes(DRAFT_ONLY) ? defOf(DRAFT_ONLY) : null, - ), - get: vi.fn(async () => undefined), - withPreviewDrafts() { - return this; - }, -}; - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; -}); - -vi.mock('./packages-io', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, fetchPackages: vi.fn(async () => []) }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useAdapter: () => ({}) }; -}); - -import { InterfacesPillar } from './StudioDesignSurface'; - -/** Every `object-view` the canvas mounted, by object: each is one `/meta/object/NAME` read in the running app. */ -const objectViewMounts: string[] = []; -function ObjectViewRecorder({ schema }: { schema: { objectName?: string } }) { - React.useEffect(() => { - objectViewMounts.push(String(schema.objectName)); - }, [schema.objectName]); - return
; -} - -beforeAll(() => { - ComponentRegistry.register('object-view', ObjectViewRecorder as never, { namespace: 'plugin-view' }); -}); - -beforeEach(() => { - objectViewMounts.length = 0; - state.published = [PUBLISHED]; - state.holdObjectList = null; -}); - -afterEach(cleanup); - -function pillar(publishNonce: number) { - return ( - - - - ); -} - -async function openLeaf(name: string) { - fireEvent.click(await screen.findByTitle(`object · ${name}`)); -} - -describe('InterfacesPillar canvas — a draft-only object has no runtime to preview (objectui#12508)', () => { - it('a draft-only object shows the not-published empty state and mounts no object-view', async () => { - render(pillar(0)); - await openLeaf(DRAFT_ONLY); - expect(await screen.findByTestId('studio-canvas-object-unpublished')).toHaveTextContent( - 'This object is not published yet', - ); - expect(screen.queryByTestId('object-view-recorder')).toBeNull(); - expect(objectViewMounts).toEqual([]); - }); - - it('CONTROL: a published object mounts the runtime object-view, as before', async () => { - render(pillar(0)); - await openLeaf(PUBLISHED); - expect(await screen.findByTestId('object-view-recorder')).toHaveAttribute('data-object', PUBLISHED); - expect(objectViewMounts).toEqual([PUBLISHED]); - expect(screen.queryByTestId('studio-canvas-object-unpublished')).toBeNull(); - }); - - it('after a publish, the answer read before it does not hide the object: the grid mounts once the re-read answers, no reload', async () => { - const { rerender } = render(pillar(0)); - await openLeaf(DRAFT_ONLY); - await screen.findByTestId('studio-canvas-object-unpublished'); - expect(objectViewMounts).toEqual([]); - - // The publish makes the draft live; the pillar's re-read is held, so the - // only answer the pillar has is the one read under publish 0. - let release!: () => void; - state.holdObjectList = new Promise((r) => { - release = r; - }); - state.published = [PUBLISHED, DRAFT_ONLY]; - rerender(pillar(1)); - - expect(await screen.findByTestId('studio-canvas-object-pending')).toBeInTheDocument(); - expect(screen.queryByTestId('studio-canvas-object-unpublished')).toBeNull(); - - await act(async () => { - release(); - }); - expect(await screen.findByTestId('object-view-recorder')).toHaveAttribute('data-object', DRAFT_ONLY); - expect(screen.queryByTestId('studio-canvas-object-unpublished')).toBeNull(); - expect(objectViewMounts).toEqual([DRAFT_ONLY]); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.componentListServedTitles-12688.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.componentListServedTitles-12688.test.tsx deleted file mode 100644 index 139a99a4619..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.componentListServedTitles-12688.test.tsx +++ /dev/null @@ -1,254 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#12688 — on a zh-CN session the dashboard property panel's component - * list draws the widget titles the server's `/meta` boundary localized, while - * every editor keeps the authored title. - * - * The list (`DashboardDefaultInspector`) drew each widget's title from the - * leaf's buffer: the dashboard's pending draft, else its `/layers` code layer. - * No server localizes either, so the list read "Task Count vs Avg Progress" - * beside a served dashboard reading 任务数与平均进度. The console's metadata - * store already holds the `/meta` dashboard list, which the server answers - * translated (`translateDashboard`). The list now draws that answer's title for - * every widget whose authored title still equals the published one. - * - * The pillar is the real `InterfacesPillar`, with the real - * `DashboardDefaultInspector` and `DashboardWidgetInspector`, over a mocked - * metadata client answering as objectstack does: `layered('dashboard')` is the - * authored English layer. The metadata store (`MetadataCtx`) serves the - * dashboard list as the server answers it for the session's language. The - * canvas is a stub: the list and the inspectors are what is pinned, and the - * canvas's own pass is not this card's. - * - * - zh: the list draws 任务数与平均进度 for `combo_count_vs_progress`, and a - * widget the bundle leaves alone reads as authored; - * - zh: a widget whose title was edited in the draft, and one added there, - * draw their authored title beside a served sibling, and the published - * layer is read for that draft; - * - zh: the widget inspector's Title input keeps the authored title; - * - en: the served list repeats the authored titles, and the list reads as - * before. - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; -import { DashboardSchema } from '@objectstack/spec/ui'; -import { I18nProvider } from '@object-ui/i18n'; -import { MetadataCtx } from '@object-ui/react'; - -const PKG = 'com.example.showcase'; -const DASH = 'showcase_chart_gallery'; - -const NAV = [{ id: 'nav_charts', type: 'dashboard', label: 'Chart Gallery', dashboardName: DASH }]; - -const widget = (id: string, title: string) => ({ - id, - type: 'metric', - title, - dataset: 'tasks_ds', - values: ['task_count'], - layout: { x: 0, y: 0, w: 3, h: 2 }, -}); - -/** The published layer, as `/layers` serves it: authored, never localized. */ -const CODE = { - name: DASH, - label: 'Chart Gallery', - widgets: [ - widget('kpi_total', 'Total Tasks'), - widget('kpi_progress', 'Avg Progress'), - widget('combo_count_vs_progress', 'Task Count vs Avg Progress'), - ], -}; - -/** The same dashboard as the `/meta` dashboard list answers a zh-CN request (`translateDashboard`). */ -const SERVED_ZH = { - ...CODE, - widgets: [ - widget('kpi_total', '任务总数'), - widget('kpi_progress', 'Avg Progress'), - widget('combo_count_vs_progress', '任务数与平均进度'), - ], -}; - -/** What the server answers an en-US request: the showcase's English bundle repeats the authored title. */ -const SERVED_EN = JSON.parse(JSON.stringify(CODE)) as typeof CODE; - -/** The dashboard's pending draft: one translated widget retitled, one widget added. */ -function editedDraft() { - const draft = JSON.parse(JSON.stringify(CODE)) as typeof CODE; - draft.widgets[2] = { ...draft.widgets[2], title: 'Count vs Progress' }; - draft.widgets.push(widget('kpi_spent', 'Total Spent')); - return draft; -} - -const state: { served: unknown; draft: unknown } = { served: SERVED_ZH, draft: null }; - -const mockClient = { - // The Studio's dataset pickers read the draft-overlaid catalog (objectstack#27518). - withPreviewDrafts: vi.fn((): unknown => mockClient), - list: vi.fn(async (type: string) => (type === 'app' ? [{ name: 'showcase_app', label: 'Showcase' }] : [])), - listDrafts: vi.fn(async () => []), - layered: vi.fn(async (type: string) => { - if (type === 'app') return { effective: { name: 'showcase_app', label: 'Showcase', navigation: NAV } }; - // As the server serves an admitted author: the pending draft as stored (objectstack#30859). - if (type === 'dashboard') { - return { effective: JSON.parse(JSON.stringify(CODE)), draft: state.draft ? JSON.parse(JSON.stringify(state.draft)) : null }; - } - return { code: null, overlay: null, overlayScope: null, effective: null }; - }), - getDraft: vi.fn(async (type: string) => - type === 'dashboard' && state.draft ? { item: JSON.parse(JSON.stringify(state.draft)) } : null, - ), - save: vi.fn(async () => ({ success: true, version: 'v1', state: 'draft' })), - get: vi.fn(async () => undefined), -}; - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; -}); - -vi.mock('./packages-io', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, fetchPackages: vi.fn(async () => []) }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useAdapter: () => ({}) }; -}); - -// Pay the dynamic `@objectstack/lint` load at collection, never inside a case's -// clocked window (`check:test-source-alias`). -import '@objectstack/lint'; -import { InterfacesPillar } from './StudioDesignSurface'; -import { registerMetadataPreview } from '../metadata-admin/preview-registry'; -import { registerMetadataInspector } from '../metadata-admin/inspector-registry'; -import { registerMetadataDefaultInspector } from '../metadata-admin/default-inspector-registry'; -import { DashboardDefaultInspector } from '../metadata-admin/inspectors/DashboardDefaultInspector'; -import { DashboardWidgetInspector } from '../metadata-admin/inspectors/DashboardWidgetInspector'; - -// A stub canvas: the leaf needs a registered preview to be draft-editable, -// and the canvas's own drawing is not what this file pins. -registerMetadataPreview('dashboard', () => null); -registerMetadataDefaultInspector('dashboard', DashboardDefaultInspector); -registerMetadataInspector('dashboard', DashboardWidgetInspector); - -/** The console's metadata store: the `/meta` dashboard list as served for the session's language. */ -function metadataStore(served: unknown) { - return { - apps: [], - objects: [], - dashboards: [served], - reports: [], - pages: [], - loading: false, - error: null, - refresh: async () => {}, - invalidate: () => {}, - ensureType: async () => [], - getItem: async () => null, - getItemsByType: () => [], - getTypeStatus: () => 'ready' as const, - }; -} - -beforeEach(() => { - state.served = SERVED_ZH; - state.draft = null; - for (const fn of Object.values(mockClient)) fn.mockClear(); -}); - -afterEach(() => { - cleanup(); -}); - -/** Render the pillar in `language`, and return the dashboard's component list once `firstRow` is in it. */ -async function componentList(language: 'en' | 'zh', firstRow: string): Promise { - render( - - - - - - - , - ); - const inspector = await screen.findByTestId('if-inspector', undefined, { timeout: 8000 }); - await within(inspector).findByRole('button', { name: firstRow }, { timeout: 8000 }); - return inspector; -} - -/** The component list's rows, by the text of each row's title button (the one before its kind tag), in order. */ -function rows(inspector: HTMLElement): string[] { - return Array.from(inspector.querySelectorAll('[data-widget-kind]')).map( - (kind) => kind.previousElementSibling?.textContent ?? '', - ); -} - -describe('the objectui#12688 dashboard fixture is what the spec accepts', () => { - it('the authored layer, the zh-CN answer and the edited draft all parse against DashboardSchema', () => { - expect(DashboardSchema.safeParse(CODE).success).toBe(true); - expect(DashboardSchema.safeParse(SERVED_ZH).success).toBe(true); - expect(DashboardSchema.safeParse(editedDraft()).success).toBe(true); - }); -}); - -describe('objectui#12688 — the zh-CN component list draws the served widget titles', () => { - it('combo_count_vs_progress reads 任务数与平均进度, and a widget the bundle leaves alone reads as authored', async () => { - const inspector = await componentList('zh', '任务数与平均进度'); - - expect(rows(inspector)).toEqual(['任务总数', 'Avg Progress', '任务数与平均进度']); - expect(within(inspector).getByRole('button', { name: '任务数与平均进度' })).toHaveAttribute('title', '任务数与平均进度'); - expect(inspector).not.toHaveTextContent('Task Count vs Avg Progress'); - }); -}); - -describe('objectui#12688 — a widget changed or added in the draft draws its authored title', () => { - it('the retitled widget and the added one read as authored, beside a served sibling', async () => { - state.draft = editedDraft(); - // The served sibling is the row to wait for: it can draw only after the - // published layer, read once the draft is the buffer, has been paired. - const inspector = await componentList('zh', '任务总数'); - - expect(rows(inspector)).toEqual(['任务总数', 'Avg Progress', 'Count vs Progress', 'Total Spent']); - expect(inspector).not.toHaveTextContent('任务数与平均进度'); - // The draft is the buffer, so the published layer was read to pair with. - expect(mockClient.layered.mock.calls.filter((c) => c[0] === 'dashboard')).toHaveLength(1); - }); -}); - -/** - * objectstack#36373 restates this case: the inspector's Title box reads the - * title in the session's language, as the canvas and the list beside it do. - * objectui#12688 kept the authored English here because an edit then wrote - * the source; an edit now writes the session language's entry - * (`servedLabel.ts`), so the box can show what the page shows. - */ -describe('objectstack#36373 — the widget inspector reads the served title on the same zh-CN session', () => { - it("the widget inspector's Title input reads the served title, not the English source", async () => { - const inspector = await componentList('zh', '任务数与平均进度'); - - fireEvent.click(within(inspector).getByRole('button', { name: '任务数与平均进度' })); - - expect(await screen.findByDisplayValue('任务数与平均进度', undefined, { timeout: 8000 })).toHaveAttribute( - 'id', - 'widget-title', - ); - expect(screen.queryByDisplayValue('Task Count vs Avg Progress')).toBeNull(); - }); -}); - -describe('objectui#12688 — an English session reads as before', () => { - it('the en-US answer repeats the authored titles, and the list draws them unchanged', async () => { - state.served = SERVED_EN; - const inspector = await componentList('en', 'Task Count vs Avg Progress'); - - expect(rows(inspector)).toEqual(['Total Tasks', 'Avg Progress', 'Task Count vs Avg Progress']); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.customize-28562.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.customize-28562.test.tsx deleted file mode 100644 index f6fa555018d..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.customize-28562.test.tsx +++ /dev/null @@ -1,1079 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#28562 (ADR-0146 D2, D3) — on a read-only base, the Interfaces - * pillar customizes a view, dashboard or report (and an `object` leaf's list - * view) into the base's paired customization package. - * - * Through the mounted pillar, its real autosaves, the real header controls - * and the real ensure-door client (`ensureCustomizationPackage`) over a fetch - * stub that answers 201 when it creates the pair and 200 after. The metadata - * client is a server double holding the base's rows, the pair's rows and the - * pair's drafts, and recording every write. The pillar is handed what the - * Studio surface hands it (`StudioBaseCustomization`) by a host that, like - * the surface, takes the pair's id from the door's answer. - * - * Pinned: - * - Customize is offered on the base's item and writes nothing; the first - * saved edit asks the door once and writes the draft into the pair, with - * the override declared at the base's version and no `_` key, the base - * untouched; the badge then reads the served declaration; - * - a second item asks the door again and is answered 200; - * - a walled caller sees Customize disabled, and nothing is asked or sent; - * - Restore deletes the pair's draft and row of the item, and the base's - * item reads back, on a dashboard and on a list view; - * - the read-only mark does not link these types to Setup's overlay page; - * - CONTROL: a writable package edits and saves in place, with no door and - * no declaration. - * - * objectstack#30059 — and the app's navigation, through the rail's own nav - * editor: the first saved edit copies the whole app into the pair, declaring - * the override; the pickers offer the pair's items; the rail marks the - * override and counts it under "only customizations"; Restore deletes it. - * - * objectstack#30063 — and a page, through its designer as a dashboard is: - * the first saved edit copies the whole page into the pair, declaring the - * override; Restore deletes it; the rail marks the page and counts it under - * "only customizations"; on a writable package the page saves in place. - * - * objectstack#30089 — and a list view's selection actions: the first field - * update added in the list-view panel is written into the pair's copy of the - * view, declaring the override, the base untouched. - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; -import { ComponentRegistry } from '@object-ui/core'; -import { MetadataCtx, type MetadataContextValue } from '@object-ui/react'; - -const BASE = 'com.example.hotcrm'; -const PAIR = 'com.example.hotcrm.custom'; - -const OBJECT_DEF = { - name: 'opportunity', - label: 'Opportunity', - fields: { - name: { name: 'name', label: 'Name', type: 'text' }, - stage: { name: 'stage', label: 'Stage', type: 'text' }, - amount: { name: 'amount', label: 'Amount', type: 'currency' }, - close_date: { name: 'close_date', label: 'Close date', type: 'date' }, - start_date: { name: 'start_date', label: 'Start date', type: 'date' }, - }, -}; - -const NAV = [ - { id: 'nav_pipeline', type: 'dashboard', label: 'Pipeline', dashboardName: 'pipeline' }, - { id: 'nav_forecast', type: 'dashboard', label: 'Forecast', dashboardName: 'forecast' }, - { id: 'nav_opps', type: 'object', label: 'Opportunities', objectName: 'opportunity' }, -]; -const APP = { name: 'crm_app', label: 'CRM', navigation: NAV }; - -/** The base's rows as its read serves them: the protection envelope rides along. */ -const BASE_ROWS: Record> = { - 'app/crm_app': { ...APP, _packageId: BASE }, - 'dashboard/pipeline': { name: 'pipeline', label: 'Pipeline', widgets: [], _packageId: BASE }, - 'dashboard/forecast': { name: 'forecast', label: 'Forecast', widgets: [], _packageId: BASE }, - // objectstack#30063 — a page no navigation entry opens: the rail lists it under its type. - 'page/crm_welcome': { - name: 'crm_welcome', - label: 'Welcome', - type: 'home', - kind: 'full', - regions: [{ name: 'main', components: [{ type: 'element:text', properties: { content: 'Shipped text' } }] }], - _packageId: BASE, - }, - 'view/opportunity.default': { - name: 'opportunity.default', - object: 'opportunity', - viewKind: 'list', - label: 'Close dates', - isDefault: true, - config: { - type: 'calendar', - data: { provider: 'object', object: 'opportunity' }, - columns: ['name', 'stage'], - calendar: { startDateField: 'close_date', titleField: 'name' }, - }, - }, -}; - -const srv = vi.hoisted(() => ({ - base: new Map>(), - pairActive: new Map>(), - pairDrafts: new Map>(), - /** objectstack#30059 — what the pair's list read serves, by type. */ - pairListed: new Map>>(), - pairExists: false, - ensure: [] as number[], - ensureRefusal: null as null | { status: number; message: string }, - saves: [] as Array<{ type: string; name: string; body: Record; opts: Record }>, - resets: [] as Array<{ type: string; name: string; opts: Record }>, - version: 0, -})); - -const clone = (v: T): T => JSON.parse(JSON.stringify(v)) as T; -const k = (type: string, name: string) => `${type}/${name}`; - -const mockClient = vi.hoisted(() => ({ - list: vi.fn(async (type: string, opts: { packageId?: string } = {}) => { - if (opts.packageId === PAIR) return clone(srv.pairListed.get(type) ?? []); - if (type === 'app') return [{ name: 'crm_app', label: 'CRM' }]; - if (type === 'object') return [{ name: 'opportunity', label: 'Opportunity' }]; - if (type === 'page') return [{ name: 'crm_welcome', label: 'Welcome', _packageId: BASE }]; - return []; - }), - listDrafts: vi.fn(async () => []), - get: vi.fn(async (type: string) => (type === 'object' ? OBJECT_DEF : undefined)), - references: vi.fn(async () => []), - layered: vi.fn(async (type: string, name: string) => { - if (type === 'object') return { effective: OBJECT_DEF, code: OBJECT_DEF }; - // N-10: the pair's row is served over the base's item. - const overlay = srv.pairActive.get(k(type, name)) ?? null; - const code = srv.base.get(k(type, name)) ?? null; - return { - code: code ? clone(code) : null, - overlay: overlay ? clone(overlay) : null, - overlayScope: overlay ? 'env' : null, - effective: clone(overlay ?? code), - }; - }), - getDraft: vi.fn(async (type: string, name: string, opts: { packageId?: string } = {}) => { - const draft = opts.packageId === PAIR ? srv.pairDrafts.get(k(type, name)) : undefined; - return draft ? { type, name, item: clone(draft), version: `v${srv.version}` } : null; - }), - save: vi.fn(async (type: string, name: string, item: unknown, opts: Record = {}) => { - srv.saves.push({ type, name, body: clone(item) as Record, opts: clone(opts) }); - if (opts.packageId !== PAIR) { - throw Object.assign(new Error(`Package '${String(opts.packageId)}' is read-only.`), { status: 403 }); - } - srv.pairDrafts.set(k(type, name), clone(item) as Record); - srv.version += 1; - return { success: true, version: `v${srv.version}`, state: 'draft' }; - }), - reset: vi.fn(async (type: string, name: string, opts: Record = {}) => { - srv.resets.push({ type, name, opts: clone(opts) }); - if (opts.state === 'draft') srv.pairDrafts.delete(k(type, name)); - else srv.pairActive.delete(k(type, name)); - return { success: true }; - }), - withPreviewDrafts() { - return this; - }, -})); - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { - ...mod, - useMetadataClient: () => mockClient, - // Both take environment overlays, so the read-only mark would link them to Setup. - useMetadataTypes: () => ({ - loading: false, - error: null, - entries: [ - { type: 'dashboard', allowEnvironmentOverlay: true }, - { type: 'view', allowEnvironmentOverlay: true }, - ], - }), - }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useAdapter: () => ({}) }; -}); - -vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() } })); - -import { InterfacesPillar, type StudioBaseCustomization } from './StudioDesignSurface'; -import { ensureCustomizationPackage } from './packages-io'; -import { registerMetadataPreview } from '../metadata-admin/preview-registry'; -import { t, tFormat } from '../metadata-admin/i18n'; -import type { PackageCustomizationsState } from './CustomizationMark'; -import { indexCustomizations } from './customizationMarks'; - -/** The dashboard canvas, reduced to its label and one in-place edit. */ -function BoardCanvas({ draft, onPatch }: { draft: Record; onPatch?: (patch: Record) => void }) { - return ( -
-

{String(draft?.label ?? '')}

- -
- ); -} - -/** objectstack#30063 — the page designer, reduced to its first text block and one in-place edit of it. */ -function PageCanvas({ draft, onPatch }: { draft: Record; onPatch?: (patch: Record) => void }) { - const regions = (draft?.regions ?? []) as Array<{ name: string; components: Array<{ type: string; properties: { content: string } }> }>; - const content = regions[0]?.components[0]?.properties.content ?? ''; - return ( -
-

{content}

- -
- ); -} - -/** Stands in for `plugin-view`'s `object-view`, recording the schema the canvas hands it. */ -function ObjectViewRecorder({ schema }: { schema: Record }) { - return
{JSON.stringify(schema)}
; -} - -const METADATA: MetadataContextValue = { - apps: [], - objects: [OBJECT_DEF], - dashboards: [], - reports: [], - pages: [], - loading: false, - error: null, - refresh: async () => {}, - invalidate: () => {}, - ensureType: async () => [], - getItem: async () => null, - getItemsByType: () => [], -}; - -function json(body: unknown, status = 200): Response { - return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); -} - -beforeAll(() => { - registerMetadataPreview('dashboard', BoardCanvas as never); - registerMetadataPreview('page', PageCanvas as never); - ComponentRegistry.register('object-view', ObjectViewRecorder as never, { namespace: 'plugin-view' }); -}); - -beforeEach(() => { - srv.base.clear(); - for (const [key, row] of Object.entries(BASE_ROWS)) srv.base.set(key, clone(row)); - srv.pairActive.clear(); - srv.pairDrafts.clear(); - srv.pairListed.clear(); - srv.pairExists = false; - srv.ensure.length = 0; - srv.ensureRefusal = null; - srv.saves.length = 0; - srv.resets.length = 0; - srv.version = 0; - for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear?: () => void }).mockClear?.(); - vi.stubGlobal( - 'fetch', - vi.fn(async (input: unknown, init?: RequestInit) => { - const path = new URL(String(input), 'http://localhost').pathname; - if (path === `/api/v1/packages/${BASE}/ensure-customization` && init?.method === 'POST') { - if (srv.ensureRefusal) { - srv.ensure.push(srv.ensureRefusal.status); - return json({ success: false, error: { code: 'FORBIDDEN', message: srv.ensureRefusal.message } }, srv.ensureRefusal.status); - } - const created = !srv.pairExists; - srv.pairExists = true; - srv.ensure.push(created ? 201 : 200); - return json( - { - success: true, - data: { basePackageId: BASE, packageId: PAIR, namespace: 'hotcrm_custom', dependencyRange: '^4', created, writable: true }, - }, - created ? 201 : 200, - ); - } - return json([]); - }) as unknown as typeof fetch, - ); -}); - -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -const MARKS_OFF: PackageCustomizationsState = { status: 'off' }; - -/** What the Studio surface hands the pillar on a read-only base: the pair's id comes from the door's answer. */ -function Host({ - readOnly = true, - walled = false, - basedOn = '4.0.0', - listedPair = null, - marks = MARKS_OFF, -}: { - readOnly?: boolean; - walled?: boolean; - basedOn?: string | null; - listedPair?: string | null; - marks?: PackageCustomizationsState; -}) { - const [pairId, setPairId] = React.useState(listedPair); - const ensurePackage = React.useCallback(async () => { - const answer = await ensureCustomizationPackage(BASE); - setPairId(answer.packageId); - return answer; - }, []); - const ensure = React.useCallback(async () => (await ensurePackage()).packageId, [ensurePackage]); - const customization = React.useMemo( - () => - readOnly - ? { base: BASE, baseLabel: 'HotCRM', basedOn, walled, pairId, ensure, ensurePackage, marks } - : null, - [readOnly, basedOn, walled, pairId, ensure, ensurePackage, marks], - ); - return ; -} - -function mount(props: React.ComponentProps = {}) { - return render( - - - - - , - ); -} - -const header = () => screen.getByTestId('if-item-header'); -const patchBoard = () => fireEvent.click(screen.getByRole('button', { name: 'patch the board' })); -const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); - -/** The Pipeline dashboard open, as the pillar opens the first leaf. */ -async function openPipeline(): Promise { - await waitFor(() => expect(screen.getByTestId('board-label')).toHaveTextContent(/^Pipeline/), { timeout: 8000 }); -} - -async function openForecast(): Promise { - fireEvent.click(screen.getByRole('button', { name: /Forecast/ })); - await waitFor(() => expect(screen.getByTestId('board-label')).toHaveTextContent(/^Forecast/), { timeout: 8000 }); -} - -async function customize(): Promise { - fireEvent.click(await within(header()).findByTestId('studio-customize', undefined, { timeout: 8000 })); - await waitFor(() => expect(within(header()).queryByTestId('studio-customize')).toBeNull()); -} - -/** - * objectstack#29692 — Restore is asked from the override mark's popover, and - * confirmed in the same dialog the item menu opened before. - */ -async function openRestoreDialog(): Promise { - fireEvent.click(await within(header()).findByTestId('studio-override-chip', undefined, { timeout: 8000 })); - const popover = await screen.findByTestId('studio-override-popover'); - await waitFor(() => expect(within(popover).getByTestId('studio-override-restore')).toBeEnabled(), { timeout: 8000 }); - fireEvent.click(within(popover).getByTestId('studio-override-restore')); - return screen.findByTestId('studio-restore-original-dialog'); -} - -async function restore(): Promise { - fireEvent.click(within(await openRestoreDialog()).getByTestId('studio-restore-original-confirm')); -} - -describe('Customize a read-only base’s dashboard into its pair (objectstack#28562)', () => { - it('Customize is offered and writes nothing; until it is pressed the canvas edits nothing', async () => { - mount(); - await openPipeline(); - expect(within(header()).getByTestId('studio-customize')).toBeEnabled(); - - patchBoard(); - expect(screen.getByTestId('board-label')).toHaveTextContent(/^Pipeline$/); - - await customize(); - await sleep(2000); - expect(srv.ensure).toEqual([]); - expect(srv.saves).toEqual([]); - expect(within(header()).queryByTestId('studio-override-chip')).toBeNull(); - }); - - it('the first saved edit asks the door once and writes the pair’s draft, declaring the override; the base is untouched', async () => { - mount(); - await openPipeline(); - await customize(); - - patchBoard(); - await waitFor(() => expect(srv.saves).toHaveLength(1), { timeout: 8000 }); - expect(srv.ensure).toEqual([201]); - const [saved] = srv.saves; - expect(saved).toMatchObject({ type: 'dashboard', name: 'pipeline', opts: { mode: 'draft', packageId: PAIR } }); - expect(saved!.body).toStrictEqual({ - name: 'pipeline', - label: 'Pipeline (ours)', - widgets: [], - overrides: { package: BASE, basedOn: '4.0.0' }, - }); - expect(srv.base.get('dashboard/pipeline')).toStrictEqual(BASE_ROWS['dashboard/pipeline']); - - // The badge reads the declaration the pair's draft now serves. - const chip = await within(header()).findByTestId('studio-override-chip', undefined, { timeout: 8000 }); - expect(chip).toHaveTextContent(tFormat('engine.studio.customize.overrides', 'en', { package: 'HotCRM' })); - // objectstack#29692 — pressed, the mark says the version it was taken from. - fireEvent.click(chip); - expect(await screen.findByTestId('studio-override-popover-facts')).toHaveTextContent( - tFormat('engine.studio.customize.overridesTitle', 'en', { package: 'HotCRM', basedOn: '4.0.0' }), - ); - fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' }); - await waitFor(() => expect(screen.queryByTestId('studio-override-popover')).toBeNull()); - - // A later edit of the same item asks the door no more. - patchBoard(); - await waitFor(() => expect(srv.saves).toHaveLength(2), { timeout: 8000 }); - expect(srv.ensure).toEqual([201]); - expect(srv.saves[1]!.opts.packageId).toBe(PAIR); - }); - - it('the first save into the pair is pinned to "no draft there", the next to the version it was answered', async () => { - mount(); - await openPipeline(); - await customize(); - - patchBoard(); - await waitFor(() => expect(srv.saves).toHaveLength(1), { timeout: 8000 }); - expect(srv.saves[0]!.opts).toMatchObject({ packageId: PAIR, ifNoneMatch: '*' }); - expect(srv.saves[0]!.opts).not.toHaveProperty('ifMatch'); - - patchBoard(); - await waitFor(() => expect(srv.saves).toHaveLength(2), { timeout: 8000 }); - expect(srv.saves[1]!.opts).toMatchObject({ packageId: PAIR, ifMatch: 'v1' }); - expect(srv.saves[1]!.opts).not.toHaveProperty('ifNoneMatch'); - }); - - it('a second item asks the door again and is answered 200; it is written into the same pair', async () => { - mount(); - await openPipeline(); - await customize(); - patchBoard(); - await waitFor(() => expect(srv.saves).toHaveLength(1), { timeout: 8000 }); - - await openForecast(); - await customize(); - patchBoard(); - await waitFor(() => expect(srv.saves).toHaveLength(2), { timeout: 8000 }); - expect(srv.ensure).toEqual([201, 200]); - expect(srv.saves[1]).toMatchObject({ type: 'dashboard', name: 'forecast', opts: { packageId: PAIR } }); - expect(srv.saves[1]!.body.overrides).toEqual({ package: BASE, basedOn: '4.0.0' }); - }); - - it('a refused door is shown as the server sent it, and nothing is saved', async () => { - const sentence = 'Only the platform operator may create a customization package under the group posture.'; - srv.ensureRefusal = { status: 403, message: sentence }; - mount(); - await openPipeline(); - await customize(); - - patchBoard(); - await waitFor(() => expect(srv.ensure).toEqual([403]), { timeout: 8000 }); - // The envelope's sentence and code, as every package read here shows a refusal. - expect(await screen.findByTestId('studio-refusal-message', undefined, { timeout: 8000 })).toHaveTextContent( - `${sentence} (FORBIDDEN)`, - ); - expect(srv.saves).toEqual([]); - }); - - it('a walled caller sees Customize disabled, with the reason; nothing is asked or sent', async () => { - mount({ walled: true }); - await openPipeline(); - const button = within(header()).getByTestId('studio-customize'); - expect(button).toBeDisabled(); - expect(within(header()).getByTestId('studio-customize-blocked')).toHaveAttribute( - 'title', - t('engine.studio.customize.walled', 'en'), - ); - - fireEvent.click(button); - patchBoard(); - await sleep(2000); - expect(screen.getByTestId('board-label')).toHaveTextContent(/^Pipeline$/); - expect(srv.ensure).toEqual([]); - expect(srv.saves).toEqual([]); - }); - - it('a base whose listed manifest states no version: Customize is disabled, saying so', async () => { - mount({ basedOn: null }); - await openPipeline(); - expect(within(header()).getByTestId('studio-customize')).toBeDisabled(); - expect(within(header()).getByTestId('studio-customize-blocked')).toHaveAttribute('data-block', 'noVersion'); - }); - - it('the read-only mark does not link a dashboard to Setup’s overlay page', async () => { - mount(); - await openPipeline(); - const mark = within(header()).getByTestId('studio-readonly-link'); - expect(mark.tagName).toBe('SPAN'); - expect(mark).toHaveTextContent(t('engine.studio.pkg.readonly', 'en')); - }); -}); - -describe('Restore package original (objectstack#28562)', () => { - it('on a customized dashboard: the pair’s draft and row are deleted at the pair, and the base reads back', async () => { - srv.pairExists = true; - srv.pairActive.set('dashboard/pipeline', { - name: 'pipeline', - label: 'Pipeline (ours)', - widgets: [], - overrides: { package: BASE, basedOn: '4.0.0' }, - }); - mount({ listedPair: PAIR }); - await waitFor(() => expect(screen.getByTestId('board-label')).toHaveTextContent('Pipeline (ours)'), { timeout: 8000 }); - // Served as an override: badged, editable, and no Customize to press. - await within(header()).findByTestId('studio-override-chip', undefined, { timeout: 8000 }); - expect(within(header()).queryByTestId('studio-customize')).toBeNull(); - expect(within(header()).queryByTestId('studio-readonly-link')).toBeNull(); - - await restore(); - await waitFor(() => expect(srv.resets).toHaveLength(2), { timeout: 8000 }); - expect(srv.resets).toEqual([ - { type: 'dashboard', name: 'pipeline', opts: { state: 'draft', packageId: PAIR } }, - { type: 'dashboard', name: 'pipeline', opts: { packageId: PAIR } }, - ]); - await waitFor(() => expect(screen.getByTestId('board-label')).toHaveTextContent(/^Pipeline$/), { timeout: 8000 }); - await waitFor(() => expect(within(header()).queryByTestId('studio-override-chip')).toBeNull()); - expect(within(header()).getByTestId('studio-customize')).toBeInTheDocument(); - expect(srv.ensure).toEqual([]); - expect(srv.saves).toEqual([]); - }); - - it('Cancel deletes nothing', async () => { - srv.pairExists = true; - srv.pairActive.set('dashboard/pipeline', { - name: 'pipeline', - label: 'Pipeline (ours)', - widgets: [], - overrides: { package: BASE, basedOn: '4.0.0' }, - }); - mount({ listedPair: PAIR }); - fireEvent.click(within(await openRestoreDialog()).getByTestId('studio-restore-original-cancel')); - await sleep(300); - expect(srv.resets).toEqual([]); - }); - - it('objectstack#29692 — one door: the item’s ⋯ menu offers no Restore, and the dialog names the item as its rail row does', async () => { - srv.pairExists = true; - srv.pairActive.set('dashboard/pipeline', { - name: 'pipeline', - label: 'Pipeline (ours)', - widgets: [], - overrides: { package: BASE, basedOn: '4.0.0' }, - }); - mount({ listedPair: PAIR }); - await within(header()).findByTestId('studio-override-chip', undefined, { timeout: 8000 }); - fireEvent.pointerDown(screen.getByTestId('if-item-more'), { button: 0, ctrlKey: false }); - await screen.findByTestId('if-item-view-definition'); - expect(screen.queryByTestId('studio-restore-original')).toBeNull(); - fireEvent.keyDown(screen.getByTestId('if-item-view-definition'), { key: 'Escape' }); - await waitFor(() => expect(screen.queryByTestId('if-item-view-definition')).toBeNull()); - - const railRow = within(screen.getByTestId('studio-rail-interfaces')).getByRole('button', { name: /Pipeline/ }); - // The row's label, without the kind word the row prints after it. - const railText = railRow.querySelector('.flex-1')?.textContent?.trim() ?? ''; - expect(railText).toBe('Pipeline'); - const dialog = await openRestoreDialog(); - expect(within(dialog).getByRole('heading')).toHaveTextContent( - tFormat('engine.studio.customize.restoreConfirm', 'en', { package: 'HotCRM', item: railText }), - ); - fireEvent.click(within(dialog).getByTestId('studio-restore-original-cancel')); - }); -}); - -/** The calendar setting `key` of the list-view panel. */ -function setting(key: string): HTMLElement { - const control = document.getElementById(`mdf-studio-list-view-calendar.${key}`); - if (!control) throw new Error(`no calendar.${key} setting`); - return control; -} - -async function pick(key: string, text: string) { - await waitFor(() => expect(setting(key)).toBeEnabled(), { timeout: 8000 }); - fireEvent.keyDown(setting(key), { key: 'ArrowDown' }); - const listbox = await screen.findByRole('listbox'); - const hit = within(listbox) - .getAllByRole('option') - .find((o) => (o.querySelector('code')?.previousElementSibling?.textContent ?? o.textContent) === text); - if (!hit) throw new Error(`calendar.${key} lists no "${text}"`); - fireEvent.click(hit); -} - -async function openOpportunities(): Promise { - await openPipeline(); - fireEvent.click(screen.getByRole('button', { name: /Opportunities/ })); - await screen.findByTestId('studio-list-view-inspector', undefined, { timeout: 8000 }); - await waitFor(() => expect(setting('startDateField')).toHaveTextContent('Close date'), { timeout: 8000 }); -} - -/** Whether the header's view switcher (the title's ▾) offers New view; closes it again. */ -async function newViewOffered(): Promise { - fireEvent.click(within(header()).getByTestId('list-view-switcher')); - const menu = await screen.findByTestId('list-view-switcher-menu'); - const offered = within(menu).queryByTestId('list-view-switcher-new') !== null; - fireEvent.keyDown(menu, { key: 'Escape' }); - await waitFor(() => expect(screen.queryByTestId('list-view-switcher-menu')).toBeNull()); - return offered; -} - -const canvasSchema = () => JSON.parse(screen.getByTestId('object-view-schema').textContent ?? '{}') as Record; - -describe('Customize an object leaf’s list view into the pair (objectstack#28562)', () => { - it('the panel is read-only until Customize; the first edit writes the view’s draft into the pair, declaring the override', async () => { - mount(); - await openOpportunities(); - expect(setting('startDateField')).toBeDisabled(); - // A new view would be a new item of the base: the header's view switcher offers none. - expect(await newViewOffered()).toBe(false); - - await customize(); - expect(srv.ensure).toEqual([]); - await pick('startDateField', 'Start date'); - await waitFor(() => expect(srv.saves).toHaveLength(1), { timeout: 8000 }); - expect(srv.ensure).toEqual([201]); - const [saved] = srv.saves; - expect(saved).toMatchObject({ type: 'view', name: 'opportunity.default', opts: { mode: 'draft', packageId: PAIR } }); - expect((saved!.body.config as Record).calendar).toEqual({ startDateField: 'start_date', titleField: 'name' }); - expect(saved!.body.overrides).toEqual({ package: BASE, basedOn: '4.0.0' }); - // Read at the base before the pair was there: pinned to "no draft in the pair". - expect(saved!.opts).toMatchObject({ ifNoneMatch: '*' }); - expect(srv.base.get('view/opportunity.default')).toStrictEqual(BASE_ROWS['view/opportunity.default']); - await within(header()).findByTestId('studio-override-chip', undefined, { timeout: 8000 }); - expect(await newViewOffered()).toBe(false); - }); - - it('Restore brings back the base’s columns', async () => { - const base = BASE_ROWS['view/opportunity.default']!; - srv.pairExists = true; - srv.pairActive.set('view/opportunity.default', { - ...clone(base), - config: { ...(clone(base.config) as Record), columns: ['name', 'amount', 'stage'] }, - overrides: { package: BASE, basedOn: '4.0.0' }, - }); - mount({ listedPair: PAIR }); - await openPipeline(); - fireEvent.click(screen.getByRole('button', { name: /Opportunities/ })); - await waitFor(() => expect(JSON.stringify(canvasSchema())).toContain('amount'), { timeout: 8000 }); - await within(header()).findByTestId('studio-override-chip', undefined, { timeout: 8000 }); - - await restore(); - await waitFor(() => expect(srv.resets).toHaveLength(2), { timeout: 8000 }); - expect(srv.resets.map((r) => [r.type, r.name, r.opts])).toEqual([ - ['view', 'opportunity.default', { state: 'draft', packageId: PAIR }], - ['view', 'opportunity.default', { packageId: PAIR }], - ]); - await waitFor(() => expect(JSON.stringify(canvasSchema())).not.toContain('amount'), { timeout: 8000 }); - await waitFor(() => expect(within(header()).queryByTestId('studio-override-chip')).toBeNull()); - }); -}); - -describe('Customize a list view’s selection actions into the pair (objectstack#30089)', () => { - it('the first field update added on a read-only base is written into the pair’s copy, declaring the override', async () => { - const base = BASE_ROWS['view/opportunity.default']!; - const grid = { ...clone(base), config: { type: 'grid', data: { provider: 'object', object: 'opportunity' }, columns: ['name', 'stage'] } }; - srv.base.set('view/opportunity.default', grid); - mount(); - await openPipeline(); - fireEvent.click(screen.getByRole('button', { name: /Opportunities/ })); - const section = await screen.findByTestId('list-view-bulk', undefined, { timeout: 8000 }); - // Read-only until Customize: nothing to pick, nothing to add. - expect(within(section).queryByTestId('list-view-bulk-add-def')).toBeNull(); - - await customize(); - fireEvent.click(await within(screen.getByTestId('list-view-bulk')).findByTestId('list-view-bulk-add-def', undefined, { timeout: 8000 })); - const form = await screen.findByTestId('list-view-bulk-new-def'); - fireEvent.change(within(form).getByTestId('list-view-bulk-new-def-label'), { target: { value: 'Change stage' } }); - const fieldPick = document.getElementById('studio-list-view-bulk-new-def-field')!; - await waitFor(() => expect(fieldPick).toBeEnabled(), { timeout: 8000 }); - fireEvent.keyDown(fieldPick, { key: 'ArrowDown' }); - const listbox = await screen.findByRole('listbox'); - fireEvent.click(within(listbox).getAllByRole('option').find((o) => o.querySelector('code')?.textContent === 'stage')!); - fireEvent.click(within(form).getByTestId('list-view-bulk-new-def-add')); - - await waitFor(() => expect(srv.saves).toHaveLength(1), { timeout: 8000 }); - expect(srv.ensure).toEqual([201]); - const [saved] = srv.saves; - expect(saved).toMatchObject({ type: 'view', name: 'opportunity.default', opts: { mode: 'draft', packageId: PAIR } }); - expect((saved!.body.config as Record).bulkActionDefs).toEqual([ - { - name: 'update_stage', - label: 'Change stage', - operation: 'update', - params: [{ name: 'stage', label: 'Stage', type: 'text', required: true }], - }, - ]); - expect(saved!.body.overrides).toEqual({ package: BASE, basedOn: '4.0.0' }); - expect(saved!.opts).toMatchObject({ ifNoneMatch: '*' }); - expect(srv.base.get('view/opportunity.default')).toStrictEqual(grid); - }); -}); - -describe('CONTROL: a writable package is edited in place (objectstack#28562)', () => { - it('no Customize and no badge; an edit saves at the package with no declaration, and no door is asked', async () => { - srv.base.set('dashboard/pipeline', { name: 'pipeline', label: 'Pipeline', widgets: [] }); - mockClient.save.mockImplementationOnce(async (type: string, name: string, item: unknown, opts: Record = {}) => { - srv.saves.push({ type, name, body: clone(item) as Record, opts: clone(opts) }); - return { success: true, version: 'v1', state: 'draft' }; - }); - mount({ readOnly: false }); - await openPipeline(); - expect(within(header()).queryByTestId('studio-customize')).toBeNull(); - expect(within(header()).queryByTestId('studio-readonly-link')).toBeNull(); - - patchBoard(); - await waitFor(() => expect(srv.saves).toHaveLength(1), { timeout: 8000 }); - expect(srv.saves[0]).toMatchObject({ type: 'dashboard', name: 'pipeline', opts: { packageId: BASE } }); - expect(srv.saves[0]!.body).toStrictEqual({ name: 'pipeline', label: 'Pipeline (ours)', widgets: [] }); - expect(srv.ensure).toEqual([]); - expect(within(header()).queryByTestId('studio-override-chip')).toBeNull(); - }); -}); - -/* ───────────── objectstack#30059 — the app's navigation ───────────── */ - -/** The served app override of the base's app: the pair's whole copy, one entry added. */ -const CONTRACTS_ENTRY = { id: 'nav_contracts', type: 'object', label: 'Contracts', objectName: 'contract' }; -const APP_OVERRIDE = { ...APP, navigation: [...NAV, CONTRACTS_ENTRY], overrides: { package: BASE, basedOn: '4.0.0' } }; - -/** The base's customization read listing the app's override (what the server serves once it is published). */ -function marksListingTheApp(): PackageCustomizationsState { - const read = { - packageId: BASE, - overrides: [{ type: 'app', name: 'crm_app', basedOn: '4.0.0' }], - extensions: [], - switchedOff: [], - contributions: [], - counts: { overrides: 1, extensions: 0, switchedOff: 0 }, - } as never; - return { status: 'read', read, index: indexCustomizations(BASE, read)!, baseName: 'HotCRM', contributorNames: new Map() }; -} - -const rail = () => screen.getByTestId('studio-rail-interfaces'); - -/** The "+" menu's item `testId`, the menu opened first. */ -async function addFromMenu(testId: string): Promise { - fireEvent.pointerDown(await within(rail()).findByTestId('if-create-menu', undefined, { timeout: 8000 }), { - button: 0, - ctrlKey: false, - }); - fireEvent.click(await screen.findByTestId(testId)); -} - -/** Open the picker named `name` and return its listbox. */ -async function openPicker(name: string): Promise { - fireEvent.keyDown(screen.getByRole('combobox', { name }), { key: 'ArrowDown' }); - return screen.findByRole('listbox'); -} - -async function openNavRestoreDialog(): Promise { - fireEvent.click(await within(rail()).findByTestId('if-nav-override-mark', undefined, { timeout: 8000 })); - const popover = await screen.findByTestId('if-nav-override-popover'); - await waitFor(() => expect(within(popover).getByTestId('if-nav-override-restore')).toBeEnabled(), { timeout: 8000 }); - fireEvent.click(within(popover).getByTestId('if-nav-override-restore')); - return screen.findByTestId('studio-restore-original-dialog'); -} - -describe('Customize a read-only base’s navigation into its pair (objectstack#30059)', () => { - it('Edit is offered and writes nothing; the first saved edit copies the whole app into the pair, declaring the override; the base is untouched', async () => { - mount(); - await openPipeline(); - fireEvent.click(await within(rail()).findByTestId('if-edit-nav', undefined, { timeout: 8000 })); - expect(await within(rail()).findByTestId('if-nav-saved-to')).toBeInTheDocument(); - // objectstack#30436 — and the sheet's second sentence, naming the pair. - expect(within(rail()).getByTestId('if-nav-saved-to-environment')).toHaveTextContent( - 'These changes are kept in this environment’s database as items of com.example.hotcrm.custom, not in your project’s source. They reach another environment only through os package export.', - ); - await sleep(1500); - expect(srv.ensure).toEqual([]); - expect(srv.saves).toEqual([]); - fireEvent.click(within(rail()).getByTestId('if-edit-nav')); - await waitFor(() => expect(within(rail()).queryByTestId('if-nav-saved-to')).toBeNull()); - - // The "+" adds a navigation entry on the read-only base, as on a writable one. - await addFromMenu('if-add-nav-separator'); - await waitFor(() => expect(srv.saves).toHaveLength(1), { timeout: 8000 }); - expect(srv.ensure).toEqual([201]); - const [saved] = srv.saves; - // Read at the base before the pair was there: pinned to "no draft in the pair". - expect(saved).toMatchObject({ type: 'app', name: 'crm_app', opts: { mode: 'draft', packageId: PAIR, ifNoneMatch: '*' } }); - // The whole app, without the base's `_` keys, declaring the override at the base's version. - expect(saved!.body).toStrictEqual({ - name: 'crm_app', - label: 'CRM', - navigation: [...NAV, { id: 'nav_item_4', type: 'separator' }], - overrides: { package: BASE, basedOn: '4.0.0' }, - }); - expect(srv.base.get('app/crm_app')).toStrictEqual(BASE_ROWS['app/crm_app']); - - // The rail marks the override the pair's draft now serves. - fireEvent.click(await within(rail()).findByTestId('if-nav-override-mark', undefined, { timeout: 8000 })); - expect(await screen.findByTestId('if-nav-override-facts')).toHaveTextContent( - tFormat('engine.studio.customize.overridesTitle', 'en', { package: 'HotCRM', basedOn: '4.0.0' }), - ); - }); - - it('the pickers offer the pair’s items after the base’s; an entry bound to the pair’s object is saved into the pair gated on it', async () => { - srv.pairExists = true; - srv.pairListed.set('object', [{ name: 'contract', label: 'Contract' }]); - srv.pairListed.set('dashboard', [{ name: 'renewals', label: 'Renewals' }]); - mount({ listedPair: PAIR }); - await openPipeline(); - await addFromMenu('if-add-nav-object'); - - let listbox = await openPicker(t('engine.studio.nav.linkObject', 'en')); - await within(listbox).findByRole('option', { name: 'Contract (contract)' }, { timeout: 8000 }); - expect(within(listbox).getByRole('option', { name: 'Opportunity (opportunity)' })).toBeInTheDocument(); - fireEvent.click(within(listbox).getByRole('option', { name: 'Contract (contract)' })); - await waitFor(() => expect(srv.saves.length).toBeGreaterThan(0), { timeout: 8000 }); - await waitFor( - () => - expect(JSON.parse(JSON.stringify((srv.saves.at(-1)!.body.navigation as unknown[]).at(-1)))).toStrictEqual({ - id: 'nav_item_4', - type: 'object', - objectName: 'contract', - // The pair's object can be removed while the copy still names it: the entry gates on it. - requiresObject: 'contract', - }), - { timeout: 8000 }, - ); - expect(srv.saves.every((save) => save.opts.packageId === PAIR)).toBe(true); - expect(srv.saves.at(-1)!.body.overrides).toEqual({ package: BASE, basedOn: '4.0.0' }); - - // Rebound to an object the base ships, the entry carries no gate. - const saved = srv.saves.length; - listbox = await openPicker(t('engine.studio.nav.linkObject', 'en')); - fireEvent.click(within(listbox).getByRole('option', { name: 'Opportunity (opportunity)' })); - await waitFor(() => expect(srv.saves.length).toBeGreaterThan(saved), { timeout: 8000 }); - await waitFor( - () => - expect(JSON.parse(JSON.stringify((srv.saves.at(-1)!.body.navigation as unknown[]).at(-1)))).toStrictEqual({ - id: 'nav_item_4', - type: 'object', - objectName: 'opportunity', - }), - { timeout: 8000 }, - ); - - // A dashboard entry's picker offers the pair's dashboard. - const dashboardChoice = screen.getAllByRole('radio').find((r) => (r as HTMLInputElement).value === 'dashboard')!; - fireEvent.click(dashboardChoice); - listbox = await openPicker(t('engine.inspector.appNav.type.dashboard', 'en')); - expect(await within(listbox).findByRole('option', { name: /renewals/ }, { timeout: 8000 })).toBeInTheDocument(); - }); - - it('the rail marks a served override and counts it under "only customizations", which keeps the navigation', async () => { - srv.pairExists = true; - srv.pairActive.set('app/crm_app', clone(APP_OVERRIDE)); - mount({ listedPair: PAIR, marks: marksListingTheApp() }); - await openPipeline(); - const mark = await within(rail()).findByTestId('if-nav-override-mark', undefined, { timeout: 8000 }); - expect(within(mark).getByTestId('customization-mark')).toHaveAttribute('data-kind', 'customized'); - const only = await within(rail()).findByTestId('studio-rail-customizations-only', undefined, { timeout: 8000 }); - expect(only).toHaveTextContent(tFormat('engine.list.customizations.only', 'en', { marked: 1 })); - - fireEvent.click(only); - expect(only).toHaveAttribute('aria-pressed', 'true'); - expect(within(rail()).getByRole('button', { name: /Contracts/ })).toBeInTheDocument(); - expect(within(rail()).getByRole('button', { name: /Pipeline/ })).toBeInTheDocument(); - }); - - it('Restore deletes the pair’s draft and row of the app after a confirmation, and the base’s navigation reads back', async () => { - srv.pairExists = true; - srv.pairActive.set('app/crm_app', clone(APP_OVERRIDE)); - mount({ listedPair: PAIR }); - await openPipeline(); - await within(rail()).findByRole('button', { name: /Contracts/ }, { timeout: 8000 }); - - // Cancel deletes nothing. - fireEvent.click(within(await openNavRestoreDialog()).getByTestId('studio-restore-original-cancel')); - await sleep(300); - expect(srv.resets).toEqual([]); - - const dialog = await openNavRestoreDialog(); - expect(within(dialog).getByRole('heading')).toHaveTextContent( - tFormat('engine.studio.customize.restoreConfirm', 'en', { package: 'HotCRM', item: 'CRM' }), - ); - fireEvent.click(within(dialog).getByTestId('studio-restore-original-confirm')); - await waitFor(() => expect(srv.resets).toHaveLength(2), { timeout: 8000 }); - expect(srv.resets).toEqual([ - { type: 'app', name: 'crm_app', opts: { state: 'draft', packageId: PAIR } }, - { type: 'app', name: 'crm_app', opts: { packageId: PAIR } }, - ]); - await waitFor(() => expect(within(rail()).queryByRole('button', { name: /Contracts/ })).toBeNull(), { timeout: 8000 }); - await waitFor(() => expect(within(rail()).queryByTestId('if-nav-override-mark')).toBeNull()); - expect(within(rail()).getByTestId('if-edit-nav')).toBeInTheDocument(); - expect(srv.base.get('app/crm_app')).toStrictEqual(BASE_ROWS['app/crm_app']); - expect(srv.saves).toEqual([]); - }); - - it('a walled caller is offered neither the navigation edit nor the "+"', async () => { - mount({ walled: true }); - await openPipeline(); - await sleep(500); - expect(within(rail()).queryByTestId('if-edit-nav')).toBeNull(); - expect(within(rail()).queryByTestId('if-create-menu')).toBeNull(); - expect(srv.ensure).toEqual([]); - }); - - it('CONTROL: on a writable package the navigation saves at the package, with no door and no declaration', async () => { - srv.base.set('app/crm_app', clone(APP)); - mockClient.save.mockImplementationOnce(async (type: string, name: string, item: unknown, opts: Record = {}) => { - srv.saves.push({ type, name, body: clone(item) as Record, opts: clone(opts) }); - return { success: true, version: 'v1', state: 'draft' }; - }); - mount({ readOnly: false }); - await openPipeline(); - await addFromMenu('if-add-nav-separator'); - await waitFor(() => expect(srv.saves).toHaveLength(1), { timeout: 8000 }); - expect(srv.saves[0]).toMatchObject({ type: 'app', name: 'crm_app', opts: { packageId: BASE } }); - expect(srv.saves[0]!.body).toStrictEqual({ ...APP, navigation: [...NAV, { id: 'nav_item_4', type: 'separator' }] }); - expect(srv.ensure).toEqual([]); - expect(within(rail()).queryByTestId('if-nav-override-mark')).toBeNull(); - expect(within(rail()).queryByTestId('if-nav-saved-to')).toBeNull(); - }); -}); - -/* ───────────── objectstack#30063 — a page ───────────── */ - -const SHIPPED_REGIONS = BASE_ROWS['page/crm_welcome']!.regions; -const OURS_REGIONS = [{ name: 'main', components: [{ type: 'element:text', properties: { content: 'Shipped text (ours)' } }] }]; -/** The served page override: the pair's whole copy, its text changed. */ -const PAGE_OVERRIDE = { - name: 'crm_welcome', - label: 'Welcome', - type: 'home', - kind: 'full', - regions: OURS_REGIONS, - overrides: { package: BASE, basedOn: '4.0.0' }, -}; -const patchPage = () => fireEvent.click(screen.getByRole('button', { name: 'patch the page' })); - -/** The Welcome page open from its rail row, past the first leaf the pillar opens. */ -async function openWelcome(text: RegExp = /^Shipped text$/): Promise { - await openPipeline(); - fireEvent.click(await within(rail()).findByRole('button', { name: /Welcome/ }, { timeout: 8000 })); - await waitFor(() => expect(screen.getByTestId('page-text')).toHaveTextContent(text), { timeout: 8000 }); -} - -/** The base's customization read listing the page's override. */ -function marksListingThePage(): PackageCustomizationsState { - const read = { - packageId: BASE, - overrides: [{ type: 'page', name: 'crm_welcome', basedOn: '4.0.0' }], - extensions: [], - switchedOff: [], - contributions: [], - counts: { overrides: 1, extensions: 0, switchedOff: 0 }, - } as never; - return { status: 'read', read, index: indexCustomizations(BASE, read)!, baseName: 'HotCRM', contributorNames: new Map() }; -} - -describe('Customize a read-only base’s page into its pair (objectstack#30063)', () => { - it('Customize is offered and writes nothing; the first designer edit copies the whole page into the pair, declaring the override; the base is untouched', async () => { - mount(); - await openWelcome(); - expect(within(header()).getByTestId('studio-customize')).toBeEnabled(); - // Until it is pressed the designer edits nothing. - patchPage(); - expect(screen.getByTestId('page-text')).toHaveTextContent(/^Shipped text$/); - - await customize(); - await sleep(1500); - expect(srv.ensure).toEqual([]); - expect(srv.saves).toEqual([]); - - patchPage(); - await waitFor(() => expect(srv.saves).toHaveLength(1), { timeout: 8000 }); - expect(srv.ensure).toEqual([201]); - const [saved] = srv.saves; - // Read at the base before the pair was there: pinned to "no draft in the pair". - expect(saved).toMatchObject({ type: 'page', name: 'crm_welcome', opts: { mode: 'draft', packageId: PAIR, ifNoneMatch: '*' } }); - // The whole page, without the base's `_` keys, declaring the override at the base's version. - expect(saved!.body).toStrictEqual({ - name: 'crm_welcome', - label: 'Welcome', - type: 'home', - kind: 'full', - regions: OURS_REGIONS, - overrides: { package: BASE, basedOn: '4.0.0' }, - }); - expect(srv.base.get('page/crm_welcome')).toStrictEqual(BASE_ROWS['page/crm_welcome']); - await within(header()).findByTestId('studio-override-chip', undefined, { timeout: 8000 }); - - // The next designer edit saves into the pair's copy, at the version it was answered. - patchPage(); - await waitFor(() => expect(srv.saves).toHaveLength(2), { timeout: 8000 }); - expect(srv.ensure).toEqual([201]); - expect(srv.saves[1]!.opts).toMatchObject({ packageId: PAIR, ifMatch: 'v1' }); - expect(srv.saves[1]!.body.overrides).toEqual({ package: BASE, basedOn: '4.0.0' }); - }); - - it('a served override opens in the designer as the pair’s copy, editable, with no Customize to press', async () => { - srv.pairExists = true; - srv.pairActive.set('page/crm_welcome', clone(PAGE_OVERRIDE)); - mount({ listedPair: PAIR }); - await openWelcome(/^Shipped text \(ours\)$/); - await within(header()).findByTestId('studio-override-chip', undefined, { timeout: 8000 }); - expect(within(header()).queryByTestId('studio-customize')).toBeNull(); - - patchPage(); - await waitFor(() => expect(srv.saves).toHaveLength(1), { timeout: 8000 }); - expect(srv.saves[0]).toMatchObject({ type: 'page', name: 'crm_welcome', opts: { packageId: PAIR } }); - expect(srv.saves[0]!.body.overrides).toEqual({ package: BASE, basedOn: '4.0.0' }); - }); - - it('Restore deletes the pair’s draft and row of the page, and the shipped page reads back', async () => { - srv.pairExists = true; - srv.pairActive.set('page/crm_welcome', clone(PAGE_OVERRIDE)); - mount({ listedPair: PAIR }); - await openWelcome(/^Shipped text \(ours\)$/); - await restore(); - await waitFor(() => expect(srv.resets).toHaveLength(2), { timeout: 8000 }); - expect(srv.resets).toEqual([ - { type: 'page', name: 'crm_welcome', opts: { state: 'draft', packageId: PAIR } }, - { type: 'page', name: 'crm_welcome', opts: { packageId: PAIR } }, - ]); - await waitFor(() => expect(screen.getByTestId('page-text')).toHaveTextContent(/^Shipped text$/), { timeout: 8000 }); - await waitFor(() => expect(within(header()).queryByTestId('studio-override-chip')).toBeNull()); - expect(within(header()).getByTestId('studio-customize')).toBeInTheDocument(); - expect(srv.base.get('page/crm_welcome')!.regions).toStrictEqual(SHIPPED_REGIONS); - expect(srv.saves).toEqual([]); - }); - - it('the rail marks a customized page and counts it under "only customizations", which lists it', async () => { - srv.pairExists = true; - srv.pairActive.set('page/crm_welcome', clone(PAGE_OVERRIDE)); - mount({ listedPair: PAIR, marks: marksListingThePage() }); - await openPipeline(); - const row = await within(rail()).findByRole('button', { name: /Welcome/ }, { timeout: 8000 }); - await waitFor(() => expect(within(row).getByTestId('customization-mark')).toHaveAttribute('data-kind', 'customized'), { - timeout: 8000, - }); - const only = await within(rail()).findByTestId('studio-rail-customizations-only', undefined, { timeout: 8000 }); - expect(only).toHaveTextContent(tFormat('engine.list.customizations.only', 'en', { marked: 1 })); - - fireEvent.click(only); - expect(only).toHaveAttribute('aria-pressed', 'true'); - expect(within(rail()).getByRole('button', { name: /Welcome/ })).toBeInTheDocument(); - expect(within(rail()).queryByRole('button', { name: /Forecast/ })).toBeNull(); - }); - - it('CONTROL: on a writable package a page edit saves at the package, with no door and no declaration', async () => { - mockClient.save.mockImplementationOnce(async (type: string, name: string, item: unknown, opts: Record = {}) => { - srv.saves.push({ type, name, body: clone(item) as Record, opts: clone(opts) }); - return { success: true, version: 'v1', state: 'draft' }; - }); - mount({ readOnly: false }); - await openWelcome(); - expect(within(header()).queryByTestId('studio-customize')).toBeNull(); - patchPage(); - await waitFor(() => expect(srv.saves).toHaveLength(1), { timeout: 8000 }); - expect(srv.saves[0]).toMatchObject({ type: 'page', name: 'crm_welcome', opts: { packageId: BASE } }); - expect(srv.saves[0]!.body).not.toHaveProperty('overrides'); - expect(srv.saves[0]!.body.regions).toStrictEqual(OURS_REGIONS); - expect(srv.ensure).toEqual([]); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.customizePackagelessView-35600.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.customizePackagelessView-35600.test.tsx deleted file mode 100644 index 54a8a5620a4..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.customizePackagelessView-35600.test.tsx +++ /dev/null @@ -1,340 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#35600 (ADR-0146 D2, D11) — on a read-only base, an `object` - * leaf's page lists every list view of the object, and Customize declares an - * override of the BASE's view. The server refuses that declaration for a view - * the base does not ship (`NOT_OVERRIDABLE`, 403). So Customize is offered - * only on a view the base ships, read from the layered read at the base (its - * code layer): - * - * - a view created in the app (a package-less row: no code layer, an - * environment row) offers no Customize, sends nothing, and the panel says - * it is edited in the app; - * - a view nothing at the base serves (a view the pair adds) offers no - * Customize and sends nothing either; - * - CONTROL: the base's own view is still customized into the pair, - * declaring the override. - * - * Through the mounted pillar, the real header controls and the real - * ensure-door client over a fetch stub. The metadata client is a server - * double whose layered read answers as the server does for each kind of row, - * and whose draft door refuses an override of a view the base does not ship - * as the server does. - */ - -// Paid at collection, not inside a clocked case (check:test-source-alias). -import '@objectstack/lint'; -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; -import { ComponentRegistry } from '@object-ui/core'; -import { MetadataCtx, type MetadataContextValue } from '@object-ui/react'; - -const BASE = 'com.example.hotcrm'; -const PAIR = 'com.example.hotcrm.custom'; - -const calendarConfig = (startDateField: string) => ({ - type: 'calendar', - data: { provider: 'object', object: 'opportunity' }, - columns: ['name', 'stage'], - calendar: { startDateField, titleField: 'name' }, -}); - -/** The base's view: its layered read at the base serves a code layer. */ -const BASE_VIEW = { - name: 'opportunity.default', - object: 'opportunity', - viewKind: 'list', - label: 'Close dates', - isDefault: true, - config: calendarConfig('close_date'), -}; -/** A view created in the app (the console's New view): bound to no package, so no code layer and an environment row. */ -const ENV_VIEW = { - name: 'opportunity.console_made', - object: 'opportunity', - viewKind: 'list', - label: 'Console made', - config: calendarConfig('close_date'), -}; -/** A view the pair adds: the layered read at the base answers 404, which the client reads as all layers empty. */ -const PAIR_VIEW = { - name: 'opportunity.pair_added', - object: 'opportunity', - viewKind: 'list', - label: 'Pair added', - config: calendarConfig('close_date'), -}; - -/** The object as the shell's metadata serves it, its views merged in (`mergeViewsIntoObjects`). */ -const flat = (v: typeof BASE_VIEW | typeof ENV_VIEW) => ({ - ...v.config, - name: v.name, - label: v.label, - isDefault: 'isDefault' in v ? v.isDefault : false, -}); -const OBJECT_DEF = { - name: 'opportunity', - label: 'Opportunity', - fields: { - name: { name: 'name', label: 'Name', type: 'text' }, - stage: { name: 'stage', label: 'Stage', type: 'text' }, - close_date: { name: 'close_date', label: 'Close date', type: 'date' }, - start_date: { name: 'start_date', label: 'Start date', type: 'date' }, - }, - listViews: { - [BASE_VIEW.name]: flat(BASE_VIEW), - [ENV_VIEW.name]: flat(ENV_VIEW), - [PAIR_VIEW.name]: flat(PAIR_VIEW), - }, -}; - -const APP = { name: 'crm_app', label: 'CRM', navigation: [{ id: 'nav_opps', type: 'object', label: 'Opportunities', objectName: 'opportunity' }] }; - -const srv = vi.hoisted(() => ({ - ensure: [] as number[], - saves: [] as Array<{ type: string; name: string; body: Record; opts: Record }>, - refused: [] as Array<{ name: string; code: string; status: number }>, -})); - -const clone = (v: T): T => JSON.parse(JSON.stringify(v)) as T; - -const mockClient = vi.hoisted(() => ({ - list: vi.fn(async (type: string) => { - if (type === 'app') return [{ name: 'crm_app', label: 'CRM' }]; - if (type === 'object') return [{ name: 'opportunity', label: 'Opportunity' }]; - return []; - }), - listDrafts: vi.fn(async () => []), - get: vi.fn(), - references: vi.fn(async () => []), - layered: vi.fn(), - getDraft: vi.fn(async () => null), - save: vi.fn(), - reset: vi.fn(async () => ({ success: true })), - withPreviewDrafts() { - return this; - }, -})); - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { - ...mod, - useMetadataClient: () => mockClient, - useMetadataTypes: () => ({ loading: false, error: null, entries: [{ type: 'view', allowEnvironmentOverlay: true }] }), - }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useAdapter: () => ({}) }; -}); - -vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() } })); - -import { InterfacesPillar, type StudioBaseCustomization } from './StudioDesignSurface'; -import { ensureCustomizationPackage } from './packages-io'; -import { tFormat } from '../metadata-admin/i18n'; -import type { PackageCustomizationsState } from './CustomizationMark'; - -/** Stands in for `plugin-view`'s `object-view`. */ -function ObjectViewRecorder({ schema }: { schema: Record }) { - return
{JSON.stringify(schema)}
; -} - -const METADATA: MetadataContextValue = { - apps: [], - objects: [OBJECT_DEF], - dashboards: [], - reports: [], - pages: [], - loading: false, - error: null, - refresh: async () => {}, - invalidate: () => {}, - ensureType: async () => [], - getItem: async () => null, - getItemsByType: () => [], -}; - -function json(body: unknown, status = 200): Response { - return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); -} - -beforeAll(() => { - ComponentRegistry.register('object-view', ObjectViewRecorder as never, { namespace: 'plugin-view' }); -}); - -beforeEach(() => { - srv.ensure.length = 0; - srv.saves.length = 0; - srv.refused.length = 0; - for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear?: () => void }).mockClear?.(); - mockClient.get.mockImplementation(async (type: string) => (type === 'object' ? OBJECT_DEF : undefined)); - // The layered read at the base, as the server answers it for each kind of row (measured on a running server). - mockClient.layered.mockImplementation(async (type: string, name: string) => { - if (type === 'app') return { code: APP, overlay: null, overlayScope: null, effective: APP }; - if (type === 'object') return { code: OBJECT_DEF, overlay: null, overlayScope: null, effective: OBJECT_DEF }; - if (name === BASE_VIEW.name) return { code: clone(BASE_VIEW), overlay: null, overlayScope: null, effective: clone(BASE_VIEW) }; - if (name === ENV_VIEW.name) return { code: null, overlay: clone(ENV_VIEW), overlayScope: 'env', effective: clone(ENV_VIEW) }; - return { code: null, overlay: null, overlayScope: null, effective: null }; - }); - // The draft door: an override of a view the base does not ship is refused as the server refuses it. - mockClient.save.mockImplementation(async (type: string, name: string, item: unknown, opts: Record = {}) => { - const body = clone(item) as Record; - srv.saves.push({ type, name, body, opts: clone(opts) }); - if (body.overrides && name !== BASE_VIEW.name) { - srv.refused.push({ name, code: 'NOT_OVERRIDABLE', status: 403 }); - throw Object.assign(new Error(`'view/${name}' declares an override of '${BASE}', which ships no view named '${name}'.`), { - status: 403, - code: 'NOT_OVERRIDABLE', - }); - } - return { success: true, version: `v${srv.saves.length}`, state: 'draft' }; - }); - vi.stubGlobal( - 'fetch', - vi.fn(async (input: unknown, init?: RequestInit) => { - const path = new URL(String(input), 'http://localhost').pathname; - if (path === `/api/v1/packages/${BASE}/ensure-customization` && init?.method === 'POST') { - const created = srv.ensure.length === 0; - srv.ensure.push(created ? 201 : 200); - return json( - { - success: true, - data: { basePackageId: BASE, packageId: PAIR, namespace: 'hotcrm_custom', dependencyRange: '^4', created, writable: true }, - }, - created ? 201 : 200, - ); - } - return json([]); - }) as unknown as typeof fetch, - ); -}); - -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -const MARKS_OFF: PackageCustomizationsState = { status: 'off' }; - -/** What the Studio surface hands the pillar on a read-only base. */ -function Host() { - const [pairId, setPairId] = React.useState(null); - const ensurePackage = React.useCallback(async () => { - const answer = await ensureCustomizationPackage(BASE); - setPairId(answer.packageId); - return answer; - }, []); - const ensure = React.useCallback(async () => (await ensurePackage()).packageId, [ensurePackage]); - const customization = React.useMemo( - () => ({ base: BASE, baseLabel: 'HotCRM', basedOn: '4.0.0', walled: false, pairId, ensure, ensurePackage, marks: MARKS_OFF }), - [pairId, ensure, ensurePackage], - ); - return ; -} - -function mount() { - return render( - - - - - , - ); -} - -const header = () => screen.getByTestId('if-item-header'); -const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); - -function setting(key: string): HTMLElement { - const control = document.getElementById(`mdf-studio-list-view-calendar.${key}`); - if (!control) throw new Error(`no calendar.${key} setting`); - return control; -} - -async function pick(key: string, text: string) { - await waitFor(() => expect(setting(key)).toBeEnabled(), { timeout: 8000 }); - fireEvent.keyDown(setting(key), { key: 'ArrowDown' }); - const listbox = await screen.findByRole('listbox'); - const hit = within(listbox) - .getAllByRole('option') - .find((o) => (o.querySelector('code')?.previousElementSibling?.textContent ?? o.textContent) === text); - if (!hit) throw new Error(`calendar.${key} lists no "${text}"`); - fireEvent.click(hit); -} - -/** The Opportunities page open on its entry's view (the base's default). */ -async function openOpportunities(): Promise { - await screen.findByTestId('studio-list-view-inspector', undefined, { timeout: 8000 }); - await waitFor(() => expect(setting('startDateField')).toHaveTextContent('Close date'), { timeout: 8000 }); -} - -/** Pick the view labelled `label` in the header's view switcher. */ -async function pickView(label: string, viewId: string): Promise { - fireEvent.click(within(header()).getByTestId('list-view-switcher')); - const menu = await screen.findByTestId('list-view-switcher-menu'); - const hit = Array.from(menu.querySelectorAll('[data-testid^="view-switcher-row-"]')) - .map((row) => within(row).getAllByRole('button')[0]!) - .find((b) => b.textContent === label); - if (!hit) throw new Error(`the view switcher lists no "${label}"`); - fireEvent.click(hit); - await waitFor( - () => expect(screen.getByTestId('studio-list-view-inspector')).toHaveAttribute('data-view-id', viewId), - { timeout: 8000 }, - ); -} - -describe('Customize is offered only on a list view the read-only base ships (objectstack#35600)', () => { - it('a view created in the app: no Customize, nothing sent, and the panel says where it is edited', async () => { - mount(); - await openOpportunities(); - await pickView('Console made', ENV_VIEW.name); - - const note = await screen.findByTestId('list-view-read-only'); - await waitFor(() => expect(note).toHaveAttribute('data-reason', 'environment'), { timeout: 8000 }); - expect(note).toHaveTextContent(tFormat('engine.studio.inspector.listView.environmentView', 'en', { package: 'HotCRM' })); - expect(within(header()).queryByTestId('studio-customize')).toBeNull(); - expect(setting('startDateField')).toBeDisabled(); - - await sleep(1500); - expect(srv.ensure).toEqual([]); - expect(srv.saves).toEqual([]); - expect(srv.refused).toEqual([]); - }); - - it('a view nothing at the base serves (one the pair adds): no Customize, nothing sent', async () => { - mount(); - await openOpportunities(); - await pickView('Pair added', PAIR_VIEW.name); - - const note = await screen.findByTestId('list-view-read-only'); - await waitFor(() => expect(note).toHaveAttribute('data-reason', 'none'), { timeout: 8000 }); - expect(note).toHaveTextContent(tFormat('engine.studio.inspector.listView.notShipped', 'en', { package: 'HotCRM' })); - expect(within(header()).queryByTestId('studio-customize')).toBeNull(); - - await sleep(1500); - expect(srv.ensure).toEqual([]); - expect(srv.saves).toEqual([]); - }); - - it('CONTROL: the base’s own view is customized into the pair, declaring the override, and the save is not refused', async () => { - mount(); - await openOpportunities(); - expect(screen.getByTestId('list-view-read-only')).not.toHaveAttribute('data-reason'); - - fireEvent.click(await within(header()).findByTestId('studio-customize', undefined, { timeout: 8000 })); - await pick('startDateField', 'Start date'); - await waitFor(() => expect(srv.saves).toHaveLength(1), { timeout: 8000 }); - expect(srv.ensure).toEqual([201]); - const [saved] = srv.saves; - expect(saved).toMatchObject({ type: 'view', name: BASE_VIEW.name, opts: { mode: 'draft', packageId: PAIR } }); - expect(saved!.body.overrides).toEqual({ package: BASE, basedOn: '4.0.0' }); - expect(srv.refused).toEqual([]); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.editRailWidth-12519.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.editRailWidth-12519.test.tsx deleted file mode 100644 index 249f728395d..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.editRailWidth-12519.test.tsx +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#12519 (epic objectui#12446, decision 1) — editing the Interfaces - * navigation keeps the 240 px rail. - * - * Edit turned the rail into the navigation editor and widened it, so the - * content column and the inspector aside moved right on Edit and back on - * Done. The rail now carries `STUDIO_RAIL_WIDTH` in both modes, and the - * editor's rows carry an always-drawn remove control that Tab reaches. - * - * jsdom lays nothing out, so the width is read as the rail's class: the token - * the 240 px comes from. The rendered widths were read once in Chromium for - * the pull request; nothing here re-reads them. - */ -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen, fireEvent, cleanup, within } from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; -import { MemoryRouter } from 'react-router-dom'; - -const PKG = 'com.acme.app'; - -const NAV = [ - { id: 'nav_home', type: 'page', label: 'Home menu', pageName: 'home' }, - { - id: 'nav_work', - type: 'group', - label: 'Work', - expanded: true, - children: [{ id: 'nav_tasks', type: 'object', label: 'Tasks', objectName: 'acme_task' }], - }, -]; -const APP = { name: 'acme_app', label: 'Acme', navigation: NAV }; -const HOME = { name: 'home', label: 'Home', type: 'app', regions: [{ name: 'main', components: [] }] }; - -const server = vi.hoisted(() => ({ active: new Map>() })); - -const mockClient = vi.hoisted(() => { - const k = (type: string, name: string) => `${type}/${name}`; - return { - list: vi.fn(async (type: string) => - [...server.active.entries()] - .filter(([key]) => key.startsWith(`${type}/`)) - .map(([, row]) => ({ name: row.name, label: row.label ?? row.name })), - ), - listDrafts: vi.fn(async () => []), - listTypes: vi.fn(async () => ({ entries: [] })), - get: vi.fn(async () => null), - references: vi.fn(async () => []), - layered: vi.fn(async (type: string, name: string) => { - const eff = server.active.get(k(type, name)) ?? null; - return { code: null, overlay: eff, overlayScope: eff ? 'env' : null, effective: eff, editable: true, deletable: true, resettable: false, lock: 'none' }; - }), - getDraft: vi.fn(async (type: string, name: string) => { - throw Object.assign(new Error(`No pending draft exists for ${type}/${name}.`), { code: 'NO_DRAFT', status: 404 }); - }), - save: vi.fn(async (type: string, name: string, item: unknown) => ({ type, name, item })), - publish: vi.fn(async () => ({ success: true })), - reset: vi.fn(async () => ({})), - }; -}); - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; -}); - -vi.mock('./packages-io', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, fetchPackages: vi.fn(async () => []) }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useAdapter: () => ({}) }; -}); - -vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), dismiss: vi.fn() } })); - -import { InterfacesPillar } from './StudioDesignSurface'; -import { STUDIO_RAIL_WIDTH } from './studio-tokens'; -import { registerMetadataPreview } from '../metadata-admin/preview-registry'; -import { PagePreview } from '../metadata-admin/previews/PagePreview'; - -vi.stubGlobal( - 'fetch', - vi.fn(async () => new Response('null', { status: 404, headers: { 'content-type': 'application/json' } })), -); - -registerMetadataPreview('page', PagePreview); - -beforeEach(() => { - server.active.clear(); - server.active.set('app/acme_app', JSON.parse(JSON.stringify(APP))); - server.active.set('page/home', JSON.parse(JSON.stringify(HOME))); -}); - -afterEach(cleanup); - -/** The rail's width utilities: every `w-*` token on the `nav` element. */ -const widthClasses = (rail: HTMLElement) => rail.className.split(/\s+/).filter((c) => /^w-/.test(c)); - -async function openRail(): Promise { - render( - - undefined} /> - , - ); - const home = await screen.findByRole('button', { name: 'Home menu Page' }, { timeout: 8000 }); - return home.closest('nav') as HTMLElement; -} - -describe('objectui#12519 — the Interfaces rail keeps its width while the navigation is edited', () => { - it('the rail carries the same width class in and out of edit mode, and the content column stays its next sibling', async () => { - const rail = await openRail(); - const column = screen.getByTestId('if-content-column'); - expect(widthClasses(rail)).toEqual([STUDIO_RAIL_WIDTH]); - expect(rail.nextElementSibling).toBe(column); - - fireEvent.click(within(rail).getByRole('button', { name: /^Edit$/ })); - // Edit mode: the rail holds the navigation editor now. - expect(await within(rail).findAllByRole('button', { name: 'Remove nav item' })).not.toHaveLength(0); - expect(widthClasses(rail)).toEqual([STUDIO_RAIL_WIDTH]); - expect(rail.nextElementSibling).toBe(screen.getByTestId('if-content-column')); - - fireEvent.click(within(rail).getByRole('button', { name: /^Done$/ })); - await within(rail).findByRole('button', { name: 'Home menu Page' }); - expect(widthClasses(rail)).toEqual([STUDIO_RAIL_WIDTH]); - }); - - it('in edit mode each top-level row draws its remove control without a hover, and Tab reaches it after its row', async () => { - const user = userEvent.setup(); - const rail = await openRail(); - fireEvent.click(within(rail).getByRole('button', { name: /^Edit$/ })); - const removes = await within(rail).findAllByRole('button', { name: 'Remove nav item' }); - // One per top-level entry; a group's children are edited in the inspector. - expect(removes).toHaveLength(NAV.length); - for (const remove of removes) { - const classes = remove.className.split(/\s+/); - expect(classes).toContain('w-6'); - expect(classes).not.toContain('w-0'); - expect(classes).not.toContain('opacity-0'); - } - const row = removes[0].closest('button[aria-pressed]') as HTMLElement; - row.focus(); - await user.tab(); - expect(removes[0]).toHaveFocus(); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.formViewWarnings-29311.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.formViewWarnings-29311.test.tsx deleted file mode 100644 index 82ed9edebb2..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.formViewWarnings-29311.test.tsx +++ /dev/null @@ -1,206 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#29311 — a form view opened in Studio's Interfaces pillar hands - * its canvas the view's served warnings, and never saves them. - * - * Since objectstack#29196 the view read serves a section that names a field - * its object lacks as a `_diagnostics.warnings` entry (`{ path, message }`, - * path `config.sections.N.fields.M`). The pillar's leaf load took the body - * through `extractDraftBody`, which strips `_diagnostics` (a read decoration), - * and handed the canvas no verdict, so the form view canvas had nothing to - * show. The load now keeps the verdict before the strip, beside the body it - * judged, and passes it as the preview contract's `diagnostics`. - * - * The cases (harness: objectstack#28561's off-nav deep link): - * - a pending draft's warning reaches the canvas, at its path, with the - * server's message; - * - with no pending draft, the published layer's verdict is the one handed; - * - an empty `warnings`, or none, hands nothing; - * - once the author edits the value the warning judged, it is dropped (the - * pillar does not read the leaf again after an autosave), and the save - * that sends the edit carries no `_diagnostics`. - */ -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen, cleanup, fireEvent, waitFor } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; - -const PKG = 'com.acme.crm'; - -/** The lint's wording, as the server serves it (objectstack#29196). */ -const MESSAGE = - 'crm_lead.intake: field "no_such_field" is not a field on object "crm_lead" — it is silently skipped and never renders on the form'; -const WARNING = { path: 'config.sections.0.fields.1', message: MESSAGE }; - -const formView = { - name: 'crm_lead.intake', - label: 'Lead intake', - object: 'crm_lead', - viewKind: 'form', - config: { type: 'simple', sections: [{ name: 'overview', label: 'Overview', fields: ['name', 'no_such_field'] }] }, -}; - -/** What the mocked server holds: the published row, its layer's verdict, and a pending draft. */ -const server = vi.hoisted(() => ({ - published: new Map>>(), - layerDiagnostics: undefined as Record | undefined, - draft: null as Record | null, -})); - -const mockClient = vi.hoisted(() => ({ - list: vi.fn(async (type: string) => server.published.get(type) ?? []), - listDrafts: vi.fn(async () => []), - listTypes: vi.fn(async () => ({ entries: [] })), - get: vi.fn(async () => null), - references: vi.fn(async () => []), - layered: vi.fn(async (type: string, name: string) => { - const eff = (server.published.get(type) ?? []).find((row) => row.name === name) ?? null; - return { - code: null, - overlay: eff, - overlayScope: eff ? 'env' : null, - effective: eff, - // As the server serves an admitted author: the pending draft as stored (objectstack#30859). - // Stored, so without the read's `_diagnostics` decoration. - draft: server.draft ? Object.fromEntries(Object.entries(server.draft).filter(([key]) => !key.startsWith('_'))) : null, - editable: true, - deletable: true, - resettable: false, - lock: 'none', - ...(server.layerDiagnostics ? { _diagnostics: server.layerDiagnostics } : {}), - }; - }), - getDraft: vi.fn(async (type: string, name: string) => { - if (server.draft) return { type, name, item: server.draft }; - throw Object.assign(new Error(`No pending draft exists for ${type}/${name}.`), { code: 'NO_DRAFT', status: 404 }); - }), - save: vi.fn(async (type: string, name: string, item: unknown) => ({ type, name, item })), - publish: vi.fn(async () => ({ success: true })), - reset: vi.fn(async () => ({})), -})); - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useAdapter: () => ({}) }; -}); - -vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), dismiss: vi.fn() } })); - -// The `view` resource's list filter is registered here, as the console registers it. -import '../../services/builtinComponents'; -import { InterfacesPillar } from './StudioDesignSurface'; -import { registerMetadataPreview, type MetadataPreviewProps } from '../metadata-admin/preview-registry'; - -vi.stubGlobal( - 'fetch', - vi.fn(async () => new Response('null', { status: 404, headers: { 'content-type': 'application/json' } })), -); - -/** A canvas that lists the diagnostics it was handed, and renames the field the warning judged. */ -function StubPreview({ name, draft, diagnostics, onPatch }: MetadataPreviewProps) { - const config = (draft as { config?: { sections?: Array<{ fields: string[] }> } }).config; - return ( -
- {name} -
    - {(diagnostics ?? []).map((d, i) => ( -
  • - {d.message} -
  • - ))} -
- -
- ); -} -registerMetadataPreview('view', StubPreview); - -beforeEach(() => { - server.published.clear(); - server.published.set('view', [formView]); - server.layerDiagnostics = undefined; - server.draft = null; - for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear: () => void }).mockClear(); -}); - -afterEach(cleanup); - -function renderPillar() { - render( - - - , - ); -} - -const canvas = () => screen.findByTestId('stub-canvas', undefined, { timeout: 8000 }); -const handed = () => screen.queryAllByTestId('canvas-diagnostic'); - -describe('objectstack#29311 — the Interfaces pillar hands a form view its served warnings', () => { - it('a pending draft\'s warning reaches the canvas at its path, with the server\'s message', async () => { - server.draft = { ...formView, _diagnostics: { valid: true, warnings: [WARNING] } }; - renderPillar(); - await canvas(); - await waitFor(() => expect(handed()).toHaveLength(1)); - expect(handed()[0]).toHaveAttribute('data-path', WARNING.path); - expect(handed()[0]).toHaveAttribute('data-severity', 'warning'); - expect(handed()[0]).toHaveTextContent(MESSAGE); - }); - - it('with no pending draft, the published layer\'s verdict is the one handed', async () => { - server.layerDiagnostics = { valid: true, warnings: [WARNING] }; - renderPillar(); - await canvas(); - await waitFor(() => expect(handed()).toHaveLength(1)); - expect(handed()[0]).toHaveTextContent(MESSAGE); - }); - - it('an empty warnings list, or no _diagnostics at all, hands nothing', async () => { - server.draft = { ...formView, _diagnostics: { valid: true, warnings: [] } }; - renderPillar(); - await canvas(); - await waitFor(() => expect(mockClient.getDraft).toHaveBeenCalled()); - expect(handed()).toHaveLength(0); - cleanup(); - - server.draft = { ...formView }; - renderPillar(); - await canvas(); - expect(handed()).toHaveLength(0); - }); - - it('an edit to the judged value drops the warning, and its save carries no _diagnostics', async () => { - server.draft = { ...formView, _diagnostics: { valid: true, warnings: [WARNING] } }; - renderPillar(); - await canvas(); - await waitFor(() => expect(handed()).toHaveLength(1)); - - fireEvent.click(screen.getByRole('button', { name: 'fix field' })); - await waitFor(() => expect(handed()).toHaveLength(0)); - - await waitFor(() => expect(mockClient.save).toHaveBeenCalled(), { timeout: 8000 }); - const [type, name, item] = mockClient.save.mock.calls.at(-1)! as unknown as [string, string, Record]; - expect([type, name]).toEqual(['view', formView.name]); - expect(item).not.toHaveProperty('_diagnostics'); - expect(JSON.stringify(item)).not.toContain('_diagnostics'); - expect((item.config as { sections: Array<{ fields: string[] }> }).sections[0].fields).toEqual(['name', 'status']); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.heldListItem-27459.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.heldListItem-27459.test.tsx deleted file mode 100644 index c194537d902..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.heldListItem-27459.test.tsx +++ /dev/null @@ -1,207 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#27459 — the Interfaces pillar holds an item just added to a - * dashboard's own list property unsent until it is filled in, instead of - * autosaving it for the draft door to refuse. - * - * The card: Properties → Global Filters → "Add item", then a Label edit. The - * autosave PUT `globalFilters[N] = {}`, the door answered 422 on - * `globalFilters.N.field`, the Label save carried the same item and was refused - * too, and the Label edit was gone after a reload. The pillar now holds the - * dashboard as it holds a widget waiting for its binding (objectui#11910): - * nothing is sent, a neutral line names the input with a "Show me", and - * filling the item in lets the next autosave send every edit kept meanwhile. - * - * Mounted with a metadata client double that records every save, a stub - * canvas and the real `DashboardDefaultInspector` (its spec-driven form). - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; -import { DashboardSchema } from '@objectstack/spec/ui'; - -const NAV = [{ id: 'nav_sales', type: 'dashboard', label: 'Sales', dashboardName: 'sales_dash' }]; - -/** One bound widget and no list property yet: the dashboard parses with the spec as served. */ -const SALES_DASH = { - name: 'sales_dash', - label: 'Sales', - widgets: [ - { - id: 'pipeline', - type: 'metric', - title: 'Pipeline', - dataset: 'sales_ds', - values: ['revenue'], - layout: { x: 0, y: 0, w: 3, h: 2 }, - }, - ], -}; - -const mockClient = { - withPreviewDrafts: vi.fn((): unknown => mockClient), - save: vi.fn(async (_type: string, _name: string, _body: Record) => ({ - success: true, - version: 'v1', - state: 'draft', - })), - list: vi.fn(async (type: string) => { - if (type === 'app') return [{ name: 'acme_app', label: 'Acme' }]; - if (type === 'dashboard') return [SALES_DASH]; - return []; - }), - listDrafts: vi.fn(async () => []), - layered: vi.fn(async (type: string) => { - if (type === 'app') return { effective: { name: 'acme_app', label: 'Acme', active: true, navigation: NAV } }; - if (type === 'dashboard') return { effective: JSON.parse(JSON.stringify(SALES_DASH)) }; - return { code: null, overlay: null, overlayScope: null, effective: null }; - }), - getDraft: vi.fn(async () => null), - get: vi.fn(async () => undefined), -}; - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; -}); - -vi.mock('./packages-io', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, fetchPackages: vi.fn(async () => []) }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useAdapter: () => ({}) }; -}); - -import { InterfacesPillar } from './StudioDesignSurface'; -import { registerMetadataPreview } from '../metadata-admin/preview-registry'; -import { registerMetadataDefaultInspector } from '../metadata-admin/default-inspector-registry'; -import { DashboardDefaultInspector } from '../metadata-admin/inspectors/DashboardDefaultInspector'; -import { t, tFormat } from '../metadata-admin/i18n'; - -// A stub canvas: the leaf needs a registered preview to be draft-editable, -// and the canvas's own drawing is not what this file pins. -registerMetadataPreview('dashboard', () => null); -registerMetadataDefaultInspector('dashboard', DashboardDefaultInspector); - -beforeEach(() => { - for (const fn of Object.values(mockClient)) fn.mockClear(); -}); -afterEach(cleanup); - -function mountPillar(onHeldEditChange?: (clause: string | null) => void) { - return render( - - - , - ); -} - -function dashboardSaves(): Array> { - return mockClient.save.mock.calls.filter((c) => c[0] === 'dashboard').map((c) => c[2]); -} - -/** Past the autosave's 1.5 s debounce. */ -async function outlastDebounce(): Promise { - await act(async () => { - await new Promise((r) => setTimeout(r, 2300)); - }); -} - -/** The dashboard's properties are open, with its Filters section expanded: its Global Filters row is drawn. */ -async function ready(): Promise { - const inspector = await screen.findByTestId('if-inspector', undefined, { timeout: 8000 }); - fireEvent.click(await within(inspector).findByRole('button', { name: /^Filters/ }, { timeout: 8000 })); - await within(inspector).findByText('Global Filters', { selector: 'label' }, { timeout: 8000 }); - return inspector; -} - -/** The form row of the list property labelled `label`: its label and its repeater. */ -function listRow(inspector: HTMLElement, label: string): HTMLElement { - const row = within(inspector).getByText(label, { selector: 'label' }).parentElement?.parentElement; - if (!row) throw new Error(`no form row for ${label}`); - return row; -} - -/** The dashboard's own Label input commits on blur. */ -function editLabel(inspector: HTMLElement, value: string): void { - const input = within(inspector).getByDisplayValue('Sales'); - fireEvent.change(input, { target: { value } }); - fireEvent.blur(input); -} - -const clause = tFormat('engine.studio.held.listItemNeedsInput', 'en', { input: 'Field', n: 1, list: 'Global Filters' }); - -describe('an item just added to a dashboard list property is held until it is filled in (objectstack#27459)', () => { - it('Global Filters → Add item, then a Label edit: nothing is sent, no red strip, the line names the Field', async () => { - const report = vi.fn(); - mountPillar(report); - const inspector = await ready(); - fireEvent.click(within(listRow(inspector, 'Global Filters')).getByRole('button', { name: t('engine.form.addItem', 'en') })); - editLabel(inspector, 'Sales v2'); - await outlastDebounce(); - - expect(dashboardSaves(), 'the unfinished item is not sent, nor the Label edit with it').toEqual([]); - expect(screen.queryByTestId('studio-refusal'), 'no red strip on the normal path').toBeNull(); - expect(screen.getByTestId('studio-held-message')).toHaveTextContent( - tFormat('engine.studio.held.line', 'en', { clause }), - ); - // Publish's half: the surface is told what is held. - expect(report).toHaveBeenLastCalledWith(clause); - }); - - it('"Show me" focuses the list in the dashboard properties', async () => { - mountPillar(); - const inspector = await ready(); - const row = listRow(inspector, 'Global Filters'); - fireEvent.click(within(row).getByRole('button', { name: t('engine.form.addItem', 'en') })); - const show = await within(await screen.findByTestId('studio-held')).findByRole('button', { - name: t('engine.studio.refusal.show', 'en'), - }); - (document.activeElement as HTMLElement | null)?.blur(); - fireEvent.click(show); - await waitFor(() => expect(row.contains(document.activeElement)).toBe(true)); - }); - - it('filling the Field in sends one save carrying the item and the Label edit kept meanwhile, and clears the line', async () => { - const report = vi.fn(); - mountPillar(report); - const inspector = await ready(); - const row = listRow(inspector, 'Global Filters'); - fireEvent.click(within(row).getByRole('button', { name: t('engine.form.addItem', 'en') })); - editLabel(inspector, 'Sales v2'); - await outlastDebounce(); - expect(dashboardSaves()).toEqual([]); - - const field = within(row).getByLabelText('Field'); - fireEvent.change(field, { target: { value: 'stage' } }); - fireEvent.blur(field); - await waitFor(() => expect(dashboardSaves()).toHaveLength(1), { timeout: 4000 }); - const [sent] = dashboardSaves(); - expect(sent.label).toBe('Sales v2'); - expect(sent.globalFilters).toEqual([expect.objectContaining({ field: 'stage' })]); - expect( - DashboardSchema.safeParse(JSON.parse(JSON.stringify(sent))).success, - 'the body sent is one the door accepts', - ).toBe(true); - await waitFor(() => expect(screen.queryByTestId('studio-held')).toBeNull()); - expect(screen.queryByTestId('studio-refusal')).toBeNull(); - expect(report).toHaveBeenLastCalledWith(null); - }); - - // CONTROL: an edit to a dashboard with no unfinished item saves at once. - it('a Label edit alone saves at once, with no line', async () => { - mountPillar(); - const inspector = await ready(); - editLabel(inspector, 'Sales v2'); - await waitFor(() => expect(dashboardSaves()).toHaveLength(1), { timeout: 4000 }); - expect(dashboardSaves()[0].label).toBe('Sales v2'); - expect(screen.queryByTestId('studio-held')).toBeNull(); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.heldWidget-11910.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.heldWidget-11910.test.tsx deleted file mode 100644 index 7f1983cb308..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.heldWidget-11910.test.tsx +++ /dev/null @@ -1,448 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#11910 — the Interfaces pillar holds a new dashboard widget unsent - * until it is bound, instead of drawing a red refusal. - * - * The card: *Add widget* → *Metric* made the leaf autosave PUT the widget as - * `{ id, type, title }`, the draft door answered 422 on its `dataset` and - * `values`, and "Changes not saved" showed right after the click. The pillar now - * holds such a dashboard as the Data and Automations pillars hold theirs - * (objectui#11786): nothing is sent, the widget's inspector says what it needs, - * a neutral line on the canvas names it, and binding it lets the next autosave - * go. A finished widget the server refuses still shows the red strip. - * - * Mounted with a metadata client double that records every save, the real - * `DashboardPreview` canvas (its *Add widget* picker) and the real - * `DashboardWidgetInspector`. - * - * objectui#11951: removing a bound widget's last measure (or the last dimension - * a two-measure scatter needs) is held the same way, not sent as a shape the - * spec refuses; the second `describe` pins it through the inspector's own - * remove buttons. - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; -import { MemoryRouter } from 'react-router-dom'; -import { DashboardSchema } from '@objectstack/spec/ui'; -// Module-scope import of the lazily loaded canvas renderer (AGENTS.md, -// flaky-test discipline). -import '@object-ui/plugin-dashboard'; - -const NAV = [{ id: 'nav_sales', type: 'dashboard', label: 'Sales', dashboardName: 'sales_dash' }]; - -/** One bound widget: the dashboard parses with the spec as served. */ -const SALES_DASH = { - name: 'sales_dash', - label: 'Sales', - widgets: [ - { - id: 'pipeline', - type: 'metric', - title: 'Pipeline', - dataset: 'sales_ds', - values: ['revenue'], - layout: { x: 0, y: 0, w: 3, h: 2 }, - }, - ], -}; - -const DATASETS = [ - { - name: 'sales_ds', - label: 'Sales', - object: 'opportunity', - dimensions: [{ name: 'stage', label: 'Stage' }], - measures: [{ name: 'revenue', label: 'Revenue', aggregate: 'sum' }], - }, -]; - -/** The object a nav entry added in the last pin is bound to (objectui#11776). */ -const TASK = { name: 'acme_task', label: 'Task' }; - -let refuseDashboard: Error | null; -/** The dashboard the metadata double serves; objectui#11951's pins swap in their own. */ -let dashFixture: Record = SALES_DASH; - -const mockClient = { - // The Studio's dataset pickers read the draft-overlaid catalog (objectstack#27518). - withPreviewDrafts: vi.fn((): unknown => mockClient), - save: vi.fn(async (type: string, _name: string, _body: Record) => { - if (type === 'dashboard' && refuseDashboard) throw refuseDashboard; - return { success: true, version: 'v1', state: 'draft' }; - }), - list: vi.fn(async (type: string) => { - if (type === 'app') return [{ name: 'acme_app', label: 'Acme' }]; - if (type === 'dataset') return DATASETS; - if (type === 'dashboard') return [dashFixture]; - if (type === 'object') return [TASK]; - return []; - }), - listDrafts: vi.fn(async () => []), - layered: vi.fn(async (type: string) => { - if (type === 'app') return { effective: { name: 'acme_app', label: 'Acme', active: true, navigation: NAV } }; - if (type === 'dashboard') return { effective: JSON.parse(JSON.stringify(dashFixture)) }; - return { code: null, overlay: null, overlayScope: null, effective: null }; - }), - getDraft: vi.fn(async () => null), - get: vi.fn(async (type: string, name: string) => - type === 'dataset' ? DATASETS.find((d) => d.name === name) : undefined, - ), -}; - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; -}); - -vi.mock('./packages-io', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, fetchPackages: vi.fn(async () => []) }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useAdapter: () => ({}) }; -}); - -// Pay the dynamic `@objectstack/lint` load at collection, never inside a case's -// clocked window (`check:test-source-alias`). -import '@objectstack/lint'; -import { InterfacesPillar } from './StudioDesignSurface'; -import { registerMetadataPreview } from '../metadata-admin/preview-registry'; -import { registerMetadataInspector } from '../metadata-admin/inspector-registry'; -import { DashboardPreview } from '../metadata-admin/previews/DashboardPreview'; -import { DashboardWidgetInspector } from '../metadata-admin/inspectors/DashboardWidgetInspector'; -import { t, tFormat } from '../metadata-admin/i18n'; - -registerMetadataPreview('dashboard', DashboardPreview); -registerMetadataInspector('dashboard', DashboardWidgetInspector); - -beforeEach(() => { - refuseDashboard = null; - dashFixture = SALES_DASH; - for (const fn of Object.values(mockClient)) fn.mockClear(); -}); -afterEach(cleanup); - -function mountPillar(onHeldEditChange?: (clause: string | null) => void) { - return render( - - - , - ); -} - -function dashboardSaves(): Array> { - return mockClient.save.mock.calls.filter((c) => c[0] === 'dashboard').map((c) => c[2]); -} - -/** The right rail: the inspector's own aside (classic layout). */ -function rail(): HTMLElement { - return screen.getByRole('complementary'); -} - -/** Past the autosave's 1.5 s debounce. */ -async function outlastDebounce(): Promise { - await act(async () => { - await new Promise((r) => setTimeout(r, 2300)); - }); -} - -async function flush(): Promise { - await act(async () => { - await new Promise((r) => setTimeout(r, 0)); - }); -} - -/** The dashboard leaf is open on its canvas, in design mode. */ -async function ready(): Promise { - await screen.findByTitle('dashboard · sales_dash', undefined, { timeout: 8000 }); - await screen.findByRole('button', { name: t('engine.inspector.add.widget', 'en') }, { timeout: 8000 }); -} - -/** *Add widget* → *Metric (KPI)*: the canvas selects the new widget, whose inspector opens. */ -async function addMetric(): Promise { - await userEvent.click(screen.getByRole('button', { name: t('engine.inspector.add.widget', 'en') })); - await userEvent.click(await screen.findByRole('button', { name: /^Metric \(KPI\)/ })); - await within(rail()).findByDisplayValue('New metric (kpi)', undefined, { timeout: 8000 }); -} - -async function bindDataset(): Promise { - await userEvent.click(within(rail()).getByRole('combobox', { name: t('engine.inspector.widget.dataset', 'en') })); - await userEvent.click(await screen.findByRole('option', { name: 'Sales' })); - await flush(); -} - -/** The measures editor is the second "Add field" in the binding section (dimensions first). */ -async function addMeasure(): Promise { - const adds = await within(rail()).findAllByRole('button', { name: t('engine.form.addFieldPlain', 'en') }); - expect(adds.length, 'the dimensions and measures editors').toBe(2); - fireEvent.click(adds[1]); - const dialog = await screen.findByRole('dialog'); - fireEvent.click(within(dialog).getByText(/^Revenue/)); - await flush(); -} - -const heldLine = (input: string, widget = 'New metric (kpi)') => - tFormat('engine.studio.held.line', 'en', { - clause: tFormat('engine.studio.held.widgetNeedsInput', 'en', { input: t(input, 'en'), widget }), - }); - -describe('a new dashboard widget is held until it is bound (objectui#11910)', () => { - it('Add widget → Metric sends nothing and shows no red strip; the line and the inspector name the dataset', async () => { - const report = vi.fn(); - mountPillar(report); - await ready(); - await addMetric(); - await outlastDebounce(); - - expect(dashboardSaves(), 'the unbound widget is not sent').toEqual([]); - expect(screen.queryByTestId('studio-refusal'), 'no red strip on the normal path').toBeNull(); - expect(screen.getByTestId('studio-held-message')).toHaveTextContent(heldLine('engine.inspector.widget.dataset')); - expect(within(rail()).getByTestId('widget-field-held-hint-dataset')).toHaveTextContent( - t('engine.studio.held.inputHint', 'en'), - ); - // Publish's half: the surface is told what is held. - expect(report).toHaveBeenLastCalledWith( - tFormat('engine.studio.held.widgetNeedsInput', 'en', { - input: t('engine.inspector.widget.dataset', 'en'), - widget: 'New metric (kpi)', - }), - ); - }); - - it('a dataset moves the hold to the measures; a measure sends the save, which the spec accepts, and clears it', async () => { - const report = vi.fn(); - mountPillar(report); - await ready(); - await addMetric(); - await bindDataset(); - await outlastDebounce(); - expect(dashboardSaves()).toEqual([]); - expect(screen.getByTestId('studio-held-message')).toHaveTextContent(heldLine('engine.inspector.widget.values')); - expect(within(rail()).queryByTestId('widget-field-held-hint-dataset')).toBeNull(); - expect(within(rail()).getByTestId('widget-field-held-hint-values')).toBeInTheDocument(); - - await addMeasure(); - await waitFor(() => expect(dashboardSaves()).toHaveLength(1), { timeout: 4000 }); - const [sent] = dashboardSaves(); - expect((sent.widgets as unknown[])[1]).toMatchObject({ - id: 'widget_1', - type: 'metric', - dataset: 'sales_ds', - values: ['revenue'], - }); - expect(DashboardSchema.safeParse(sent).success, 'the body sent is one the door accepts').toBe(true); - await waitFor(() => expect(screen.queryByTestId('studio-held')).toBeNull()); - expect(within(rail()).queryByTestId('widget-field-held-hint-values')).toBeNull(); - expect(screen.queryByTestId('studio-refusal')).toBeNull(); - expect(report).toHaveBeenLastCalledWith(null); - }); - - it('"Show me" reopens the held widget after its inspector was closed', async () => { - mountPillar(); - await ready(); - await addMetric(); - expect( - within(screen.getByTestId('studio-held')).queryByRole('button', { name: t('engine.studio.refusal.show', 'en') }), - 'no "Show me" while that widget is the one open', - ).toBeNull(); - - fireEvent.click(within(rail()).getByRole('button', { name: t('engine.inspector.widget.close', 'en') })); - await waitFor(() => expect(within(rail()).queryByDisplayValue('New metric (kpi)')).toBeNull()); - fireEvent.click( - within(screen.getByTestId('studio-held')).getByRole('button', { name: t('engine.studio.refusal.show', 'en') }), - ); - expect(await within(rail()).findByDisplayValue('New metric (kpi)')).toBeInTheDocument(); - expect(within(rail()).getByTestId('widget-field-held-hint-dataset')).toBeInTheDocument(); - }); - - // CONTROL: errors stay for finished work. - it('a finished widget the server refuses still shows the red strip, and no held line', async () => { - refuseDashboard = Object.assign(new Error('Validation failed'), { - status: 422, - issues: [{ path: 'widgets.1.dataset', message: 'Dataset "sales_ds" is not published' }], - }); - mountPillar(); - await ready(); - await addMetric(); - await bindDataset(); - await addMeasure(); - await waitFor(() => expect(dashboardSaves()).toHaveLength(1), { timeout: 4000 }); - expect(await screen.findByTestId('studio-refusal')).toBeInTheDocument(); - expect(screen.queryByTestId('studio-held')).toBeNull(); - }); - - // CONTROL: every type the picker offers needs a binding on the installed - // spec (the predicate's pins walk them all), so the "saves at once" control - // is an edit on a dashboard whose widgets are all bound. - it('an edit to a dashboard whose widgets are all bound saves at once, with no line', async () => { - mountPillar(); - await ready(); - const [pipeline] = await screen.findAllByTestId('dashboard-preview-widget-pipeline', undefined, { timeout: 8000 }); - fireEvent.click(pipeline); - const title = await within(rail()).findByDisplayValue('Pipeline'); - fireEvent.change(title, { target: { value: 'Pipeline value' } }); - await waitFor(() => expect(dashboardSaves()).toHaveLength(1), { timeout: 4000 }); - expect(screen.queryByTestId('studio-held')).toBeNull(); - }); - - // Only the leaf autosave is held: the nav editor's own save is another buffer. - it('a held widget does not hold the navigation save', async () => { - mountPillar(); - await ready(); - await addMetric(); - fireEvent.click(screen.getByTitle(/^Edit navigation/)); - fireEvent.click(await screen.findByRole('button', { name: /Add nav item/ }, { timeout: 8000 })); - // *Link object* is the shared `Select` since objectui#11865: open its list and pick. - fireEvent.keyDown(screen.getByTestId('nav-link-object'), { key: 'ArrowDown' }); - fireEvent.click(await screen.findByRole('option', { name: new RegExp(`\\(${TASK.name}\\)$`) })); - await waitFor(() => expect(mockClient.save.mock.calls.filter((c) => c[0] === 'app')).toHaveLength(1), { - timeout: 4000, - }); - expect(dashboardSaves(), 'the widget is still held').toEqual([]); - expect(screen.getByTestId('studio-held')).toBeInTheDocument(); - }); -}); - -describe('a bound widget whose binding the author empties is held, not sent refused (objectui#11951)', () => { - /** A bar with one dimension and a scatter with two measures, beside the bound metric. */ - const BINDINGS_DASH = { - ...SALES_DASH, - widgets: [ - ...SALES_DASH.widgets, - { - id: 'by_stage', - type: 'bar', - title: 'By stage', - dataset: 'sales_ds', - dimensions: ['stage'], - values: ['revenue'], - layout: { x: 3, y: 0, w: 3, h: 2 }, - }, - { - id: 'spread', - type: 'scatter', - title: 'Spread', - dataset: 'sales_ds', - dimensions: ['stage'], - values: ['revenue', 'deal_count'], - layout: { x: 6, y: 0, w: 3, h: 2 }, - }, - ], - }; - - /** Selects the canvas widget `id`, whose inspector opens on `title`. */ - async function selectWidget(id: string, title: string): Promise { - const [tile] = await screen.findAllByTestId(`dashboard-preview-widget-${id}`, undefined, { timeout: 8000 }); - fireEvent.click(tile); - await within(rail()).findByDisplayValue(title, undefined, { timeout: 8000 }); - } - - /** - * The inspector's own remove button on a member of a binding list, named by - * the row's label — a measure's reads `LABEL · AGGREGATE` (objectstack#36373). - */ - function remove(label: string): void { - fireEvent.click( - within(rail()).getByRole('button', { name: tFormat('engine.viewColumnPanes.remove', 'en', { label }) }), - ); - } - - it('the precondition: the dashboard as served parses with the spec', () => { - expect(DashboardSchema.safeParse(BINDINGS_DASH).success).toBe(true); - }); - - it('removing a metric\'s last measure sends nothing and shows no red strip; picking another sends it', async () => { - const report = vi.fn(); - mountPillar(report); - await ready(); - await selectWidget('pipeline', 'Pipeline'); - remove('Revenue · Sum'); - await outlastDebounce(); - - expect(dashboardSaves(), 'the emptied measure list is not sent').toEqual([]); - expect(screen.queryByTestId('studio-refusal'), 'no red strip while the author is mid-way').toBeNull(); - expect(screen.getByTestId('studio-held-message')).toHaveTextContent( - heldLine('engine.inspector.widget.values', 'Pipeline'), - ); - expect(within(rail()).getByTestId('widget-field-held-hint-values')).toHaveTextContent( - t('engine.studio.held.inputHint', 'en'), - ); - expect(report).toHaveBeenLastCalledWith( - tFormat('engine.studio.held.widgetNeedsInput', 'en', { - input: t('engine.inspector.widget.values', 'en'), - widget: 'Pipeline', - }), - ); - - await addMeasure(); - await waitFor(() => expect(dashboardSaves()).toHaveLength(1), { timeout: 4000 }); - const [sent] = dashboardSaves(); - expect((sent.widgets as unknown[])[0]).toMatchObject({ id: 'pipeline', values: ['revenue'] }); - expect(DashboardSchema.safeParse(sent).success, 'the body sent is one the door accepts').toBe(true); - await waitFor(() => expect(screen.queryByTestId('studio-held')).toBeNull()); - expect(within(rail()).queryByTestId('widget-field-held-hint-values')).toBeNull(); - expect(report).toHaveBeenLastCalledWith(null); - }); - - it('removing a one-measure bar\'s last dimension saves at once, as the spec accepts it', async () => { - dashFixture = BINDINGS_DASH; - mountPillar(); - await ready(); - await selectWidget('by_stage', 'By stage'); - remove('Stage'); - await waitFor(() => expect(dashboardSaves()).toHaveLength(1), { timeout: 4000 }); - const [sent] = dashboardSaves(); - expect((sent.widgets as unknown[])[1]).toMatchObject({ id: 'by_stage', dimensions: [], values: ['revenue'] }); - expect(DashboardSchema.safeParse(sent).success, 'an emptied dimension list is one the door accepts').toBe(true); - expect(screen.queryByTestId('studio-held')).toBeNull(); - expect(within(rail()).queryByTestId('widget-field-held-hint-dimensions')).toBeNull(); - }); - - it('removing a two-measure scatter\'s last dimension holds it, and the inspector names the dimensions', async () => { - dashFixture = BINDINGS_DASH; - mountPillar(); - await ready(); - await selectWidget('spread', 'Spread'); - remove('Stage'); - await outlastDebounce(); - - expect(dashboardSaves(), 'a scatter the spec refuses for want of a dimension is not sent').toEqual([]); - expect(screen.queryByTestId('studio-refusal')).toBeNull(); - expect(screen.getByTestId('studio-held-message')).toHaveTextContent( - heldLine('engine.inspector.widget.dimensions', 'Spread'), - ); - expect(within(rail()).getByTestId('widget-field-held-hint-dimensions')).toHaveTextContent( - t('engine.studio.held.inputHint', 'en'), - ); - expect(within(rail()).queryByTestId('widget-field-held-hint-values')).toBeNull(); - }); - - // CONTROL: a finished but wrong widget is still sent when the author empties - // a binding beside what is wrong, and the refusal shows. - it('a widget with a dataset the author wrote wrong is sent when its last measure is removed, and the refusal shows', async () => { - dashFixture = { - ...SALES_DASH, - widgets: [{ ...SALES_DASH.widgets[0], dataset: 'Sales Pipeline' }], - }; - refuseDashboard = Object.assign(new Error('Validation failed'), { - status: 422, - issues: [{ path: 'widgets.0.dataset', message: 'Identifier must be lowercase snake_case' }], - }); - mountPillar(); - await ready(); - await selectWidget('pipeline', 'Pipeline'); - // No such dataset, so no member text: the row reads the name. - remove('revenue'); - await waitFor(() => expect(dashboardSaves()).toHaveLength(1), { timeout: 4000 }); - expect((dashboardSaves()[0].widgets as unknown[])[0]).toMatchObject({ dataset: 'Sales Pipeline', values: [] }); - expect(await screen.findByTestId('studio-refusal')).toBeInTheDocument(); - expect(screen.queryByTestId('studio-held')).toBeNull(); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.navActionServedRows-36725.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.navActionServedRows-36725.test.tsx deleted file mode 100644 index 619a0d4bc66..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.navActionServedRows-36725.test.tsx +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#36725 — a global action opened from an app nav leaf (the - * Interfaces pillar's `action` case) is designed in the rail's home inspector, - * the action designer. That host hands it the served `action` type row, so the - * designer draws its refusal catalogue (`refusals`) and declared texts - * (`texts`) with their served rows: the key-only record control and the row's - * help text, where with no schema and no form it drew neither row at all. - * - * The real pillar, rail and action designer; the type row is built from the - * spec the way the server builds it (`actionForm`, `ActionSchema` through - * `z.toJSONSchema(…, { io: 'input' })`). The stand-ins are the metadata - * client and the data adapter. - */ - -import '@testing-library/jest-dom/vitest'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; -import { z } from 'zod'; -import { ActionSchema, actionForm } from '@objectstack/spec/ui'; - -const ACTION_JSON_SCHEMA = z.toJSONSchema(ActionSchema as unknown as z.ZodType, { - io: 'input', - unrepresentable: 'any', -}) as Record; - -/** The served row's help text for `key`, read off the form the server serves. */ -function servedHelpText(key: string): string { - for (const section of actionForm.sections ?? []) { - for (const row of section.fields ?? []) { - if (typeof row !== 'string' && row.field === key) return String(row.helpText); - } - } - throw new Error(`actionForm declares no ${key} row`); -} - -const NAV = [ - { id: 'nav_home', type: 'page', label: 'Home', pageName: 'home' }, - { id: 'nav_sign', type: 'action', label: 'Sign', actionDef: { actionName: 'sign_now' } }, -]; - -/** A global script action: no `objectName`, as a nav action is by construction. */ -const SIGN = { - name: 'sign_now', - label: 'Sign Now', - type: 'script', - locations: ['list_toolbar'], - body: { language: 'js', source: "throw { code: 'SIGN_IN_REQUIRED' };" }, - refusals: { SIGN_IN_REQUIRED: { message: 'Sign in first.', status: 401 } }, - texts: { email_subject: { message: 'Task signed' } }, -}; - -const ACTION_TYPE_ROW = { - type: 'action', - name: 'action', - label: 'Action', - domain: 'ui', - allowEnvironmentOverlay: true, - allowRuntimeCreate: true, - schema: ACTION_JSON_SCHEMA, - form: actionForm, -}; - -const mockClient = { - list: vi.fn(async (type: string) => (type === 'app' ? [{ name: 'acme_app', label: 'Acme' }] : [])), - listDrafts: vi.fn(async () => []), - layered: vi.fn(async (type: string, name: string) => { - if (type === 'app') return { effective: { name: 'acme_app', label: 'Acme', navigation: NAV } }; - if (type === 'action' && name === 'sign_now') return { effective: SIGN }; - return { effective: { name, kind: 'blocks', blocks: [] } }; - }), - getDraft: vi.fn(async () => null), - save: vi.fn(async () => ({})), - get: vi.fn(async () => undefined), - withPreviewDrafts() { return this; }, -}; - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [ACTION_TYPE_ROW] }) }; -}); - -vi.mock('./packages-io', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, fetchPackages: vi.fn(async () => []) }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useAdapter: () => ({}) }; -}); - -// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). -import '@objectstack/lint'; -import { InterfacesPillar } from './StudioDesignSurface'; -import { registerMetadataPreview } from '../metadata-admin/preview-registry'; -import { ActionPreview } from '../metadata-admin/previews/ActionPreview'; -import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; -import { t } from '../metadata-admin/i18n'; - -// The `action` preview alone, as in StudioDesignSurface.interfacesAction.test.tsx: -// it is what makes the leaf an editable surface, so the rail mounts its home inspector. -registerMetadataPreview('action', ActionPreview); -registerBuiltinInspectors(); - -afterEach(cleanup); - -describe('Interfaces pillar — a nav action draws refusals and texts from their served rows (objectstack#36725)', () => { - it('draws each as the key-only record control with the served help text, and no raw JSON', async () => { - render( - - - , - ); - fireEvent.click(await screen.findByTitle('action · sign_now')); - // The rail's home inspector is the action designer (its Behavior section)… - await screen.findByText(t('engine.inspector.action.behavior', 'en'), {}, { timeout: 8000 }); - // …and, handed the served schema, it draws its "More fields". - expect(screen.getByText(t('engine.inspector.moreFields', 'en'))).toBeInTheDocument(); - - // No editor on the rail holds either record as JSON text (the raw JSON face). - const jsonHolders = Array.from(document.querySelectorAll('textarea')).filter( - (el) => el.value.includes('"SIGN_IN_REQUIRED"') || el.value.includes('"email_subject"'), - ); - expect(jsonHolders).toEqual([]); - // The served rows' help text, and the key-only control drawing each entry under its key. - expect(screen.getByText(servedHelpText('refusals'))).toBeInTheDocument(); - expect(screen.getByText(servedHelpText('texts'))).toBeInTheDocument(); - const rows = screen.getByTestId('action-served-rows'); - expect(within(rows).getByText('SIGN_IN_REQUIRED', { selector: 'span' })).toBeInTheDocument(); - expect(within(rows).getByText('email_subject', { selector: 'span' })).toBeInTheDocument(); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.offNavDeepLink-28561.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.offNavDeepLink-28561.test.tsx deleted file mode 100644 index bfd2397fd14..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.offNavDeepLink-28561.test.tsx +++ /dev/null @@ -1,175 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#28561 — Studio's "All metadata" area opens a page, dashboard, - * report or view in the Interfaces pillar by URL (`?surface=:`, - * ADR-0146 D1: "a pillar type opened from the directory opens its pillar"). - * - * The pillar resolved a `?surface=` deep link through its nav tree alone, so - * an item no nav entry opens (objectstack#26889's off-nav items) fell back to - * the first leaf: the link landed in the right pillar on the wrong item. These - * cases pin that it now opens the item from the package's own lists, with or - * without an app, and still falls back to the first leaf for a name the - * package does not hold. The harness is objectstack#26889's. - */ -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen, cleanup, waitFor } from '@testing-library/react'; -import { MemoryRouter, useLocation } from 'react-router-dom'; - -const PKG = 'com.acme.crm'; - -const NAV = [ - { id: 'nav_home', type: 'page', label: 'Home menu', pageName: 'home' }, - { id: 'nav_ops', type: 'dashboard', label: 'Ops board', dashboardName: 'ops' }, - { id: 'nav_my_leads', type: 'object', label: 'My leads', objectName: 'crm_lead', viewName: 'mine' }, -]; - -/** What the mocked server holds, per metadata type: published rows and `_drafts` headers. */ -const server = vi.hoisted(() => ({ - published: new Map>>(), - drafts: new Map>>(), -})); - -const mockClient = vi.hoisted(() => ({ - list: vi.fn(async (type: string) => server.published.get(type) ?? []), - listDrafts: vi.fn(async (opts?: { type?: string }) => server.drafts.get(opts?.type ?? '') ?? []), - listTypes: vi.fn(async () => ({ entries: [] })), - get: vi.fn(async () => null), - references: vi.fn(async () => []), - layered: vi.fn(async (type: string, name: string) => { - const eff = (server.published.get(type) ?? []).find((row) => row.name === name) ?? null; - return { code: null, overlay: eff, overlayScope: eff ? 'env' : null, effective: eff, editable: true, deletable: true, resettable: false, lock: 'none' }; - }), - getDraft: vi.fn(async (type: string, name: string) => { - throw Object.assign(new Error(`No pending draft exists for ${type}/${name}.`), { code: 'NO_DRAFT', status: 404 }); - }), - save: vi.fn(async (type: string, name: string, item: unknown) => ({ type, name, item })), - publish: vi.fn(async () => ({ success: true })), - reset: vi.fn(async () => ({})), -})); - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useAdapter: () => ({}) }; -}); - -vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), dismiss: vi.fn() } })); - -// The `view` resource's list filter (the aggregated container is no item) is -// registered here, as the console registers it. -import '../../services/builtinComponents'; -import { InterfacesPillar } from './StudioDesignSurface'; -import { registerMetadataPreview, type MetadataPreviewProps } from '../metadata-admin/preview-registry'; - -vi.stubGlobal( - 'fetch', - vi.fn(async () => new Response('null', { status: 404, headers: { 'content-type': 'application/json' } })), -); - -/** A canvas that says what it was opened on, and whether it may write. */ -function StubPreview({ type, name, onPatch }: MetadataPreviewProps) { - return ( -
- {`${type}:${name}`} -
- ); -} -for (const type of ['page', 'dashboard', 'report', 'view']) registerMetadataPreview(type, StubPreview); - -const page = (name: string, label: string, extra: Record = {}) => ({ name, label, type: 'app', ...extra }); - -function seedWithApp() { - server.published.set('app', [{ name: 'crm_app', label: 'CRM', navigation: NAV }]); - server.published.set('page', [page('home', 'Home'), page('lead_detail', 'Lead Detail', { type: 'record', object: 'crm_lead' })]); - server.published.set('dashboard', [ - { name: 'ops', label: 'Ops' }, - { name: 'sales_overview', label: 'Sales Overview' }, - ]); - server.published.set('report', [{ name: 'pipeline', label: 'Pipeline' }]); - server.published.set('view', [ - { name: 'crm_lead.mine', label: 'Mine', object: 'crm_lead', viewKind: 'list', config: { type: 'grid', columns: ['name'] } }, - { name: 'crm_lead.hot', label: 'Hot Leads', object: 'crm_lead', viewKind: 'list', config: { type: 'grid', columns: ['name'] } }, - { name: 'crm_lead.web_form', label: 'Web Form', object: 'crm_lead', viewKind: 'form', config: { type: 'simple', sections: [] } }, - // The container the server keeps beside the expanded items: no item of its own. - { name: 'crm_lead', object: 'crm_lead', listViews: { hot: { columns: ['name'] } } }, - ]); - server.drafts.set('page', [{ name: 'welcome', label: 'Welcome', packageId: PKG }]); -} - -function seedNoApp() { - server.published.set('dashboard', [{ name: 'service_overview', label: 'Service Overview' }]); - server.published.set('page', [page('case_detail', 'Case Detail', { type: 'record', object: 'crm_case' })]); -} - -beforeEach(() => { - server.published.clear(); - server.drafts.clear(); - for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear: () => void }).mockClear(); -}); - -afterEach(cleanup); - -function Where() { - const { search } = useLocation(); - return
{search}
; -} - -function renderPillar(surface: string) { - render( - - - - , - ); -} - -const surfaceParam = () => new URLSearchParams(screen.getByTestId('where').textContent ?? '').get('surface'); - -const canvas = () => screen.findByTestId('stub-canvas', undefined, { timeout: 8000 }); - -describe('objectstack#28561 — Interfaces opens an off-nav item by `?surface=`', () => { - // objectstack#30046 — a form view: a link to a LIST view lands on its - // object's page instead (`InterfacesPillar.offNavListViews-30046`). - it('a view no nav entry opens: the view, not the first leaf', async () => { - seedWithApp(); - renderPillar('view:crm_lead.web_form'); - expect(await canvas()).toHaveTextContent('view:crm_lead.web_form'); - expect(surfaceParam()).toBe('view:crm_lead.web_form'); - }); - - it('a report and a record page no entry opens', async () => { - seedWithApp(); - renderPillar('report:pipeline'); - expect(await canvas()).toHaveTextContent('report:pipeline'); - cleanup(); - renderPillar('page:lead_detail'); - expect(await canvas()).toHaveTextContent('page:lead_detail'); - }); - - it('a package with no app opens the dashboard the link names', async () => { - seedNoApp(); - renderPillar('dashboard:service_overview'); - expect(await canvas()).toHaveTextContent('dashboard:service_overview'); - expect(screen.queryByText('This package has no app yet')).toBeNull(); - }); - - it('CONTROL: an item a nav entry opens still opens through its entry', async () => { - seedWithApp(); - renderPillar('dashboard:ops'); - expect(await canvas()).toHaveTextContent('dashboard:ops'); - }); - - it('CONTROL: a name the package does not hold falls back to the first leaf', async () => { - seedWithApp(); - renderPillar('view:crm_lead.gone'); - expect(await canvas()).toHaveTextContent('page:home'); - await waitFor(() => expect(surfaceParam()).toBe('page:home')); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.offNavItems-26889.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.offNavItems-26889.test.tsx deleted file mode 100644 index e4376ddb276..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.offNavItems-26889.test.tsx +++ /dev/null @@ -1,263 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#26889 — the Interfaces pillar lists a package's views, pages, - * dashboards and reports whether or not a navigation entry names them, and a - * package with no app still lists what it ships. - * - * The rail used to be the app's navigation tree and nothing else, so an item - * no entry opens (a list view off the menu, a record page, a module package's - * dashboard) could not be opened in Studio at all, and a package with no app - * showed only its "no app yet" notice. Under the tree there is now one section - * per type with the items no entry opens; each row opens its item in the - * pillar's canvas, read-only on a read-only package. - * - * - an item a nav entry opens keeps its tree row and is not listed again (a - * page / dashboard entry's target, and the view an `object` entry's - * `viewName` names); - * - a draft-only item is listed, by the label its `_drafts` row carries; - * - the aggregated view container the server keeps for dual-read is not an - * item (Setup › Metadata leaves it out the same way); - * - the "no app yet" notice stays, with the sections under it. - */ -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { act, render, screen, fireEvent, cleanup, within } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; - -const PKG = 'com.acme.crm'; - -const NAV = [ - { id: 'nav_home', type: 'page', label: 'Home menu', pageName: 'home' }, - { id: 'nav_ops', type: 'dashboard', label: 'Ops board', dashboardName: 'ops' }, - { id: 'nav_my_leads', type: 'object', label: 'My leads', objectName: 'crm_lead', viewName: 'mine' }, -]; - -/** What the mocked server holds, per metadata type: published rows and `_drafts` headers. */ -const server = vi.hoisted(() => ({ - published: new Map>>(), - drafts: new Map>>(), -})); - -const mockClient = vi.hoisted(() => ({ - list: vi.fn(async (type: string) => server.published.get(type) ?? []), - listDrafts: vi.fn(async (opts?: { type?: string }) => server.drafts.get(opts?.type ?? '') ?? []), - listTypes: vi.fn(async () => ({ entries: [] })), - get: vi.fn(async () => null), - references: vi.fn(async () => []), - layered: vi.fn(async (type: string, name: string) => { - const eff = (server.published.get(type) ?? []).find((row) => row.name === name) ?? null; - return { code: null, overlay: eff, overlayScope: eff ? 'env' : null, effective: eff, editable: true, deletable: true, resettable: false, lock: 'none' }; - }), - getDraft: vi.fn(async (type: string, name: string) => { - throw Object.assign(new Error(`No pending draft exists for ${type}/${name}.`), { code: 'NO_DRAFT', status: 404 }); - }), - save: vi.fn(async (type: string, name: string, item: unknown) => ({ type, name, item })), - publish: vi.fn(async () => ({ success: true })), - reset: vi.fn(async () => ({})), -})); - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useAdapter: () => ({}) }; -}); - -vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), dismiss: vi.fn() } })); - -// The `view` resource's list filter (the aggregated container is no item) is -// registered here, as the console registers it. -import '../../services/builtinComponents'; -import { InterfacesPillar } from './StudioDesignSurface'; -import { registerMetadataPreview, type MetadataPreviewProps } from '../metadata-admin/preview-registry'; -import { STUDIO_RAIL_ROW_ACTIVE } from './studio-tokens'; - -vi.stubGlobal( - 'fetch', - vi.fn(async () => new Response('null', { status: 404, headers: { 'content-type': 'application/json' } })), -); - -/** A canvas that says what it was opened on, and whether it may write. */ -function StubPreview({ type, name, onPatch }: MetadataPreviewProps) { - return ( -
- {`${type}:${name}`} -
- ); -} -for (const type of ['page', 'dashboard', 'report', 'view']) registerMetadataPreview(type, StubPreview); - -const page = (name: string, label: string, extra: Record = {}) => ({ name, label, type: 'app', ...extra }); - -function seedWithApp() { - server.published.set('app', [{ name: 'crm_app', label: 'CRM', navigation: NAV }]); - server.published.set('page', [page('home', 'Home'), page('lead_detail', 'Lead Detail', { type: 'record', object: 'crm_lead' })]); - server.published.set('dashboard', [ - { name: 'ops', label: 'Ops' }, - { name: 'sales_overview', label: 'Sales Overview' }, - ]); - server.published.set('report', [{ name: 'pipeline', label: 'Pipeline' }]); - server.published.set('view', [ - { name: 'crm_lead.mine', label: 'Mine', object: 'crm_lead', viewKind: 'list', config: { type: 'grid', columns: ['name'] } }, - // objectstack#30046 — a form view: a list view of `crm_lead`, which an - // entry opens, is reached by that entry's header dropdown and not listed - // here (`InterfacesPillar.offNavListViews-30046`). - { name: 'crm_lead.web_form', label: 'Web Form', object: 'crm_lead', viewKind: 'form', config: { type: 'simple', sections: [] } }, - // The container the server keeps beside the expanded items: no item of its own. - { name: 'crm_lead', object: 'crm_lead', listViews: { hot: { columns: ['name'] } } }, - ]); - server.drafts.set('page', [{ name: 'welcome', label: 'Welcome', packageId: PKG }]); -} - -function seedNoApp() { - server.published.set('dashboard', [{ name: 'service_overview', label: 'Service Overview' }]); - server.published.set('page', [page('case_detail', 'Case Detail', { type: 'record', object: 'crm_case' })]); -} - -beforeEach(() => { - server.published.clear(); - server.drafts.clear(); - for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear: () => void }).mockClear(); -}); - -afterEach(cleanup); - -function renderPillar(props: { readOnly?: boolean } = {}) { - render( - - - , - ); -} - -/** The sections under the tree, once the package's items are read. */ -async function offNav(): Promise { - return screen.findByTestId('if-off-nav', undefined, { timeout: 8000 }); -} - -/** Every rail row's `type · name`, in rail order. */ -function railTitles(scope: HTMLElement): string[] { - return within(scope) - .getAllByRole('button') - .map((b) => b.getAttribute('title') ?? '') - .filter((title) => title.includes(' · ')); -} - -describe('objectstack#26889 — Interfaces lists what no navigation entry names', () => { - it('lists the views, pages, dashboards and reports no entry opens, one section per type', async () => { - seedWithApp(); - renderPillar(); - const sections = await offNav(); - expect(within(sections).getByTestId('if-off-nav-page')).toBeInTheDocument(); - expect(railTitles(sections)).toEqual([ - 'page · lead_detail', - 'page · welcome', - 'dashboard · sales_overview', - 'report · pipeline', - 'view · crm_lead.web_form', - ]); - // A draft-only page reads as the label its `_drafts` row carries. - expect(within(sections).getByRole('button', { name: 'Welcome' })).toHaveAttribute('title', 'page · welcome'); - // Each type was read for this package, published and draft. - for (const type of ['view', 'page', 'dashboard', 'report']) { - expect(mockClient.list).toHaveBeenCalledWith(type, { packageId: PKG }); - expect(mockClient.listDrafts).toHaveBeenCalledWith({ packageId: PKG, type }); - } - }); - - it('an item a nav entry opens is listed once, in the tree, and never again', async () => { - seedWithApp(); - renderPillar(); - const sections = await offNav(); - const rail = sections.closest('nav') as HTMLElement; - const titles = railTitles(rail); - expect(titles.filter((t) => t === 'page · home')).toHaveLength(1); - expect(titles.filter((t) => t === 'dashboard · ops')).toHaveLength(1); - // The view the `My leads` entry names (`viewName: 'mine'`) is that entry's row. - expect(titles).not.toContain('view · crm_lead.mine'); - expect(within(sections).queryByText('Home')).toBeNull(); - expect(within(sections).queryByText('Mine')).toBeNull(); - // The aggregated container is not listed as a view. - expect(titles).not.toContain('view · crm_lead'); - }); - - it('a view, a record page and a dashboard no entry names each open in the canvas', async () => { - seedWithApp(); - renderPillar(); - const sections = await offNav(); - for (const [label, opened] of [ - ['Web Form', 'view:crm_lead.web_form'], - ['Lead Detail', 'page:lead_detail'], - ['Sales Overview', 'dashboard:sales_overview'], - ] as const) { - fireEvent.click(within(sections).getByRole('button', { name: label })); - expect(await screen.findByText(opened, undefined, { timeout: 8000 })).toBeInTheDocument(); - expect(screen.getByTestId('if-breadcrumb')).toHaveTextContent(label); - // The row it was opened from is the active one, and only it. - const active = within(sections).getAllByRole('button').filter((b) => b.className.includes(STUDIO_RAIL_ROW_ACTIVE)); - expect(active.map((b) => b.textContent)).toEqual([label]); - } - }); - - it('a package with no app keeps its notice and lists its dashboard and page, which open', async () => { - seedNoApp(); - renderPillar(); - const sections = await offNav(); - expect(screen.getByText('This package has no app yet.')).toBeInTheDocument(); - expect(screen.getByText('This package has no app yet')).toBeInTheDocument(); - expect(railTitles(sections)).toEqual(['page · case_detail', 'dashboard · service_overview']); - - fireEvent.click(within(sections).getByRole('button', { name: 'Service Overview' })); - expect(await screen.findByText('dashboard:service_overview', undefined, { timeout: 8000 })).toBeInTheDocument(); - // The canvas shows the item now, not the empty state; the rail keeps its notice. - expect(screen.queryByText('This package has no app yet')).toBeNull(); - expect(screen.getByText('This package has no app yet.')).toBeInTheDocument(); - - fireEvent.click(within(sections).getByRole('button', { name: 'Case Detail' })); - expect(await screen.findByText('page:case_detail', undefined, { timeout: 8000 })).toBeInTheDocument(); - }); - - it('a read-only package lists them too, and opens them read-only', async () => { - seedNoApp(); - renderPillar({ readOnly: true }); - const sections = await offNav(); - fireEvent.click(within(sections).getByRole('button', { name: 'Service Overview' })); - const canvas = await screen.findByTestId('stub-canvas', undefined, { timeout: 8000 }); - expect(canvas).toHaveTextContent('dashboard:service_overview'); - expect(canvas).toHaveAttribute('data-writable', 'no'); - expect(mockClient.save).not.toHaveBeenCalled(); - }); - - it('CONTROL: a writable package opens them writable', async () => { - seedNoApp(); - renderPillar(); - const sections = await offNav(); - fireEvent.click(within(sections).getByRole('button', { name: 'Service Overview' })); - expect(await screen.findByTestId('stub-canvas', undefined, { timeout: 8000 })).toHaveAttribute('data-writable', 'yes'); - }); - - it('CONTROL: a package whose every item an entry opens draws no sections', async () => { - server.published.set('app', [{ name: 'crm_app', label: 'CRM', navigation: NAV }]); - server.published.set('page', [page('home', 'Home')]); - server.published.set('dashboard', [{ name: 'ops', label: 'Ops' }]); - renderPillar(); - await screen.findByRole('button', { name: 'Home menu Page' }, { timeout: 8000 }); - await vi.waitFor(() => expect(mockClient.listDrafts).toHaveBeenCalledWith({ packageId: PKG, type: 'view' })); - // Every read settled, and what it answered rendered. - await act(async () => { - await Promise.all(mockClient.listDrafts.mock.results.map((r) => r.value)); - await new Promise((r) => setTimeout(r, 50)); - }); - expect(screen.queryByTestId('if-off-nav')).toBeNull(); - // CONTROL of the control: the same package with one more dashboard lists it. - cleanup(); - server.published.set('dashboard', [{ name: 'ops', label: 'Ops' }, { name: 'extra', label: 'Extra' }]); - renderPillar(); - expect(railTitles(await offNav())).toEqual(['dashboard · extra']); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.offNavListViews-30046.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.offNavListViews-30046.test.tsx deleted file mode 100644 index eb3e2743810..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.offNavListViews-30046.test.tsx +++ /dev/null @@ -1,463 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#30046 (Scope 6–8) — what the Interfaces rail's 不在导航中 → 视图 - * group lists, and where a list view in it opens. - * - * Scope 1–5 put an object's list views in the header's title (object / view ▾). - * The group under the navigation tree still listed every view no entry named: - * a list view whose object has a navigation entry was listed there although - * the dropdown reaches it, a form view read as its machine name - * (`crm_lead.form`) under a heading that said nothing of what was left, and a - * list view picked there opened a page of its own (`surface=view:`), not the - * object's page with its dropdown. - * - * Pinned, through the mounted pillar, its real list-view buffer and the real - * panel (the client is a recorder): - * - Scope 7: a list view of an object with a nav entry is not listed, a view - * only drafted here included; CONTROL: the list views of an object with no - * entry stay listed; - * - Scope 8: a form view is listed under a readable name (its label, else the - * object's name and the word for a form), and the group's heading says - * what it holds (forms, list views, or both); - * - Scope 6: a list view picked there opens on the object's page, title - * object / view ▾, with that view in the panel and the address; the - * panel keeps what the view page offered (条件格式化 and the spec form's - * sections); a link to the view (`surface=view:`) lands on the same page, - * on the object's nav entry when it has one; CONTROL: a form view still - * opens as itself. - */ - -// Paid at collection, not inside a clocked case (check:test-source-alias). -import '@objectstack/lint'; -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { MemoryRouter, useLocation } from 'react-router-dom'; -import { ComponentRegistry } from '@object-ui/core'; -import { MetadataCtx, type MetadataContextValue } from '@object-ui/react'; - -const PKG = 'com.acme.crm'; - -const NAV = [{ id: 'nav_leads', type: 'object', label: 'Leads', objectName: 'crm_lead' }]; - -const grid = (object: string, extra: Record = {}) => ({ - type: 'grid', - data: { provider: 'object', object }, - columns: ['name'], - ...extra, -}); -const listView = (object: string, key: string, label: string, extra: Record = {}, body: Record = {}) => ({ - name: `${object}.${key}`, - object, - viewKind: 'list', - label, - ...extra, - config: grid(object, body), -}); -const formView = (object: string, key: string, label?: string, extra: Record = {}) => ({ - name: `${object}.${key}`, - object, - viewKind: 'form', - ...(label ? { label } : {}), - ...extra, - config: { type: 'simple', sections: [{ label: 'Main', fields: ['name'] }] }, -}); - -/** The views the package publishes, by name. */ -let published: Record> = {}; -/** The views only drafted in this package, by name. */ -let drafts: Record> = {}; - -function seed() { - published = Object.fromEntries( - [ - listView('crm_lead', 'all', 'All leads', { isDefault: true }), - listView('crm_lead', 'hot', 'Hot leads'), - // A default form that is public (`sharing.enabled`): still loaded, so - // still listed (objectstack-ai/objectstack#36425 hides only internal ones). - { - ...formView('crm_lead', 'form', undefined, { isDefault: true }), - config: { type: 'simple', sharing: { enabled: true }, sections: [{ label: 'Main', fields: ['name'] }] }, - }, - formView('crm_lead', 'contact_us', 'Contact us'), - // An internal default form (not public): the Console's create and edit - // forms no longer load it (#36425), so the rail does not list it. - formView('crm_case', 'form', undefined, { isDefault: true }), - listView('crm_case', 'open', 'Open cases', { isDefault: true }), - listView('crm_case', 'mine', 'My cases', {}, { - conditionalFormatting: [{ condition: "record.status == 'urgent'", style: { color: 'red' } }], - }), - ].map((row) => [row.name, row]), - ); - drafts = Object.fromEntries([listView('crm_lead', 'drafted', 'Drafted leads')].map((row) => [row.name, row])); -} - -const OBJECTS = [ - { name: 'crm_lead', label: 'Lead' }, - { name: 'crm_case', label: 'Case' }, -]; - -/** An object as the shell's merged metadata holds it: its list views keyed by item name. */ -function objectDef(name: string) { - const own = Object.values(published).filter((row) => row.object === name && row.viewKind === 'list'); - return { - name, - label: OBJECTS.find((o) => o.name === name)?.label ?? name, - fields: { name: { name: 'name', label: 'Name', type: 'text' }, status: { name: 'status', label: 'Status', type: 'text' } }, - listViews: Object.fromEntries( - own.map((row) => [row.name, { ...row.config, name: row.name, label: row.label, ...(row.isDefault ? { isDefault: true } : {}) }]), - ), - }; -} - -const mockClient: Record = { - save: vi.fn(async (..._args: unknown[]) => ({ success: true, version: 'v1', state: 'draft' })), - list: vi.fn(async (type: string) => { - if (type === 'app') return [{ name: 'crm_app', label: 'CRM', navigation: NAV }]; - if (type === 'object') return OBJECTS; - if (type === 'view') return Object.values(published); - return []; - }), - listDrafts: vi.fn(async (opts?: { type?: string }) => - opts?.type === 'view' ? Object.values(drafts).map((d) => ({ name: d.name, label: d.label, packageId: PKG })) : [], - ), - listTypes: vi.fn(async () => ({ entries: [] })), - references: vi.fn(async () => []), - layered: vi.fn(async (type: string, name: string) => { - if (type === 'app') return { effective: { name: 'crm_app', label: 'CRM', navigation: NAV } }; - if (type === 'object') return { effective: objectDef(name), code: objectDef(name) }; - if (type === 'view') { - const row = published[name] ?? null; - return { code: null, overlay: row, overlayScope: row ? 'env' : null, effective: row, editable: true }; - } - return { effective: { name } }; - }), - getDraft: vi.fn(async (type: string, name: string) => { - const row = type === 'view' ? drafts[name] : undefined; - if (row) return { type, name, item: { ...row, _draft: true }, version: 'v1' }; - throw Object.assign(new Error(`No pending draft exists for ${type}/${name}.`), { code: 'NO_DRAFT', status: 404 }); - }), - get: vi.fn(async (type: string, name: string) => (type === 'object' ? objectDef(name) : undefined)), - publish: vi.fn(async () => ({ success: true })), -}; -// The draft-overlaid reads: the package's view drafts are tagged `_draft`, as the server serves them. -const previewClient: Record = Object.assign(Object.create(mockClient), { - list: vi.fn(async (type: string, opts?: unknown) => - type === 'view' - ? [...Object.values(published), ...Object.values(drafts).map((d) => ({ ...d, _draft: true, _packageId: PKG }))] - : mockClient.list(type, opts), - ), -}); -mockClient.withPreviewDrafts = () => previewClient; - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; -}); - -vi.mock('./packages-io', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, fetchPackages: vi.fn(async () => []) }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useAdapter: () => ({}) }; -}); - -vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), dismiss: vi.fn() } })); - -// The `view` resource's list filter (the aggregated container is no item) is -// registered here, as the console registers it. -import '../../services/builtinComponents'; -import { InterfacesPillar } from './StudioDesignSurface'; -import { registerMetadataPreview, type MetadataPreviewProps } from '../metadata-admin/preview-registry'; -import { t, tFormat } from '../metadata-admin/i18n'; -import { STUDIO_RAIL_ROW_ACTIVE } from './studio-tokens'; -import { __setCelFormulaLoader } from '../metadata-admin/celAuthoring'; - -/** A formula engine whose one verdict is: an expression that ends after an operator does not parse. */ -function stubCelEngine() { - __setCelFormulaLoader(() => - Promise.resolve({ - validateExpression: (_role: string, input: unknown) => { - const src = typeof input === 'string' ? input : String((input as { source?: string })?.source ?? ''); - return /[*+\-/&|=<>]\s*$/.test(src) - ? { ok: false, errors: [{ message: 'Parse error: expression ends after an operator' }], warnings: [] } - : { ok: true, errors: [], warnings: [] }; - }, - introspectScope: () => ({ fields: ['name', 'status'], roots: ['record'], functions: ['has'] }), - inferExpressionType: () => 'boolean' as const, - }) as never, - ); -} - -/** A view page's canvas that says what it was opened on. */ -function StubPreview({ type, name }: MetadataPreviewProps) { - return
{`${type}:${name}`}
; -} -registerMetadataPreview('view', StubPreview); - -/** Stands in for `plugin-view`'s `object-view` on an object page's canvas. */ -function ObjectViewRecorder({ schema }: { schema: Record }) { - return
{JSON.stringify(schema)}
; -} - -function metadata(): MetadataContextValue { - return { - apps: [], - objects: OBJECTS.map((o) => objectDef(o.name)), - dashboards: [], - reports: [], - pages: [], - loading: false, - error: null, - refresh: async () => {}, - invalidate: () => {}, - ensureType: async () => [], - getItem: async () => null, - getItemsByType: () => [], - }; -} - -vi.stubGlobal( - 'fetch', - vi.fn(async () => new Response('null', { status: 404, headers: { 'content-type': 'application/json' } })), -); - -beforeAll(() => { - ComponentRegistry.register('object-view', ObjectViewRecorder as never, { namespace: 'plugin-view' }); -}); -beforeEach(() => { - seed(); - for (const fn of [mockClient.save, mockClient.list, mockClient.listDrafts, previewClient.list]) fn.mockClear(); - window.confirm = vi.fn(() => false) as unknown as typeof window.confirm; -}); -afterEach(() => { - cleanup(); - __setCelFormulaLoader(undefined); -}); - -/** The address the pillar writes, as a reload or a shared link reads it. */ -let address = new URLSearchParams(); -function AddressProbe() { - const { search } = useLocation(); - React.useEffect(() => { - address = new URLSearchParams(search); - }, [search]); - return null; -} - -function mountPillar(search = '') { - render( - - - - - - , - ); -} - -/** The 视图 group under the tree, once the package's views are read. */ -async function viewGroup(): Promise { - return screen.findByTestId('if-off-nav-view', undefined, { timeout: 8000 }); -} - -/** The group's rows, as `type · name` (their tooltip), in rail order. */ -function rowNames(group: HTMLElement): string[] { - return within(group) - .getAllByRole('button') - .map((b) => b.getAttribute('title') ?? '') - .filter((title) => title.startsWith('view · ')); -} - -/** The group's rows, as an author reads them. */ -function rowTexts(group: HTMLElement): string[] { - return within(group) - .getAllByRole('button') - .filter((b) => (b.getAttribute('title') ?? '').startsWith('view · ')) - .map((b) => b.textContent ?? ''); -} - -/** The view item name the object page's panel shows beneath its title. */ -const shownView = () => screen.queryByTestId('studio-list-view-inspector')?.getAttribute('data-view-id') ?? null; - -/** Every view row's read settled: the drafts headers and the draft-overlaid list. */ -async function viewsRead() { - await waitFor(() => expect(mockClient.listDrafts).toHaveBeenCalledWith({ packageId: PKG, type: 'view' })); - await waitFor(() => expect(previewClient.list).toHaveBeenCalledWith('view', { packageId: PKG })); - await new Promise((r) => setTimeout(r, 50)); -} - -describe('不在导航中 → 视图 lists what the dropdown does not reach (objectstack#30046 Scope 7)', () => { - it('a list view of an object with a nav entry is not listed, a drafted one included', async () => { - mountPillar(); - const group = await viewGroup(); - await viewsRead(); - const names = rowNames(group); - expect(names).not.toContain('view · crm_lead.all'); - expect(names).not.toContain('view · crm_lead.hot'); - expect(names).not.toContain('view · crm_lead.drafted'); - }); - - it('what is listed: the form views, and the list views of an object no entry opens', async () => { - mountPillar(); - const group = await viewGroup(); - await viewsRead(); - // The internal default `crm_case.form` is not listed (#36425). - expect(rowNames(group).sort()).toEqual( - ['view · crm_case.mine', 'view · crm_case.open', 'view · crm_lead.contact_us', 'view · crm_lead.form'].sort(), - ); - }); - - it('CONTROL: the list views of an object with no entry stay listed', async () => { - mountPillar(); - const group = await viewGroup(); - await viewsRead(); - expect(rowNames(group)).toEqual(expect.arrayContaining(['view · crm_case.mine', 'view · crm_case.open'])); - }); -}); - -describe('the group names what it holds, and a form view by a readable name (objectstack#30046 Scope 8)', () => { - it('a form view reads its label, else the object’s name and the word for a form; never its machine name', async () => { - mountPillar(); - const group = await viewGroup(); - await viewsRead(); - const texts = rowTexts(group); - expect(texts).toContain(tFormat('engine.studio.if.offNav.formName', 'en', { object: 'Lead' })); - expect(texts).toContain('Contact us'); - expect(texts).not.toContain('crm_lead.form'); - }); - - it('the heading says it holds form and list views; with only forms left, form views', async () => { - mountPillar(); - const group = await viewGroup(); - await viewsRead(); - expect(group).toHaveTextContent(t('engine.studio.if.offNav.viewMixed', 'en')); - - cleanup(); - for (const name of Object.keys(published)) if (name.startsWith('crm_case.')) delete published[name]; - mountPillar(); - const forms = await viewGroup(); - await viewsRead(); - expect(rowNames(forms).sort()).toEqual(['view · crm_lead.contact_us', 'view · crm_lead.form']); - expect(forms).toHaveTextContent(t('engine.studio.if.offNav.viewForms', 'en')); - expect(forms).not.toHaveTextContent(t('engine.studio.if.offNav.viewMixed', 'en')); - }); - - it('CONTROL: with no form view, the heading stays 视图', async () => { - for (const name of Object.keys(published)) if (published[name]!.viewKind === 'form') delete published[name]; - mountPillar(); - const group = await viewGroup(); - await viewsRead(); - expect(rowNames(group)).toEqual(expect.arrayContaining(['view · crm_case.mine', 'view · crm_case.open'])); - expect(group).toHaveTextContent(t('engine.studio.if.offNav.view', 'en')); - expect(group).not.toHaveTextContent(t('engine.studio.if.offNav.viewForms', 'en')); - }); -}); - -describe('a list view opened from 不在导航中 lands on its object’s page (objectstack#30046 Scope 6)', () => { - it('opens on the object page: title object / view ▾, the view in the panel and the address, its row active', async () => { - mountPillar(); - const group = await viewGroup(); - await viewsRead(); - fireEvent.click(within(group).getByRole('button', { name: 'My cases' })); - - await screen.findByTestId('studio-list-view-inspector', undefined, { timeout: 8000 }); - await waitFor(() => expect(shownView()).toBe('crm_case.mine')); - expect(screen.getByTestId('if-list-view-title-object')).toHaveTextContent('Case'); - expect(within(screen.getByTestId('if-item-header')).getByTestId('list-view-switcher')).toHaveTextContent('My cases'); - // No view page: its canvas is not mounted. - expect(screen.queryByTestId('stub-canvas')).toBeNull(); - await waitFor(() => expect(address.get('surface')).toBe('object:crm_case')); - expect(address.get('view')).toBe('crm_case.mine'); - // The row it was opened from is the active one, and only it. - const active = within(group).getAllByRole('button').filter((b) => b.className.includes(STUDIO_RAIL_ROW_ACTIVE)); - expect(active.map((b) => b.textContent)).toEqual(['My cases']); - }); - - it('the panel keeps what the view page offered: 条件格式化 with the view’s rules, and the spec form’s sections', async () => { - mountPillar(); - const group = await viewGroup(); - await viewsRead(); - fireEvent.click(within(group).getByRole('button', { name: 'My cases' })); - await waitFor(() => expect(shownView()).toBe('crm_case.mine'), { timeout: 8000 }); - - const more = await screen.findByTestId('list-view-more', undefined, { timeout: 8000 }); - expect(within(more).getByTestId('list-view-conditional-formatting')).toBeInTheDocument(); - expect(within(more).getByDisplayValue("record.status == 'urgent'")).toBeInTheDocument(); - expect(within(more).getByTestId('list-view-spec-form')).toBeInTheDocument(); - }); - - it('a second view of the same object is one more pick in the rail, on the same page', async () => { - mountPillar(); - const group = await viewGroup(); - await viewsRead(); - fireEvent.click(within(group).getByRole('button', { name: 'My cases' })); - await waitFor(() => expect(shownView()).toBe('crm_case.mine'), { timeout: 8000 }); - fireEvent.click(within(group).getByRole('button', { name: 'Open cases' })); - await waitFor(() => expect(shownView()).toBe('crm_case.open')); - expect(screen.getByTestId('if-list-view-title-object')).toHaveTextContent('Case'); - // The object's default view: the address names the object alone. - await waitFor(() => expect(address.has('view')).toBe(false)); - expect(address.get('surface')).toBe('object:crm_case'); - }); - - it('a link to an object with no entry (a reload of that page) opens it on the view it names', async () => { - mountPillar('?surface=object%3Acrm_case&view=crm_case.mine'); - await screen.findByTestId('studio-list-view-inspector', undefined, { timeout: 8000 }); - await waitFor(() => expect(shownView()).toBe('crm_case.mine')); - expect(screen.getByTestId('if-list-view-title-object')).toHaveTextContent('Case'); - }); - - it('a link to the view itself (`surface=view:`) lands on the same page; with a nav entry, on the entry', async () => { - mountPillar('?surface=view%3Acrm_case.mine'); - await screen.findByTestId('studio-list-view-inspector', undefined, { timeout: 8000 }); - await waitFor(() => expect(shownView()).toBe('crm_case.mine')); - expect(screen.queryByTestId('stub-canvas')).toBeNull(); - - cleanup(); - mountPillar('?surface=view%3Acrm_lead.hot'); - await screen.findByTestId('studio-list-view-inspector', undefined, { timeout: 8000 }); - await waitFor(() => expect(shownView()).toBe('crm_lead.hot')); - expect(screen.getByTestId('if-list-view-title-object')).toHaveTextContent('Leads'); - await waitFor(() => expect(address.get('nav')).toBe('nav_leads')); - expect(address.get('view')).toBe('crm_lead.hot'); - }); - - it('CONTROL: a form view still opens as itself', async () => { - mountPillar(); - const group = await viewGroup(); - await viewsRead(); - fireEvent.click(within(group).getByRole('button', { name: 'Contact us' })); - expect(await screen.findByText('view:crm_lead.contact_us', undefined, { timeout: 8000 })).toBeInTheDocument(); - expect(screen.queryByTestId('studio-list-view-inspector')).toBeNull(); - }); - - it('a formatting rule whose CEL does not parse holds the view’s autosave, as the view page held Save', async () => { - stubCelEngine(); - mountPillar(); - const group = await viewGroup(); - await viewsRead(); - fireEvent.click(within(group).getByRole('button', { name: 'My cases' })); - await waitFor(() => expect(shownView()).toBe('crm_case.mine'), { timeout: 8000 }); - const rule = () => screen.getByTestId('cf-rule-0').querySelector('[role="combobox"]') as HTMLTextAreaElement; - await waitFor(() => expect(rule()).toBeInTheDocument(), { timeout: 8000 }); - - fireEvent.change(rule(), { target: { value: 'record.status ==' } }); - await screen.findByTestId('studio-held', undefined, { timeout: 4000 }); - // Past the autosave's 1.5 s debounce: nothing was sent. - await new Promise((r) => setTimeout(r, 2000)); - expect(mockClient.save.mock.calls.filter((c: unknown[]) => c[0] === 'view')).toEqual([]); - - // Fixed, it is sent to the view it was made on. - fireEvent.change(rule(), { target: { value: "record.status == 'open'" } }); - await waitFor(() => expect(mockClient.save.mock.calls.some((c: unknown[]) => c[0] === 'view')).toBe(true), { timeout: 8000 }); - const [, name, body] = mockClient.save.mock.calls.find((c: unknown[]) => c[0] === 'view') as [string, string, Record]; - expect(name).toBe('crm_case.mine'); - expect(body.config.conditionalFormatting[0].condition).toBe("record.status == 'open'"); - }, 20000); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.reportHeld-27785.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.reportHeld-27785.test.tsx deleted file mode 100644 index 023fd211e05..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.reportHeld-27785.test.tsx +++ /dev/null @@ -1,295 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#27785 — the Interfaces pillar holds a report unsent while an item - * just added to one of its list properties, or a chart whose type was picked - * before its axes, is unfinished, instead of autosaving it for the draft door - * to refuse. - * - * The card: Order → "Add item" sent `order: [{}]` (422 `order.0.by`), a joined - * report's Blocks → "Add item" sent `blocks: [{}]` (422), and a chart type - * picked first sent `chart: { type }` (422 `chart.xAxis` / `chart.yAxis`). - * Every later save carried the same body and was refused too. The pillar now - * holds the report as it holds the dashboard's list items (objectstack#27459): - * nothing is sent, a neutral line names the input with a "Show me", and - * filling it in lets the next autosave send every edit kept meanwhile. - * - * Mounted with a metadata client double that records every save, a stub - * canvas and the real `ReportDefaultInspector` (its spec-driven form and its - * own chart panel). - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; -import { ReportSchema } from '@objectstack/spec/ui'; - -const NAV = [{ id: 'nav_rep', type: 'report', label: 'Sales report', reportName: 'sales_report' }]; - -const SUMMARY_REPORT = { - name: 'sales_report', - label: 'Sales report', - type: 'summary', - dataset: 'sales_ds', - rows: ['stage'], - values: ['revenue'], -}; - -const JOINED_REPORT = { - name: 'sales_report', - label: 'Sales report', - type: 'joined', - blocks: [{ name: 'won', dataset: 'sales_ds' }], -}; - -const DATASETS = [ - { - name: 'sales_ds', - label: 'Sales', - object: 'opportunity', - dimensions: [{ name: 'stage', label: 'Stage' }], - measures: [{ name: 'revenue', label: 'Revenue', aggregate: 'sum' }], - }, -]; - -/** The report the pillar opens, as served: it parses with the spec. */ -let stored: Record = SUMMARY_REPORT; - -const mockClient = { - withPreviewDrafts: vi.fn((): unknown => mockClient), - save: vi.fn(async (_type: string, _name: string, _body: Record) => ({ - success: true, - version: 'v1', - state: 'draft', - })), - list: vi.fn(async (type: string) => { - if (type === 'app') return [{ name: 'acme_app', label: 'Acme' }]; - if (type === 'dataset') return DATASETS; - if (type === 'report') return [stored]; - return []; - }), - listDrafts: vi.fn(async () => []), - layered: vi.fn(async (type: string) => { - if (type === 'app') return { effective: { name: 'acme_app', label: 'Acme', active: true, navigation: NAV } }; - if (type === 'report') return { effective: JSON.parse(JSON.stringify(stored)) }; - return { code: null, overlay: null, overlayScope: null, effective: null }; - }), - getDraft: vi.fn(async () => null), - get: vi.fn(async (type: string, name: string) => - type === 'dataset' ? DATASETS.find((d) => d.name === name) : undefined, - ), -}; - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; -}); - -vi.mock('./packages-io', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, fetchPackages: vi.fn(async () => []) }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useAdapter: () => ({}) }; -}); - -// Pay the dynamic `@objectstack/lint` load at collection, never inside a case's -// clocked window (`check:test-source-alias`). -import '@objectstack/lint'; -import { InterfacesPillar } from './StudioDesignSurface'; -import { registerMetadataPreview } from '../metadata-admin/preview-registry'; -import { registerMetadataDefaultInspector } from '../metadata-admin/default-inspector-registry'; -import { ReportDefaultInspector } from '../metadata-admin/inspectors/ReportDefaultInspector'; -import { t, tFormat } from '../metadata-admin/i18n'; - -// A stub canvas: the leaf needs a registered preview to be draft-editable, -// and the canvas's own drawing is not what this file pins. -registerMetadataPreview('report', () => null); -registerMetadataDefaultInspector('report', ReportDefaultInspector); - -beforeEach(() => { - stored = SUMMARY_REPORT; - for (const fn of Object.values(mockClient)) fn.mockClear(); -}); -afterEach(cleanup); - -const L = (key: string) => t(key, 'en'); - -function mountPillar(onHeldEditChange?: (clause: string | null) => void) { - return render( - - - , - ); -} - -function reportSaves(): Array> { - return mockClient.save.mock.calls.filter((c) => c[0] === 'report').map((c) => c[2]); -} - -/** Past the autosave's 1.5 s debounce. */ -async function outlastDebounce(): Promise { - await act(async () => { - await new Promise((r) => setTimeout(r, 2300)); - }); -} - -/** The report's properties are open, with the list property labelled `list` drawn. */ -async function ready(list: string): Promise { - const inspector = await screen.findByTestId('if-inspector', undefined, { timeout: 8000 }); - await within(inspector).findByText(list, { selector: 'label' }, { timeout: 8000 }); - return inspector; -} - -/** The form row of the list property labelled `label`: its label and its repeater. */ -function listRow(inspector: HTMLElement, label: string): HTMLElement { - const row = within(inspector).getByText(label, { selector: 'label' }).parentElement?.parentElement; - if (!row) throw new Error(`no form row for ${label}`); - return row; -} - -/** The report's own Label input. */ -function editLabel(inspector: HTMLElement, value: string): void { - const input = within(inspector).getByLabelText(L('engine.inspector.report.label')); - fireEvent.change(input, { target: { value } }); - fireEvent.blur(input); -} - -/** Picks `option` in the inspector select labelled `label`. */ -async function pick(inspector: HTMLElement, label: string, option: string | RegExp): Promise { - fireEvent.keyDown(within(inspector).getByRole('combobox', { name: label }), { key: 'ArrowDown' }); - await waitFor(() => expect(screen.queryAllByRole('option').length).toBeGreaterThan(0)); - fireEvent.click(screen.getByRole('option', { name: option })); -} - -const orderClause = tFormat('engine.studio.held.listItemNeedsInput', 'en', { input: 'Sort By', n: 1, list: 'Sort Order' }); -const heldLine = (clause: string) => tFormat('engine.studio.held.line', 'en', { clause }); - -describe('an item just added to a report list property is held until it is filled in (objectstack#27785)', () => { - it('Order → Add item, then a Label edit: nothing is sent, no red strip, the line names the Order By', async () => { - const report = vi.fn(); - mountPillar(report); - const inspector = await ready('Sort Order'); - fireEvent.click(within(listRow(inspector, 'Sort Order')).getByRole('button', { name: L('engine.form.addItem') })); - editLabel(inspector, 'Sales v2'); - await outlastDebounce(); - - expect(reportSaves(), 'the unfinished item is not sent, nor the Label edit with it').toEqual([]); - expect(screen.queryByTestId('studio-refusal'), 'no red strip on the normal path').toBeNull(); - expect(screen.getByTestId('studio-held-message')).toHaveTextContent(heldLine(orderClause)); - // Publish's half: the surface is told what is held. - expect(report).toHaveBeenLastCalledWith(orderClause); - }); - - it('"Show me" focuses the list in the report properties', async () => { - mountPillar(); - const inspector = await ready('Sort Order'); - const row = listRow(inspector, 'Sort Order'); - fireEvent.click(within(row).getByRole('button', { name: L('engine.form.addItem') })); - const show = await within(await screen.findByTestId('studio-held')).findByRole('button', { - name: L('engine.studio.refusal.show'), - }); - (document.activeElement as HTMLElement | null)?.blur(); - fireEvent.click(show); - await waitFor(() => expect(row.contains(document.activeElement)).toBe(true)); - }); - - it('filling the Order By in sends one save carrying the item and the Label edit kept meanwhile', async () => { - const report = vi.fn(); - mountPillar(report); - const inspector = await ready('Sort Order'); - const row = listRow(inspector, 'Sort Order'); - fireEvent.click(within(row).getByRole('button', { name: L('engine.form.addItem') })); - editLabel(inspector, 'Sales v2'); - await outlastDebounce(); - expect(reportSaves()).toEqual([]); - - const by = within(row).getByLabelText('Sort By'); - fireEvent.change(by, { target: { value: 'stage' } }); - fireEvent.blur(by); - await waitFor(() => expect(reportSaves()).toHaveLength(1), { timeout: 4000 }); - const [sent] = reportSaves(); - expect(sent.label).toBe('Sales v2'); - expect(sent.order).toEqual([expect.objectContaining({ by: 'stage' })]); - expect( - ReportSchema.safeParse(JSON.parse(JSON.stringify(sent))).success, - 'the body sent is one the door accepts', - ).toBe(true); - await waitFor(() => expect(screen.queryByTestId('studio-held')).toBeNull()); - expect(report).toHaveBeenLastCalledWith(null); - }); - - it('a joined report’s Blocks → Add item: nothing is sent, the line names the block’s Name', async () => { - stored = JOINED_REPORT; - const report = vi.fn(); - mountPillar(report); - const inspector = await ready('Blocks'); - fireEvent.click(within(listRow(inspector, 'Blocks')).getByRole('button', { name: L('engine.form.addItem') })); - await outlastDebounce(); - - const clause = tFormat('engine.studio.held.listItemNeedsInput', 'en', { input: 'Name', n: 2, list: 'Blocks' }); - expect(reportSaves()).toEqual([]); - expect(screen.queryByTestId('studio-refusal')).toBeNull(); - expect(screen.getByTestId('studio-held-message')).toHaveTextContent(heldLine(clause)); - expect(report).toHaveBeenLastCalledWith(clause); - }); - - // CONTROL: an edit to a report with nothing unfinished saves at once. - it('a Label edit alone saves at once, with no line', async () => { - mountPillar(); - const inspector = await ready('Sort Order'); - editLabel(inspector, 'Sales v2'); - await waitFor(() => expect(reportSaves()).toHaveLength(1), { timeout: 4000 }); - expect(reportSaves()[0].label).toBe('Sales v2'); - expect(screen.queryByTestId('studio-held')).toBeNull(); - }); -}); - -describe('a chart type picked before its axes is held until both axes are picked (objectstack#27785)', () => { - const x = L('engine.inspector.report.chartX'); - const y = L('engine.inspector.report.chartY'); - - it('nothing is sent while an axis is unset; the line names it, and "Show me" focuses its picker', async () => { - const report = vi.fn(); - mountPillar(report); - const inspector = await ready('Sort Order'); - await pick(inspector, L('engine.inspector.report.chartType'), L('engine.inspector.widget.type.bar')); - await outlastDebounce(); - - const clauseX = tFormat('engine.studio.held.reportChartNeedsInput', 'en', { input: x }); - expect(reportSaves(), 'the chart without axes is not sent').toEqual([]); - expect(screen.queryByTestId('studio-refusal')).toBeNull(); - expect(screen.getByTestId('studio-held-message')).toHaveTextContent(heldLine(clauseX)); - expect(report).toHaveBeenLastCalledWith(clauseX); - - (document.activeElement as HTMLElement | null)?.blur(); - fireEvent.click(within(screen.getByTestId('studio-held')).getByRole('button', { name: L('engine.studio.refusal.show') })); - await waitFor(() => expect(document.activeElement).toBe(within(inspector).getByRole('combobox', { name: x }))); - - await pick(inspector, x, 'Stage'); - await outlastDebounce(); - expect(reportSaves(), 'one axis is not enough').toEqual([]); - expect(screen.getByTestId('studio-held-message')).toHaveTextContent( - heldLine(tFormat('engine.studio.held.reportChartNeedsInput', 'en', { input: y })), - ); - }); - - it('both axes picked: one save carrying the whole chart, and the line clears', async () => { - const report = vi.fn(); - mountPillar(report); - const inspector = await ready('Sort Order'); - await pick(inspector, L('engine.inspector.report.chartType'), L('engine.inspector.widget.type.bar')); - await pick(inspector, x, 'Stage'); - await pick(inspector, y, /^Revenue/); - await waitFor(() => expect(reportSaves()).toHaveLength(1), { timeout: 4000 }); - const [sent] = reportSaves(); - expect(sent.chart).toEqual(expect.objectContaining({ type: 'bar', xAxis: 'stage', yAxis: 'revenue' })); - expect(ReportSchema.safeParse(JSON.parse(JSON.stringify(sent))).success).toBe(true); - await waitFor(() => expect(screen.queryByTestId('studio-held')).toBeNull()); - expect(report).toHaveBeenLastCalledWith(null); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.reportJoined-29022.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.reportJoined-29022.test.tsx deleted file mode 100644 index 3f1c1a79edc..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.reportJoined-29022.test.tsx +++ /dev/null @@ -1,218 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#29022 — the Interfaces pillar holds a report switched to Joined - * in its Properties until its first block is added, instead of autosaving a - * body the draft door refuses. - * - * The card: Report type = Joined sent `type: 'joined'` with the dataset and - * measures cleared and no `blocks` (422 at `blocks`); a Description edit then - * sent the same body plus the edit (422 again), and a reload dropped both with - * no prompt. Now nothing is sent, a neutral line names the Blocks list with a - * "Show me", and the surface is told what is held (its leave guard and Publish - * read that). - * - * Mounted as `InterfacesPillar.reportHeld-27785.test.tsx` mounts it: a metadata - * client double that records every save, a stub canvas and the real - * `ReportDefaultInspector` with its type picker. - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; - -const NAV = [{ id: 'nav_rep', type: 'report', label: 'Sales report', reportName: 'sales_report' }]; - -const SUMMARY_REPORT = { - name: 'sales_report', - label: 'Sales report', - type: 'summary', - dataset: 'sales_ds', - rows: ['stage'], - values: ['revenue'], -}; - -const DATASETS = [ - { - name: 'sales_ds', - label: 'Sales', - object: 'opportunity', - dimensions: [{ name: 'stage', label: 'Stage' }], - measures: [{ name: 'revenue', label: 'Revenue', aggregate: 'sum' }], - }, -]; - -/** The report the pillar opens, as served: it parses with the spec. */ -let stored: Record = SUMMARY_REPORT; - -const mockClient = { - withPreviewDrafts: vi.fn((): unknown => mockClient), - save: vi.fn(async (_type: string, _name: string, _body: Record) => ({ - success: true, - version: 'v1', - state: 'draft', - })), - list: vi.fn(async (type: string) => { - if (type === 'app') return [{ name: 'acme_app', label: 'Acme' }]; - if (type === 'dataset') return DATASETS; - if (type === 'report') return [stored]; - return []; - }), - listDrafts: vi.fn(async () => []), - layered: vi.fn(async (type: string) => { - if (type === 'app') return { effective: { name: 'acme_app', label: 'Acme', active: true, navigation: NAV } }; - if (type === 'report') return { effective: JSON.parse(JSON.stringify(stored)) }; - return { code: null, overlay: null, overlayScope: null, effective: null }; - }), - getDraft: vi.fn(async () => null), - get: vi.fn(async (type: string, name: string) => - type === 'dataset' ? DATASETS.find((d) => d.name === name) : undefined, - ), -}; - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; -}); - -vi.mock('./packages-io', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, fetchPackages: vi.fn(async () => []) }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useAdapter: () => ({}) }; -}); - -import { InterfacesPillar } from './StudioDesignSurface'; -import { registerMetadataPreview } from '../metadata-admin/preview-registry'; -import { registerMetadataDefaultInspector } from '../metadata-admin/default-inspector-registry'; -import { ReportDefaultInspector } from '../metadata-admin/inspectors/ReportDefaultInspector'; -import { t, tFormat } from '../metadata-admin/i18n'; -// The pillar reaches the console's dynamic `@objectstack/lint` imports; their -// first load is paid here, at collection, never inside a case's clock -// (`check:test-source-alias`). -import '@objectstack/lint'; - -// A stub canvas: the leaf needs a registered preview to be draft-editable, -// and the canvas's own drawing is not what this file pins. -registerMetadataPreview('report', () => null); -registerMetadataDefaultInspector('report', ReportDefaultInspector); - -beforeEach(() => { - stored = SUMMARY_REPORT; - for (const fn of Object.values(mockClient)) fn.mockClear(); -}); -afterEach(cleanup); - -const L = (key: string) => t(key, 'en'); - -function mountPillar(onHeldEditChange?: (clause: string | null) => void) { - return render( - - - , - ); -} - -function reportSaves(): Array> { - return mockClient.save.mock.calls.filter((c) => c[0] === 'report').map((c) => c[2]); -} - -/** Past the autosave's 1.5 s debounce. */ -async function outlastDebounce(): Promise { - await act(async () => { - await new Promise((r) => setTimeout(r, 2300)); - }); -} - -/** The report's properties are open, with the list property labelled `list` drawn. */ -async function ready(list: string): Promise { - const inspector = await screen.findByTestId('if-inspector', undefined, { timeout: 8000 }); - await within(inspector).findByText(list, { selector: 'label' }, { timeout: 8000 }); - return inspector; -} - -/** The form row of the list property labelled `label`: its label and its repeater. */ -function listRow(inspector: HTMLElement, label: string): HTMLElement { - const row = within(inspector).getByText(label, { selector: 'label' }).parentElement?.parentElement; - if (!row) throw new Error(`no form row for ${label}`); - return row; -} - -/** The report's own Label input. */ -function editLabel(inspector: HTMLElement, value: string): void { - const input = within(inspector).getByLabelText(L('engine.inspector.report.label')); - fireEvent.change(input, { target: { value } }); - fireEvent.blur(input); -} - -/** Picks `option` in the inspector select labelled `label`. */ -async function pick(inspector: HTMLElement, label: string, option: string | RegExp): Promise { - fireEvent.keyDown(within(inspector).getByRole('combobox', { name: label }), { key: 'ArrowDown' }); - await waitFor(() => expect(screen.queryAllByRole('option').length).toBeGreaterThan(0)); - fireEvent.click(screen.getByRole('option', { name: option })); -} - -const heldLine = (clause: string) => tFormat('engine.studio.held.line', 'en', { clause }); -const joinedClause = tFormat('engine.studio.held.reportJoinedNeedsBlock', 'en', { list: 'Blocks' }); - -describe('a report switched to Joined is held until its first block is added (objectstack#29022)', () => { - it('Report type = Joined, then a Label edit: nothing is sent, no red strip, the line names Blocks', async () => { - const report = vi.fn(); - mountPillar(report); - const inspector = await ready('Sort Order'); - await pick(inspector, L('engine.inspector.report.type'), L('engine.inspector.report.type.joined')); - editLabel(inspector, 'Sales v2'); - await outlastDebounce(); - - expect(reportSaves(), 'the joined report without blocks is not sent, nor the Label edit with it').toEqual([]); - expect(screen.queryByTestId('studio-refusal'), 'no red strip on the normal path').toBeNull(); - expect(screen.getByTestId('studio-held-message')).toHaveTextContent(heldLine(joinedClause)); - // The surface's half: its leave guard and Publish read the held clause. - expect(report).toHaveBeenLastCalledWith(joinedClause); - }); - - it('"Show me" focuses the Blocks list in the report properties', async () => { - mountPillar(); - const inspector = await ready('Sort Order'); - await pick(inspector, L('engine.inspector.report.type'), L('engine.inspector.report.type.joined')); - await within(inspector).findByText('Blocks', { selector: 'label' }); - const row = listRow(inspector, 'Blocks'); - const show = await within(await screen.findByTestId('studio-held')).findByRole('button', { - name: L('engine.studio.refusal.show'), - }); - (document.activeElement as HTMLElement | null)?.blur(); - fireEvent.click(show); - await waitFor(() => expect(row.contains(document.activeElement)).toBe(true)); - }); - - it('Blocks → Add item hands the hold to the new block, still unsent', async () => { - const report = vi.fn(); - mountPillar(report); - const inspector = await ready('Sort Order'); - await pick(inspector, L('engine.inspector.report.type'), L('engine.inspector.report.type.joined')); - await within(inspector).findByText('Blocks', { selector: 'label' }); - fireEvent.click(within(listRow(inspector, 'Blocks')).getByRole('button', { name: L('engine.form.addItem') })); - await outlastDebounce(); - - const clause = tFormat('engine.studio.held.listItemNeedsInput', 'en', { input: 'Name', n: 1, list: 'Blocks' }); - expect(reportSaves()).toEqual([]); - expect(screen.queryByTestId('studio-refusal')).toBeNull(); - expect(screen.getByTestId('studio-held-message')).toHaveTextContent(heldLine(clause)); - expect(report).toHaveBeenLastCalledWith(clause); - }); - - // CONTROL: a type switch the door accepts saves at once. - it('Report type = Tabular saves at once, with no line', async () => { - mountPillar(); - const inspector = await ready('Sort Order'); - await pick(inspector, L('engine.inspector.report.type'), L('engine.inspector.report.type.tabular')); - await waitFor(() => expect(reportSaves()).toHaveLength(1), { timeout: 4000 }); - expect(reportSaves()[0].type).toBe('tabular'); - expect(screen.queryByTestId('studio-held')).toBeNull(); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.saveErrorClears-11950.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.saveErrorClears-11950.test.tsx deleted file mode 100644 index 4abba71c7cb..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.saveErrorClears-11950.test.tsx +++ /dev/null @@ -1,250 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#11950 — a leaf save that goes through clears the red refusal strip - * an earlier save of that leaf showed. - * - * The card: an Interfaces leaf (a dashboard here) whose autosave the draft door - * refused showed "Changes not saved", and the strip stayed after the next edit - * was saved. The leaf `doSave` set the pillar's error in its `catch` and - * nothing but a leaf (re)load cleared it, so the strip went on saying the - * draft was refused after the draft had been saved, until the author left the - * leaf. Each save now starts clear, as the Data and Automations pillars' saves - * do: as it is sent, before the request. - * - * Mounted like `InterfacesPillar.heldWidget-11910.test.tsx`: a metadata client - * double that answers each dashboard save from a script (refuse, hold in - * flight, or accept), the real `DashboardPreview` canvas and the real - * `DashboardWidgetInspector`. Edits go through the bound widget's title. - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; -import { MemoryRouter } from 'react-router-dom'; -// Module-scope import of the lazily loaded canvas renderer (AGENTS.md, -// flaky-test discipline). -import '@object-ui/plugin-dashboard'; - -const NAV = [{ id: 'nav_sales', type: 'dashboard', label: 'Sales', dashboardName: 'sales_dash' }]; - -/** One bound widget: an edit to its title is a finished edit, sent at once. */ -const SALES_DASH = { - name: 'sales_dash', - label: 'Sales', - widgets: [ - { - id: 'pipeline', - type: 'metric', - title: 'Pipeline', - dataset: 'sales_ds', - values: ['revenue'], - layout: { x: 0, y: 0, w: 3, h: 2 }, - }, - ], -}; - -const DATASETS = [ - { - name: 'sales_ds', - label: 'Sales', - object: 'opportunity', - dimensions: [{ name: 'stage', label: 'Stage' }], - measures: [{ name: 'revenue', label: 'Revenue', aggregate: 'sum' }], - }, -]; - -/** A save the double holds in flight until the test lets it land. */ -interface Held { - hold: Promise; - land: () => void; -} - -function held(): Held { - let land = () => {}; - const hold = new Promise((resolve) => { - land = resolve; - }); - return { hold, land }; -} - -/** How the double answers each dashboard save, in order; past the end it accepts. */ -let script: Array; - -/** The draft door's 422, naming one issue on the dashboard's only widget. */ -function refusal(message: string): Error { - return Object.assign(new Error('Validation failed'), { - status: 422, - issues: [{ path: 'widgets.0.dataset', message }], - }); -} - -const mockClient = { - // The Studio's dataset pickers read the draft-overlaid catalog (objectstack#27518). - withPreviewDrafts: vi.fn((): unknown => mockClient), - save: vi.fn(async (type: string, _name: string, _body: Record) => { - if (type === 'dashboard') { - const step = script.shift() ?? 'accept'; - if (step instanceof Error) throw step; - if (step !== 'accept') await step.hold; - } - return { success: true, version: 'v1', state: 'draft' }; - }), - list: vi.fn(async (type: string) => { - if (type === 'app') return [{ name: 'acme_app', label: 'Acme' }]; - if (type === 'dataset') return DATASETS; - if (type === 'dashboard') return [SALES_DASH]; - return []; - }), - listDrafts: vi.fn(async () => []), - layered: vi.fn(async (type: string) => { - if (type === 'app') return { effective: { name: 'acme_app', label: 'Acme', active: true, navigation: NAV } }; - if (type === 'dashboard') return { effective: JSON.parse(JSON.stringify(SALES_DASH)) }; - return { code: null, overlay: null, overlayScope: null, effective: null }; - }), - getDraft: vi.fn(async () => null), - get: vi.fn(async (type: string, name: string) => - type === 'dataset' ? DATASETS.find((d) => d.name === name) : undefined, - ), -}; - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; -}); - -vi.mock('./packages-io', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, fetchPackages: vi.fn(async () => []) }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useAdapter: () => ({}) }; -}); - -import { InterfacesPillar } from './StudioDesignSurface'; -import { registerMetadataPreview } from '../metadata-admin/preview-registry'; -import { registerMetadataInspector } from '../metadata-admin/inspector-registry'; -import { DashboardPreview } from '../metadata-admin/previews/DashboardPreview'; -import { DashboardWidgetInspector } from '../metadata-admin/inspectors/DashboardWidgetInspector'; -import { t } from '../metadata-admin/i18n'; - -registerMetadataPreview('dashboard', DashboardPreview); -registerMetadataInspector('dashboard', DashboardWidgetInspector); - -beforeEach(() => { - script = []; - for (const fn of Object.values(mockClient)) fn.mockClear(); -}); -afterEach(cleanup); - -function mountPillar() { - return render( - - - , - ); -} - -function dashboardSaves(): Array> { - return mockClient.save.mock.calls.filter((c) => c[0] === 'dashboard').map((c) => c[2]); -} - -/** The right rail: the inspector's own aside (classic layout). */ -function rail(): HTMLElement { - return screen.getByRole('complementary'); -} - -async function flush(): Promise { - await act(async () => { - await new Promise((r) => setTimeout(r, 0)); - }); -} - -/** The dashboard leaf is open on its canvas, its bound widget's inspector in the rail. */ -async function openPipeline(): Promise { - await screen.findByTitle('dashboard · sales_dash', undefined, { timeout: 8000 }); - const [pipeline] = await screen.findAllByTestId('dashboard-preview-widget-pipeline', undefined, { timeout: 8000 }); - fireEvent.click(pipeline); - return within(rail()).findByDisplayValue('Pipeline'); -} - -/** A finished edit: the widget's title, which the autosave sends as save number `nth`. */ -async function retitle(title: HTMLElement, value: string, nth: number): Promise { - fireEvent.change(title, { target: { value } }); - await waitFor(() => expect(dashboardSaves()).toHaveLength(nth), { timeout: 4000 }); - await flush(); -} - -/** *Add widget* → *Metric (KPI)*: an unbound widget, which the pillar holds unsent (objectui#11910). */ -async function addMetric(): Promise { - await userEvent.click(screen.getByRole('button', { name: t('engine.inspector.add.widget', 'en') })); - await userEvent.click(await screen.findByRole('button', { name: /^Metric \(KPI\)/ })); - await within(rail()).findByDisplayValue('New metric (kpi)', undefined, { timeout: 8000 }); -} - -const FIRST = 'Dataset "sales_ds" is not published'; -const SECOND = 'Dataset "sales_ds" was deleted'; - -describe('a leaf save that goes through clears the refusal an earlier save showed (objectui#11950)', () => { - it('a refused save, then a save that goes through, leaves no strip', async () => { - script = [refusal(FIRST), 'accept']; - mountPillar(); - const title = await openPipeline(); - - await retitle(title, 'Pipeline value', 1); - expect(await screen.findByTestId('studio-refusal-detail')).toHaveTextContent(FIRST); - - await retitle(title, 'Pipeline total', 2); - expect(dashboardSaves()[1]).toMatchObject({ widgets: [{ id: 'pipeline', title: 'Pipeline total' }] }); - await waitFor(() => expect(screen.queryByTestId('studio-refusal'), 'the saved draft shows no refusal').toBeNull()); - }); - - // CONTROL: the reset does not swallow a refusal. - it('a second refused save still shows its own refusal', async () => { - script = [refusal(FIRST), refusal(SECOND)]; - mountPillar(); - const title = await openPipeline(); - - await retitle(title, 'Pipeline value', 1); - expect(await screen.findByTestId('studio-refusal-detail')).toHaveTextContent(FIRST); - - await retitle(title, 'Pipeline total', 2); - await waitFor(() => expect(screen.getByTestId('studio-refusal-detail')).toHaveTextContent(SECOND)); - expect(screen.getAllByTestId('studio-refusal'), 'one strip, the latest save\'s').toHaveLength(1); - expect(screen.getByTestId('studio-refusal-detail')).not.toHaveTextContent(FIRST); - }); - - // The held notice is the pillar's other line, read from the buffer rather - // than from a save: a save that clears the refusal leaves it standing. The - // sequence the pillar allows is on the same leaf, an unbound widget added - // while a save is in flight; it holds one leaf's buffer only (objectui#11272), - // so no other leaf's save can land beside a held one. - it('a save in flight clears the refusal as it is sent, and leaves the hold an edit taken meanwhile raised', async () => { - const inFlight = held(); - script = [refusal(FIRST), inFlight]; - mountPillar(); - const title = await openPipeline(); - - await retitle(title, 'Pipeline value', 1); - expect(await screen.findByTestId('studio-refusal')).toBeInTheDocument(); - - await retitle(title, 'Pipeline total', 2); - expect(screen.queryByTestId('studio-refusal'), 'cleared as the save is sent, as the other pillars\' saves are').toBeNull(); - - await addMetric(); - expect(screen.getByTestId('studio-held')).toBeInTheDocument(); - - await act(async () => { - inFlight.land(); - }); - await flush(); - expect(screen.queryByTestId('studio-refusal')).toBeNull(); - expect(screen.getByTestId('studio-held'), 'the unbound widget is still held').toBeInTheDocument(); - expect(within(rail()).getByTestId('widget-field-held-hint-dataset')).toBeInTheDocument(); - expect(dashboardSaves(), 'and still unsent').toHaveLength(2); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.showMeFocus-26730.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.showMeFocus-26730.test.tsx deleted file mode 100644 index 32eb0df3d61..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.showMeFocus-26730.test.tsx +++ /dev/null @@ -1,190 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#26730 — the Interfaces strip gets a "Show me" that ends on the input. - * - * Measured before this card: a refused leaf save on the Interfaces page showed - * its strip with no "Show me" at all, because the leaf save placed nothing - * (`issueRefusal` with no locator). A dashboard's widget and a report's own - * properties are now placed, and "Show me" opens them with the focus on the - * input the sentence names: the widget's Title, the report's Label. - * - * Mounted like `InterfacesPillar.saveErrorClears-11950.test.tsx`: a metadata - * client double whose leaf save answers the draft door's 422, with the real - * registered previews and inspectors. - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; -// Module-scope import of the lazily loaded canvas renderer (AGENTS.md, -// flaky-test discipline). -import '@object-ui/plugin-dashboard'; - -const DASH_NAV = [{ id: 'nav_sales', type: 'dashboard', label: 'Sales', dashboardName: 'sales_dash' }]; -const REPORT_NAV = [{ id: 'nav_rep', type: 'report', label: 'Sales report', reportName: 'sales_report' }]; - -/** The app's navigation: the leaf the pillar opens first. */ -let nav: Array> = DASH_NAV; - -/** One bound widget: an edit to its title is a finished edit, sent at once. */ -const SALES_DASH = { - name: 'sales_dash', - label: 'Sales', - widgets: [ - { - id: 'pipeline', - type: 'metric', - title: 'Pipeline', - dataset: 'sales_ds', - values: ['revenue'], - layout: { x: 0, y: 0, w: 3, h: 2 }, - }, - ], -}; - -const SALES_REPORT = { - name: 'sales_report', - label: 'Sales report', - type: 'tabular', - dataset: 'sales_ds', - values: ['revenue'], -}; - -const DATASETS = [ - { - name: 'sales_ds', - label: 'Sales', - object: 'opportunity', - dimensions: [{ name: 'stage', label: 'Stage' }], - measures: [{ name: 'revenue', label: 'Revenue', aggregate: 'sum' }], - }, -]; - -/** The draft door's 422 for every leaf save, naming `issuePath`. */ -let issuePath = 'widgets.0.title'; - -function refusal(): Error { - return Object.assign(new Error('Validation failed'), { - status: 422, - issues: [{ path: issuePath, message: 'Too long' }], - }); -} - -const mockClient = { - // The Studio's dataset pickers read the draft-overlaid catalog (objectstack#27518). - withPreviewDrafts: vi.fn((): unknown => mockClient), - save: vi.fn(async (type: string, _name: string, _body: Record) => { - if (type === 'dashboard' || type === 'report') throw refusal(); - return { success: true, version: 'v1', state: 'draft' }; - }), - list: vi.fn(async (type: string) => { - if (type === 'app') return [{ name: 'acme_app', label: 'Acme' }]; - if (type === 'dataset') return DATASETS; - if (type === 'dashboard') return [SALES_DASH]; - if (type === 'report') return [SALES_REPORT]; - return []; - }), - listDrafts: vi.fn(async () => []), - layered: vi.fn(async (type: string) => { - if (type === 'app') return { effective: { name: 'acme_app', label: 'Acme', active: true, navigation: nav } }; - if (type === 'dashboard') return { effective: JSON.parse(JSON.stringify(SALES_DASH)) }; - if (type === 'report') return { effective: JSON.parse(JSON.stringify(SALES_REPORT)) }; - return { code: null, overlay: null, overlayScope: null, effective: null }; - }), - getDraft: vi.fn(async () => null), - get: vi.fn(async (type: string, name: string) => - type === 'dataset' ? DATASETS.find((d) => d.name === name) : undefined, - ), -}; - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; -}); - -vi.mock('./packages-io', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, fetchPackages: vi.fn(async () => []) }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useAdapter: () => ({}) }; -}); - -import { InterfacesPillar } from './StudioDesignSurface'; -import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; -import { registerBuiltinPreviews } from '../metadata-admin/previews'; -import { t, tFormat } from '../metadata-admin/i18n'; - -registerBuiltinPreviews(); -registerBuiltinInspectors(); - -beforeEach(() => { - nav = DASH_NAV; - issuePath = 'widgets.0.title'; - for (const fn of Object.values(mockClient)) fn.mockClear(); -}); -afterEach(cleanup); - -function mountPillar() { - return render( - - - , - ); -} - -/** The right rail: the inspector's own aside (classic layout). */ -function rail(): HTMLElement { - return screen.getByTestId('if-inspector'); -} - -const L = (key: string) => t(key, 'en'); - -describe('Interfaces page — "Show me" puts the focus on the input the refusal names (objectstack#26730)', () => { - it('a dashboard widget\'s title: the widget opens with the focus on its Title', async () => { - mountPillar(); - await screen.findByTitle('dashboard · sales_dash', undefined, { timeout: 8000 }); - const [pipeline] = await screen.findAllByTestId('dashboard-preview-widget-pipeline', undefined, { timeout: 8000 }); - fireEvent.click(pipeline); - fireEvent.change(await within(rail()).findByDisplayValue('Pipeline'), { target: { value: 'Pipeline value' } }); - - const strip = await screen.findByTestId('studio-refusal', undefined, { timeout: 4000 }); - expect(within(strip).getByTestId('studio-refusal-message')).toHaveTextContent( - tFormat('engine.studio.refusal.widgetInput', 'en', { input: L('engine.inspector.widget.title'), widget: 'Pipeline value' }), - ); - - // Away from the widget: Escape drops the selection, so its inspector closes. - fireEvent.keyDown(document, { key: 'Escape' }); - await waitFor(() => expect(within(rail()).queryByDisplayValue('Pipeline value')).toBeNull()); - - fireEvent.click(within(strip).getByRole('button', { name: L('engine.studio.refusal.show') })); - const title = await within(rail()).findByDisplayValue('Pipeline value', undefined, { timeout: 4000 }); - await waitFor(() => expect(document.activeElement).toBe(title)); - }); - - it('a report\'s own input: its properties open with the focus on it', async () => { - nav = REPORT_NAV; - issuePath = 'label'; - mountPillar(); - await screen.findByTitle('report · sales_report', undefined, { timeout: 8000 }); - const label = (await within(rail()).findByLabelText(L('engine.inspector.report.label'), undefined, { - timeout: 8000, - })) as HTMLInputElement; - fireEvent.change(label, { target: { value: 'Sales by stage' } }); - - const strip = await screen.findByTestId('studio-refusal', undefined, { timeout: 4000 }); - expect(within(strip).getByTestId('studio-refusal-message')).toHaveTextContent( - tFormat('engine.studio.refusal.reportInput', 'en', { input: L('engine.inspector.report.label') }), - ); - - const show = within(strip).getByRole('button', { name: L('engine.studio.refusal.show') }); - show.focus(); - fireEvent.click(show); - await waitFor(() => expect(document.activeElement).toBe(within(rail()).getByLabelText(L('engine.inspector.report.label')))); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.slotGutter-12611.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.slotGutter-12611.test.tsx deleted file mode 100644 index b68eec4ce69..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.slotGutter-12611.test.tsx +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#12611 — the Interfaces canvas beside a right-hand panel keeps a - * 16 px gutter instead of 24, so a dashboard's tiles get their width. - * - * objectui#12725 re-points this file. The folded "Canvas / Properties" toggle - * it pinned is gone with the folded layout: the Studio surface's right slot - * shows the properties OR the copilot, and the pillar portals its inspector - * into the slot. So the dot that said "the folded aside holds an editor" is - * now the slot being asked for its properties: a selection calls `showProps`, - * and the element's inspector is in the slot's target. The 16 px gutter moves - * with the slot; the classic layout (no slot) keeps 24 px and its own aside. - * The slot's chrome itself is pinned in - * `StudioDesignSurface.rightSlot-12725.test.tsx`. - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; - -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addListener: () => {}, - removeListener: () => {}, - addEventListener: () => {}, - removeEventListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; - -const NAV = [{ id: 'nav_dash', type: 'dashboard', label: 'Overview', dashboardName: 'sales_overview' }]; - -const mockClient = { - save: vi.fn(async () => ({})), - list: vi.fn(async (type: string) => (type === 'app' ? [{ name: 'acme_app', label: 'Acme' }] : [])), - listDrafts: vi.fn(async () => []), - layered: vi.fn(async (type: string, name: string) => { - if (type === 'app') return { effective: { name: 'acme_app', label: 'Acme', navigation: NAV } }; - if (type === 'dashboard') return { effective: { name: 'sales_overview', label: 'Sales' } }; - return { effective: { name } }; - }), - getDraft: vi.fn(async () => null), - get: vi.fn(async () => undefined), - withPreviewDrafts() { - return this; - }, -}; - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; -}); - -vi.mock('./packages-io', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, fetchPackages: vi.fn(async () => []) }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useAdapter: () => ({}) }; -}); - -import { InterfacesPillar } from './StudioDesignSurface'; -import { StudioRightSlotContext } from './studioRightSlotState'; -import { registerMetadataPreview } from '../metadata-admin/preview-registry'; -import { registerMetadataInspector } from '../metadata-admin/inspector-registry'; -import { t } from '../metadata-admin/i18n'; - -function StubInspector(): React.ReactElement { - return
; -} - -function StubDashboardPreview(props: Record): React.ReactElement { - const onSel = props.onSelectionChange as ((s: unknown) => void) | undefined; - return ( - - ); -} - -registerMetadataPreview('dashboard', StubDashboardPreview as never); -registerMetadataInspector('dashboard', StubInspector as never); - -afterEach(cleanup); - -const slotCalls = { claims: 0, releases: 0, showProps: 0 }; - -// Stable, as the surface's own are (`useCallback`): a claim per mount. -const claimProps = () => { - slotCalls.claims += 1; - return () => { - slotCalls.releases += 1; - }; -}; -const showProps = () => { - slotCalls.showProps += 1; -}; - -/** The Studio surface's right slot, reduced to what the pillar reads of it. */ -function SlotHost({ children }: { children: React.ReactNode }) { - const [target, setTarget] = React.useState(null); - const handle = React.useMemo( - () => ({ propsTarget: target, mode: 'copilot' as const, claimProps, showProps }), - [target], - ); - return ( - - {children} -
- - ); -} - -function mountPillar(inSlot: boolean) { - slotCalls.claims = 0; - slotCalls.releases = 0; - slotCalls.showProps = 0; - const pillar = ; - return render( - {inSlot ? {pillar} : pillar}, - ); -} - -async function openDashboard() { - fireEvent.click(await screen.findByTitle('dashboard · sales_overview')); - await screen.findByTestId('pick-block', undefined, { timeout: 4000 }); -} - -describe('the Interfaces canvas beside the right slot (objectui#12611, objectui#12725)', () => { - it('a selection asks the slot for its properties, and the element’s inspector is in the slot', async () => { - const { unmount } = mountPillar(true); - await openDashboard(); - expect(slotCalls.claims).toBe(1); - const target = screen.getByTestId('slot-target'); - // Nothing selected and no home inspector registered: the invitation, in the slot. - expect(within(target).getByTestId('if-inspector')).toHaveTextContent(t('engine.studio.inspector.emptyLine1', 'en')); - expect(slotCalls.showProps).toBe(0); - - fireEvent.click(screen.getByTestId('pick-block')); - expect(await within(target).findByTestId('stub-inspector', undefined, { timeout: 4000 })).toBeInTheDocument(); - expect(slotCalls.showProps).toBe(1); - - fireEvent.click(screen.getByLabelText(t('engine.studio.deselect', 'en'))); - await waitFor(() => expect(within(target).queryByTestId('stub-inspector')).toBeNull()); - expect(slotCalls.showProps).toBe(1); - - unmount(); - expect(slotCalls.releases).toBe(1); - }); - - it('beside the slot, the canvas keeps a 16 px gutter and draws no toggle of its own', async () => { - mountPillar(true); - await openDashboard(); - const main = screen.getByTestId('if-canvas-main'); - expect(main).toHaveClass('px-4'); - expect(main).not.toHaveClass('px-6'); - expect(screen.queryByTestId('studio-center-tabs')).toBeNull(); - expect(screen.queryByTestId('if-properties-toggle')).toBeNull(); - }); - - it('CONTROL — no slot (the classic layout): a 24 px gutter, the aside beside the canvas and its toggle', async () => { - mountPillar(false); - await openDashboard(); - const main = screen.getByTestId('if-canvas-main'); - expect(main).toHaveClass('px-6'); - expect(main).not.toHaveClass('px-4'); - expect(screen.queryByTestId('studio-center-tabs')).toBeNull(); - expect(screen.getByTestId('if-properties-toggle')).toBeInTheDocument(); - expect(main.parentElement?.contains(screen.getByTestId('if-inspector'))).toBe(true); - expect(slotCalls.claims).toBe(0); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.sourcePage-12522.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.sourcePage-12522.test.tsx deleted file mode 100644 index f50808b185d..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.sourcePage-12522.test.tsx +++ /dev/null @@ -1,267 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#12522 — the page designer for a source page (`kind: 'html'` / - * `'react'`), and Run mode for a block-tree page. - * - * - The properties of an html page show what the page IS: its label - * (editable, and the edit autosaves), its identifier, the "Written in" kind, - * and every navigation entry that opens it, a nested one with its group. - * objectui#12725 — they are the whole aside now: no Source / Properties - * tabs; the code editor opens from the item's ⋯ menu (View definition). - * - The status line under the source editor says "Saved" for the buffer as it - * was read, "Unsaved" once it is edited, and "Saved HH:MM" once the - * pillar's own save of it lands. - * - The Design / Run switch is disabled on a source page (Run draws exactly - * what Design draws), and the reason is the wrapper's: a tab stop, and a - * visually hidden copy both buttons are described by (objectui#12303). - * - CONTROL, a block-tree page: the switch is live, Design draws the block - * canvas's chrome ("Add block", the selectable block), and Run renders the - * page without any of it. - * - * The canvas and inspectors are the REAL registered page designers; the client - * is a server double that records every save, as in the sibling - * `StudioDesignSurface.interfacesReadOnly-11136.test.tsx`. - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen, fireEvent, cleanup, waitFor, within } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; - -const PKG = 'com.acme.app'; - -const NAV = [ - { id: 'nav_home', type: 'page', label: 'Home', pageName: 'home' }, - { id: 'nav_landing', type: 'page', label: 'Landing', pageName: 'landing' }, - { - id: 'grp_help', - type: 'group', - label: 'Help', - children: [{ id: 'nav_landing_again', type: 'page', label: 'Start here', pageName: 'landing' }], - }, -]; -const APP = { name: 'acme_app', label: 'Acme', navigation: NAV }; - -/** A block page: one region, one leaf block the canvas renders and can select. */ -const HOME = { - name: 'home', - label: 'Home', - type: 'app', - regions: [{ name: 'main', components: [{ id: 'hello', type: 'element:text', properties: { content: 'Hello' } }] }], -}; - -/** A source page: no block tree. */ -const LANDING = { name: 'landing', label: 'Landing page', type: 'app', kind: 'html', source: '

Hi

' }; - -const server = vi.hoisted(() => ({ - active: new Map>(), - saves: [] as Array<{ type: string; name: string; body: Record }>, -})); - -const mockClient = vi.hoisted(() => { - const k = (type: string, name: string) => `${type}/${name}`; - return { - list: vi.fn(async (type: string) => - [...server.active.entries()] - .filter(([key]) => key.startsWith(`${type}/`)) - .map(([, row]) => ({ name: row.name, label: row.label ?? row.name })), - ), - listDrafts: vi.fn(async () => []), - listTypes: vi.fn(async () => ({ entries: [] })), - get: vi.fn(async () => null), - references: vi.fn(async () => []), - layered: vi.fn(async (type: string, name: string) => { - const eff = server.active.get(k(type, name)) ?? null; - return { code: null, overlay: eff, overlayScope: eff ? 'env' : null, effective: eff, editable: true, deletable: true, resettable: false, lock: 'none' }; - }), - getDraft: vi.fn(async (type: string, name: string) => { - throw Object.assign(new Error(`No pending draft exists for ${type}/${name}.`), { code: 'NO_DRAFT', status: 404 }); - }), - save: vi.fn(async (type: string, name: string, item: unknown) => { - server.saves.push({ type, name, body: JSON.parse(JSON.stringify(item)) as Record }); - return { type, name, item }; - }), - publish: vi.fn(async () => ({ success: true })), - reset: vi.fn(async () => ({})), - }; -}); - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; -}); - -vi.mock('./packages-io', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, fetchPackages: vi.fn(async () => []) }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useAdapter: () => dataSource }; -}); - -vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); - -// Monaco's loader fails (offline), so the source editor is its textarea. -vi.mock('@monaco-editor/react', () => { - const Editor = () => null; - return { Editor, default: Editor, loader: { init: () => Promise.reject(new Error('offline')) } }; -}); - -// The bundled Monaco loads: the page's probe awaits plugin-editor's -// `configureBundledMonaco` before `loader.init()` (its own suite drives it). -vi.mock('@object-ui/plugin-editor', () => ({ configureBundledMonaco: () => Promise.resolve() })); - -import { InterfacesPillar } from './StudioDesignSurface'; -import '../../services/builtinComponents.js'; -import { t, tFormat } from '../metadata-admin/i18n'; -import { createEmptyDataSource, failOnAbsorbedFetchError } from './__tests__/emptyDataSource'; -import { registerMetadataPreview } from '../metadata-admin/preview-registry'; -import { registerMetadataInspector } from '../metadata-admin/inspector-registry'; -import { registerMetadataDefaultInspector } from '../metadata-admin/default-inspector-registry'; -import { PagePreview } from '../metadata-admin/previews/PagePreview'; -import { PageBlockInspector } from '../metadata-admin/inspectors/PageBlockInspector'; -import { PageDefaultInspector } from '../metadata-admin/inspectors/PageDefaultInspector'; - -const dataSource = createEmptyDataSource(); -failOnAbsorbedFetchError(); - -registerMetadataPreview('page', PagePreview); -registerMetadataInspector('page', PageBlockInspector); -registerMetadataDefaultInspector('page', PageDefaultInspector); - -const key = (type: string, name: string) => `${type}/${name}`; - -beforeEach(() => { - server.active.clear(); - server.saves.length = 0; - for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear: () => void }).mockClear(); - server.active.set(key('app', APP.name), JSON.parse(JSON.stringify(APP))); - server.active.set(key('page', HOME.name), JSON.parse(JSON.stringify(HOME))); - server.active.set(key('page', LANDING.name), JSON.parse(JSON.stringify(LANDING))); -}); - -afterEach(cleanup); - -function renderPillar() { - return render( - - - , - ); -} - -function rail(): HTMLElement { - return screen.getByRole('complementary'); -} - -/** The home page (a block page) open: the pillar lands on it. */ -async function openHome(): Promise { - await screen.findByRole('button', { name: 'Select hello' }, { timeout: 8000 }); -} - -/** The landing page (an html page) open: its properties fill the aside. */ -async function openLanding(): Promise { - renderPillar(); - await openHome(); - fireEvent.click(screen.getByRole('button', { name: /^Landing/ })); - return within(rail()).findByTestId('source-page-properties', undefined, { timeout: 8000 }); -} - -/** objectui#12725 — the code editor, opened from the item's ⋯ menu (View definition). */ -async function openSource(): Promise<{ editor: HTMLTextAreaElement; sheet: HTMLElement }> { - fireEvent.pointerDown(screen.getByTestId('if-item-more'), { button: 0, ctrlKey: false }); - fireEvent.click(await screen.findByTestId('if-item-view-definition')); - const sheet = await screen.findByTestId('if-definition-sheet'); - const editor = await within(sheet).findByRole('textbox', { name: 'Page source' }, { timeout: 8000 }); - return { editor: editor as HTMLTextAreaElement, sheet }; -} - -function modeButtons(): { design: HTMLElement; run: HTMLElement } { - const toggle = screen.getByTestId('canvas-mode-toggle'); - return { - design: within(toggle).getByRole('button', { name: 'Design' }), - run: within(toggle).getByRole('button', { name: 'Run' }), - }; -} - -describe('Interfaces pillar — a source page (objectui#12522)', () => { - it("the properties list the page's label, identifier, kind and the navigation entries that open it", async () => { - const props = await openLanding(); - // objectui#12725 — no Source / Properties tab strip over them. - expect(within(rail()).queryAllByRole('tab')).toHaveLength(0); - - expect(within(props).getByLabelText(t('engine.studio.if.pageProps.label', 'en'))).toHaveValue('Landing page'); - expect(within(props).getByTestId('source-page-identifier')).toHaveTextContent('landing'); - expect(within(props).getByTestId('source-page-kind')).toHaveTextContent( - t('engine.studio.interfaces.create.pageKindHtml', 'en'), - ); - const entries = within(within(props).getByTestId('source-page-nav-entries')).getAllByRole('listitem'); - expect(entries.map((li) => li.getAttribute('data-nav-id'))).toEqual(['nav_landing', 'nav_landing_again']); - expect(entries[1]).toHaveTextContent('Help › Start here'); - // The page that is not this one is not listed. - expect(within(props).queryByText('Home')).toBeNull(); - }); - - it('a label edit in the properties autosaves, and the status line moves from Unsaved to Saved HH:MM', async () => { - await openLanding(); - const label = await within(rail()).findByLabelText(t('engine.studio.if.pageProps.label', 'en')); - fireEvent.change(label, { target: { value: 'Welcome' } }); - - await waitFor(() => expect(server.saves).toHaveLength(1), { timeout: 8000 }); - expect(server.saves[0]).toMatchObject({ type: 'page', name: 'landing', body: { label: 'Welcome', kind: 'html' } }); - - const { sheet } = await openSource(); - await waitFor(() => expect(within(sheet).getByTestId('source-page-status')).toHaveAttribute('data-state', 'saved')); - expect(within(sheet).getByTestId('source-page-status').textContent).toMatch(/^Saved \d{1,2}:\d{2}/); - }); - - it('a source edit reads Unsaved until its save lands', async () => { - await openLanding(); - const { editor, sheet } = await openSource(); - expect(within(sheet).getByTestId('source-page-status')).toHaveTextContent(t('engine.studio.if.pageSaved', 'en')); - fireEvent.change(editor, { target: { value: '

Hello

' } }); - expect(within(sheet).getByTestId('source-page-status')).toHaveTextContent(t('engine.studio.if.pageUnsaved', 'en')); - await waitFor(() => expect(server.saves).toHaveLength(1), { timeout: 8000 }); - }); - - it('the Design / Run switch is disabled, and says why through a focusable wrapper (objectui#12303 pattern)', async () => { - await openLanding(); - - const { design, run } = modeButtons(); - expect(design).toBeDisabled(); - expect(run).toBeDisabled(); - const reason = screen.getByTestId('canvas-mode-reason'); - expect(reason).toHaveClass('sr-only'); - expect(reason).toHaveTextContent( - tFormat('engine.studio.if.modeSourcePage', 'en', { kind: t('engine.studio.interfaces.create.pageKindHtml', 'en') }), - ); - expect(design).toHaveAttribute('aria-describedby', reason.id); - expect(run).toHaveAttribute('aria-describedby', reason.id); - const wrapper = reason.closest('[data-disabled-reason]') as HTMLElement; - expect(wrapper).toHaveAttribute('tabindex', '0'); - expect(wrapper).toHaveAttribute('aria-describedby', reason.id); - }); -}); - -describe('Interfaces pillar — Run mode of a block-tree page (objectui#12522 control)', () => { - it('Design draws the block canvas chrome; Run renders the page without it, through a live switch', async () => { - renderPillar(); - await openHome(); - - const { design, run } = modeButtons(); - expect(design).toBeEnabled(); - expect(run).toBeEnabled(); - expect(screen.queryByTestId('canvas-mode-reason')).toBeNull(); - expect(screen.getAllByRole('button', { name: 'Add block' }).length).toBeGreaterThan(0); - - fireEvent.click(run); - - await waitFor(() => expect(screen.queryByRole('button', { name: 'Select hello' })).toBeNull(), { timeout: 8000 }); - expect(screen.queryAllByRole('button', { name: 'Add block' })).toHaveLength(0); - expect(await screen.findByText('Hello', undefined, { timeout: 8000 })).toBeInTheDocument(); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/ListViewBulkActionsSection.tsx b/ui/packages/app-shell/src/views/studio-design/ListViewBulkActionsSection.tsx deleted file mode 100644 index 9cda9840783..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/ListViewBulkActionsSection.tsx +++ /dev/null @@ -1,633 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#30089 — the selection-bar actions of a list view, in the - * list-view panel: the buttons the list shows when rows are selected. Two keys - * of the list body, both the spec's (`ListViewSchema`), and no other: - * - * - `bulkActions` — names of actions the object declares, picked by label. - * The grid promotes each to that action (its label, params, `visible`), so - * it runs once per selected record. The built-in Delete is offered here - * too, under its reserved name `delete`. - * - `bulkActionDefs` — field updates (`operation: 'update'`): a label, the - * fields the dialog asks for (one param per field, named for it, so the - * value is written to that field) and a confirmation sentence. A def is - * written only once it has a label and a field, and only when the spec's - * `BulkActionDefSchema` accepts it. - * - * The built-in Delete: the grid shows it on the selection bar while the view - * declares neither key. Once the view declares either, Delete stays only when - * `bulkActions` names it (`bulkDeleteStateOf`). The section says which holds. - * - * A def of another kind (`delete`, an aggregate `custom` dispatch) is shown - * with its label and can be removed; it is edited in metadata. A name in - * `bulkActions` the object does not declare is shown marked, with its remove - * button. An emptied key is removed, never written empty, so a view that - * declares neither key is saved as it was. - * - * Only a grid draws the selection bar these keys configure, so only a grid - * view shows the section (`listViewHasSelectionBar`). Writes go through the - * panel's `writeBody`, the buffer every other section edits, so a read-only - * base's view is written through the same customization copy. - */ - -import * as React from 'react'; -import { Plus, X } from 'lucide-react'; -import { - Button, - Input, - Label, - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from '@object-ui/components'; -import { BulkActionDefSchema, resolveI18nLabel, type I18nLabel } from '@objectstack/spec/ui'; -import { useMetadataClient } from '../metadata-admin/useMetadata.js'; -import { readFields } from '../metadata-admin/previews/object-fields-io.js'; -import { t, tFormat } from '../metadata-admin/i18n.js'; -import { isStudioHiddenSystemField } from './studioHiddenSystemField.js'; - -type Row = Record; - -function isPlainObject(v: unknown): v is Row { - return !!v && typeof v === 'object' && !Array.isArray(v); -} - -function namesOf(v: unknown): string[] { - return Array.isArray(v) ? v.filter((n): n is string => typeof n === 'string' && n !== '') : []; -} - -function defsOf(v: unknown): Row[] { - return Array.isArray(v) ? v.filter(isPlainObject) : []; -} - -/** The reserved `bulkActions` name of the grid's built-in Delete. */ -export const BUILTIN_BULK_DELETE = 'delete'; - -/** Whether a list body's type draws the selection bar these keys configure: a grid. */ -export function listViewHasSelectionBar(body: Row): boolean { - return body.type === undefined || body.type === 'grid'; -} - -/** - * What the grid does with its built-in Delete for this body: `default` — the - * view declares no selection action, so Delete shows; `kept` — `bulkActions` - * names it; `dropped` — the view declares its own actions and not Delete. - */ -export type BulkDeleteState = 'default' | 'kept' | 'dropped'; - -export function bulkDeleteStateOf(body: Row): BulkDeleteState { - const names = namesOf(body.bulkActions); - if (names.length > 0) return names.some((n) => n.toLowerCase() === BUILTIN_BULK_DELETE) ? 'kept' : 'dropped'; - return defsOf(body.bulkActionDefs).length > 0 ? 'dropped' : 'default'; -} - -/** `body` with `key` set to `list`, or without `key` when `list` is empty. */ -function withList(body: Row, key: 'bulkActions' | 'bulkActionDefs', list: unknown[]): Row { - const { [key]: _dropped, ...rest } = body; - return list.length > 0 ? { ...rest, [key]: list } : rest; -} - -/** The field types a field update can ask for: a value the dialog can collect and the patch can write. */ -const UPDATABLE_FIELD_TYPES: ReadonlySet = new Set([ - 'text', 'textarea', 'email', 'url', 'phone', - 'number', 'currency', 'percent', - 'date', 'datetime', 'time', - 'boolean', 'toggle', - 'select', 'multiselect', 'radio', 'checkboxes', - 'lookup', 'master_detail', 'user', -]); - -/** A field a field update can ask for, with what its param needs from the field. */ -export interface UpdatableField { - name: string; - label: string; - type: string; - multiple: boolean; - options?: Array<{ label: string; value: string | number | boolean }>; - /** The record picker's object, for a `lookup` / `master_detail` field. */ - reference?: string; -} - -interface ObjectAction { - name: string; - label: string; -} - -function optionsOf(def: Row, locale: string): UpdatableField['options'] { - if (!Array.isArray(def.options)) return undefined; - const options = def.options.flatMap((o) => { - if (!isPlainObject(o)) return []; - const value = o.value; - if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') return []; - const label = resolveI18nLabel(o.label as I18nLabel | undefined, locale) || String(value); - return [{ label, value }]; - }); - return options.length > 0 ? options : undefined; -} - -/** The object's fields a field update can ask for: writable, of an updatable type, and not platform-injected. */ -export function updatableFieldsOf(object: Row | null, locale: string): UpdatableField[] { - if (!object) return []; - return readFields(object.fields).entries.flatMap(({ name, def }) => { - const type = typeof def.type === 'string' ? def.type : ''; - if (!UPDATABLE_FIELD_TYPES.has(type)) return []; - if (def.readonly === true || isStudioHiddenSystemField(def)) return []; - const reference = typeof def.reference === 'string' && def.reference !== '' ? def.reference : undefined; - // A record picker with no object to search cannot be drawn. - if ((type === 'lookup' || type === 'master_detail') && !reference) return []; - const options = optionsOf(def, locale); - return [ - { - name, - label: resolveI18nLabel(def.label as I18nLabel | undefined, locale) || name, - type, - multiple: def.multiple === true, - ...(options ? { options } : {}), - ...(reference && type !== 'user' ? { reference } : {}), - }, - ]; - }); -} - -function objectActionsOf(object: Row | null, locale: string): ObjectAction[] { - if (!object || !Array.isArray(object.actions)) return []; - return object.actions.flatMap((a) => { - if (!isPlainObject(a) || typeof a.name !== 'string' || a.name === '') return []; - return [{ name: a.name, label: resolveI18nLabel(a.label as I18nLabel | undefined, locale) || a.name }]; - }); -} - -/** The param a field update asks for `field` with: named for the field, so its value is written there. */ -export function bulkParamOfField(field: UpdatableField): Row { - return { - name: field.name, - label: field.label, - type: field.type, - required: true, - ...(field.multiple ? { multiple: true } : {}), - ...(field.options ? { options: field.options } : {}), - ...(field.reference ? { object: field.reference } : {}), - }; -} - -/** A def name no other selection action of the view holds: `update_`, else with `_N`. */ -function freeDefName(fields: string[], taken: string[]): string { - const wanted = `update_${fields.join('_')}`.slice(0, 60).replace(/_+$/, ''); - const held = new Set(taken); - if (!held.has(wanted)) return wanted; - let i = 2; - while (held.has(`${wanted}_${i}`)) i += 1; - return `${wanted}_${i}`; -} - -/** The first refusal the spec's `BulkActionDefSchema` answers `def` with, or `null` when it accepts it. */ -export function bulkDefRefusal(def: Row): string | null { - const verdict = BulkActionDefSchema.safeParse(def); - if (verdict.success) return null; - const issue = verdict.error.issues[0]; - return issue ? `${issue.path.join('.') || 'def'}: ${issue.message}` : 'invalid'; -} - -/** The object as the panel's other pickers read it: drafts overlaid. */ -function useObjectRead(objectName: string): { object: Row | null; loading: boolean; error: string | null } { - const client = useMetadataClient(); - const [state, setState] = React.useState<{ for: string; object: Row | null; error: string | null }>({ - for: '', - object: null, - error: null, - }); - React.useEffect(() => { - let cancelled = false; - client - .withPreviewDrafts(true) - .get('object', objectName) - .then( - (obj) => { - if (!cancelled) setState({ for: objectName, object: isPlainObject(obj) ? obj : null, error: null }); - }, - (err: unknown) => { - if (!cancelled) setState({ for: objectName, object: null, error: err instanceof Error ? err.message : String(err) }); - }, - ); - return () => { - cancelled = true; - }; - }, [client, objectName]); - const current = state.for === objectName; - return { object: current ? state.object : null, loading: !current, error: current ? state.error : null }; -} - -const ACTION_PICK_ID = 'studio-list-view-bulk-action-pick'; - -function RemoveButton({ name, onClick, locale }: { name: string; onClick: () => void; locale: string }) { - return ( - - ); -} - -/** Pick one of `fields` to add; the trigger reads `placeholder`. */ -function FieldPick({ - id, - fields, - placeholder, - onPick, - disabled, -}: { - id: string; - fields: UpdatableField[]; - placeholder: string; - onPick: (field: UpdatableField) => void; - disabled?: boolean; -}) { - return ( - - ); -} - -/** The params of a field update as chips: label, machine name, remove (never the last one). */ -function ParamChips({ - params, - onRemove, - readOnly, - locale, -}: { - params: Row[]; - onRemove: (name: string) => void; - readOnly: boolean; - locale: string; -}) { - return ( -
- {params.map((p) => { - const name = typeof p.name === 'string' ? p.name : ''; - const label = typeof p.label === 'string' && p.label ? p.label : name; - return ( - - {label} - {!readOnly && params.length > 1 && onRemove(name)} locale={locale} />} - - ); - })} -
- ); -} - -/** One field update of the view, edited in place. */ -function FieldUpdateRow({ - def, - index, - fields, - onChange, - onRemove, - readOnly, - locale, -}: { - def: Row; - index: number; - fields: UpdatableField[]; - onChange: (next: Row) => void; - onRemove: () => void; - readOnly: boolean; - locale: string; -}) { - const name = String(def.name ?? ''); - const params = defsOf(def.params); - const asked = new Set(params.map((p) => p.name)); - const label = typeof def.label === 'string' ? def.label : ''; - // A served def carries `confirmText` as the parsed `{ dialect, source }` - // envelope, the shorthand string lifted: the sentence is its `source`, and an - // edit keeps the envelope. - const envelope = isPlainObject(def.confirmText) ? def.confirmText : null; - const confirm = - typeof def.confirmText === 'string' ? def.confirmText : typeof envelope?.source === 'string' ? envelope.source : ''; - const setText = (key: 'label' | 'confirmText', value: string) => { - const { [key]: _dropped, ...rest } = def; - const kept = key === 'confirmText' && envelope ? { ...envelope, source: value } : value; - onChange(value.trim() ? { ...rest, [key]: kept } : rest); - }; - return ( -
-
- setText('label', e.target.value)} - placeholder={t('engine.studio.inspector.listView.bulk.defLabelPlaceholder', locale)} - disabled={readOnly} - className="h-7 flex-1 text-xs" - data-testid="list-view-bulk-def-label" - /> - {!readOnly && } -
-

{t('engine.studio.inspector.listView.bulk.defFields', locale)}

- onChange({ ...def, params: params.filter((p) => p.name !== field) })} - /> - {!readOnly && ( - !asked.has(f.name))} - placeholder={t('engine.studio.inspector.listView.bulk.addField', locale)} - onPick={(f) => onChange({ ...def, params: [...params, bulkParamOfField(f)] })} - /> - )} - setText('confirmText', e.target.value)} - placeholder={t('engine.studio.inspector.listView.bulk.confirmPlaceholder', locale)} - disabled={readOnly} - className="h-7 text-xs" - data-testid="list-view-bulk-def-confirm" - /> -
- ); -} - -/** The "Add field update" form: held here until it has a label and a field. */ -function NewFieldUpdate({ - fields, - onAdd, - onCancel, - locale, -}: { - fields: UpdatableField[]; - onAdd: (draft: { label: string; params: Row[]; confirmText: string }) => string | null; - onCancel: () => void; - locale: string; -}) { - const [label, setLabel] = React.useState(''); - const [picked, setPicked] = React.useState([]); - const [confirm, setConfirm] = React.useState(''); - const [refusal, setRefusal] = React.useState(null); - const ready = label.trim() !== '' && picked.length > 0; - const params = picked.map(bulkParamOfField); - return ( -
- setLabel(e.target.value)} - placeholder={t('engine.studio.inspector.listView.bulk.defLabelPlaceholder', locale)} - className="h-7 text-xs" - data-testid="list-view-bulk-new-def-label" - /> -

{t('engine.studio.inspector.listView.bulk.defFields', locale)}

- setPicked((p) => p.filter((f) => f.name !== name))} - /> - !picked.some((p) => p.name === f.name))} - placeholder={t('engine.studio.inspector.listView.bulk.addField', locale)} - onPick={(f) => setPicked((p) => [...p, f])} - /> - setConfirm(e.target.value)} - placeholder={t('engine.studio.inspector.listView.bulk.confirmPlaceholder', locale)} - className="h-7 text-xs" - data-testid="list-view-bulk-new-def-confirm" - /> - {refusal && ( -

- {refusal} -

- )} -
- - -
-
- ); -} - -export function ListViewBulkActionsSection({ - objectName, - body, - writeBody, - readOnly, - locale, -}: { - objectName: string; - body: Row; - writeBody: (next: Row) => void; - readOnly: boolean; - locale: string; -}) { - const { object, loading, error } = useObjectRead(objectName); - const actions = React.useMemo(() => objectActionsOf(object, locale), [object, locale]); - const fields = React.useMemo(() => updatableFieldsOf(object, locale), [object, locale]); - const [adding, setAdding] = React.useState(false); - - const names = namesOf(body.bulkActions); - const defs = Array.isArray(body.bulkActionDefs) ? (body.bulkActionDefs as unknown[]) : []; - const deleteState = bulkDeleteStateOf(body); - const deleteLabel = t('engine.studio.inspector.listView.bulk.builtinDelete', locale); - const labelOfName = (name: string): { label: string; known: boolean } => { - if (name.toLowerCase() === BUILTIN_BULK_DELETE) return { label: deleteLabel, known: true }; - const action = actions.find((a) => a.name === name); - return action ? { label: action.label, known: true } : { label: name, known: false }; - }; - const offered = [ - ...actions.filter((a) => !names.includes(a.name) && a.name.toLowerCase() !== BUILTIN_BULK_DELETE), - ...(names.some((n) => n.toLowerCase() === BUILTIN_BULK_DELETE) ? [] : [{ name: BUILTIN_BULK_DELETE, label: deleteLabel }]), - ]; - const writeNames = (next: string[]) => writeBody(withList(body, 'bulkActions', next)); - const writeDefs = (next: unknown[]) => writeBody(withList(body, 'bulkActionDefs', next)); - - const addDef = (draft: { label: string; params: Row[]; confirmText: string }): string | null => { - const taken = [...names, ...defs.flatMap((d) => (isPlainObject(d) && typeof d.name === 'string' ? [d.name] : []))]; - const def: Row = { - name: freeDefName(draft.params.map((p) => String(p.name)), taken), - label: draft.label, - operation: 'update', - params: draft.params, - ...(draft.confirmText ? { confirmText: draft.confirmText } : {}), - }; - const refusal = bulkDefRefusal(def); - if (refusal) return refusal; - writeDefs([...defs, def]); - setAdding(false); - return null; - }; - - return ( -
-
-

{t('engine.studio.inspector.listView.bulk', locale)}

-

- {t('engine.studio.inspector.listView.bulk.intro', locale)} -

-
-

- {t(`engine.studio.inspector.listView.bulk.delete.${deleteState}`, locale)} -

- {error && ( -

- {tFormat('engine.studio.inspector.listView.bulk.readFailed', locale, { reason: error })} -

- )} - -
- - {names.length > 0 && ( -
- {names.map((name) => { - const { label, known } = labelOfName(name); - const stale = !loading && !error && !known; - return ( -
- - {label} - {name} - {stale && ( - {t('engine.studio.inspector.listView.bulk.notAnAction', locale)} - )} - - {!readOnly && writeNames(names.filter((n) => n !== name))} locale={locale} />} -
- ); - })} -
- )} - {!readOnly && ( - - )} -
- -
-

{t('engine.studio.inspector.listView.bulk.fieldUpdates', locale)}

- {defs.map((def, i) => { - if (!isPlainObject(def)) return null; - const name = String(def.name ?? ''); - const removeDef = () => writeDefs(defs.filter((_, j) => j !== i)); - if (def.operation === 'update') { - return ( - writeDefs(defs.map((d, j) => (j === i ? next : d)))} - /> - ); - } - // Another kind of def: shown, removable, edited in metadata. - const label = typeof def.label === 'string' && def.label ? def.label : name; - return ( -
- - {label} - {t('engine.studio.inspector.listView.bulk.inMetadata', locale)} - - {!readOnly && } -
- ); - })} - {!readOnly && - (adding ? ( - setAdding(false)} locale={locale} /> - ) : ( - - ))} -
-
- ); -} diff --git a/ui/packages/app-shell/src/views/studio-design/ListViewChartSection.tsx b/ui/packages/app-shell/src/views/studio-design/ListViewChartSection.tsx deleted file mode 100644 index fb14dc6a060..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/ListViewChartSection.tsx +++ /dev/null @@ -1,355 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#27933 — the binding of a chart view, in the list-view panel: - * the ADR-0021 dataset the chart reads, the measures it plots (`values`) and - * the dimensions it groups them by, all in the list body's `chart` block - * (`ListChartConfigSchema`), plus the chart type the spec's enum lists. - * - * The datasets offered are the ones whose base `object` is this object, and a - * dataset's measures and dimensions are its own: read through the reading the - * Create View dialog picks from (`useObjectDatasetBinding`), from the drafts - * a Studio author sees when the pillar provides them. Each is picked by its - * label; what is written is its name. - * - * - Another dataset keeps only the measures and dimensions it declares too. A - * name it does not declare binds nothing, so it is dropped, never kept. A - * dataset whose members the catalog does not list keeps none. - * - A stored name the bound dataset does not declare is shown, marked, with - * its remove button, so the author sees why the chart plots nothing. - * - No measure left: the `values` key is removed, not written empty. The spec - * requires it, so the pillar holds the edit as it holds every unset input - * (`listViewTypeHeldEdit`) rather than sending one the draft door refuses. - * - The catalog, or the bound dataset, cannot be read: the stored names are - * shown as they are, with the reason, and nothing is offered to replace - * them. The panel itself never fails on it. - * - No dataset is built on this object: the section says so, and offers no - * empty picker. - */ - -import * as React from 'react'; -import { Loader2, X } from 'lucide-react'; -import { Label, Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@object-ui/components'; -import { getListVariantSchema } from '../metadata-admin/view-schema.js'; -import type { DatasetDimensionInfo, DatasetMeasureInfo } from '../metadata-admin/previews/useDatasetCatalog.js'; -import { t, tFormat } from '../metadata-admin/i18n.js'; -import { useStudioDatasetAuthoring } from './datasetCreate.js'; -import { datasetOptionLabel, useObjectDatasetBinding } from './objectDatasets.js'; -import { DraftChip } from './StudioDraftMark.js'; - -type Row = Record; -type DatasetMember = DatasetMeasureInfo | DatasetDimensionInfo; - -function isPlainObject(v: unknown): v is Row { - return !!v && typeof v === 'object' && !Array.isArray(v); -} - -function namesOf(v: unknown): string[] { - return Array.isArray(v) ? v.filter((n): n is string => typeof n === 'string' && n !== '') : []; -} - -const DATASET_ID = 'studio-list-view-chart-dataset'; -const CHART_TYPE_ID = 'studio-list-view-chart-type'; - -/** The label each input of the `chart` block is drawn with, as the held notice names it. */ -const CHART_INPUT_LABEL_KEYS: Readonly> = { - dataset: 'engine.studio.inspector.listView.chart.dataset', - values: 'engine.studio.inspector.listView.chart.measures', - dimensions: 'engine.studio.inspector.listView.chart.dimensions', - chartType: 'engine.inspector.report.chartType', -}; - -/** The chart section's label for an input of the `chart` block, or `null` for one it does not draw. */ -export function chartInputLabel(key: string, locale: string): string | null { - const labelKey = CHART_INPUT_LABEL_KEYS[key]; - return labelKey ? t(labelKey, locale) : null; -} - -/** The spec's chart types (the `chartType` enum of the `chart` block) and its default. */ -function chartTypeChoices(): { options: string[]; fallback: string } { - const prop = getListVariantSchema()?.properties?.chart?.properties?.chartType; - const options = Array.isArray(prop?.enum) ? prop.enum.filter((v: unknown): v is string => typeof v === 'string') : []; - return { options, fallback: typeof prop?.default === 'string' ? prop.default : '' }; -} - -function chartTypeLabel(type: string, locale: string): string { - const key = `engine.inspector.widget.type.${type}`; - const text = t(key, locale); - return text === key ? type : text; -} - -/** `row` with `names` under `key`, or without the key when there are none. */ -function withNames(row: Row, key: string, names: string[]): Row { - const { [key]: _dropped, ...rest } = row; - return names.length > 0 ? { ...rest, [key]: names } : rest; -} - -/** - * The measures or the dimensions of the chart: the stored names in order, each - * by its label, and a picker that adds one the dataset declares. - * `members` is `null` when the dataset's members are unknown: the stored names - * are then shown as they are, unjudged, and nothing is offered. - */ -function MemberList({ - id, - label, - names, - members, - readOnly, - locale, - addText, - noneDeclaredText, - onChange, -}: { - id: string; - label: string; - names: string[]; - members: ReadonlyArray | null; - readOnly: boolean; - locale: string; - addText: string; - noneDeclaredText: string; - onChange: (next: string[]) => void; -}): React.ReactElement { - const remaining = members ? members.filter((m) => !names.includes(m.name)) : []; - return ( -
- - {names.length > 0 && ( -
- {names.map((name) => { - const member = members?.find((m) => m.name === name); - const stale = members !== null && !member; - return ( -
- - {member?.label || name} - {name} - {stale && ( - - {t('engine.studio.inspector.listView.chart.notInDataset', locale)} - - )} - - {!readOnly && ( - - )} -
- ); - })} -
- )} - {members && members.length === 0 ? ( -

{noneDeclaredText}

- ) : ( - members && - !readOnly && ( - - ) - )} -
- ); -} - -export function ListViewChartSection({ - objectName, - body, - writeBody, - readOnly, - locale, - marked, -}: { - objectName: string; - body: Row; - writeBody: (next: Row) => void; - readOnly: boolean; - locale: string; - /** objectui#12725 — the copilot drafted a setting of this block. */ - marked: boolean; -}): React.ReactElement { - const chart = isPlainObject(body.chart) ? body.chart : null; - const dataset = typeof chart?.dataset === 'string' ? chart.dataset : ''; - const values = namesOf(chart?.values); - const dimensions = namesOf(chart?.dimensions); - const authoring = useStudioDatasetAuthoring(); - const { catalog, datasets, bound, semantics } = useObjectDatasetBinding(objectName, dataset || undefined, { - previewDrafts: authoring !== null, - }); - const writeChart = (next: Row) => writeBody({ ...body, chart: next }); - - const pickDataset = (name: string) => { - if (name === dataset) return; - const entry = datasets.find((d) => d.name === name); - // A catalog entry that lists no member at all may be a name-only summary: - // nothing is known to carry over, so nothing does. - const known = !!entry && entry.measures.length + entry.dimensions.length > 0; - const keep = (names: string[], members: ReadonlyArray) => - known ? names.filter((n) => members.some((m) => m.name === n)) : []; - let next: Row = { ...(chart ?? {}), dataset: name }; - next = withNames(next, 'values', keep(values, entry?.measures ?? [])); - next = withNames(next, 'dimensions', keep(dimensions, entry?.dimensions ?? [])); - writeChart(next); - }; - - // The members to judge the stored names by, or `null` when they are unknown: - // no dataset of this object bound, its read pending or failed. - const judged = bound && !semantics.loading && !semantics.error; - const measures = judged ? semantics.measures : null; - const dims = judged ? semantics.dimensions : null; - const { options: chartTypes, fallback: defaultChartType } = chartTypeChoices(); - const chartType = typeof chart?.chartType === 'string' ? chart.chartType : defaultChartType; - const canPick = !catalog.loading && !catalog.error && datasets.length > 0; - - return ( -
-
-

- {t('engine.studio.inspector.listView.chart', locale)} - {marked && } -

-

- {t('engine.studio.inspector.listView.chart.intro', locale)} -

-
-
- - {catalog.loading ? ( -

- {t('engine.studio.loading', locale)} -

- ) : catalog.error ? ( -

- {tFormat('engine.studio.inspector.listView.chart.readFailed', locale, { reason: catalog.error })} -

- ) : datasets.length === 0 ? ( -

- {t('engine.studio.inspector.listView.chart.noDatasets', locale)} -

- ) : null} - {canPick ? ( - - ) : ( - dataset && ( -

- {dataset} -

- ) - )} -
- {bound && semantics.loading && ( -

- {t('engine.studio.loading', locale)} -

- )} - {bound && semantics.error && ( -

- {tFormat('engine.studio.inspector.listView.chart.membersFailed', locale, { reason: semantics.error })} -

- )} - {(dataset || values.length > 0 || dimensions.length > 0) && ( - <> - writeChart(withNames(chart ?? {}, 'values', next))} - /> - writeChart(withNames(chart ?? {}, 'dimensions', next))} - /> - - )} - {chart && chartTypes.length > 0 && ( -
- - -
- )} -
- ); -} diff --git a/ui/packages/app-shell/src/views/studio-design/ListViewMoreSection.tsx b/ui/packages/app-shell/src/views/studio-design/ListViewMoreSection.tsx deleted file mode 100644 index bec0545aa3d..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/ListViewMoreSection.tsx +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#30046 (Scope 6) — the list-view settings the object page's panel - * did not offer, which only the view's own page (`surface=view:`, the view - * inspector `ViewVariantInspector`) did: the view's conditional formatting - * (条件格式化) and the sections of the spec's authoring form for a view - * (`view.form.ts`: description, quick search, table options, pagination, - * end-user controls, navigation and sharing, and each type's own block). - * - * A list view now opens on its object's page from every door, so these come - * with it, below the panel's own sections, and nothing that page offered is - * dropped. Both are the inspector's own parts, fed the same way: - * - * - `ConditionalFormattingEditor`, over the body's `conditionalFormatting`; - * its CEL verdicts are reported to the host (`onBlockingIssuesChange`), - * which holds the list-view autosave on them, as the view page held its - * Save (objectui#4527); - * - the generic `SchemaForm`, over the spec's list-variant JSONSchema and - * the localized authoring form (`getViewForm`), with every key the panel - * already edits pruned from it, so no setting has two controls: the - * columns, the filter, the sort, the chart binding, and the blocks - * `ListViewTypeSection` draws. The kanban block stays: the card section - * edits its card, not its lanes or its summary field. - * - * ⛔ No per-key field list of what is shown: what the spec form declares flows - * through. The section titles are the spec form's, localized where the locale - * overlay carries them; #30039 owns translating the rest. - */ - -import * as React from 'react'; -import { ConditionalFormattingEditor } from '../metadata-admin/ConditionalFormattingEditor.js'; -import { SchemaForm } from '../metadata-admin/SchemaForm.js'; -import type { FormViewSpec } from '../metadata-admin/SchemaForm.js'; -import { getListVariantSchema, getViewForm } from '../metadata-admin/view-schema.js'; -import type { ObjectFieldOption } from '../metadata-admin/widgets.js'; -import type { LoadState } from '../metadata-admin/loadState.js'; -import { t } from '../metadata-admin/i18n.js'; - -type Row = Record; - -/** - * The body keys the list-view panel edits with its own sections, pruned from - * the spec form here: the columns (and the canvas), the filter, the sort, the - * conditional formatting above, the chart binding (`ListViewChartSection`) - * and the type blocks `ListViewTypeSection` draws. `data` and `name` the spec - * form's own pruning already drops (`getViewForm`). - */ -const EDITED_BY_THE_PANEL: ReadonlySet = new Set([ - 'columns', - 'filter', - 'sort', - 'conditionalFormatting', - 'chart', - 'calendar', - 'gallery', - 'timeline', - 'gantt', - 'map', - 'tree', - 'timesheet', -]); - -/** The fields the curated controls own, hidden from the form as the view inspector hides them. */ -const HIDDEN_FIELDS = ['type', 'object', 'label']; - -/** The localized spec form, without the keys the panel edits, and without a section left empty. */ -function panelViewForm(locale: string): FormViewSpec | undefined { - const form = getViewForm(locale); - if (!form) return undefined; - const fieldName = (f: unknown): unknown => (typeof f === 'string' ? f : (f as { field?: unknown } | null)?.field); - const sections = (form.sections ?? []) - .map((section) => ({ - ...section, - fields: (section.fields ?? []).filter((f: unknown) => !EDITED_BY_THE_PANEL.has(String(fieldName(f)))), - })) - .filter((section) => section.fields.length > 0); - return { ...form, sections }; -} - -/** `next` with every key the form does not edit as `body` holds it (present or absent). */ -function repinned(next: Row, body: Row): Row { - const merged: Row = { ...next }; - for (const key of [...EDITED_BY_THE_PANEL, 'data', 'name']) { - if (key in body) merged[key] = body[key]; - else delete merged[key]; - } - return merged; -} - -export function ListViewMoreSection({ - body, - writeBody, - objectName, - fieldNames, - fieldCatalog, - readOnly, - locale, - onBlockingIssuesChange, -}: { - /** The view's list body (`config` of a view item). */ - body: Row; - writeBody: (next: Row) => void; - objectName: string | undefined; - /** The object's field names, for the formatting rules' autocomplete. */ - fieldNames: string[]; - fieldCatalog: LoadState; - readOnly: boolean; - locale: string; - /** How many formatting rules' CEL does not parse: the host holds the autosave while it is not 0. */ - onBlockingIssuesChange?: (count: number) => void; -}): React.ReactElement { - const tLocal = React.useCallback((key: string) => t(key, locale), [locale]); - const rules = Array.isArray(body.conditionalFormatting) ? (body.conditionalFormatting as unknown[]) : []; - const form = React.useMemo(() => panelViewForm(locale), [locale]); - const schema = getListVariantSchema(); - // Each field's `type` and `multiple` from the loaded catalog, so a formatting - // rule that compares a list field with a scalar is refused while typing. The - // CEL editor keys its lint on the list-valued names, not on this array. - const fieldDefs = - fieldCatalog.status === 'loaded' - ? fieldCatalog.data.map((f) => ({ name: f.name, type: f.type, multiple: f.multiple })) - : undefined; - return ( -
-
- { - const { conditionalFormatting: _dropped, ...rest } = body; - writeBody(next.length > 0 ? { ...rest, conditionalFormatting: next } : rest); - }} - onBlockingIssuesChange={onBlockingIssuesChange} - /> -
- {schema && form && ( -
- writeBody(repinned(next, body))} - /> -
- )} -
- ); -} diff --git a/ui/packages/app-shell/src/views/studio-design/ListViewTypeSection.tsx b/ui/packages/app-shell/src/views/studio-design/ListViewTypeSection.tsx deleted file mode 100644 index bb0f39ea895..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/ListViewTypeSection.tsx +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#27895 — the settings of a list view's own type, in the - * list-view panel: a calendar's start date and title fields, a gallery's - * cover and card fields, a timeline's dates, scale and grouping, and the - * blocks of a gantt, a map and a tree. - * - * Each type keeps its settings in the list body's block of the same name - * (`calendar`, `gallery`, …, on the spec's `ListViewSchema`). The section is - * that block, rendered from the spec's own JSONSchema for it - * (`getListVariantSchema`) by the generic {@link SchemaForm}: which settings - * a type has, which are required and which values an enum allows all come - * from the spec, so a key the spec adds to a block shows up here with no - * change. ⛔ No per-type field list. A setting that names a field (`*Field`, - * `*Fields`) is a picker over the object's fields, by label, as the form - * draws it wherever it is given a field catalog. - * - * Not here: `grid`, which has no block; `kanban`, whose card has its own - * section (`KanbanCardSection`); and `chart`, whose block binds an ADR-0021 - * dataset and that dataset's measures, not the object's fields: its section - * is `ListViewChartSection` (objectstack#27933). - * - * A required setting can be cleared (the field picker offers "None"). That - * edit is held, not sent, as the pillar holds every edit the spec refuses - * only for an unset input (`listViewTypeHeldEdit`): the draft door would - * refuse it with a 422, and every later save with it. The chart's block is - * held by the same rule, named by its own section's labels. - */ - -import * as React from 'react'; -import type { ListViewVisualization } from '@object-ui/core'; -import { ListViewSchema } from '@objectstack/spec/ui'; -import { SchemaForm } from '../metadata-admin/SchemaForm.js'; -import { getListVariantSchema } from '../metadata-admin/view-schema.js'; -import type { ObjectFieldOption } from '../metadata-admin/widgets.js'; -import type { LoadState } from '../metadata-admin/loadState.js'; -import { t, tFormat, translateSchemaFieldLabel } from '../metadata-admin/i18n.js'; -import { prettifyFieldName } from '../metadata-admin/field-source-label.js'; -import { DraftChip } from './StudioDraftMark.js'; -import { objectHeldInput, type StudioHeld } from './metadataError.js'; -import { chartInputLabel } from './ListViewChartSection.js'; - -type Row = Record; -type JsonSchema = Record; - -function isPlainObject(v: unknown): v is Row { - return !!v && typeof v === 'object' && !Array.isArray(v); -} - -/** The view types whose block is edited somewhere else, or not by object field (see the module docblock). */ -const EDITED_ELSEWHERE: ReadonlySet = new Set(['kanban', 'chart']); - -/** - * The copy of each view type's name. A total record over the visualizations, - * so a type the spec adds fails the build here until it has a name; every key - * is spelled out, so the i18n gates can see it. - */ -const VIEW_TYPE_LABEL_KEYS: Record = { - grid: 'engine.inspector.view.type.grid', - kanban: 'engine.inspector.view.type.kanban', - calendar: 'engine.inspector.view.type.calendar', - gallery: 'engine.inspector.view.type.gallery', - timeline: 'engine.inspector.view.type.timeline', - gantt: 'engine.inspector.view.type.gantt', - map: 'engine.inspector.view.type.map', - chart: 'engine.inspector.view.type.chart', - tree: 'engine.inspector.view.type.tree', - timesheet: 'engine.inspector.view.type.timesheet', -}; - -/** - * The spec's JSONSchema for the block a list body of `type` keeps its own - * settings in, or `null` when this section does not edit that type: a value - * the spec's `type` enum does not carry, a type with no block, or one edited - * elsewhere. - */ -export function listViewTypeBlockSchema(type: unknown): JsonSchema | null { - if (typeof type !== 'string' || EDITED_ELSEWHERE.has(type)) return null; - const list = getListVariantSchema(); - const types: unknown = list?.properties?.type?.enum; - if (!Array.isArray(types) || !types.includes(type)) return null; - const block = list?.properties?.[type]; - return isPlainObject(block) && block.type === 'object' && isPlainObject(block.properties) ? block : null; -} - -/** - * The field names a type's block holds, read by the form's own convention for - * a field setting: a string under a `*Field` key, the strings under a - * `*Fields` key. - */ -export function fieldNamesHeldByTypeBlock(block: unknown): string[] { - if (!isPlainObject(block)) return []; - const held: string[] = []; - for (const [key, value] of Object.entries(block)) { - if (/.Field$/.test(key) && typeof value === 'string' && value) held.push(value); - else if (/Fields$/.test(key) && Array.isArray(value)) { - for (const v of value) if (typeof v === 'string' && v) held.push(v); - } - } - return held; -} - -function typeLabelOf(type: string, locale: string): string { - const key = (VIEW_TYPE_LABEL_KEYS as Record)[type]; - return key ? t(key, locale) : type; -} - -/** - * The edit the pillar holds for a list body whose type's block the spec - * refuses only because a required setting is unset, or `null`. Asked of the - * spec's `ListViewSchema` (`objectHeldInput`): a block that is finished but - * wrong is sent, and its refusal shows as before. `input` is the setting's - * label as the section draws it, so "Show me" focuses that control. A chart's - * block is asked the same, its input named by `ListViewChartSection`. - */ -export function listViewTypeHeldEdit(body: Row, locale: string): StudioHeld | null { - const type = body.type; - if (type === 'chart') { - const key = objectHeldInput(body, ListViewSchema, 'chart'); - if (key === null) return null; - const input = chartInputLabel(key, locale) ?? prettifyFieldName(key); - return { - clause: tFormat('engine.studio.held.listViewTypeNeedsInput', locale, { input, type: typeLabelOf(type, locale) }), - target: null, - input, - }; - } - const schema = listViewTypeBlockSchema(type); - if (!schema || typeof type !== 'string') return null; - const key = objectHeldInput(body, ListViewSchema, type); - if (key === null) return null; - const input = - translateSchemaFieldLabel(key, schema.properties[key]?.title as string | undefined, locale) || prettifyFieldName(key); - return { - clause: tFormat('engine.studio.held.listViewTypeNeedsInput', locale, { input, type: typeLabelOf(type, locale) }), - target: null, - input, - }; -} - -export function ListViewTypeSection({ - type, - schema, - body, - writeBody, - fieldCatalog, - readOnly, - locale, - marked, -}: { - type: string; - /** {@link listViewTypeBlockSchema} of `type`. */ - schema: JsonSchema; - body: Row; - writeBody: (next: Row) => void; - fieldCatalog: LoadState; - readOnly: boolean; - locale: string; - /** objectui#12725 — the copilot drafted a setting of this block. */ - marked: boolean; -}): React.ReactElement { - const block = isPlainObject(body[type]) ? body[type] : undefined; - const typeLabel = typeLabelOf(type, locale); - return ( -
-
-

- {tFormat('engine.studio.inspector.listView.typeSettings', locale, { type: typeLabel })} - {marked && } -

-

- {t('engine.studio.inspector.listView.typeSettings.intro', locale)} -

-
- writeBody({ ...body, [type]: next })} - /> -
- ); -} diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.addView-27836.test.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.addView-27836.test.tsx deleted file mode 100644 index 251f8f751a4..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.addView-27836.test.tsx +++ /dev/null @@ -1,287 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#27836 — New view, from an `object` leaf's view switcher (the - * header's title, objectstack#30046): the type first, then the fields that - * type requires, picked by label; the view is created in the package draft and - * the panel shows it. - * - * The REAL hook (`useObjectListViewDraft`), the REAL title switcher - * (`ObjectListViewTitle`), the REAL panel and the REAL Create View dialog over - * a REAL `MetadataClient`, whose transport judges every view PUT with the - * installed spec's `view` schema and answers the write door's 422 on refusal. - * - * Pinned: - * - a kanban and a calendar are created, each under its own name, with the - * picked fields, in the package draft (`If-None-Match: *`), and the spec - * accepts them; the panel then edits the new view, and the default grid is - * not written; - * - the switcher lists the new view, and picking the nav entry's view there - * shows that one again; - * - a name a view already holds is refused: nothing is written, the dialog - * stays open, and the panel says why. - */ - -// Paid at collection, not inside a clocked case (check:test-source-alias). -import '@objectstack/lint'; -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { MetadataCtx, type MetadataContextValue } from '@object-ui/react'; -import { MetadataClient } from '@object-ui/data-objectstack'; -import { getMetadataTypeSchema } from '@objectstack/spec/kernel'; - -const PKG = 'com.acme.app'; -const DEFAULT_VIEW = 'acme_task.default'; - -const OBJECT_DEF = { - name: 'acme_task', - label: 'Task', - fields: { - title: { name: 'title', label: 'Title', type: 'text' }, - status: { - name: 'status', - label: 'Status', - type: 'select', - options: [ - { value: 'open', label: 'Open' }, - { value: 'done', label: 'Done' }, - ], - }, - due_date: { name: 'due_date', label: 'Due date', type: 'date' }, - }, -}; - -const gridView = { - name: DEFAULT_VIEW, - object: 'acme_task', - viewKind: 'list', - isDefault: true, - config: { type: 'grid', data: { provider: 'object', object: 'acme_task' }, columns: ['title', 'status'] }, -}; - -const server = { - active: new Map>(), - drafts: new Map>(), - puts: [] as Array<{ name: string; pkg: string | null; ifNoneMatch: string | null; status: number; body: any }>, -}; - -const json = (status: number, body: unknown) => - new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); - -async function serve(input: RequestInfo | URL, init?: RequestInit): Promise { - const method = (init?.method ?? 'GET').toUpperCase(); - const url = new URL(String(input), 'http://studio.test'); - const meta = url.pathname.match(/^\/api\/v1\/meta\/(.+)$/); - if (!meta) return json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); - const seg = meta[1].split('/').map(decodeURIComponent); - const key = `${seg[0]}/${seg[1]}`; - if (seg[0] === '_drafts') { - return json(200, { drafts: [...server.drafts.keys()].map((k) => ({ type: k.split('/')[0], name: k.split('/')[1] })) }); - } - if (method === 'PUT') { - const body = JSON.parse(String(init?.body ?? '{}')); - const verdict = getMetadataTypeSchema('view')!.safeParse(body); - const ifNoneMatch = new Headers(init?.headers).get('If-None-Match'); - server.puts.push({ name: seg[1]!, pkg: url.searchParams.get('package'), ifNoneMatch, status: verdict.success ? 200 : 422, body }); - if (!verdict.success) { - return json(422, { - success: false, - error: { code: 'INVALID_METADATA', message: 'view failed validation', details: { issues: verdict.error.issues } }, - }); - } - server.drafts.set(key, body); - return json(200, { success: true, version: 'v1', state: 'draft' }); - } - if (seg[0] === 'object' && seg.length === 2) return json(200, { type: 'object', name: seg[1], item: OBJECT_DEF }); - if (seg[0] === 'view' && seg.length === 1) return json(200, [...server.active.values()]); - if (seg.length === 3 && seg[2] === 'layers') { - // As the server answers an admitted author (objectstack#30859): a pending draft is served as stored, as `draft`, and an item with only a draft still has layers. - const row = server.active.get(key); - const draft = server.drafts.get(key) ?? null; - return row || draft - ? json(200, { code: null, overlay: row ?? null, overlayScope: row ? 'env' : null, effective: row ?? null, draft }) - : json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); - } - if (seg.length === 2 && url.searchParams.get('state') === 'draft') { - const draft = server.drafts.get(key); - return draft - ? json(200, { type: seg[0], name: seg[1], item: { ...draft, _draft: true }, version: 'v1' }) - : json(404, { error: { code: 'NO_DRAFT', message: 'absent' } }); - } - const row = server.active.get(key); - return row ? json(200, { type: seg[0], name: seg[1], item: row }) : json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); -} - -const client = new MetadataClient({ baseUrl: '', fetch: vi.fn(serve) as unknown as typeof fetch }); - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => client }; -}); -const toastError = vi.fn(); -vi.mock('sonner', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, toast: Object.assign(vi.fn(), mod.toast, { error: (...args: unknown[]) => toastError(...args) }) }; -}); - -import { ObjectListViewInspector, useObjectListViewDraft } from './ObjectListViewInspector'; -import { ObjectListViewTitle } from './ObjectListViewTitle'; -import type { Surface } from './navSurface'; -import { tFormat } from '../metadata-admin/i18n'; - -const METADATA: MetadataContextValue = { - apps: [], - objects: [OBJECT_DEF], - dashboards: [], - reports: [], - pages: [], - loading: false, - error: null, - refresh: async () => {}, - invalidate: () => {}, - ensureType: async () => [], - getItem: async () => null, - getItemsByType: () => [], -}; - -const LEAF: Surface = { type: 'object', name: 'acme_task', label: 'Tasks' }; - -function Host() { - const listView = useObjectListViewDraft({ client, packageId: PKG, leaf: LEAF, publishNonce: 0 }); - return ( - <> -

- -

- - - ); -} - -async function settle() { - await act(async () => { - for (let i = 0; i < 25; i++) await new Promise((r) => setTimeout(r, 0)); - }); -} - -async function openPanel(): Promise { - render( - - - , - ); - await settle(); -} - -/** Opens the switcher (the title's ▾) and reads its rows, by label. */ -async function openSwitcher(): Promise { - if (!screen.queryByTestId('list-view-switcher-menu')) fireEvent.click(screen.getByTestId('list-view-switcher')); - const menu = await screen.findByTestId('list-view-switcher-menu'); - return Array.from(menu.querySelectorAll('[data-testid^="view-switcher-row-"]')).map( - (row) => row.querySelector('button')?.textContent ?? '', - ); -} - -/** The view item name the panel shows beneath its title. */ -const shownView = () => screen.getByTestId('studio-list-view-inspector').getAttribute('data-view-id'); - -const typeCard = (type: string) => - Array.from(document.querySelectorAll('button[data-testid^="create-view-type-"]')).find( - (b) => b.getAttribute('data-testid') === `create-view-type-${type}`, - ); -const picker = (key: string) => screen.getByTestId(`create-view-required-${key}`); -const submitButton = () => screen.getByTestId('create-view-submit') as HTMLButtonElement; - -/** "Add view", pick `type`, pick each required field by its label, name the view `label`, and press Create. */ -async function addView(type: string, picks: Array<[key: string, label: string]>, label: string) { - await openSwitcher(); - fireEvent.click(await screen.findByTestId('list-view-switcher-new')); - await waitFor(() => expect(typeCard(type)?.disabled).toBe(false)); - fireEvent.click(typeCard(type)!); - for (const [key, option] of picks) { - await waitFor(() => expect(picker(key)).toBeEnabled()); - fireEvent.keyDown(picker(key), { key: 'ArrowDown' }); - const listbox = await screen.findByRole('listbox'); - const hit = within(listbox).getAllByRole('option').find((o) => o.textContent === option); - if (!hit) throw new Error(`${type}: ${key} lists no "${option}"`); - fireEvent.click(hit); - await waitFor(() => expect(picker(key).textContent).toBe(option)); - } - fireEvent.change(screen.getByTestId('create-view-name-input'), { target: { value: label } }); - await waitFor(() => expect(submitButton().disabled).toBe(false)); - fireEvent.click(submitButton()); - await settle(); -} - -beforeEach(() => { - server.active.clear(); - server.drafts.clear(); - server.puts = []; - toastError.mockClear(); - server.active.set(`view/${DEFAULT_VIEW}`, gridView); -}); -afterEach(cleanup); - -describe('ObjectListViewInspector — "Add view" creates a view of the chosen type and opens it (objectstack#27836)', () => { - it('a kanban: born with the picked group-by field in the package draft, accepted by the spec, and opened in the panel', async () => { - await openPanel(); - expect(shownView()).toBe(DEFAULT_VIEW); - await addView('kanban', [['groupByField', 'Status']], 'Pipeline board'); - - expect(server.puts).toHaveLength(1); - const [put] = server.puts; - expect(put).toMatchObject({ name: 'acme_task.pipeline_board', pkg: PKG, ifNoneMatch: '*', status: 200 }); - expect(put.body).toMatchObject({ name: 'acme_task.pipeline_board', object: 'acme_task', viewKind: 'list', label: 'Pipeline board' }); - expect(put.body.config.type).toBe('kanban'); - expect(put.body.config.kanban).toMatchObject({ groupByField: 'status' }); - // Never the object's default: the default grid stays the one it was. - expect(put.body.isDefault).toBeUndefined(); - expect(server.puts.some((p) => p.name === DEFAULT_VIEW)).toBe(false); - - // The dialog closed, and the panel now edits the board, card section included. - await waitFor(() => expect(screen.queryByTestId('create-view-submit')).toBeNull()); - await waitFor(() => expect(shownView()).toBe('acme_task.pipeline_board')); - expect(screen.getByTestId('list-view-kanban-card')).toBeInTheDocument(); - expect(screen.getByTestId('list-view-switcher')).toHaveTextContent('Pipeline board'); - }); - - it('a calendar: born with its start-date and title fields, picked by label', async () => { - await openPanel(); - await addView('calendar', [['startDateField', 'Due date'], ['titleField', 'Title']], 'Due dates'); - - expect(server.puts).toHaveLength(1); - const [put] = server.puts; - expect(put).toMatchObject({ name: 'acme_task.due_dates', pkg: PKG, ifNoneMatch: '*', status: 200 }); - expect(put.body.config.type).toBe('calendar'); - expect(put.body.config.calendar).toEqual({ startDateField: 'due_date', titleField: 'title' }); - await waitFor(() => expect(shownView()).toBe('acme_task.due_dates')); - }); - - it('the switcher lists the new view, and picking the entry\'s view there shows that one again', async () => { - await openPanel(); - await addView('kanban', [['groupByField', 'Status']], 'Pipeline board'); - await waitFor(() => expect(shownView()).toBe('acme_task.pipeline_board')); - - const rows = await openSwitcher(); - expect(rows).toContain('Pipeline board'); - expect(rows).toContain('Default view'); - fireEvent.click(screen.getByTestId(`view-switcher-row-${DEFAULT_VIEW}`).querySelector('button')!); - await settle(); - expect(shownView()).toBe(DEFAULT_VIEW); - }); - - it('a name a view already holds: nothing is written, the dialog stays open, and the panel says why', async () => { - server.active.set('view/acme_task.pipeline_board', { ...gridView, name: 'acme_task.pipeline_board', isDefault: undefined }); - await openPanel(); - await addView('kanban', [['groupByField', 'Status']], 'Pipeline board'); - - expect(server.puts).toEqual([]); - expect(toastError).toHaveBeenCalledWith( - tFormat('engine.studio.inspector.listView.addViewTaken', 'en', { name: 'acme_task.pipeline_board' }), - ); - expect(screen.getByTestId('create-view-submit')).toBeInTheDocument(); - expect(shownView()).toBe(DEFAULT_VIEW); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.bulkActions-30089.test.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.bulkActions-30089.test.tsx deleted file mode 100644 index bd6f0fe57b6..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.bulkActions-30089.test.tsx +++ /dev/null @@ -1,454 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#30089 — the list-view panel's selection actions: the object's - * actions picked into `bulkActions`, and field updates written to - * `bulkActionDefs` (label, the fields the dialog asks for, a confirmation). - * - * The REAL hook (`useObjectListViewDraft`) and the REAL panel over a REAL - * `MetadataClient`, whose transport judges every view PUT with the installed - * spec's `view` schema and answers the write door's 422 on refusal; each - * written def is judged again with `BulkActionDefSchema`. - * - * Pinned: - * - picking an action writes `bulkActions`, by name; the built-in Delete is - * offered as `delete`, and the section says whether Delete stays; - * - adding a field update writes one def the spec accepts, its params taken - * from the fields (options of a select, the object of a lookup); - * - editing a def's label, fields and confirmation, and removing a def or an - * action, round-trip; an emptied key is removed, not written empty; - * - a def of another kind is shown and removable, a name the object does not - * declare is shown marked; - * - a read-only package shows the actions and offers no edit; - * - CONTROLS: a view with neither key saves byte-for-byte as it was read, an - * edit elsewhere adds neither key, and a kanban view has no such section. - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { MetadataCtx, type MetadataContextValue } from '@object-ui/react'; -import { MetadataClient } from '@object-ui/data-objectstack'; -import { getMetadataTypeSchema } from '@objectstack/spec/kernel'; -import { BulkActionDefSchema } from '@objectstack/spec/ui'; - -const PKG = 'com.acme.app'; -const VIEW = 'acme_task.default'; - -const OBJECT_DEF = { - name: 'acme_task', - label: 'Task', - fields: { - title: { name: 'title', label: 'Title', type: 'text' }, - status: { - name: 'status', - label: 'Status', - type: 'select', - options: [ - { value: 'open', label: 'Open', color: '#94A3B8' }, - { value: 'done', label: 'Done' }, - ], - }, - assignee: { name: 'assignee', label: 'Assignee', type: 'user' }, - project: { name: 'project', label: 'Project', type: 'lookup', reference: 'acme_project' }, - due_date: { name: 'due_date', label: 'Due date', type: 'date' }, - score: { name: 'score', label: 'Score', type: 'formula', expression: '1' }, - code: { name: 'code', label: 'Code', type: 'text', readonly: true }, - }, - actions: [ - { name: 'close_task', label: 'Close task', type: 'script' }, - { name: 'escalate', label: 'Escalate', type: 'script' }, - ], -}; - -const view = (config: Record) => ({ - name: VIEW, - object: 'acme_task', - viewKind: 'list', - isDefault: true, - config: { data: { provider: 'object', object: 'acme_task' }, columns: ['title', 'status'], ...config }, -}); - -const server = { - active: new Map>(), - puts: [] as Array<{ name: string; status: number; body: any }>, -}; - -const json = (status: number, body: unknown) => - new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); - -async function serve(input: RequestInfo | URL, init?: RequestInit): Promise { - const method = (init?.method ?? 'GET').toUpperCase(); - const url = new URL(String(input), 'http://studio.test'); - const meta = url.pathname.match(/^\/api\/v1\/meta\/(.+)$/); - if (!meta) return json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); - const seg = meta[1].split('/').map(decodeURIComponent); - const key = `${seg[0]}/${seg[1]}`; - if (seg[0] === '_drafts') return json(200, { drafts: [] }); - if (method === 'PUT') { - const body = JSON.parse(String(init?.body ?? '{}')); - const verdict = getMetadataTypeSchema('view')!.safeParse(body); - server.puts.push({ name: seg[1]!, status: verdict.success ? 200 : 422, body }); - if (!verdict.success) { - return json(422, { - success: false, - error: { code: 'INVALID_METADATA', message: 'view failed validation', details: { issues: verdict.error.issues } }, - }); - } - return json(200, { success: true, version: 'v2', state: 'draft' }); - } - if (seg[0] === 'object' && seg.length === 2) return json(200, { type: 'object', name: seg[1], item: OBJECT_DEF }); - if (seg.length === 3 && seg[2] === 'layers') { - const row = server.active.get(key); - return row - ? json(200, { code: null, overlay: row, overlayScope: 'env', effective: row }) - : json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); - } - if (seg.length === 2 && url.searchParams.get('state') === 'draft') { - return json(404, { error: { code: 'NO_DRAFT', message: 'absent' } }); - } - const row = server.active.get(key); - return row ? json(200, { type: seg[0], name: seg[1], item: row }) : json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); -} - -const client = new MetadataClient({ baseUrl: '', fetch: vi.fn(serve) as unknown as typeof fetch }); - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => client }; -}); - -import { ObjectListViewInspector, useObjectListViewDraft } from './ObjectListViewInspector'; -import type { Surface } from './navSurface'; - -const METADATA: MetadataContextValue = { - apps: [], - objects: [OBJECT_DEF], - dashboards: [], - reports: [], - pages: [], - loading: false, - error: null, - refresh: async () => {}, - invalidate: () => {}, - ensureType: async () => [], - getItem: async () => null, - getItemsByType: () => [], -}; - -const LEAF: Surface = { type: 'object', name: 'acme_task', label: 'Tasks' }; - -/** The panel, and the pillar autosave's one call into it: send the buffer. */ -function Host({ readOnly = false }: { readOnly?: boolean }) { - const listView = useObjectListViewDraft({ client, packageId: PKG, leaf: LEAF, publishNonce: 0 }); - return ( - <> - {String(listView.dirty)} - - - - ); -} - -async function settle() { - await act(async () => { - for (let i = 0; i < 25; i++) await new Promise((r) => setTimeout(r, 0)); - }); -} - -async function openPanel(readOnly = false): Promise { - render( - - - , - ); - await settle(); - await waitFor(() => expect(screen.getByTestId('studio-list-view-inspector')).toBeInTheDocument()); -} - -const section = () => screen.getByTestId('list-view-bulk'); -const deleteState = () => within(section()).getByTestId('list-view-bulk-delete').getAttribute('data-state'); - -/** Open the picker `id` and pick the option whose label (before its ``) is `label`. */ -async function pickFrom(id: string, label: string) { - const trigger = document.getElementById(id); - if (!trigger) throw new Error(`no picker ${id}`); - await waitFor(() => expect(trigger).toBeEnabled()); - fireEvent.keyDown(trigger, { key: 'ArrowDown' }); - const listbox = await screen.findByRole('listbox'); - const hit = within(listbox) - .getAllByRole('option') - .find((o) => o.querySelector('code')?.previousElementSibling?.textContent === label); - if (!hit) throw new Error(`${id} lists no "${label}"`); - fireEvent.click(hit); - await waitFor(() => expect(screen.queryByRole('listbox')).toBeNull()); -} - -/** The labels a picker offers, closed again. */ -async function offeredBy(id: string): Promise { - const trigger = document.getElementById(id)!; - await waitFor(() => expect(trigger).toBeEnabled()); - fireEvent.keyDown(trigger, { key: 'ArrowDown' }); - const listbox = await screen.findByRole('listbox'); - const labels = within(listbox) - .getAllByRole('option') - .map((o) => o.querySelector('code')?.previousElementSibling?.textContent ?? ''); - fireEvent.keyDown(listbox, { key: 'Escape' }); - await waitFor(() => expect(screen.queryByRole('listbox')).toBeNull()); - return labels; -} - -async function save() { - fireEvent.click(screen.getByTestId('save')); - await settle(); -} - -const lastPut = () => server.puts[server.puts.length - 1]!; - -/** Fill the "Add a field update" form and add it. */ -async function addFieldUpdate(label: string, fields: string[], confirm?: string) { - fireEvent.click(within(section()).getByTestId('list-view-bulk-add-def')); - const form = await within(section()).findByTestId('list-view-bulk-new-def'); - fireEvent.change(within(form).getByTestId('list-view-bulk-new-def-label'), { target: { value: label } }); - for (const f of fields) await pickFrom('studio-list-view-bulk-new-def-field', f); - if (confirm !== undefined) { - fireEvent.change(within(form).getByTestId('list-view-bulk-new-def-confirm'), { target: { value: confirm } }); - } - fireEvent.click(within(form).getByTestId('list-view-bulk-new-def-add')); - await waitFor(() => expect(within(section()).queryByTestId('list-view-bulk-new-def')).toBeNull()); -} - -beforeEach(() => { - server.active.clear(); - server.puts = []; -}); -afterEach(cleanup); - -describe('ObjectListViewInspector — selection actions (objectstack#30089)', () => { - it('picking an action writes `bulkActions` by name; the built-in Delete is offered as `delete`', async () => { - server.active.set(`view/${VIEW}`, view({ type: 'grid' })); - await openPanel(); - expect(deleteState()).toBe('default'); - expect(await offeredBy('studio-list-view-bulk-action-pick')).toEqual(['Close task', 'Escalate', 'Delete (built-in)']); - - await pickFrom('studio-list-view-bulk-action-pick', 'Close task'); - expect(deleteState()).toBe('dropped'); - await save(); - expect(lastPut()).toMatchObject({ name: VIEW, status: 200 }); - expect(lastPut().body.config.bulkActions).toEqual(['close_task']); - - await pickFrom('studio-list-view-bulk-action-pick', 'Delete (built-in)'); - expect(deleteState()).toBe('kept'); - await save(); - expect(lastPut()).toMatchObject({ status: 200 }); - expect(lastPut().body.config.bulkActions).toEqual(['close_task', 'delete']); - // Nothing else of the view moved. - expect(lastPut().body.config.columns).toEqual(['title', 'status']); - expect(lastPut().body.config).not.toHaveProperty('bulkActionDefs'); - }); - - it('adding a field update writes one def the spec accepts, its params taken from the fields', async () => { - server.active.set(`view/${VIEW}`, view({})); - await openPanel(); - // Only fields a patch can write are offered: no formula, no read-only field. - fireEvent.click(within(section()).getByTestId('list-view-bulk-add-def')); - expect(await offeredBy('studio-list-view-bulk-new-def-field')).toEqual([ - 'Title', - 'Status', - 'Assignee', - 'Project', - 'Due date', - ]); - fireEvent.click(screen.getByRole('button', { name: 'Cancel' })); - - await addFieldUpdate('Reassign', ['Assignee', 'Status', 'Project'], 'Reassign {{ count }} task(s) to {{ assignee }}?'); - expect(deleteState()).toBe('dropped'); - await save(); - expect(lastPut()).toMatchObject({ name: VIEW, status: 200 }); - const defs = lastPut().body.config.bulkActionDefs; - expect(defs).toEqual([ - { - name: 'update_assignee_status_project', - label: 'Reassign', - operation: 'update', - params: [ - { name: 'assignee', label: 'Assignee', type: 'user', required: true }, - { - name: 'status', - label: 'Status', - type: 'select', - required: true, - options: [ - { label: 'Open', value: 'open' }, - { label: 'Done', value: 'done' }, - ], - }, - { name: 'project', label: 'Project', type: 'lookup', required: true, object: 'acme_project' }, - ], - confirmText: 'Reassign {{ count }} task(s) to {{ assignee }}?', - }, - ]); - expect(BulkActionDefSchema.safeParse(defs[0]).success).toBe(true); - expect(lastPut().body.config).not.toHaveProperty('bulkActions'); - }); - - it('a field update waits for a label and a field before anything is written', async () => { - server.active.set(`view/${VIEW}`, view({})); - await openPanel(); - fireEvent.click(within(section()).getByTestId('list-view-bulk-add-def')); - const add = within(section()).getByTestId('list-view-bulk-new-def-add'); - expect(add).toBeDisabled(); - fireEvent.change(within(section()).getByTestId('list-view-bulk-new-def-label'), { target: { value: 'Close' } }); - expect(add).toBeDisabled(); - expect(screen.getByTestId('dirty')).toHaveTextContent('false'); - }); - - it('editing a def’s label, fields and confirmation, and removing it, round-trip; the emptied key is removed', async () => { - server.active.set( - `view/${VIEW}`, - view({ - bulkActionDefs: [ - { - name: 'set_status', - label: 'Set status', - operation: 'update', - params: [{ name: 'status', label: 'Status', type: 'select', required: true, options: [{ label: 'Open', value: 'open' }] }], - }, - ], - }), - ); - await openPanel(); - const row = within(section()).getByTestId('list-view-bulk-def'); - expect(row).toHaveAttribute('data-name', 'set_status'); - fireEvent.change(within(row).getByTestId('list-view-bulk-def-label'), { target: { value: 'Change status' } }); - await pickFrom('studio-list-view-bulk-def-0-add-field', 'Due date'); - fireEvent.change(within(row).getByTestId('list-view-bulk-def-confirm'), { target: { value: 'Change {{ count }}?' } }); - await save(); - expect(lastPut()).toMatchObject({ status: 200 }); - expect(lastPut().body.config.bulkActionDefs).toEqual([ - { - name: 'set_status', - label: 'Change status', - operation: 'update', - params: [ - { name: 'status', label: 'Status', type: 'select', required: true, options: [{ label: 'Open', value: 'open' }] }, - { name: 'due_date', label: 'Due date', type: 'date', required: true }, - ], - confirmText: 'Change {{ count }}?', - }, - ]); - - // The field just added is removed again; the def's last field cannot be. - fireEvent.click(within(row).getByRole('button', { name: 'Remove Due date' })); - expect(within(row).queryByRole('button', { name: 'Remove Status' })).toBeNull(); - await save(); - expect(lastPut().body.config.bulkActionDefs[0].params.map((p: { name: string }) => p.name)).toEqual(['status']); - - fireEvent.click(within(row).getByRole('button', { name: 'Remove Change status' })); - expect(within(section()).queryByTestId('list-view-bulk-def')).toBeNull(); - expect(deleteState()).toBe('default'); - await save(); - expect(lastPut()).toMatchObject({ status: 200 }); - expect(lastPut().body.config).not.toHaveProperty('bulkActionDefs'); - }); - - it('a served confirmation, the parsed `{ dialect, source }` envelope, is shown and edited as its sentence', async () => { - server.active.set( - `view/${VIEW}`, - view({ - bulkActionDefs: [ - { - name: 'set_status', - label: 'Set status', - operation: 'update', - params: [{ name: 'status', label: 'Status', type: 'text', required: true }], - confirmText: { dialect: 'template', source: 'Set {{ count }}?' }, - }, - ], - }), - ); - await openPanel(); - const confirm = within(section()).getByTestId('list-view-bulk-def-confirm'); - expect(confirm).toHaveValue('Set {{ count }}?'); - fireEvent.change(confirm, { target: { value: 'Set status on {{ count }}?' } }); - await save(); - expect(lastPut()).toMatchObject({ status: 200 }); - expect(lastPut().body.config.bulkActionDefs[0].confirmText).toEqual({ dialect: 'template', source: 'Set status on {{ count }}?' }); - }); - - it('removing the last action removes `bulkActions`', async () => { - server.active.set(`view/${VIEW}`, view({ bulkActions: ['escalate'] })); - await openPanel(); - expect(deleteState()).toBe('dropped'); - const row = within(section()).getByTestId('list-view-bulk-action'); - expect(row).toHaveTextContent('Escalate'); - fireEvent.click(within(row).getByRole('button', { name: 'Remove Escalate' })); - await save(); - expect(lastPut()).toMatchObject({ status: 200 }); - expect(lastPut().body.config).not.toHaveProperty('bulkActions'); - }); - - it('a def of another kind is shown and removable; a name the object does not declare is marked', async () => { - server.active.set( - `view/${VIEW}`, - view({ - bulkActions: ['archive_all', 'delete'], - bulkActionDefs: [{ name: 'purge', label: 'Purge', operation: 'delete' }], - }), - ); - await openPanel(); - expect(deleteState()).toBe('kept'); - const stale = within(section()) - .getAllByTestId('list-view-bulk-action') - .find((r) => r.getAttribute('data-name') === 'archive_all')!; - await waitFor(() => expect(stale).toHaveAttribute('data-stale', 'true')); - const other = within(section()).getByTestId('list-view-bulk-def'); - expect(other).toHaveAttribute('data-operation', 'delete'); - expect(within(other).queryByTestId('list-view-bulk-def-label')).toBeNull(); - fireEvent.click(within(other).getByRole('button', { name: 'Remove Purge' })); - await save(); - expect(lastPut().body.config).not.toHaveProperty('bulkActionDefs'); - expect(lastPut().body.config.bulkActions).toEqual(['archive_all', 'delete']); - }); - - it('a read-only package shows the actions and offers no edit', async () => { - server.active.set(`view/${VIEW}`, view({ bulkActions: ['close_task'] })); - await openPanel(true); - expect(within(section()).getByTestId('list-view-bulk-action')).toHaveTextContent('Close task'); - expect(document.getElementById('studio-list-view-bulk-action-pick')).toBeNull(); - expect(within(section()).queryByTestId('list-view-bulk-add-def')).toBeNull(); - expect(within(section()).queryByRole('button', { name: /^Remove/ })).toBeNull(); - }); - - it('CONTROL: a view with neither key saves byte-for-byte as it was read', async () => { - const stored = view({ type: 'grid', sort: [{ field: 'title', order: 'asc' }] }); - server.active.set(`view/${VIEW}`, stored); - await openPanel(); - expect(section()).toBeInTheDocument(); - expect(screen.getByTestId('dirty')).toHaveTextContent('false'); - await save(); - expect(server.puts).toHaveLength(1); - expect(JSON.stringify(server.puts[0]!.body)).toBe(JSON.stringify(stored)); - }); - - it('CONTROL: an edit elsewhere in the panel adds neither key', async () => { - server.active.set(`view/${VIEW}`, view({ type: 'grid' })); - await openPanel(); - const columns = screen.getByTestId('list-view-columns'); - fireEvent.click(within(columns).getAllByRole('button', { name: /^Remove/ })[0]!); - await save(); - expect(lastPut()).toMatchObject({ status: 200 }); - expect(lastPut().body.config).not.toHaveProperty('bulkActions'); - expect(lastPut().body.config).not.toHaveProperty('bulkActionDefs'); - }); - - it('CONTROL: a kanban view, which draws no selection bar, has no such section', async () => { - server.active.set(`view/${VIEW}`, view({ type: 'kanban', kanban: { groupByField: 'status', columns: [] } })); - await openPanel(); - expect(screen.getByTestId('list-view-kanban-card')).toBeInTheDocument(); - expect(screen.queryByTestId('list-view-bulk')).toBeNull(); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.chartBinding-27933.test.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.chartBinding-27933.test.tsx deleted file mode 100644 index 3ed2509673a..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.chartBinding-27933.test.tsx +++ /dev/null @@ -1,404 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#27933 — the list-view panel edits a chart view's binding: the - * ADR-0021 dataset of this object it reads, and that dataset's measures and - * dimensions, all in the list body's `chart` block. - * - * The REAL hook (`useObjectListViewDraft`) and the REAL panel over a REAL - * `MetadataClient`, whose transport serves the dataset catalog, judges every - * view PUT with the installed spec's `view` schema and answers the write - * door's 422 on refusal. - * - * Pinned: - * - the object's two datasets are listed by label (a dataset of another - * object is not), and the stored binding shows by label; - * - picking the other dataset keeps the measure both declare and drops the - * measure and the dimension it does not, then a dimension of its own is - * added by label; the saved draft holds that binding, the spec accepts it, - * and a reopened panel shows it; - * - a dataset that shares no measure leaves none: the `values` key is - * removed, so the pillar holds the edit (the spec would refuse it) until a - * measure is picked; - * - a stored name the bound dataset does not declare is shown, marked; - * - the catalog read fails: the stored names are shown as saved, with the - * reason, and the rest of the panel is unaffected; - * - the Studio's draft world reads the draft-overlaid catalog; - * - CONTROLS: an object with no dataset says so and offers no picker; a grid - * and a calendar view get no chart section. - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { MetadataCtx, type MetadataContextValue } from '@object-ui/react'; -import { MetadataClient } from '@object-ui/data-objectstack'; -import { getMetadataTypeSchema } from '@objectstack/spec/kernel'; - -const PKG = 'com.acme.app'; -const VIEW = 'acme_task.default'; - -const OBJECT_DEF = { - name: 'acme_task', - label: 'Task', - fields: { - title: { name: 'title', label: 'Title', type: 'text' }, - status: { name: 'status', label: 'Status', type: 'text' }, - start_date: { name: 'start_date', label: 'Start date', type: 'date' }, - }, -}; - -const HOURS = { - name: 'task_hours', - label: 'Task hours', - object: 'acme_task', - measures: [ - { name: 'record_count', label: 'Tasks', aggregate: 'count' }, - { name: 'total_hours', label: 'Total hours', aggregate: 'sum' }, - ], - dimensions: [{ name: 'by_status', label: 'By status' }], -}; -const THROUGHPUT = { - name: 'task_throughput', - label: 'Throughput', - object: 'acme_task', - measures: [ - { name: 'record_count', label: 'Tasks', aggregate: 'count' }, - { name: 'avg_cycle', label: 'Average cycle time', aggregate: 'avg' }, - ], - dimensions: [{ name: 'by_week', label: 'By week' }], -}; -const BURN = { - name: 'task_burn', - label: 'Burn', - object: 'acme_task', - measures: [{ name: 'burned', label: 'Burned', aggregate: 'sum' }], - dimensions: [], -}; -const DEALS = { - name: 'deal_stats', - label: 'Deals', - object: 'acme_deal', - measures: [{ name: 'record_count', label: 'Deals' }], - dimensions: [], -}; - -const view = (config: Record) => ({ - name: VIEW, - object: 'acme_task', - viewKind: 'list', - isDefault: true, - config: { data: { provider: 'object', object: 'acme_task' }, columns: ['title', 'status'], ...config }, -}); - -const chartView = (chart: Record) => view({ type: 'chart', chart }); - -const server = { - active: new Map>(), - datasets: [] as Array> | 'fail', - datasetListUrls: [] as string[], - puts: [] as Array<{ name: string; status: number; body: any }>, -}; - -const json = (status: number, body: unknown) => - new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); - -async function serve(input: RequestInfo | URL, init?: RequestInit): Promise { - const method = (init?.method ?? 'GET').toUpperCase(); - const url = new URL(String(input), 'http://studio.test'); - const meta = url.pathname.match(/^\/api\/v1\/meta\/(.+)$/); - if (!meta) return json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); - const seg = meta[1].split('/').map(decodeURIComponent); - const key = `${seg[0]}/${seg[1]}`; - if (seg[0] === '_drafts') return json(200, { drafts: [] }); - if (seg[0] === 'dataset' && seg.length === 1) { - server.datasetListUrls.push(url.pathname + url.search); - return server.datasets === 'fail' - ? json(503, { error: { code: 'SERVICE_UNAVAILABLE', message: 'analytics offline' } }) - : json(200, { items: server.datasets }); - } - if (method === 'PUT') { - const body = JSON.parse(String(init?.body ?? '{}')); - const verdict = getMetadataTypeSchema('view')!.safeParse(body); - server.puts.push({ name: seg[1]!, status: verdict.success ? 200 : 422, body }); - if (!verdict.success) { - return json(422, { - success: false, - error: { code: 'INVALID_METADATA', message: 'view failed validation', details: { issues: verdict.error.issues } }, - }); - } - return json(200, { success: true, version: 'v2', state: 'draft' }); - } - if (seg[0] === 'object' && seg.length === 2) return json(200, { type: 'object', name: seg[1], item: OBJECT_DEF }); - if (seg.length === 3 && seg[2] === 'layers') { - const row = server.active.get(key); - return row - ? json(200, { code: null, overlay: row, overlayScope: 'env', effective: row }) - : json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); - } - // No view draft is pending in this suite. - if (seg.length === 2 && url.searchParams.get('state') === 'draft') { - return json(404, { error: { code: 'NO_DRAFT', message: 'absent' } }); - } - const row = server.active.get(key); - return row ? json(200, { type: seg[0], name: seg[1], item: row }) : json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); -} - -const client = new MetadataClient({ baseUrl: '', fetch: vi.fn(serve) as unknown as typeof fetch }); - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => client }; -}); - -import { listViewHeldEdit, ObjectListViewInspector, useObjectListViewDraft } from './ObjectListViewInspector'; -import { StudioDatasetAuthoringContext } from './datasetCreate'; -import type { Surface } from './navSurface'; - -const METADATA: MetadataContextValue = { - apps: [], - objects: [OBJECT_DEF], - dashboards: [], - reports: [], - pages: [], - loading: false, - error: null, - refresh: async () => {}, - invalidate: () => {}, - ensureType: async () => [], - getItem: async () => null, - getItemsByType: () => [], -}; - -const LEAF: Surface = { type: 'object', name: 'acme_task', label: 'Tasks' }; - -/** The panel, the pillar's held judgement of its buffer, and the autosave's one call into it. */ -function Host({ readOnly = false }: { readOnly?: boolean }) { - const listView = useObjectListViewDraft({ client, packageId: PKG, leaf: LEAF, publishNonce: 0 }); - return ( - <> - {String(listView.dirty)} - {listViewHeldEdit(listView, 'en')?.input ?? ''} - - - - ); -} - -async function settle() { - await act(async () => { - for (let i = 0; i < 25; i++) await new Promise((r) => setTimeout(r, 0)); - }); -} - -async function openPanel({ readOnly = false, studio = false }: { readOnly?: boolean; studio?: boolean } = {}): Promise { - const host = ; - render( - - {studio ? ( - {host} - ) : ( - host - )} - , - ); - await settle(); - await waitFor(() => expect(screen.getByTestId('studio-list-view-inspector')).toBeInTheDocument()); -} - -const section = () => screen.getByTestId('list-view-chart'); -const datasetTrigger = () => within(section()).getByTestId('list-view-chart-dataset-trigger'); - -/** The labels a select lists, as an author opens it. */ -async function optionsOf(trigger: HTMLElement): Promise { - fireEvent.keyDown(trigger, { key: 'ArrowDown' }); - const listbox = await screen.findByRole('listbox'); - const labels = within(listbox) - .getAllByRole('option') - .map((o) => o.textContent ?? ''); - fireEvent.keyDown(listbox, { key: 'Escape' }); - await settle(); - return labels; -} - -/** Pick the option whose text starts with `label` in the select `trigger`. */ -async function pick(trigger: HTMLElement, label: string) { - await waitFor(() => expect(trigger).toBeEnabled()); - fireEvent.keyDown(trigger, { key: 'ArrowDown' }); - const listbox = await screen.findByRole('listbox'); - const hit = within(listbox) - .getAllByRole('option') - .find((o) => (o.textContent ?? '').startsWith(label)); - if (!hit) throw new Error(`no option "${label}"`); - fireEvent.click(hit); - await settle(); -} - -const addPicker = (key: 'values' | 'dimensions') => document.getElementById(`studio-list-view-chart-${key}`)!; - -/** The names a member list holds, in order, and the ones marked as not in the dataset. */ -function members(key: 'values' | 'dimensions') { - const rows = within(screen.getByTestId(`list-view-chart-${key}`)).queryAllByTestId('list-view-chart-member'); - return { - names: rows.map((r) => r.getAttribute('data-name')), - labels: rows.map((r) => r.firstElementChild?.firstElementChild?.textContent), - stale: rows.filter((r) => r.getAttribute('data-stale') === 'true').map((r) => r.getAttribute('data-name')), - }; -} - -async function save() { - fireEvent.click(screen.getByTestId('save')); - await settle(); -} - -beforeEach(() => { - server.active.clear(); - server.datasets = [HOURS, THROUGHPUT, BURN, DEALS]; - server.datasetListUrls = []; - server.puts = []; -}); -afterEach(cleanup); - -describe('objectstack#27933 — a chart view’s dataset binding in the list-view panel', () => { - it('lists the object’s datasets by label, never another object’s, and shows the stored binding by label', async () => { - server.active.set(`view/${VIEW}`, chartView({ dataset: 'task_hours', values: ['total_hours'], dimensions: ['by_status'] })); - await openPanel(); - await waitFor(() => expect(datasetTrigger()).toHaveTextContent('Task hours (task_hours)')); - expect(await optionsOf(datasetTrigger())).toEqual([ - 'Task hours (task_hours)', - 'Throughput (task_throughput)', - 'Burn (task_burn)', - ]); - await waitFor(() => expect(members('values').labels).toEqual(['Total hours'])); - expect(members('dimensions').labels).toEqual(['By status']); - // The add pickers offer the bound dataset's other members, by label. - expect(await optionsOf(addPicker('values'))).toEqual(['Tasksrecord_count']); - // Opening the panel edits nothing, so the autosave has nothing to send. - expect(screen.getByTestId('dirty')).toHaveTextContent('false'); - expect(server.puts).toEqual([]); - }); - - it('another dataset keeps the shared measure, drops what it does not declare; each pick saves, and a reopened panel shows it', async () => { - server.active.set( - `view/${VIEW}`, - chartView({ chartType: 'line', dataset: 'task_hours', values: ['record_count', 'total_hours'], dimensions: ['by_status'] }), - ); - await openPanel(); - await waitFor(() => expect(members('values').names).toEqual(['record_count', 'total_hours'])); - - await pick(datasetTrigger(), 'Throughput'); - expect(datasetTrigger()).toHaveTextContent('Throughput (task_throughput)'); - await waitFor(() => expect(members('values').names).toEqual(['record_count'])); - expect(members('values').stale).toEqual([]); - expect(members('dimensions').names).toEqual([]); - - await pick(addPicker('dimensions'), 'By week'); - await pick(addPicker('values'), 'Average cycle time'); - expect(members('values').labels).toEqual(['Tasks', 'Average cycle time']); - expect(screen.getByTestId('held')).toHaveTextContent(/^$/); - - await save(); - expect(server.puts).toHaveLength(1); - expect(server.puts[0]!.status).toBe(200); - expect(server.puts[0]!.body.config.chart).toEqual({ - chartType: 'line', - dataset: 'task_throughput', - values: ['record_count', 'avg_cycle'], - dimensions: ['by_week'], - }); - - // Reopen on what was saved: the panel shows the stored binding. - server.active.set(`view/${VIEW}`, server.puts[0]!.body); - cleanup(); - await openPanel(); - await waitFor(() => expect(datasetTrigger()).toHaveTextContent('Throughput (task_throughput)')); - await waitFor(() => expect(members('values').labels).toEqual(['Tasks', 'Average cycle time'])); - expect(members('dimensions').labels).toEqual(['By week']); - }); - - it('a dataset that shares no measure leaves none: the edit is held until one is picked, never sent for the spec to refuse', async () => { - server.active.set(`view/${VIEW}`, chartView({ dataset: 'task_hours', values: ['total_hours'] })); - await openPanel(); - await waitFor(() => expect(members('values').names).toEqual(['total_hours'])); - - await pick(datasetTrigger(), 'Burn'); - expect(members('values').names).toEqual([]); - // Held on the unset measures, by the label the section draws them with. - expect(screen.getByTestId('held')).toHaveTextContent('Measures'); - // What the hold keeps from the draft door: the spec refuses the block without measures. - const refused = getMetadataTypeSchema('view')!.safeParse(chartView({ dataset: 'task_burn' })); - expect(refused.success).toBe(false); - // An empty list would be finished-but-wrong, which is sent: the key is removed instead. - expect(within(section()).getByTestId('list-view-chart-dimensions')).toHaveTextContent('This dataset declares no dimensions.'); - - await pick(addPicker('values'), 'Burned'); - expect(screen.getByTestId('held')).toHaveTextContent(/^$/); - await save(); - expect(server.puts.map((p) => p.status)).toEqual([200]); - expect(server.puts[0]!.body.config.chart).toEqual({ dataset: 'task_burn', values: ['burned'] }); - }); - - it('marks a stored name the bound dataset does not declare, and lets it be removed', async () => { - server.active.set(`view/${VIEW}`, chartView({ dataset: 'task_hours', values: ['record_count', 'retired_measure'] })); - await openPanel(); - await waitFor(() => expect(members('values').stale).toEqual(['retired_measure'])); - fireEvent.click(within(screen.getByTestId('list-view-chart-values')).getByRole('button', { name: /retired_measure/ })); - await settle(); - expect(members('values').names).toEqual(['record_count']); - await save(); - expect(server.puts[0]!.body.config.chart).toEqual({ dataset: 'task_hours', values: ['record_count'] }); - }); - - it('a failed catalog read shows the stored names as saved, with the reason; the panel carries on', async () => { - server.datasets = 'fail'; - server.active.set(`view/${VIEW}`, chartView({ dataset: 'task_hours', values: ['total_hours'], dimensions: ['by_status'] })); - await openPanel(); - await waitFor(() => expect(within(section()).getByTestId('list-view-chart-read-failed')).toHaveTextContent('analytics offline')); - expect(within(section()).queryByTestId('list-view-chart-dataset-trigger')).toBeNull(); - expect(within(section()).getByTestId('list-view-chart-stored-dataset')).toHaveTextContent('task_hours'); - expect(members('values')).toEqual({ names: ['total_hours'], labels: ['total_hours'], stale: [] }); - expect(members('dimensions').names).toEqual(['by_status']); - expect(addPicker('values')).toBeNull(); - expect(screen.getByTestId('list-view-columns')).toBeInTheDocument(); - }); - - it('reads the draft-overlaid catalog in the Studio’s draft world', async () => { - server.active.set(`view/${VIEW}`, chartView({ dataset: 'task_hours', values: ['total_hours'] })); - await openPanel({ studio: true }); - await waitFor(() => expect(datasetTrigger()).toHaveTextContent('Task hours')); - expect(server.datasetListUrls).toEqual(['/api/v1/meta/dataset?preview=draft']); - }); - - it('a read-only package shows the binding and offers no edit', async () => { - server.active.set(`view/${VIEW}`, chartView({ dataset: 'task_hours', values: ['total_hours'] })); - await openPanel({ readOnly: true }); - await waitFor(() => expect(members('values').labels).toEqual(['Total hours'])); - expect(datasetTrigger()).toBeDisabled(); - expect(addPicker('values')).toBeNull(); - expect(within(screen.getByTestId('list-view-chart-values')).queryByRole('button')).toBeNull(); - }); - - it('CONTROL: an object with no dataset says so and offers no empty picker', async () => { - server.datasets = [DEALS]; - server.active.set(`view/${VIEW}`, chartView({ dataset: 'task_hours', values: ['total_hours'] })); - await openPanel(); - await waitFor(() => expect(within(section()).getByTestId('list-view-chart-no-datasets')).toBeInTheDocument()); - expect(within(section()).queryByTestId('list-view-chart-dataset-trigger')).toBeNull(); - expect(addPicker('values')).toBeNull(); - }); - - it('CONTROL: a grid and a calendar view get no chart section', async () => { - server.active.set(`view/${VIEW}`, view({ type: 'grid' })); - await openPanel(); - expect(screen.queryByTestId('list-view-chart')).toBeNull(); - cleanup(); - server.active.set(`view/${VIEW}`, view({ type: 'calendar', calendar: { startDateField: 'start_date' } })); - await openPanel(); - expect(screen.getByTestId('list-view-type-settings')).toBeInTheDocument(); - expect(screen.queryByTestId('list-view-chart')).toBeNull(); - expect(server.datasetListUrls).toEqual([]); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.copilotMarks-12725.test.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.copilotMarks-12725.test.tsx deleted file mode 100644 index 25d4f46226c..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.copilotMarks-12725.test.tsx +++ /dev/null @@ -1,287 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#12725 (item 3) — an `object` leaf's list-view properties mark the - * view settings the AI copilot changed, and the elements it added to an array - * setting (a kanban card's fields), from the draft read's `draftChanges` - * (objectstack#24298 / #24395). - * - * The REAL hook (`useObjectListViewDraft`) and the REAL panel over a REAL - * `MetadataClient`, whose transport is an in-memory server answering as the - * framework does. - * - * Pinned: - * - a setting whose answering entry is `by: 'copilot'` shows the draft chip; - * the elements the copilot added to `kanban.columns` are marked and the - * published ones are not, read by comparing the draft's array with the - * published one — read from the ONE layered read a pending draft takes for - * its stored `draft` layer (objectstack#30859), never a second one; - * - the source line names the added elements and the minutes since `at`; - * - a `studio` entry draws nothing and adds no read; - * - CONTROLS: a published view with no draft draws nothing; a draft whose read - * recorded no `draftChanges` draws nothing and adds no `/layers` read; a - * draft created over no published body (`[]`) marks every element without one; - * - the panel's save sends `?surface=studio`, once. - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'; -import { MetadataCtx, type MetadataContextValue } from '@object-ui/react'; -import { MetadataClient } from '@object-ui/data-objectstack'; - -const PKG = 'com.acme.app'; -const VIEW = 'acme_loan.default'; - -const OBJECT_DEF = { - name: 'acme_loan', - label: 'Loan', - fields: { - book: { name: 'book', label: 'Book', type: 'text' }, - reader: { name: 'reader', label: 'Reader', type: 'text' }, - due_date: { name: 'due_date', label: 'Due date', type: 'date' }, - status: { name: 'status', label: 'Status', type: 'text' }, - }, -}; - -/** The object's default list view as a kanban board, with these card fields. */ -const kanbanView = (cardFields: string[], extra: Record = {}) => ({ - name: VIEW, - object: 'acme_loan', - viewKind: 'list', - isDefault: true, - config: { - type: 'kanban', - data: { provider: 'object', object: 'acme_loan' }, - columns: ['book', 'status'], - kanban: { groupByField: 'status', columns: cardFields }, - ...extra, - }, -}); - -const server = { - active: new Map>(), - drafts: new Map; draftChanges?: unknown[] }>(), - requests: [] as Array<{ method: string; path: string; search: string }>, -}; - -const json = (status: number, body: unknown) => - new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); - -async function serve(input: RequestInfo | URL, init?: RequestInit): Promise { - const method = (init?.method ?? 'GET').toUpperCase(); - const url = new URL(String(input), 'http://studio.test'); - server.requests.push({ method, path: url.pathname, search: url.search }); - const meta = url.pathname.match(/^\/api\/v1\/meta\/(.+)$/); - if (!meta) return json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); - const seg = meta[1].split('/').map(decodeURIComponent); - const key = `${seg[0]}/${seg[1]}`; - if (seg[0] === '_drafts') { - return json(200, { drafts: [...server.drafts.keys()].map((k) => ({ type: k.split('/')[0], name: k.split('/')[1], packageId: PKG })) }); - } - if (method === 'PUT') return json(200, { success: true, version: 'v2', state: 'draft' }); - if (seg[0] === 'object' && seg.length === 2) return json(200, { type: 'object', name: seg[1], item: OBJECT_DEF }); - if (seg.length === 3 && seg[2] === 'layers') { - // As the server answers an admitted author (objectstack#30859): a pending draft is served as stored, as `draft`, and an item with only a draft still has layers. - const row = server.active.get(key); - const draft = server.drafts.get(key)?.row ?? null; - return row || draft - ? json(200, { code: null, overlay: row ?? null, overlayScope: row ? 'env' : null, effective: row ?? null, draft }) - : json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); - } - if (seg.length === 2 && url.searchParams.get('state') === 'draft') { - const draft = server.drafts.get(key); - if (!draft) return json(404, { error: { code: 'NO_DRAFT', message: 'absent' } }); - return json(200, { - type: seg[0], - name: seg[1], - item: { ...draft.row, _draft: true }, - version: 'v1', - ...(draft.draftChanges ? { draftChanges: draft.draftChanges } : {}), - }); - } - const row = server.active.get(key); - return row ? json(200, { type: seg[0], name: seg[1], item: row }) : json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); -} - -const client = new MetadataClient({ baseUrl: '', fetch: vi.fn(serve) as unknown as typeof fetch }); - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => client }; -}); - -import { ObjectListViewInspector, useObjectListViewDraft } from './ObjectListViewInspector'; -import type { Surface } from './navSurface'; -import { tFormat } from '../metadata-admin/i18n'; - -const METADATA: MetadataContextValue = { - apps: [], - objects: [OBJECT_DEF], - dashboards: [], - reports: [], - pages: [], - loading: false, - error: null, - refresh: async () => {}, - invalidate: () => {}, - ensureType: async () => [], - getItem: async () => null, - getItemsByType: () => [], -}; - -const LEAF: Surface = { type: 'object', name: 'acme_loan', label: 'Loans' }; -const minutesAgo = (n: number) => new Date(Date.now() - n * 60_000 - 5_000).toISOString(); - -function Host() { - const listView = useObjectListViewDraft({ client, packageId: PKG, leaf: LEAF, publishNonce: 0 }); - return ( - <> - -