You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@skywalking.apache.org by wu...@apache.org on 2026/06/27 02:05:34 UTC
(skywalking-horizon-ui) branch main updated: UI correctness pass: comment audit, verified gap fixes, manual-fire query model, colored status cards, BFF boot-crash fix (#81)
This is an automated email from the ASF dual-hosted git repository.
wu-sheng pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/skywalking-horizon-ui.git
The following commit(s) were added to refs/heads/main by this push:
new 30c11ce UI correctness pass: comment audit, verified gap fixes, manual-fire query model, colored status cards, BFF boot-crash fix (#81)
30c11ce is described below
commit 30c11ce5ed580fcb7f0cfad11027a7dd9867c05d
Author: 吴晟 Wu Sheng <wu...@foxmail.com>
AuthorDate: Sat Jun 27 10:05:28 2026 +0800
UI correctness pass: comment audit, verified gap fixes, manual-fire query model, colored status cards, BFF boot-crash fix (#81)
feat(ui): colored status-chip cards, manual-fire query model, + correctness pass (#81)
Colored value-mapping cards: a format:'enum' card renders each matched value — or metric label — as a colored status chip (ok/warn/err/info/neutral), editable in the layer-dashboard admin's value-map editor. The K8s Node Status card consumes it, showing a node's active conditions (Ready green, *Pressure/NetworkUnavailable amber-red) instead of a raw 1. Also fixes the widget schema silently stripping format/valueMap/valueColors/labelTopN from the resolver's request body, so the existin [...]
Browser Errors manual-fire: mirrors the Logs tab — stage filter edits into an applied snapshot, fetch only on Run query, and reset to the prompt (clearing the category filter) on service switch.
Critical fix: the BFF crashed on boot because /api/ebpf/network/processes had no ROUTE_POLICY entry and the RBAC guard throws on any unpoliced route. It was masked by a stale dev process and invisible to type-check; caught by booting fresh against the demo OAP.
Hygiene + bug fixes: codebase-wide comment audit (strip ~331 non-earning comments, restore 8 over-removed gotchas) feeding a 32-finding gap review that was adversarially verified (5 false-positives dropped) — fixes for a loading-stuck modal, two missing-Escape dropdowns, Logs/Browser-Errors cascade-clear on service switch, Logs page reset, source-map clear on service switch, a partial form reset, and a label-case regression.
Profiling: consistent, honest create gating; network tasks pick their instance in-dialog and validate it has rover-monitored processes before Create.
Docs + i18n: profiling create-gating and Logs/Browser-Errors manual-fire docs; 18 i18n keys across all 8 locales for the new profiling strings.
Validation: type-check 0, lint clean, both builds, license check, 278 unit tests, i18n complete across 8 locales; the colored chips, Browser-Errors manual-fire gate, and the network-processes route all live-validated headless against the demo OAP. The LayerDashboardsAdmin XL-file decomposition is intentionally deferred to its own focused PR.
---
CHANGELOG.md | 30 +
apps/bff/eslint.config.mjs | 8 +
apps/bff/src/bundled_templates/layers/k8s.json | 21 +-
.../src/bundled_templates/layers/k8s_service.json | 4 +-
apps/bff/src/client/cluster.ts | 6 +-
apps/bff/src/client/index.ts | 5 +-
apps/bff/src/config/loader.ts | 16 +-
apps/bff/src/config/schema.ts | 15 +-
apps/bff/src/http/admin/alarm-rules.ts | 4 -
apps/bff/src/http/admin/inspect.ts | 10 -
apps/bff/src/http/admin/live-debug.ts | 7 -
apps/bff/src/http/config/dashboard.ts | 2 +-
apps/bff/src/http/config/layer-template.ts | 10 +-
apps/bff/src/http/query/alarms.ts | 15 -
apps/bff/src/http/query/async-profile.ts | 7 +-
apps/bff/src/http/query/dashboard.test.ts | 16 +-
apps/bff/src/http/query/dashboard.ts | 514 +----
apps/bff/src/http/query/ebpf.ts | 50 +-
apps/bff/src/http/query/endpoint-dependency.ts | 6 +-
apps/bff/src/http/query/instance.ts | 9 +-
apps/bff/src/http/query/landing.ts | 3 -
apps/bff/src/http/query/log.ts | 6 +-
apps/bff/src/http/query/pod-log.ts | 2 -
apps/bff/src/http/query/profile.ts | 5 -
apps/bff/src/http/query/topology.ts | 8 +-
apps/bff/src/http/query/trace.ts | 16 +-
apps/bff/src/http/query/zipkin.ts | 9 -
apps/bff/src/logic/alarms/bundled.ts | 22 +-
apps/bff/src/logic/alarms/store.ts | 1 -
apps/bff/src/logic/browser-errors/store.ts | 3 +-
apps/bff/src/logic/dashboard/gates.ts | 111 +
apps/bff/src/logic/dashboard/mqe.ts | 118 +
apps/bff/src/logic/dashboard/parsers.ts | 181 ++
apps/bff/src/logic/dashboard/schema.ts | 157 ++
apps/bff/src/logic/inspect/attribution.ts | 5 +-
apps/bff/src/logic/inspect/parser-oal.ts | 2 -
apps/bff/src/logic/layers/loader.ts | 2 +-
apps/bff/src/logic/oap/hierarchy.ts | 1 -
.../src/logic/templates/global-defaults-bundled.ts | 11 +-
apps/bff/src/rbac/route-policy.ts | 1 +
apps/bff/src/rbac/verbs.ts | 2 -
apps/bff/src/util/dns-fanout.ts | 3 +-
apps/bff/src/util/window.ts | 11 +-
apps/ui/eslint.config.mjs | Bin 2037 -> 3146 bytes
apps/ui/src/api/client.ts | 2 +
apps/ui/src/api/scopes/layer-template.ts | 3 -
apps/ui/src/api/scopes/network-profile.ts | 11 +
apps/ui/src/api/scopes/overview.ts | 2 -
apps/ui/src/components/charts/AlarmsTimeline.vue | 58 +-
apps/ui/src/components/charts/TopList.vue | 2 -
apps/ui/src/components/primitives/CatalogNav.vue | 3 -
apps/ui/src/components/primitives/TagInput.vue | 3 -
.../src/components/primitives/useEscapeToClose.ts | 44 +
apps/ui/src/controls/debugPanel.ts | 2 -
.../features/admin/_shared/TranslationEditor.vue | 334 ---
.../admin/_shared/useSingletonTemplateEditor.ts | 319 +++
.../features/admin/auth-status/AuthStatusView.vue | 6 -
.../admin/global-defaults/GlobalDefaultsAdmin.vue | 7 -
.../features/admin/infra-3d/Infra3dAdminView.vue | 464 +---
.../features/admin/infra-3d/Infra3dLayerRow.vue | 209 ++
.../features/admin/infra-3d/useInfra3dLevels.ts | 123 ++
.../admin/layer-templates/LayerDashboardsAdmin.vue | 104 +-
.../layer-templates/layer-dashboards.geometry.ts | 47 +
.../NewOverviewDashboardModal.vue | 104 +
.../overview-templates/OverviewEditCanvas.vue | 670 ++++++
.../overview-templates/OverviewTemplatesAdmin.vue | 1485 +------------
.../overview-templates/OverviewWidgetDrawer.vue | 482 +++++
.../admin/overview-templates/constants.ts} | 23 +-
.../admin/overview-templates/widget-mock.ts | 91 +
apps/ui/src/features/admin/roles/RolesView.vue | 9 -
.../admin/translations/TranslationFieldPanel.vue | 170 ++
.../admin/translations/TranslationPreview.vue | 402 ----
.../admin/translations/TranslationsView.vue | 506 +----
.../admin/translations/useTranslationDraft.ts | 351 +++
.../admin/translations/useTranslationPicker.ts | 149 ++
.../ui/src/features/admin/users/UsersAdminView.vue | 3 -
apps/ui/src/features/alarms/AlarmDetailPanel.vue | 29 +-
apps/ui/src/features/alarms/AlarmFilterRow.vue | 212 ++
apps/ui/src/features/alarms/AlarmSnapshotChart.vue | 5 +-
apps/ui/src/features/alarms/AlarmWindowPicker.vue | 159 ++
apps/ui/src/features/alarms/AlarmsView.vue | 554 +----
apps/ui/src/features/alarms/useAlarmFilters.ts | 146 ++
apps/ui/src/features/alarms/useAlarmWindow.ts | 182 ++
.../ui/src/features/infra-3d/Infra3DLayerPanel.vue | 300 +++
apps/ui/src/features/infra-3d/Infra3DScene.vue | 932 ++------
apps/ui/src/features/infra-3d/Infra3DView.vue | 861 +-------
apps/ui/src/features/infra-3d/PipelineTimeline.vue | 12 +-
.../infra-3d/composables/useInfra3dAlarms.ts | 17 +-
.../infra-3d/composables/useInfra3dLoader.ts | 525 +++++
.../infra-3d/composables/useInfra3dPipeline.ts | 6 +-
.../infra-3d/composables/useLiveTopology.ts | 7 +-
.../infra-3d/composables/useSceneCamera.ts | 244 +++
.../features/infra-3d/composables/useSceneEdges.ts | 261 +++
.../infra-3d/composables/useSceneMaterials.ts | 463 ++++
.../infra-3d/composables/useScenePlacement.ts | 21 +-
.../ui/src/features/operate/_shared/MonacoYaml.vue | 2 -
.../operate/alerting-rules/AlertingRulesView.vue | 1 -
.../ui/src/features/operate/dsl/OalCatalogView.vue | 1 -
.../ui/src/features/operate/dsl/syntaxHighlight.ts | 5 -
apps/ui/src/features/operate/dsl/useRuleEditor.ts | 1 -
.../operate/explore/ExploreBrowserErrorList.vue | 146 ++
.../features/operate/explore/ExploreLogView.vue | 618 +-----
.../features/operate/explore/ExplorePodLogList.vue | 116 +
.../src/features/operate/explore/ExploreView.vue | 3 -
.../features/operate/explore/useExploreEntity.ts | 180 ++
.../features/operate/explore/usePodLogSource.ts | 274 +++
.../src/features/operate/explore/usePodLogTail.ts | 118 +
.../operate/inspect/InspectCatalogDrawer.vue | 785 +++++++
.../src/features/operate/inspect/InspectView.vue | 905 +-------
.../src/features/operate/inspect/inspectForeign.ts | 114 +
.../ui/src/features/operate/inspect/inspectTime.ts | 93 +
.../src/features/operate/inspect/inspectTypes.ts | 55 +
.../src/features/operate/live-debug/DebugLal.vue | 369 +---
.../src/features/operate/live-debug/DebugMal.vue | 512 +----
.../src/features/operate/live-debug/DebugOal.vue | 181 +-
.../ui/src/features/operate/live-debug/LalCell.vue | 202 ++
.../src/features/operate/live-debug/lalPayload.ts | 234 ++
.../src/features/operate/live-debug/malGroups.ts | 461 ++++
apps/ui/src/features/operate/live-debug/payload.ts | 30 +
.../features/operate/live-debug/useDebugReplay.ts | 153 ++
.../operate/live-debug/useMalRecordViews.ts | 103 +
.../features/operate/live-debug/useRecordFold.ts | 94 +
apps/ui/src/i18n/locales/de.json | 20 +-
apps/ui/src/i18n/locales/en.json | 20 +-
apps/ui/src/i18n/locales/es.json | 20 +-
apps/ui/src/i18n/locales/fr.json | 20 +-
apps/ui/src/i18n/locales/ja.json | 20 +-
apps/ui/src/i18n/locales/ko.json | 20 +-
apps/ui/src/i18n/locales/pt.json | 20 +-
apps/ui/src/i18n/locales/zh-CN.json | 20 +-
apps/ui/src/layer/LayerShell.vue | 10 +-
apps/ui/src/layer/_shared/DensityHistogram.vue | 186 ++
apps/ui/src/layer/_shared/EndpointCombo.vue | 178 ++
apps/ui/src/layer/_shared/useDensityBins.ts | 79 +
apps/ui/src/layer/_shared/useEndpointCombo.ts | 92 +
.../browser-errors/LayerBrowserErrorsView.vue | 483 +----
.../layer/browser-errors/useLayerBrowserErrors.ts | 5 +-
.../layer/browser-errors/useSourceMapResolution.ts | 170 ++
.../LayerEndpointDependencyView.vue | 431 +---
.../useEndpointDependencyExpansion.ts | 181 ++
.../useEndpointDependencyLayout.ts | 287 +++
apps/ui/src/layer/logs/LayerLogsView.vue | 675 ++----
apps/ui/src/layer/logs/useLayerLogs.ts | 13 +-
apps/ui/src/layer/logs/useLogTagConditions.ts | 101 +
apps/ui/src/layer/logs/useLogTimeRange.ts | 110 +
apps/ui/src/layer/pod-logs/LayerPodLogsView.vue | 7 +-
apps/ui/src/layer/pod-logs/useLayerPodLogs.ts | 3 -
.../profiling/AsyncProfilingTaskDetailModal.vue | 177 ++
apps/ui/src/layer/profiling/EBPFProcessPicker.vue | 488 +++++
.../layer/profiling/LayerAsyncProfilingView.vue | 72 +-
.../src/layer/profiling/LayerEBPFProfilingView.vue | 926 +-------
.../layer/profiling/LayerNetworkProfilingView.vue | 115 +-
.../layer/profiling/LayerPprofProfilingView.vue | 77 +-
.../layer/profiling/LayerTraceProfilingView.vue | 325 +--
apps/ui/src/layer/profiling/NewEBPFTaskModal.vue | 356 +++
.../layer/profiling/NewTraceProfileTaskModal.vue | 326 +++
.../src/layer/profiling/PprofTaskDetailModal.vue | 170 ++
.../src/layer/profiling/ProcessTopologyGraph.vue | 4 -
apps/ui/src/layer/profiling/ProfileFlameGraph.vue | 10 +-
apps/ui/src/layer/profiling/ProfileStackTable.vue | 7 +-
.../profiling/TraceProfileTaskDetailModal.vue | 159 ++
apps/ui/src/layer/profiling/profileTimeRanges.ts | 49 +
apps/ui/src/layer/profiling/useEBPFProfiling.ts | 304 +++
apps/ui/src/layer/profiling/useNetworkProcesses.ts | 48 +
.../src/layer/service-map/DeploymentEdgePanel.vue | 149 ++
.../src/layer/service-map/DeploymentFlowsTable.vue | 101 +
.../layer/service-map/DeploymentNodePopover.vue | 134 ++
.../src/layer/service-map/LayerDeploymentView.vue | 660 +-----
.../service-map/LayerInstanceTopologyView.vue | 2 -
.../src/layer/service-map/LayerServiceMapView.vue | 2257 ++------------------
.../layer/service-map/ServiceHierarchyOverlay.vue | 3 -
.../src/layer/service-map/TopologyDetailPanels.vue | 857 ++++++++
.../src/layer/service-map/TopologyFocusPicker.vue | 288 +++
.../src/layer/service-map/TopologyNodeFilter.vue | 302 +++
.../src/layer/service-map/useDeploymentLayout.ts | 289 +++
.../src/layer/service-map/useDeploymentPanZoom.ts | 148 ++
apps/ui/src/layer/service-map/useTopologyCanvas.ts | 195 ++
apps/ui/src/layer/service-map/useTopologyLayout.ts | 404 ++++
apps/ui/src/layer/traces/LayerTracesEntry.vue | 9 +-
apps/ui/src/layer/traces/LayerTracesView.vue | 48 +-
apps/ui/src/layer/traces/LayerZipkinTracesView.vue | 772 +------
apps/ui/src/layer/traces/NativeTraceWaterfall.vue | 17 +-
apps/ui/src/layer/traces/TracePopout.vue | 17 -
apps/ui/src/layer/traces/ZipkinTracePopout.vue | 23 +-
apps/ui/src/layer/traces/useTracePopout.ts | 6 +-
apps/ui/src/layer/traces/useZipkinAutocomplete.ts | 146 ++
apps/ui/src/layer/traces/zipkinTraceRows.ts | 42 +
.../render/layer-dashboard/LayerDashboardsView.vue | 1330 ++----------
.../render/layer-dashboard/LayerEndpointPicker.vue | 342 +++
.../render/layer-dashboard/LayerInstancePicker.vue | 322 +++
.../src/render/layer-dashboard/LayerWidgetTile.vue | 454 ++++
.../src/render/layer-dashboard/useCompareEngine.ts | 338 +++
.../render/layer-dashboard/useEndpointCascade.ts | 170 ++
.../render/layer-dashboard/useInstanceCascade.ts | 157 ++
.../layer-dashboard/useLayerPageOrchestrator.ts | 2 -
.../src/render/overview/OverviewDashboardView.vue | 11 +-
apps/ui/src/render/widgets/AlarmsWidget.vue | 9 +-
apps/ui/src/render/widgets/LogDetailPopout.vue | 15 +-
apps/ui/src/render/widgets/RecordList.vue | 3 -
apps/ui/src/render/widgets/SpanDetailModal.vue | 318 +++
apps/ui/src/render/widgets/TraceDetailCard.vue | 1238 +----------
apps/ui/src/render/widgets/TraceDistribution.vue | 1 -
apps/ui/src/render/widgets/TraceStatsView.vue | 270 +++
apps/ui/src/render/widgets/TraceTreeView.vue | 400 ++++
apps/ui/src/render/widgets/TraceWaterfallView.vue | 359 ++++
.../src/render/widgets/ZipkinTraceDetailCard.vue | 6 +-
apps/ui/src/render/widgets/traceDetailShared.ts | 106 +
apps/ui/src/render/widgets/useTraceTreeZoom.ts | 77 +
apps/ui/src/shell/AdminFeatureWarning.vue | 2 -
apps/ui/src/shell/AlarmBadgeChip.vue | 104 +
apps/ui/src/shell/AppShell.vue | 77 +-
apps/ui/src/shell/AppSidebar.vue | 785 +------
apps/ui/src/shell/AppTopbar.vue | 1296 +----------
apps/ui/src/shell/AutoRefreshChip.vue | 190 ++
apps/ui/src/shell/ColdStageChip.vue | 91 +
apps/ui/src/shell/DebugEventPanel.vue | 5 +-
apps/ui/src/shell/GlobalConnectivityBanner.vue | 3 +-
apps/ui/src/shell/InfraMapPill.vue | 124 ++
apps/ui/src/shell/OapHealthChip.vue | 108 +
apps/ui/src/shell/SidebarLayerChildren.vue | 253 +++
apps/ui/src/shell/SidebarLayerRow.vue | 180 ++
apps/ui/src/shell/ThemeChip.vue | 170 ++
apps/ui/src/shell/TimeRangeChip.vue | 591 +++++
apps/ui/src/shell/router/index.ts | 57 +-
apps/ui/src/shell/useLandingOrder.ts | 18 +-
apps/ui/src/shell/useLayers.ts | 28 +-
apps/ui/src/shell/useSidebarActive.ts | 123 ++
apps/ui/src/shell/useSidebarMenu.ts | 230 ++
apps/ui/src/shell/useTopbarTimeContext.ts | 89 +
apps/ui/src/state/layerSelection.ts | 1 -
apps/ui/src/state/setup.ts | 17 +-
docs/operate/browser-source-maps.md | 8 +-
docs/operate/logs.md | 2 +-
docs/operate/profiling.md | 10 +-
packages/api-client/src/dashboard.ts | 11 +
packages/api-client/src/dsl-debugging.ts | 24 -
packages/api-client/src/ebpf.ts | 15 +-
packages/api-client/src/index.ts | 2 +
packages/api-client/src/inspect.ts | 16 -
packages/api-client/src/oal.ts | 2 -
packages/api-client/src/runtime-rule.ts | 2 -
packages/api-client/src/trace.ts | 6 -
packages/api-client/src/types.ts | 9 +-
243 files changed, 23672 insertions(+), 18873 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 916148a..df9a00f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,36 @@ The version line is shared by every package in the monorepo (apps + shared packa
- **Six instance dashboard line widgets for PHP Health Metrics** — process CPU utilization, memory used/peak, virtual memory, thread count, and open file descriptors (`meter_instance_php_*`). Each line widget uses `visibleWhen` so widgets render only when the PHP agent reports PHM data (Linux `/proc` sampling of the parent PHP process via `getppid()`).
+### Profiling
+
+- **Profiling task creation is consistent and tells you upfront what it needs.** Across all five task types (Trace / eBPF / Network / pprof / Async) the **New Task** button enables as soon as the basic entity is chosen and always carries a tooltip, and inside the create box a missing target — no profilable processes, or no instances on the service — is shown as a clear message next to a disabled **Create** rather than a silently greyed-out button.
+
+- **Network profiling picks its target instance in the create box and checks it has processes before you submit.** The create modal selects the instance inline and lists that instance's rover-monitored processes; if it has none, **Create** is blocked with a clear reason (OAP rejects a network task on a process-less instance) instead of failing after submit.
+
+- **pprof and async-profiling tasks open a detail modal with their captured logs.**
+
+### Logs
+
+- **Log and browser-error lists query on demand, not on every edit.** The per-layer Logs tab, cross-layer Log inspect, and the Browser Errors tab now stage condition changes and fetch only when you press **Run query** — a fresh tab shows a "Pick your conditions, then click Run query" prompt, and switching service resets to that prompt (clearing the level / tag / category filters), so the previous service's data never lingers under the new one.
+
+### Alarms
+
+- **The alarm timeline reads more clearly** — a clearer selection band and legend, and the detail sidebar reflows cleanly on narrow windows.
+
+### User experience
+
+- **Escape closes any dismissible panel** — modals, row popouts, and the topology focus / node-filter dropdowns all dismiss on Esc.
+
+- **Switching service clears the dependent filters** (log level / tags, browser-error category) back to a clean state, so a stale filter never silently hides the new service's data.
+
+- **Denser Kubernetes dashboard tables** — the K8s layer's table widgets show more rows without scrolling.
+
+### Dashboards
+
+- **Cards can render values as colored status chips.** A card widget with `format: enum` now takes an optional chip color per value-map entry — `ok` (green), `warn` (amber), `err` (red), `info` (blue), `neutral` (grey) — and renders each matched value, or metric label, as a colored chip instead of a bare number. Set it in the layer-dashboard admin's value-map editor, next to the existing value → label mapping.
+
+- **The Kubernetes Node Status card now reads as a status, not a number.** Instead of a raw `1`, it shows the node's active conditions as colored chips — `Ready` in green, the `*Pressure` / `NetworkUnavailable` conditions in amber/red — so node health is legible at a glance.
+
## 1.0.0
### Performance & behavior tuning
diff --git a/apps/bff/eslint.config.mjs b/apps/bff/eslint.config.mjs
index 42a8779..9c1dd18 100644
--- a/apps/bff/eslint.config.mjs
+++ b/apps/bff/eslint.config.mjs
@@ -38,4 +38,12 @@ export default tseslint.config(
'@typescript-eslint/no-empty-object-type': 'off',
},
},
+ {
+ // File-size guardrail. No NEW file may exceed 1000 lines — split it
+ // instead. The grandfather list below is the decomposition backlog: remove
+ // a file when its split lands; never add to it.
+ files: ['src/**/*.ts'],
+ ignores: ['**/*.test.ts'],
+ rules: { 'max-lines': ['error', 1000] },
+ },
);
diff --git a/apps/bff/src/bundled_templates/layers/k8s.json b/apps/bff/src/bundled_templates/layers/k8s.json
index e40c368..43e5e13 100644
--- a/apps/bff/src/bundled_templates/layers/k8s.json
+++ b/apps/bff/src/bundled_templates/layers/k8s.json
@@ -209,7 +209,7 @@
],
"showTableValues": false,
"span": 4,
- "rowSpan": 4
+ "rowSpan": 2
},
{
"id": "deployment_status",
@@ -225,7 +225,7 @@
],
"showTableValues": false,
"span": 4,
- "rowSpan": 4
+ "rowSpan": 2
},
{
"id": "deployment_replicas",
@@ -241,7 +241,7 @@
],
"showTableValues": true,
"span": 4,
- "rowSpan": 4
+ "rowSpan": 2
},
{
"id": "service_pod_status",
@@ -257,7 +257,7 @@
],
"showTableValues": false,
"span": 4,
- "rowSpan": 4
+ "rowSpan": 2
},
{
"id": "pod_not_running",
@@ -273,7 +273,7 @@
],
"showTableValues": false,
"span": 4,
- "rowSpan": 4
+ "rowSpan": 2
},
{
"id": "pod_waiting",
@@ -289,7 +289,7 @@
],
"showTableValues": false,
"span": 4,
- "rowSpan": 4
+ "rowSpan": 2
}
],
"instance": [
@@ -302,7 +302,14 @@
],
"span": 3,
"rowSpan": 1,
- "format": "int"
+ "format": "enum",
+ "valueColors": {
+ "Ready": "ok",
+ "MemoryPressure": "warn",
+ "DiskPressure": "warn",
+ "PIDPressure": "warn",
+ "NetworkUnavailable": "err"
+ }
},
{
"id": "node_pod_total",
diff --git a/apps/bff/src/bundled_templates/layers/k8s_service.json b/apps/bff/src/bundled_templates/layers/k8s_service.json
index adf68aa..8a541c5 100644
--- a/apps/bff/src/bundled_templates/layers/k8s_service.json
+++ b/apps/bff/src/bundled_templates/layers/k8s_service.json
@@ -83,7 +83,7 @@
],
"showTableValues": false,
"span": 4,
- "rowSpan": 3
+ "rowSpan": 2
},
{
"id": "pod_restarts",
@@ -98,7 +98,7 @@
],
"showTableValues": true,
"span": 4,
- "rowSpan": 3
+ "rowSpan": 2
},
{
"id": "cpu_resources",
diff --git a/apps/bff/src/client/cluster.ts b/apps/bff/src/client/cluster.ts
index ba6a84d..67caebe 100644
--- a/apps/bff/src/client/cluster.ts
+++ b/apps/bff/src/client/cluster.ts
@@ -21,11 +21,7 @@
* The BFF fires a single `/runtime/rule/list` to `oap.adminUrl` and
* exposes the result. OAP routes rule operations cluster-internally, so
* one node's list is the cluster's list — we don't fan out on the BFF
- * side. The previous "per-node convergence" view was retired alongside
- * the `adminUrls: [...]` → `adminUrl: string` config rename; if you
- * need per-node visibility for runtime rules, that's an OAP-side
- * feature ask (cluster routes already exist for `/dsl-debugging/status`
- * which the BFF probes via DNS lookup on `adminUrl`).
+ * side.
*/
import type {
diff --git a/apps/bff/src/client/index.ts b/apps/bff/src/client/index.ts
index f943e59..d99bd7c 100644
--- a/apps/bff/src/client/index.ts
+++ b/apps/bff/src/client/index.ts
@@ -82,9 +82,8 @@ export function buildOapClients(
const fetch = opts.fetch;
const primaryUrl = config.oap.adminUrl;
const timeoutMs = config.oap.timeoutMs;
- // If config.oap.auth is set, every constructed client gets the
- // basic-auth Authorization header so all upstream calls (status,
- // runtime-rule, OAL catalog, DSL debug, inspect) authenticate.
+ // One basic-auth header shared by every constructed client, so all
+ // upstream calls authenticate.
const headers: Record<string, string> | undefined = config.oap.auth
? {
authorization:
diff --git a/apps/bff/src/config/loader.ts b/apps/bff/src/config/loader.ts
index 20d9765..0c974bb 100644
--- a/apps/bff/src/config/loader.ts
+++ b/apps/bff/src/config/loader.ts
@@ -104,17 +104,13 @@ export function isAuthConfigured(cfg: HorizonConfig): boolean {
/**
* Inspect the loaded config and emit a startup warning if auth isn't
- * wired yet. Kept as a separate function (rather than inlined into
- * `loadConfig`) so callers can choose to skip it (tests) or run it on
- * config hot-reload too.
+ * wired yet. Separate from `loadConfig` so callers can skip it (tests)
+ * or run it on config hot-reload too.
*
- * The historical contract was fail-loud — a misconfigured deployment
- * crashed on boot. That was inconvenient for first-touch operators:
- * a clean `docker run` produced a CrashLoopBackOff instead of a UI
- * with a "set up auth" hint. We now boot, log a warning, and surface
- * the same information to the login page so the first interaction is
- * "open browser → see the next step" rather than "watch container
- * logs → guess what's wrong".
+ * A misconfigured deployment boots and logs a warning rather than
+ * crashing, surfacing the same information to the login page so the
+ * first interaction is "open browser → see the next step" rather than
+ * "watch container logs → guess what's wrong".
*
* Returns the input on success so callers can chain.
*/
diff --git a/apps/bff/src/config/schema.ts b/apps/bff/src/config/schema.ts
index e9e21a5..c48a7b9 100644
--- a/apps/bff/src/config/schema.ts
+++ b/apps/bff/src/config/schema.ts
@@ -239,8 +239,7 @@ const rbacSchema = z
}),
/** Landing route per role; the UI uses this to send users to the
* page that fits their job after login. Cluster status lives at
- * `/operate/cluster` (operator tooling against OAP) — the prior
- * `/admin/cluster` defaults 404'd because no such route exists. */
+ * `/operate/cluster` (operator tooling against OAP). */
landingByRole: z
.record(z.string(), z.string())
.default({
@@ -362,11 +361,10 @@ const sourceMapsSchema = z
.default({});
// Layers hidden from the sidebar / menu even when OAP reports them in
-// `listLayers`. Config-driven (replaces a former hard-coded hide list): an
-// operator can clear `excluded` to surface every reported layer, or add keys
-// for internal-only layers they don't want on the menu. The `reason` is
-// documentation for whoever reads this file — it isn't shown in the UI (an
-// excluded layer simply doesn't appear).
+// `listLayers`. An operator can clear `excluded` to surface every reported
+// layer, or add keys for internal-only layers they don't want on the menu.
+// The `reason` is documentation for whoever reads this file — it isn't shown
+// in the UI (an excluded layer simply doesn't appear).
const excludedLayerSchema = z
.object({
/** OAP layer key (UPPER_SNAKE), matched case-insensitively. */
@@ -408,8 +406,7 @@ const performanceSchema = z
})
.strict()
.default({}),
- // 3D infrastructure-map metric fan-out (relocated from the 3D
- // template's former `pipeline` block).
+ // 3D infrastructure-map metric fan-out.
infra3d: z
.object({
metricBulkSize: z.number().int().min(1).max(12).default(6),
diff --git a/apps/bff/src/http/admin/alarm-rules.ts b/apps/bff/src/http/admin/alarm-rules.ts
index 2967f4c..2797182 100644
--- a/apps/bff/src/http/admin/alarm-rules.ts
+++ b/apps/bff/src/http/admin/alarm-rules.ts
@@ -146,7 +146,6 @@ function pivot(
}));
const totalNodes = nodes.length || 1;
- /* Build per-rule node membership from the list envelope. */
const perRuleNodes = new Map<string, Set<string>>();
for (const inst of listResp.oapInstances) {
if (!inst.status) continue;
@@ -199,7 +198,6 @@ export function registerAlarmRulesRoutes(
return buildOapClients(deps.config.current, { fetch: deps.fetch }).alarmStatus();
}
- // ── GET /api/admin/alarm-rules ────────────────────────────────────
app.get(
'/api/admin/alarm-rules',
{ preHandler: auth },
@@ -249,7 +247,6 @@ export function registerAlarmRulesRoutes(
},
);
- // ── GET /api/admin/alarm-rules/:id ────────────────────────────────
app.get(
'/api/admin/alarm-rules/:id',
{ preHandler: auth },
@@ -295,7 +292,6 @@ export function registerAlarmRulesRoutes(
},
);
- // ── GET /api/admin/alarm-rules/:id/context?entity=… ───────────────
// `entity` rides as a query param (not a path segment) because entity
// names carry `::` and may carry `/` (endpoint scope) — path-segment
// encoding of those is a portability minefield across proxies.
diff --git a/apps/bff/src/http/admin/inspect.ts b/apps/bff/src/http/admin/inspect.ts
index a6d6697..6cd7f6c 100644
--- a/apps/bff/src/http/admin/inspect.ts
+++ b/apps/bff/src/http/admin/inspect.ts
@@ -101,8 +101,6 @@ export function registerInspectRoutes(app: FastifyInstance, deps: InspectRouteDe
return buildOapClients(deps.config.current, { fetch: deps.fetch });
}
- // ── /api/inspect/metrics ─────────────────────────────────────────
-
app.get(
'/api/inspect/metrics',
{ preHandler: auth },
@@ -131,7 +129,6 @@ export function registerInspectRoutes(app: FastifyInstance, deps: InspectRouteDe
},
);
- // ── /api/inspect/catalog ─────────────────────────────────────────
// Merges `/inspect/metrics` with Studio's rule-file attribution
// (source + file per metric). This is the endpoint the Inspect
// page's catalog drawer hits — the raw `/api/inspect/metrics`
@@ -176,7 +173,6 @@ export function registerInspectRoutes(app: FastifyInstance, deps: InspectRouteDe
},
);
- // ── /api/inspect/server-time ─────────────────────────────────────
// Caches OAP's `getTimeInfo` so the SPA can display dates in browser
// local TZ while sending server-TZ strings to OAP.
@@ -197,7 +193,6 @@ export function registerInspectRoutes(app: FastifyInstance, deps: InspectRouteDe
},
);
- // ── /api/inspect/exec ────────────────────────────────────────────
// Fires `mutation execExpression` against the resolved MQE base
// and returns the `ExpressionResult` payload verbatim.
@@ -238,8 +233,6 @@ export function registerInspectRoutes(app: FastifyInstance, deps: InspectRouteDe
},
);
- // ── /api/inspect/entities ────────────────────────────────────────
-
app.get(
'/api/inspect/entities',
{ preHandler: auth },
@@ -305,7 +298,6 @@ export function registerInspectRoutes(app: FastifyInstance, deps: InspectRouteDe
},
);
- // ── /api/inspect/values ──────────────────────────────────────────
// Reads VALUES of FOREIGN metric(s) the connected OAP doesn't define,
// via OAP's admin-port `POST /inspect/values` (returns the same
// ExpressionResult shape as execExpression). This is the value path
@@ -329,8 +321,6 @@ export function registerInspectRoutes(app: FastifyInstance, deps: InspectRouteDe
);
}
-// ── helpers ───────────────────────────────────────────────────────
-
/** Parse the foreign-metric `valueColumn` / `valueType` pair. Returns an
* empty object for an aware request (neither supplied), the validated pair
* for a foreign request (both supplied), or `null` after sending a 400 when
diff --git a/apps/bff/src/http/admin/live-debug.ts b/apps/bff/src/http/admin/live-debug.ts
index 0b87dbf..1cecbbd 100644
--- a/apps/bff/src/http/admin/live-debug.ts
+++ b/apps/bff/src/http/admin/live-debug.ts
@@ -72,7 +72,6 @@ export function registerDebugRoutes(app: FastifyInstance, deps: DebugRouteDeps):
return buildOapClients(deps.config.current, { fetch: deps.fetch });
}
- // ── start session ────────────────────────────────────────────────
app.post(
'/api/debug/session',
{ preHandler: auth },
@@ -130,7 +129,6 @@ export function registerDebugRoutes(app: FastifyInstance, deps: DebugRouteDeps):
},
);
- // ── poll session ─────────────────────────────────────────────────
app.get(
'/api/debug/session/:id',
{ preHandler: auth },
@@ -148,7 +146,6 @@ export function registerDebugRoutes(app: FastifyInstance, deps: DebugRouteDeps):
},
);
- // ── stop session ─────────────────────────────────────────────────
app.post(
'/api/debug/session/:id/stop',
{ preHandler: auth },
@@ -183,7 +180,6 @@ export function registerDebugRoutes(app: FastifyInstance, deps: DebugRouteDeps):
},
);
- // ── list active sessions ─────────────────────────────────────────
app.get(
'/api/debug/sessions',
{ preHandler: auth },
@@ -198,7 +194,6 @@ export function registerDebugRoutes(app: FastifyInstance, deps: DebugRouteDeps):
},
);
- // ── per-cluster status fan-out ───────────────────────────────────
// /dsl-debugging/status is a per-node read; OAP doesn't aggregate it
// cluster-wide. We turn the single `oap.adminUrl` into one URL per
// resolved IP via DNS lookup and probe each. When the hostname is
@@ -232,8 +227,6 @@ export function registerDebugRoutes(app: FastifyInstance, deps: DebugRouteDeps):
);
}
-// ── helpers ─────────────────────────────────────────────────────────
-
function ensureVerb(
req: FastifyRequest,
reply: FastifyReply,
diff --git a/apps/bff/src/http/config/dashboard.ts b/apps/bff/src/http/config/dashboard.ts
index a492840..07a50d1 100644
--- a/apps/bff/src/http/config/dashboard.ts
+++ b/apps/bff/src/http/config/dashboard.ts
@@ -35,7 +35,7 @@ import {
import { resolveEffectiveLayer } from '../../logic/layers/effective.js';
import { oapOverlayContentFor } from '../../logic/templates/overlay.js';
import { defaultWidgetsFor } from '../../logic/dashboard/defaults.js';
-import { scopeSchema } from '../query/dashboard.js';
+import { scopeSchema } from '../../logic/dashboard/schema.js';
import { localizeContent, localeFromRequest } from '../../i18n/index.js';
export interface DashboardConfigDeps {
diff --git a/apps/bff/src/http/config/layer-template.ts b/apps/bff/src/http/config/layer-template.ts
index 52acbed..a04fecc 100644
--- a/apps/bff/src/http/config/layer-template.ts
+++ b/apps/bff/src/http/config/layer-template.ts
@@ -39,11 +39,6 @@ export interface LayerTemplateConfigDeps {
sessions: SessionStore;
}
-// All zod schemas for admin template validation were removed when
-// `POST /api/admin/layer-templates/:key` was retired. Layer-template
-// updates now flow through `/api/admin/templates/save` (OAP-backed,
-// validated server-side by the OAP UI-template endpoint shape).
-
export function registerLayerTemplateRoutes(
app: FastifyInstance,
deps: LayerTemplateConfigDeps,
@@ -56,7 +51,6 @@ export function registerLayerTemplateRoutes(
return reply.send({ templates: allLayerTemplates() });
});
- // POST /api/admin/layer-templates/:key removed — operator updates
- // now go through `/api/admin/templates/save` (OAP-backed). Bundled
- // JSON is immutable at runtime.
+ // No write route here: operator updates go through `/api/admin/templates/save`
+ // (OAP-backed). Bundled JSON is immutable at runtime.
}
diff --git a/apps/bff/src/http/query/alarms.ts b/apps/bff/src/http/query/alarms.ts
index 4a721da..964f20e 100644
--- a/apps/bff/src/http/query/alarms.ts
+++ b/apps/bff/src/http/query/alarms.ts
@@ -159,8 +159,6 @@ export interface AlarmsCountResponse {
generatedAt: number;
}
-// ── GraphQL queries ──────────────────────────────────────────────────
-
/* `events` is deliberately OMITTED — demo OAP (and some storage
* backends) throw `java.io.IOException: fail to query stream` when
* events stream per-row alongside a 30+ row page. The snapshot
@@ -243,8 +241,6 @@ interface ListServicesRaw {
listServices: Array<{ name: string; normal: boolean | null }>;
}
-// ── Schemas + caps ───────────────────────────────────────────────────
-
/** Window cap for `/api/alarms` and `/api/alarms/count`. Defence-in-
* depth — the UI picker already enforces this, but a hand-crafted
* URL shouldn't pull a 24h fan-out from OAP. */
@@ -276,8 +272,6 @@ const countQuerySchema = z.object({
endTime: z.coerce.number().int().positive(),
});
-// ── Entity builder (new mode) ────────────────────────────────────────
-
/* Translate the cascade fields (`layer`, `service`, `instance`,
* `endpoint`) into the smallest precise `Entity` that the
* queryAlarms `condition.entities` filter accepts. Scope is inferred
@@ -312,8 +306,6 @@ function buildEntity(q: {
return base;
}
-// ── Row tagging ──────────────────────────────────────────────────────
-
async function tagWithLayer(
msgsRaw: AlarmMessage[],
serviceLayer: ServiceLayerCatalog,
@@ -337,13 +329,10 @@ async function tagWithLayer(
});
}
-// ── Routes ───────────────────────────────────────────────────────────
-
export function registerAlarmsQueryRoutes(app: FastifyInstance, deps: AlarmsQueryRouteDeps): void {
const auth = requireAuth(deps);
const serviceLayer = deps.serviceLayer;
- // ── GET /api/alarms ────────────────────────────────────────────────
app.get('/api/alarms', { preHandler: auth }, async (req: FastifyRequest, reply: FastifyReply) => {
const parsed = alarmsQuerySchema.safeParse(req.query);
if (!parsed.success) {
@@ -356,7 +345,6 @@ export function registerAlarmsQueryRoutes(app: FastifyInstance, deps: AlarmsQuer
}
const opts = buildOapOpts(deps.config.current, deps.fetch);
- // offset + caps are independent probes — fetch them in parallel.
const [offset, caps] = await Promise.all([
getServerOffsetMinutes(deps.config, deps.fetch),
getOapCapabilities(deps.config.current, deps.fetch),
@@ -423,7 +411,6 @@ export function registerAlarmsQueryRoutes(app: FastifyInstance, deps: AlarmsQuer
return reply.send(body);
});
- // ── GET /api/alarms/count ──────────────────────────────────────────
app.get(
'/api/alarms/count',
{ preHandler: auth },
@@ -439,7 +426,6 @@ export function registerAlarmsQueryRoutes(app: FastifyInstance, deps: AlarmsQuer
}
const opts = buildOapOpts(deps.config.current, deps.fetch);
- // offset + caps are independent probes — fetch them in parallel.
const [offset, caps] = await Promise.all([
getServerOffsetMinutes(deps.config, deps.fetch),
getOapCapabilities(deps.config.current, deps.fetch),
@@ -512,7 +498,6 @@ export function registerAlarmsQueryRoutes(app: FastifyInstance, deps: AlarmsQuer
},
);
- // ── GET /api/alarms/services?layer=X ──────────────────────────────
/* Cascading-filter helper. Returns the service roster for one OAP
* layer in alpha order so the UI populates a dropdown without
* re-implementing the listServices wire. The instance + endpoint
diff --git a/apps/bff/src/http/query/async-profile.ts b/apps/bff/src/http/query/async-profile.ts
index a2b2d5e..ae863af 100644
--- a/apps/bff/src/http/query/async-profile.ts
+++ b/apps/bff/src/http/query/async-profile.ts
@@ -110,8 +110,6 @@ function clampExecArgs(v: unknown): string | undefined {
return v.slice(0, MAX_EXEC_ARGS_LEN);
}
-// ── Async profiler queries ──────────────────────────────────────────
-
const LIST_SERVICES_FOR_RESOLVE = /* GraphQL */ `
query ListServicesForAsyncResolve($layer: String!) {
services: listServices(layer: $layer) {
@@ -170,8 +168,7 @@ const GET_ASYNC_ANALYZE = /* GraphQL */ `
}
`;
-// ── pprof queries (same shape, different OAP entry points) ──────────
-
+// pprof queries: same shape as async, different OAP entry points.
const GET_PPROF_TASK_LIST = /* GraphQL */ `
query GetPprofTaskList($request: PprofTaskListRequest!) {
pprofTaskList: queryPprofTaskList(request: $request) {
@@ -247,7 +244,6 @@ export function registerAsyncProfileRoutes(
): void {
const auth = requireAuth(deps);
- // ── Async profiler ──────────────────────────────────────────────
app.get(
'/api/layer/:key/async/tasks',
{ preHandler: auth },
@@ -351,7 +347,6 @@ export function registerAsyncProfileRoutes(
},
);
- // ── pprof (Go) ──────────────────────────────────────────────────
app.get(
'/api/layer/:key/pprof/tasks',
{ preHandler: auth },
diff --git a/apps/bff/src/http/query/dashboard.test.ts b/apps/bff/src/http/query/dashboard.test.ts
index ea1f9ac..260e0ec 100644
--- a/apps/bff/src/http/query/dashboard.test.ts
+++ b/apps/bff/src/http/query/dashboard.test.ts
@@ -16,17 +16,11 @@
*/
import { describe, it, expect } from 'vitest';
-import {
- buildFragment,
- parseSeries,
- avgOf,
- parseLabeledSeries,
- parseTopList,
- flattenTabWidgets,
- widgetSchema,
- type Window,
- type MqeResultShape,
-} from './dashboard.js';
+import { buildFragment, type MqeResultShape } from '../../logic/dashboard/mqe.js';
+import { parseSeries, avgOf, parseLabeledSeries, parseTopList } from '../../logic/dashboard/parsers.js';
+import { flattenTabWidgets } from '../../logic/dashboard/gates.js';
+import { widgetSchema } from '../../logic/dashboard/schema.js';
+import type { Window } from '../../util/window.js';
import type { DashboardWidget } from '@skywalking-horizon-ui/api-client';
const W: Window = { start: '2026-05-17 1000', end: '2026-05-17 1100', step: 'MINUTE' };
diff --git a/apps/bff/src/http/query/dashboard.ts b/apps/bff/src/http/query/dashboard.ts
index 9e1f366..4f775de 100644
--- a/apps/bff/src/http/query/dashboard.ts
+++ b/apps/bff/src/http/query/dashboard.ts
@@ -32,14 +32,12 @@
*/
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
-import { z } from 'zod';
import type {
DashboardResponse,
DashboardWidget,
DashboardWidgetResult,
FetchLike,
UITemplateClient,
- VisibleWhen,
} from '@skywalking-horizon-ui/api-client';
import type { ConfigSource } from '../../config/loader.js';
import type { SessionStore } from '../../user/sessions.js';
@@ -48,16 +46,32 @@ import { graphqlPost, buildOapOpts } from '../../client/graphql.js';
import { withColdStage } from '../../util/duration.js';
import {
defaultMinuteWindow,
- fmtForStep,
getServerOffsetMinutes,
windowFromRange,
- type TimeStep,
- type Window,
} from '../../util/window.js';
import { widgetsForScope } from '../../logic/layers/loader.js';
import { serviceLayerCatalog } from '../../logic/services/service-layer-catalog.js';
import { resolveEffectiveLayer } from '../../logic/layers/effective.js';
import { defaultWidgetsFor } from '../../logic/dashboard/defaults.js';
+import { bodySchema, MAX_REQUEST_WIDGETS } from '../../logic/dashboard/schema.js';
+import { buildFragment, type MqeResultShape } from '../../logic/dashboard/mqe.js';
+import {
+ parseSeries,
+ avgOf,
+ parseLabeledSeries,
+ parseTopList,
+ parseRecords,
+ parseTable,
+} from '../../logic/dashboard/parsers.js';
+import {
+ flattenValues,
+ mqeGatePass,
+ buildAttrMap,
+ entityGatePass,
+ vwOf,
+ isSelfGate,
+ flattenTabWidgets,
+} from '../../logic/dashboard/gates.js';
export interface DashboardRouteDeps {
config: ConfigSource;
@@ -68,164 +82,6 @@ export interface DashboardRouteDeps {
uiTemplateClient?: () => UITemplateClient;
}
-/** A leaf widget — the five queryable kinds, used both at the top level and
- * inside a tab panel. `widgetSchema` below extends it to add the `tab`
- * container (one level deep: a tab's children are leaves). */
-const leafWidgetSchema = z.object({
- id: z.string().min(1),
- title: z.string(),
- tip: z.string().optional(),
- type: z.enum(['card', 'line', 'top', 'record', 'table']),
- // Bumped from 8 to 16: JVM Memory Detail carries 11 pool metrics
- // (code cache + young/old/survivor/permgen/metaspace + z-heap +
- // compressed class space + 3 segmented codeheaps), and a few of the
- // language families approach the same range. 16 gives headroom for
- // future relabeled bundles without blowing the cap.
- expressions: z.array(z.string().min(1)).min(1).max(16),
- expressionLabels: z.array(z.string()).max(16).optional(),
- expressionUnits: z.array(z.string()).max(16).optional(),
- expressionAxes: z.array(z.number().int().min(0).max(1)).max(16).optional(),
- unit: z.string().optional(),
- tableHeaders: z.tuple([z.string(), z.string()]).optional(),
- showTableValues: z.boolean().optional(),
- span: z.number().int().min(1).max(12).optional(),
- rowSpan: z.number().int().min(1).max(64).optional(),
- // Structured visibility gate. `.catch(undefined)` makes the parse
- // TOLERANT: a legacy free-text predicate (`"<metric> has value"` /
- // `#entity.x`) left over in an OAP-stored dashboard resolves to
- // `undefined` (ungated) instead of failing the whole widget/template
- // parse. New gates are authored as the structured object.
- visibleWhen: z
- .union([
- z.object({ kind: z.literal('mqe'), expression: z.string().min(1), op: z.literal('exists') }),
- z.object({
- kind: z.literal('mqe'),
- expression: z.string().min(1),
- op: z.enum(['gt', 'lt']),
- value: z.number(),
- }),
- z.object({ kind: z.literal('entity'), attribute: z.string().min(1), op: z.literal('exists') }),
- z.object({
- kind: z.literal('entity'),
- attribute: z.string().min(1),
- op: z.literal('eq'),
- value: z.string(),
- }),
- ])
- .optional()
- .catch(undefined),
- layerScope: z.boolean().optional(),
- // Legacy x/y/w/h kept optional for back-compat.
- x: z.number().int().min(0).optional(),
- y: z.number().int().min(0).optional(),
- w: z.number().int().positive().optional(),
- h: z.number().int().positive().optional(),
-});
-
-/** Full widget schema: a leaf, plus the `tab` container. A `tab` carries no MQE
- * of its own (so `expressions` may be empty) and holds named panels of leaf
- * widgets in `tabs`. The SPA flattens to the active tab before posting; the
- * BFF also flattens (see `flattenTabWidgets`) so the pipeline only sees leaves. */
-export const widgetSchema = leafWidgetSchema
- .extend({
- type: z.enum(['card', 'line', 'top', 'record', 'table', 'tab']),
- // Relaxed to allow the empty array a `tab` container carries; the refine
- // below keeps every NON-tab leaf at ≥1 expression (an empty-MQE leaf would
- // otherwise pass here and render blank).
- expressions: z.array(z.string().min(1)).max(16),
- tabs: z
- .array(z.object({ name: z.string(), widgets: z.array(leafWidgetSchema).max(40) }))
- .max(20)
- .optional(),
- })
- .superRefine((w, ctx) => {
- if (w.type !== 'tab' && w.expressions.length === 0) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: ['expressions'],
- message: 'a non-tab widget requires at least one expression',
- });
- }
- });
-/** Shared with config/dashboard.ts (GET-config handler). */
-export const scopeSchema = z.enum([
- 'service',
- 'instance',
- 'endpoint',
- 'dependency',
- 'topology',
- 'trace',
- 'logs',
- 'traceProfiling',
- 'ebpfProfiling',
- 'asyncProfiling',
-]);
-/** Per-request queryable-widget cap (mirrors the SPA's chunk size). Enforced on
- * the body pre-expansion (zod) AND on the leaf count after tab flattening. */
-const MAX_REQUEST_WIDGETS = 40;
-const bodySchema = z.object({
- service: z.string().optional(),
- /** Selected instance name. Honored only when `scope === 'instance'`
- * (or any instance-derived scope) — the BFF flips the MQE entity to
- * `{ scope: ServiceInstance, serviceName, serviceInstanceName }` so
- * every widget on the Instance page evaluates against the chosen
- * pair instead of the parent service. */
- serviceInstance: z.string().optional(),
- /** Selected endpoint name, analogous to `serviceInstance` but for
- * the Endpoint page. Switches the entity to
- * `{ scope: Endpoint, serviceName, endpointName }`. */
- endpoint: z.string().optional(),
- // Hard cap per request — protects OAP's storage page-size cliffs
- // (CLAUDE.md warns about backend-specific thresholds). The UI is
- // responsible for chunking widget sets larger than this across
- // multiple requests; the BFF refuses oversized bodies up-front so
- // an accidentally-huge template never reaches OAP. The cap is
- // re-checked AFTER tab expansion (a container counts as 1 here but
- // flattens to many leaves) — see the handler.
- widgets: z.array(widgetSchema).max(MAX_REQUEST_WIDGETS).optional(),
- scope: scopeSchema.optional(),
- /** Global time-range, forwarded by the SPA's time picker. When all
- * three are present the BFF queries OAP at the requested precision
- * and window; otherwise it falls back to the last-hour MINUTE
- * default. `step` must match OAP's downsampling tiers and drives the
- * date-string format (verifyDateTimeString rejects a mismatch). */
- step: z.enum(['MINUTE', 'HOUR', 'DAY']).optional(),
- startMs: z.number().int().positive().optional(),
- endMs: z.number().int().positive().optional(),
-});
-
-interface MqeOwner {
- scope?: string | null;
- serviceName?: string | null;
- serviceInstanceName?: string | null;
- endpointName?: string | null;
-}
-interface MqeValueShape {
- id?: string | null;
- value?: string | null;
- /** Trace id of a RECORD_LIST sample (slow SQL / slow statements) —
- * powers the jump-to-trace icon on a `record` widget. Null on
- * non-record results. */
- traceID?: string | null;
- owner?: MqeOwner | null;
-}
-interface MqeLabelShape {
- key: string;
- value: string;
-}
-interface MqeMetadataShape {
- labels?: MqeLabelShape[] | null;
-}
-interface MqeValuesShape {
- metric?: MqeMetadataShape | null;
- values?: MqeValueShape[];
-}
-export interface MqeResultShape {
- type: string;
- error?: string | null;
- results?: MqeValuesShape[];
-}
-
const LIST_FIRST_SERVICE = /* GraphQL */ `
query FirstService($layer: String!) {
services: listServices(layer: $layer) { id name normal group }
@@ -269,328 +125,6 @@ const DEFAULT_WINDOW_MIN = 60;
function defaultWindow(offsetMinutes: number) {
return defaultMinuteWindow(offsetMinutes, DEFAULT_WINDOW_MIN);
}
-// Re-export so the existing `./dashboard.js` consumers (the test file
-// today; future fragment helpers that import Window from here) don't
-// need to know the helpers moved into the shared util.
-export { fmtForStep, type TimeStep, type Window };
-
-/** Build one aliased `execExpression` GraphQL fragment for a single
- * widget expression. The entity scope flips based on opts:
- * - `layerScope: true` → `{ scope: All }` (no service filter — GLOBAL,
- * not layer-restricted; use with care since OAP's Entity has no
- * `layer` field, so this leaks across layers if the metric is
- * shared between layers)
- * - `serviceInstanceName` set → ServiceInstance scope
- * - `endpointName` set → Endpoint scope
- * - otherwise → Service scope with the supplied serviceName
- *
- * Exported for unit testing (see dashboard.test.ts). */
-export function buildFragment(
- alias: string,
- expression: string,
- serviceName: string,
- normal: boolean,
- w: Window,
- opts: {
- layerScope?: boolean;
- serviceInstanceName?: string | null;
- endpointName?: string | null;
- /** When true, splice `coldStage: true` into the Duration literal.
- * OAP ignores it for non-BanyanDB backends, so callers can pass it
- * unconditionally when the request asked for cold-stage data. */
- coldStage?: boolean;
- } = {},
-): string {
- // We fetch metric.labels (for multi-series Line widgets — relabels()
- // returns one labeled result per percentile) and value.id /
- // owner.endpointName (for TopList widgets — top_n() returns a
- // sorted list of entities + values).
- //
- // layerScope=true skips the serviceName filter so the MQE runs
- // across the whole layer — used for cross-service rollups like the
- // "Top 20 endpoints" widget on the per-layer Service page.
- let entity: string;
- if (opts.layerScope) {
- entity = '{ scope: All }';
- } else if (opts.serviceInstanceName) {
- entity =
- `{ scope: ServiceInstance, serviceName: ${JSON.stringify(serviceName)},` +
- ` serviceInstanceName: ${JSON.stringify(opts.serviceInstanceName)},` +
- ` normal: ${normal ? 'true' : 'false'} }`;
- } else if (opts.endpointName) {
- entity =
- `{ scope: Endpoint, serviceName: ${JSON.stringify(serviceName)},` +
- ` endpointName: ${JSON.stringify(opts.endpointName)},` +
- ` normal: ${normal ? 'true' : 'false'} }`;
- } else {
- entity = `{ scope: Service, serviceName: ${JSON.stringify(serviceName)}, normal: ${normal ? 'true' : 'false'} }`;
- }
- const coldFrag = opts.coldStage ? ', coldStage: true' : '';
- return (
- `${alias}: execExpression(\n` +
- ` expression: ${JSON.stringify(expression)},\n` +
- ` entity: ${entity},\n` +
- ` duration: { start: ${JSON.stringify(w.start)}, end: ${JSON.stringify(w.end)}, step: ${w.step}${coldFrag} }\n` +
- ` ) {\n` +
- ` type error\n` +
- ` results {\n` +
- ` metric { labels { key value } }\n` +
- ` values { id value traceID owner { scope serviceName serviceInstanceName endpointName } }\n` +
- ` }\n` +
- ` }`
- );
-}
-
-export function parseSeries(r: MqeResultShape | undefined): Array<number | null> | null {
- if (!r || r.error) return null;
- const values = r.results?.[0]?.values ?? [];
- if (values.length === 0) return null;
- return values.map((v) => {
- if (v.value === null || v.value === undefined) return null;
- const n = Number(v.value);
- return Number.isFinite(n) ? n : null;
- });
-}
-export function avgOf(series: Array<number | null> | null): number | null {
- if (!series) return null;
- const xs = series.filter((v): v is number => v !== null);
- if (xs.length === 0) return null;
- return xs.reduce((a, b) => a + b, 0) / xs.length;
-}
-
-/**
- * Time-series MQE responses can carry multiple labeled results (one
- * relabel() call returns 5 results, one per percentile). Convert each
- * to a `DashboardSeries`. The label preference order:
- * - explicit `relabels(..., key='...')` from metric.labels (multi-series)
- * - fallback to the caller's expression text (single-series)
- *
- * Do NOT use `values[0].id` as a label — for time-series MQEs, OAP
- * returns the per-bucket timestamp/index as the value id, which is
- * useless as a series label.
- */
-export function parseLabeledSeries(
- r: MqeResultShape | undefined,
- fallbackLabel: string,
-): Array<{ label: string; data: Array<number | null> }> | null {
- if (!r || r.error) return null;
- const out: Array<{ label: string; data: Array<number | null> }> = [];
- for (const rs of r.results ?? []) {
- const values = rs.values ?? [];
- if (values.length === 0) continue;
- const data = values.map((v) => {
- if (v.value === null || v.value === undefined) return null;
- const n = Number(v.value);
- return Number.isFinite(n) ? n : null;
- });
- // For relabels() results OAP returns multi-result responses with
- // metric.labels populated — take the last (most-derived) label
- // value, e.g. `percentile='99'`. Single-series results have no
- // labels; fall back to the operator's expression text.
- const labels = rs.metric?.labels ?? [];
- const lbl = labels.length > 0 ? labels[labels.length - 1].value : fallbackLabel;
- out.push({ label: lbl, data });
- }
- return out.length > 0 ? out : null;
-}
-
-/**
- * Extract a sorted list from a `top_n(...)` MQE response. Names follow
- * an entity-scope priority:
- * Endpoint → "<service> · <endpoint>" or just "<endpoint>"
- * Instance → "<service> · <instance>" or just "<instance>"
- * Service → service
- * fallback → raw id
- *
- * The `<service> ·` prefix is only added when the list actually spans
- * MULTIPLE services (layer-wide top lists, where the same endpoint can
- * appear under different services and needs disambiguation). On a
- * single-service dashboard ("Top 20 APIs" under one service) every row
- * carries the same service, so the prefix is pure noise — drop it and
- * show just the endpoint / instance.
- */
-export function parseTopList(
- r: MqeResultShape | undefined,
-): Array<{ name: string; value: number | null }> | null {
- if (!r || r.error) return null;
- const values = r.results?.[0]?.values ?? [];
- if (values.length === 0) return null;
- const services = new Set<string>();
- for (const v of values) {
- if (v.owner?.serviceName) services.add(v.owner.serviceName);
- }
- const multiService = services.size > 1;
- return values.map((v) => {
- const o = v.owner;
- let name = '—';
- if (o?.endpointName) {
- name = multiService && o.serviceName ? `${o.serviceName} · ${o.endpointName}` : o.endpointName;
- } else if (o?.serviceInstanceName) {
- name = multiService && o.serviceName
- ? `${o.serviceName} · ${o.serviceInstanceName}`
- : o.serviceInstanceName;
- } else if (o?.serviceName) {
- name = o.serviceName;
- } else if (v.id) {
- name = v.id;
- }
- const num = v.value !== null && v.value !== undefined ? Number(v.value) : null;
- return { name, value: Number.isFinite(num as number) ? (num as number) : null };
- });
-}
-
-/**
- * Extract slow-SQL / slow-statement samples from a RECORD_LIST MQE
- * response (e.g. `top_n(top_n_database_statement, …)`). Each entry is one
- * sampled statement execution: `name` is the statement text (the MQE
- * value `id`), `value` the latency, and `traceId` the originating trace —
- * which the `record` widget surfaces as a jump-to-trace icon per row.
- */
-export function parseRecords(
- r: MqeResultShape | undefined,
-): Array<{ name: string; value: number | null; traceId: string | null }> | null {
- if (!r || r.error) return null;
- const values = r.results?.[0]?.values ?? [];
- if (values.length === 0) return null;
- return values.map((v) => {
- const num = v.value !== null && v.value !== undefined ? Number(v.value) : null;
- return {
- name: v.id ?? '—',
- value: Number.isFinite(num as number) ? (num as number) : null,
- traceId: v.traceID ?? null,
- };
- });
-}
-
-/**
- * Extract `table` rows from a LABELED `latest(...)` MQE response. Each
- * result is one label combination (e.g. `{phase: Running, service: x}`
- * or `{condition: Ready, node: y}`); the row name joins the label
- * VALUES (the status/phase/condition/entity dimensions) and the value
- * is the latest non-null bucket. Mirrors booster-ui's Table for
- * label-dimensioned meters that a scalar card / time-series line can't
- * represent. Rows are sorted by name for a stable render.
- */
-export function parseTable(
- r: MqeResultShape | undefined,
-): Array<{ labels: Array<{ key: string; value: string }>; value: number | null }> | null {
- if (!r || r.error) return null;
- const results = r.results ?? [];
- if (results.length === 0) return null;
- const rows = results.map((rs) => {
- const labels = (rs.metric?.labels ?? []).map((l) => ({ key: l.key, value: l.value }));
- // `latest(...)` yields one bucket, but be defensive: take the last
- // non-null value across the result's buckets.
- let value: number | null = null;
- for (const v of rs.values ?? []) {
- if (v.value === null || v.value === undefined) continue;
- const n = Number(v.value);
- if (Number.isFinite(n)) value = n;
- }
- // No labels (degenerate) → fall back to the value id as a single column.
- if (labels.length === 0 && rs.values?.[0]?.id) {
- labels.push({ key: 'name', value: rs.values[0].id as string });
- }
- return { labels, value };
- });
- // Stable order by the joined label values.
- rows.sort((a, b) =>
- a.labels.map((l) => l.value).join('·').localeCompare(b.labels.map((l) => l.value).join('·')),
- );
- return rows;
-}
-
-/* ------------------------------------------------------------------- *
- * Visibility gates (`visibleWhen`).
- *
- * `mqe` gates are existential over the WHOLE result — every labeled
- * series (relabels / histogram), every bucket — so `flattenValues`
- * collapses an MqeResultShape to its non-null numeric value set and the
- * op tests "at least one value …". `entity` gates read the selected
- * instance's attribute bag.
- * ------------------------------------------------------------------- */
-
-/** Every non-null numeric value across all labeled series + buckets. */
-function flattenValues(r: MqeResultShape | undefined): number[] {
- if (!r || r.error) return [];
- const out: number[] = [];
- for (const rs of r.results ?? []) {
- for (const v of rs.values ?? []) {
- if (v.value === null || v.value === undefined) continue;
- const n = Number(v.value);
- if (Number.isFinite(n)) out.push(n);
- }
- }
- return out;
-}
-
-function mqeGatePass(op: 'exists' | 'gt' | 'lt', value: number | undefined, vals: number[]): boolean {
- if (op === 'gt') return value !== undefined && vals.some((v) => v > value);
- if (op === 'lt') return value !== undefined && vals.some((v) => v < value);
- return vals.length > 0; // exists
-}
-
-/** Attribute lookup for the selected instance: `language` + named
- * attributes, keyed lower-case. Empty values are dropped so `exists`
- * means present-AND-non-empty (OAP reports `namespace`/`cluster` as
- * empty-string keys). */
-function buildAttrMap(
- language: string | null | undefined,
- attrs: Array<{ name: string; value: string }>,
-): Map<string, string> {
- const m = new Map<string, string>();
- if (language && language.trim()) m.set('language', language.trim());
- for (const a of attrs) {
- const v = a.value == null ? '' : String(a.value);
- if (v.trim() !== '') m.set(a.name.toLowerCase(), v);
- }
- return m;
-}
-
-/** Evaluate an entity gate. `attrs === null` means "no entity context"
- * (non-Instance scope / probe failed) → no-op (visible). */
-function entityGatePass(
- vw: Extract<VisibleWhen, { kind: 'entity' }>,
- attrs: Map<string, string> | null,
-): boolean {
- if (!attrs) return true;
- const val = attrs.get(vw.attribute.toLowerCase());
- if (vw.op === 'eq') return val !== undefined && val.toLowerCase() === vw.value.toLowerCase();
- return val !== undefined; // exists (map already excludes empties)
-}
-
-/** Normalize a widget's gate — overlay-sourced widgets may still carry a
- * legacy string; anything that isn't the structured object is no gate. */
-function vwOf(w: DashboardWidget): VisibleWhen | undefined {
- const vw = w.visibleWhen as unknown;
- return vw && typeof vw === 'object' && 'kind' in (vw as object) ? (vw as VisibleWhen) : undefined;
-}
-
-/** A `mqe` gate whose expression the widget already queries — evaluated
- * from the widget's own batch result (no extra probe, no skip). */
-function isSelfGate(w: DashboardWidget, vw: VisibleWhen): boolean {
- return vw.kind === 'mqe' && w.expressions.includes(vw.expression);
-}
-
-/** Expand `tab` containers to their leaf children so the pipeline only sees
- * queryable leaves (a tab carries no MQE). Covers the template-resolved
- * fallback + direct API callers; the SPA already flattens to the active tab.
- * Emits only the FIRST (default-active) panel — matching the lazy contract,
- * so a tab group never fans into a larger OAP request than the UI issues. */
-export function flattenTabWidgets(widgets: DashboardWidget[]): DashboardWidget[] {
- const out: DashboardWidget[] = [];
- for (const w of widgets) {
- if (w.type === 'tab') {
- const firstPanel = (w.tabs ?? [])[0];
- for (const child of firstPanel?.widgets ?? []) {
- if (child.type !== 'tab') out.push(child);
- }
- } else {
- out.push(w);
- }
- }
- return out;
-}
export function registerDashboardQueryRoute(app: FastifyInstance, deps: DashboardRouteDeps): void {
const auth = requireAuth(deps);
@@ -958,6 +492,16 @@ export function registerDashboardQueryRoute(app: FastifyInstance, deps: Dashboar
}
if (widget.type === 'card') {
+ // A colored enum card whose metric is labeled (e.g. K8s node
+ // conditions → one row per active condition) keeps the labels so
+ // the tile renders them as colored status chips; every other card
+ // collapses to the scalar average as before.
+ if (widget.format === 'enum' && widget.valueColors) {
+ const rows = parseTable(data[`w${wIdx}_e0`]);
+ if (rows && rows.some((r) => r.labels.length > 0)) {
+ return { id: widget.id, table: rows };
+ }
+ }
const first = widget.expressions.map((_, eIdx) =>
parseSeries(data[`w${wIdx}_e${eIdx}`]),
).find((s) => s !== null);
diff --git a/apps/bff/src/http/query/ebpf.ts b/apps/bff/src/http/query/ebpf.ts
index 5202842..9bec899 100644
--- a/apps/bff/src/http/query/ebpf.ts
+++ b/apps/bff/src/http/query/ebpf.ts
@@ -39,6 +39,7 @@ import type {
EBPFTaskCreationResponse,
EBPFTaskListResponse,
FetchLike,
+ NetworkProcessesResponse,
NetworkProfilingCreateRequest,
NetworkProfilingCreateResponse,
NetworkProfilingKeepAliveResponse,
@@ -309,8 +310,6 @@ async function resolveServiceId(
);
}
-// ── Process-relation metrics (network-profiling edge panel) ──────────
-
interface MqeEnv {
error?: string | null;
results?: Array<{ values?: Array<{ value: string | number | null }> }>;
@@ -359,10 +358,18 @@ function relationSeries(env: MqeEnv | undefined): Array<number | null> {
});
}
+const LIST_PROCESSES = /* GraphQL */ `
+ query listNetworkProcesses($instanceId: ID!, $duration: Duration!) {
+ listProcesses(instanceId: $instanceId, duration: $duration) {
+ id
+ name
+ }
+ }
+`;
+
export function registerEBPFRoutes(app: FastifyInstance, deps: EBPFRouteDeps): void {
const auth = requireAuth(deps);
- // ── list tasks + couldProfiling metadata ──────────────────────────
app.get(
'/api/layer/:key/ebpf/tasks',
{ preHandler: auth },
@@ -404,7 +411,6 @@ export function registerEBPFRoutes(app: FastifyInstance, deps: EBPFRouteDeps): v
},
);
- // ── create task ───────────────────────────────────────────────────
app.post(
'/api/layer/:key/ebpf/tasks',
{ preHandler: auth },
@@ -453,7 +459,6 @@ export function registerEBPFRoutes(app: FastifyInstance, deps: EBPFRouteDeps): v
},
);
- // ── per-task schedules ────────────────────────────────────────────
app.get(
'/api/ebpf/tasks/:taskId/schedules',
{ preHandler: auth },
@@ -475,7 +480,6 @@ export function registerEBPFRoutes(app: FastifyInstance, deps: EBPFRouteDeps): v
},
);
- // ── network profiling ─────────────────────────────────────────────
/** List network-profile tasks for a service. Same OAP entry-point as
* ON_CPU/OFF_CPU tasks, with target=NETWORK. OAP stores network tasks
* with trigger FIXED_TIME (EBPFProfilingMutationService sets
@@ -574,6 +578,39 @@ export function registerEBPFRoutes(app: FastifyInstance, deps: EBPFRouteDeps): v
},
);
+ /** Processes reporting on a service instance — the network task-creation
+ * modal confirms the instance has profilable processes before Create
+ * (OAP rejects a network task on an instance with none). */
+ app.get(
+ '/api/ebpf/network/processes',
+ { preHandler: auth },
+ async (req: FastifyRequest, reply: FastifyReply) => {
+ const q = req.query as { serviceInstance?: string; windowMinutes?: string };
+ const instance = (q.serviceInstance ?? '').trim();
+ const payload: NetworkProcessesResponse = { processes: [], reachable: true };
+ if (!instance) return reply.send(payload);
+ const minutes = Math.max(5, Math.min(180, Number(q.windowMinutes) || 30));
+ const endMs = Date.now();
+ const startMs = endMs - minutes * 60_000;
+ const opts = buildOapOpts(deps.config.current, deps.fetch);
+ const offset = await getServerOffsetMinutes(deps.config, deps.fetch);
+ try {
+ const data = await graphqlPost<{ listProcesses: NetworkProcessesResponse['processes'] }>(
+ opts,
+ LIST_PROCESSES,
+ {
+ instanceId: instance,
+ duration: { start: fmtMinute(startMs, offset), end: fmtMinute(endMs, offset), step: 'MINUTE' },
+ },
+ );
+ payload.processes = data.listProcesses ?? [];
+ return reply.send(payload);
+ } catch (err) {
+ return reply.send(softErr(payload, err));
+ }
+ },
+ );
+
/** Create a network-profile task on a specific service instance. */
app.post(
'/api/ebpf/network/tasks',
@@ -626,7 +663,6 @@ export function registerEBPFRoutes(app: FastifyInstance, deps: EBPFRouteDeps): v
},
);
- // ── analyze ───────────────────────────────────────────────────────
app.post(
'/api/ebpf/analyze',
{ preHandler: auth },
diff --git a/apps/bff/src/http/query/endpoint-dependency.ts b/apps/bff/src/http/query/endpoint-dependency.ts
index 6005911..d288cd1 100644
--- a/apps/bff/src/http/query/endpoint-dependency.ts
+++ b/apps/bff/src/http/query/endpoint-dependency.ts
@@ -306,7 +306,6 @@ export function registerEndpointDependencyRoute(
const durationVar = withColdStage(req, { start: window.start, end: window.end, step: window.step });
const coldStage = !!req.coldStage;
- // ── Resolve service name → id.
let serviceId = serviceArg;
let normal = true;
try {
@@ -336,7 +335,6 @@ export function registerEndpointDependencyRoute(
);
}
- // ── Resolve endpoint name → id.
let endpointId = endpointArg;
if (!/\.0_/.test(endpointArg)) {
try {
@@ -370,7 +368,6 @@ export function registerEndpointDependencyRoute(
}
}
- // ── Fetch the dependency graph.
let graph: EndpointDepResp['topology'];
try {
const data = await graphqlPost<EndpointDepResp>(opts, ENDPOINT_DEPENDENCY, {
@@ -392,11 +389,10 @@ export function registerEndpointDependencyRoute(
);
}
- // ── Per-node MQE.
const realNodes = graph.nodes.filter(
(n) => n.isReal && n.serviceName && n.name && n.name !== 'User',
);
- // ── Per-node + per-edge MQE. Build both fragment families, then fan them
+ // Per-node + per-edge MQE. Build both fragment families, then fan them
// out concurrently (disjoint OAP entities + result maps); each chunks
// internally and soft-fails per chunk, keeping the graph on a hiccup.
const nodeMetricVals = new Map<string, Record<string, number | null>>();
diff --git a/apps/bff/src/http/query/instance.ts b/apps/bff/src/http/query/instance.ts
index 113f1e6..8e68da8 100644
--- a/apps/bff/src/http/query/instance.ts
+++ b/apps/bff/src/http/query/instance.ts
@@ -120,11 +120,10 @@ export function registerInstanceRoute(app: FastifyInstance, deps: InstanceRouteD
const offset = await getServerOffsetMinutes(deps.config, deps.fetch);
const window = defaultMinuteWindow(offset, DEFAULT_WINDOW_MIN);
// OAP service-id shape: `<base64>.<digits>` (e.g.
- // `Y2hlY2tvdXQ=.1`). Anything else — including names that
- // happen to contain `.` like `mesh-svr::r3-load.sample-services`
- // — needs a `listServices` lookup. The earlier "contains `.`"
- // heuristic was too loose and broke mesh / k8s_service instance
- // queries whose service names embed dots.
+ // `Y2hlY2tvdXQ=.1`). Match this strictly, not "contains `.`":
+ // a loose substring rule mis-classifies mesh / k8s_service names
+ // that embed dots (e.g. `mesh-svr::r3-load.sample-services`) as
+ // ids — they need a `listServices` lookup instead.
let serviceId = serviceArg;
if (!/^[A-Za-z0-9+/=]+\.\d+$/.test(serviceArg)) {
try {
diff --git a/apps/bff/src/http/query/landing.ts b/apps/bff/src/http/query/landing.ts
index 0341aaf..9814976 100644
--- a/apps/bff/src/http/query/landing.ts
+++ b/apps/bff/src/http/query/landing.ts
@@ -278,7 +278,6 @@ export function registerLandingRoute(app: FastifyInstance, deps: LandingRouteDep
defaultMinuteWindow(offset, DEFAULT_WINDOW_MIN)
: defaultMinuteWindow(offset, DEFAULT_WINDOW_MIN);
- // Step 1 — service list.
let services: ListServicesRow[];
try {
const data = await graphqlPost<{ services: ListServicesRow[] }>(
@@ -336,7 +335,6 @@ export function registerLandingRoute(app: FastifyInstance, deps: LandingRouteDep
return reply.send(body);
}
- // Step 2 — resolve MQE expressions per column.
const resolved = cfg.columns.map((c) => ({
column: c,
expression: resolveMqe(c.metric, c.mqe, layerKey),
@@ -451,7 +449,6 @@ export function registerLandingRoute(app: FastifyInstance, deps: LandingRouteDep
};
});
- // Step 4 — sort + slice.
rows.sort((a, b) => {
const av = a.metrics[cfg.orderBy];
const bv = b.metrics[cfg.orderBy];
diff --git a/apps/bff/src/http/query/log.ts b/apps/bff/src/http/query/log.ts
index 9d693eb..42dbbd6 100644
--- a/apps/bff/src/http/query/log.ts
+++ b/apps/bff/src/http/query/log.ts
@@ -221,10 +221,8 @@ export async function fetchLogs(
* Resolve a service argument to an OAP service id. The arg can be
* either a name (`mesh-svr::songs.sample-services`) or an id
* (`bWVzaC1zdnI6OnNvbmdzLnNhbXBsZS1zZXJ2aWNlcw==.1`). OAP ids are
- * `<base64>.<digits>` — match strictly to avoid the previous bug
- * where a name containing `.` (e.g. `*.sample-services`) was wrongly
- * accepted as an id, leading to OAP returning empty / "service not
- * found" on the log query.
+ * `<base64>.<digits>` — match strictly, since a name containing `.`
+ * (e.g. `*.sample-services`) must not be mistaken for an id.
*/
const OAP_SERVICE_ID_RE = /^[A-Za-z0-9+/=]+\.\d+$/;
async function resolveServiceId(
diff --git a/apps/bff/src/http/query/pod-log.ts b/apps/bff/src/http/query/pod-log.ts
index 5441b7e..71cd233 100644
--- a/apps/bff/src/http/query/pod-log.ts
+++ b/apps/bff/src/http/query/pod-log.ts
@@ -108,7 +108,6 @@ function validLayerKey(k: string): boolean {
export function registerPodLogRoutes(app: FastifyInstance, deps: PodLogRouteDeps): void {
const auth = requireAuth(deps);
- // ── List a pod's containers ──────────────────────────────────────
app.get(
'/api/layer/:key/pod-logs/containers',
{ preHandler: auth },
@@ -146,7 +145,6 @@ export function registerPodLogRoutes(app: FastifyInstance, deps: PodLogRouteDeps
},
);
- // ── Tail a container's logs ──────────────────────────────────────
app.post(
'/api/layer/:key/pod-logs',
{ preHandler: auth },
diff --git a/apps/bff/src/http/query/profile.ts b/apps/bff/src/http/query/profile.ts
index 0c88789..a8c3ba7 100644
--- a/apps/bff/src/http/query/profile.ts
+++ b/apps/bff/src/http/query/profile.ts
@@ -183,7 +183,6 @@ async function resolveServiceId(
export function registerProfileRoutes(app: FastifyInstance, deps: ProfileRouteDeps): void {
const auth = requireAuth(deps);
- // ── list tasks ─────────────────────────────────────────────────────
app.get(
'/api/layer/:key/profile/tasks',
{ preHandler: auth },
@@ -213,7 +212,6 @@ export function registerProfileRoutes(app: FastifyInstance, deps: ProfileRouteDe
},
);
- // ── create task ────────────────────────────────────────────────────
app.post(
'/api/layer/:key/profile/tasks',
{ preHandler: auth },
@@ -240,7 +238,6 @@ export function registerProfileRoutes(app: FastifyInstance, deps: ProfileRouteDe
},
);
- // ── list segments for a task ──────────────────────────────────────
app.get(
'/api/profile/tasks/:taskId/segments',
{ preHandler: auth },
@@ -262,7 +259,6 @@ export function registerProfileRoutes(app: FastifyInstance, deps: ProfileRouteDe
},
);
- // ── list operation logs for a task ────────────────────────────────
app.get(
'/api/profile/tasks/:taskId/logs',
{ preHandler: auth },
@@ -284,7 +280,6 @@ export function registerProfileRoutes(app: FastifyInstance, deps: ProfileRouteDe
},
);
- // ── analyze profiled span time-ranges ─────────────────────────────
app.post(
'/api/profile/analyze',
{ preHandler: auth },
diff --git a/apps/bff/src/http/query/topology.ts b/apps/bff/src/http/query/topology.ts
index 8594d3a..c5e359b 100644
--- a/apps/bff/src/http/query/topology.ts
+++ b/apps/bff/src/http/query/topology.ts
@@ -324,7 +324,6 @@ export function registerTopologyRoute(app: FastifyInstance, deps: TopologyRouteD
const durationVar = withColdStage(req, { start: window.start, end: window.end, step: window.step });
const coldStage = !!req.coldStage;
- // ── Resolve seed service ids.
let seedIds: string[] = [];
const knownServices = new Map<string, { id: string; name: string; normal: boolean }>();
try {
@@ -380,7 +379,7 @@ export function registerTopologyRoute(app: FastifyInstance, deps: TopologyRouteD
);
}
- // ── BFS expand topology.
+ // BFS-expand the seed services out to `depth` hops.
const nodes = new Map<string, OapTopoNode>();
const calls = new Map<string, OapTopoCall>();
let frontier = seedIds.slice();
@@ -431,11 +430,6 @@ export function registerTopologyRoute(app: FastifyInstance, deps: TopologyRouteD
} satisfies TopologyResponse);
}
- // (Disconnected services are dropped a few lines below — they
- // don't belong on a topology map. The earlier "fill them in as
- // standalone nodes" pass was reverted after a closer look at
- // booster-ui's demo, which only renders connected nodes too.)
-
// ── Per-node MQE. Builds fragments off the layer's
// `topology.nodeMetrics`. Synthetic nodes (User / external) are
// skipped since OAP has no metrics for them.
diff --git a/apps/bff/src/http/query/trace.ts b/apps/bff/src/http/query/trace.ts
index c615745..42125a7 100644
--- a/apps/bff/src/http/query/trace.ts
+++ b/apps/bff/src/http/query/trace.ts
@@ -105,8 +105,6 @@ function explicitWindow(
return { start: fmtSecond(s.getTime(), offsetMinutes), end: fmtSecond(e.getTime(), offsetMinutes) };
}
-// ── Wire request shape ─────────────────────────────────────────────
-
export interface TraceListBody {
source?: TraceSource;
service?: string;
@@ -136,8 +134,6 @@ export interface TraceListBody {
previewConfig?: string;
}
-// ── Native GraphQL queries ────────────────────────────────────────
-
const LIST_SERVICES_FOR_RESOLVE = /* GraphQL */ `
query ListServicesForTrace($layer: String!) {
services: listServices(layer: $layer) {
@@ -238,12 +234,10 @@ const QUERY_TRACE_DETAIL = /* GraphQL */ `
}
`;
-// ── Helpers ────────────────────────────────────────────────────────
-
-// OAP service-id shape: `<base64>.<digits>`. Match strictly so we
-// don't mis-classify names containing `.` (e.g. `*.sample-services`)
-// as ids — the earlier "contains `.` and no whitespace" heuristic was
-// too loose and broke trace queries on mesh-layer services.
+// OAP service-id shape: `<base64>.<digits>`. Match strictly, not
+// "contains `.` and no whitespace": the loose form mis-classifies
+// mesh-layer names containing `.` (e.g. `*.sample-services`) as ids
+// and breaks their trace queries.
const OAP_SERVICE_ID_RE = /^[A-Za-z0-9+/=]+\.\d+$/;
async function resolveServiceId(
opts: GraphqlOptions,
@@ -405,8 +399,6 @@ export async function fetchZipkinList(
}
}
-// ── Routes ─────────────────────────────────────────────────────────
-
export function registerTraceRoutes(app: FastifyInstance, deps: TraceRouteDeps): void {
const auth = requireAuth(deps);
diff --git a/apps/bff/src/http/query/zipkin.ts b/apps/bff/src/http/query/zipkin.ts
index f03f287..edee784 100644
--- a/apps/bff/src/http/query/zipkin.ts
+++ b/apps/bff/src/http/query/zipkin.ts
@@ -125,7 +125,6 @@ async function zipkinFetch(
export function registerZipkinRoutes(app: FastifyInstance, deps: ZipkinRouteDeps): void {
const auth = requireAuth(deps);
- // GET /api/zipkin/services
app.get('/api/zipkin/services', { preHandler: auth }, async (_req, reply) => {
try {
const { status, body } = await zipkinFetch(deps.config.current, deps.fetch, '/api/v2/services');
@@ -137,7 +136,6 @@ export function registerZipkinRoutes(app: FastifyInstance, deps: ZipkinRouteDeps
}
});
- // GET /api/zipkin/spans?serviceName=
app.get('/api/zipkin/spans', { preHandler: auth }, async (req, reply) => {
const q = req.query as { serviceName?: string };
if (!q.serviceName) return reply.code(400).send({ error: 'missing_serviceName' });
@@ -151,7 +149,6 @@ export function registerZipkinRoutes(app: FastifyInstance, deps: ZipkinRouteDeps
}
});
- // GET /api/zipkin/remote-services?serviceName=
app.get('/api/zipkin/remote-services', { preHandler: auth }, async (req, reply) => {
const q = req.query as { serviceName?: string };
if (!q.serviceName) return reply.code(400).send({ error: 'missing_serviceName' });
@@ -168,7 +165,6 @@ export function registerZipkinRoutes(app: FastifyInstance, deps: ZipkinRouteDeps
}
});
- // GET /api/zipkin/traces?serviceName=&spanName=&minDuration=&maxDuration=&annotationQuery=&endTs=&lookback=&limit=
app.get('/api/zipkin/traces', { preHandler: auth }, async (req, reply) => {
const q = req.query as Record<string, string | undefined>;
const limit = q.limit ? Math.max(1, Math.min(200, Number(q.limit))) : 30;
@@ -215,7 +211,6 @@ export function registerZipkinRoutes(app: FastifyInstance, deps: ZipkinRouteDeps
}
});
- // GET /api/zipkin/trace/:traceId
app.get<{ Params: { traceId: string } }>(
'/api/zipkin/trace/:traceId',
{ preHandler: auth },
@@ -251,9 +246,6 @@ export function registerZipkinRoutes(app: FastifyInstance, deps: ZipkinRouteDeps
},
);
- // GET /api/zipkin/autocomplete/keys
- // GET /api/zipkin/autocomplete/values?key=X
- //
// Proxies for `/api/v2/autocompleteKeys` + `/api/v2/autocompleteValues`.
// OAP keeps a pre-configured set of "autocomplete keys" (operator
// adds to a config list) and indexes their distinct values from
@@ -289,7 +281,6 @@ export function registerZipkinRoutes(app: FastifyInstance, deps: ZipkinRouteDeps
}
});
- // GET /api/zipkin/traceMany?traceIds=t1,t2,t3
app.get('/api/zipkin/traceMany', { preHandler: auth }, async (req: FastifyRequest, reply: FastifyReply) => {
const q = req.query as { traceIds?: string };
const ids = (q.traceIds ?? '').split(',').map((s) => s.trim()).filter(Boolean);
diff --git a/apps/bff/src/logic/alarms/bundled.ts b/apps/bff/src/logic/alarms/bundled.ts
index 131923f..40a89ba 100644
--- a/apps/bff/src/logic/alarms/bundled.ts
+++ b/apps/bff/src/logic/alarms/bundled.ts
@@ -49,20 +49,14 @@ export function invalidateAlertBundleCache(): void {
}
function locateAlertBundle(): string {
- // Probe order:
- // 1. <HERE>/bundled_templates/... — bundled BFF (esbuild). After
- // `pnpm package`, dist/server.js sits next to dist/bundled_templates/,
- // so HERE = .../dist and the file is one level deeper. In the
- // container that's /app/server.js → /app/bundled_templates/. The
- // sibling layer + overview loaders already include this entry
- // first; the alert loader was missing it, which made every probe
- // collapse above WORKDIR (node:path.resolve clamps at /) and
- // print the same path three times.
- // 2. <HERE>/../../bundled_templates/... — dev (tsx). Source is at
- // apps/bff/src/logic/alarms/, bundled_templates is two levels up
- // at apps/bff/src/bundled_templates/.
- // 3. <cwd>/bundled_templates/... — operator running from a
- // relocated dist/ where neither path above works.
+ // Probe order matches the sibling layer/overview loaders. Entry 1
+ // must come first: after `pnpm package`, dist/server.js sits next to
+ // dist/bundled_templates, so HERE = dist/. Drop it and the remaining
+ // probes climb above WORKDIR — node:path.resolve clamps at `/` and
+ // every candidate collapses to the same wrong path.
+ // 1. <HERE>/bundled_templates/... — packaged dist (HERE = dist/).
+ // 2. <HERE>/../../bundled_templates/... — dev source tree (tsx).
+ // 3. <cwd>/bundled_templates/... — relocated dist/.
const candidates = [
resolve(HERE, 'bundled_templates/alert/page-setup.json'),
resolve(HERE, '../../bundled_templates/alert/page-setup.json'),
diff --git a/apps/bff/src/logic/alarms/store.ts b/apps/bff/src/logic/alarms/store.ts
index 2c9299e..df7603f 100644
--- a/apps/bff/src/logic/alarms/store.ts
+++ b/apps/bff/src/logic/alarms/store.ts
@@ -111,7 +111,6 @@ export class AlarmsStore {
overviewAlarmsLimit?: unknown;
};
- // Prefer the new shape when present.
let pinned: string[] | null = null;
if (Array.isArray(parsed.pinnedLayers)) {
pinned = parsed.pinnedLayers.filter(
diff --git a/apps/bff/src/logic/browser-errors/store.ts b/apps/bff/src/logic/browser-errors/store.ts
index 3197884..1c9ff6d 100644
--- a/apps/bff/src/logic/browser-errors/store.ts
+++ b/apps/bff/src/logic/browser-errors/store.ts
@@ -164,7 +164,7 @@ export class SourceMapStore {
if (e.origin !== 'upload') continue;
if (!victim || e.lastUsedAt < victim.lastUsedAt) victim = e;
}
- if (!victim) break; // nothing left to evict
+ if (!victim) break;
this.drop(victim.id);
}
}
@@ -345,7 +345,6 @@ export class SourceMapStore {
if (!this.entries.has(id)) return null;
const cached = this.parsed.get(id);
if (cached) {
- // refresh LRU position
this.parsed.delete(id);
this.parsed.set(id, cached);
return cached;
diff --git a/apps/bff/src/logic/dashboard/gates.ts b/apps/bff/src/logic/dashboard/gates.ts
new file mode 100644
index 0000000..8d14eee
--- /dev/null
+++ b/apps/bff/src/logic/dashboard/gates.ts
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Widget visibility gates (`visibleWhen`).
+ *
+ * `mqe` gates are existential over the WHOLE result — every labeled series
+ * (relabels / histogram), every bucket — so `flattenValues` collapses an
+ * MqeResultShape to its non-null numeric value set and the op tests "at least
+ * one value …". `entity` gates read the selected instance's attribute bag.
+ * `flattenTabWidgets` expands `tab` containers so the pipeline only sees leaves.
+ */
+
+import type { DashboardWidget, VisibleWhen } from '@skywalking-horizon-ui/api-client';
+import type { MqeResultShape } from './mqe.js';
+
+/** Every non-null numeric value across all labeled series + buckets. */
+export function flattenValues(r: MqeResultShape | undefined): number[] {
+ if (!r || r.error) return [];
+ const out: number[] = [];
+ for (const rs of r.results ?? []) {
+ for (const v of rs.values ?? []) {
+ if (v.value === null || v.value === undefined) continue;
+ const n = Number(v.value);
+ if (Number.isFinite(n)) out.push(n);
+ }
+ }
+ return out;
+}
+
+export function mqeGatePass(op: 'exists' | 'gt' | 'lt', value: number | undefined, vals: number[]): boolean {
+ if (op === 'gt') return value !== undefined && vals.some((v) => v > value);
+ if (op === 'lt') return value !== undefined && vals.some((v) => v < value);
+ return vals.length > 0; // exists
+}
+
+/** Attribute lookup for the selected instance: `language` + named
+ * attributes, keyed lower-case. Empty values are dropped so `exists`
+ * means present-AND-non-empty (OAP reports `namespace`/`cluster` as
+ * empty-string keys). */
+export function buildAttrMap(
+ language: string | null | undefined,
+ attrs: Array<{ name: string; value: string }>,
+): Map<string, string> {
+ const m = new Map<string, string>();
+ if (language && language.trim()) m.set('language', language.trim());
+ for (const a of attrs) {
+ const v = a.value == null ? '' : String(a.value);
+ if (v.trim() !== '') m.set(a.name.toLowerCase(), v);
+ }
+ return m;
+}
+
+/** Evaluate an entity gate. `attrs === null` means "no entity context"
+ * (non-Instance scope / probe failed) → no-op (visible). */
+export function entityGatePass(
+ vw: Extract<VisibleWhen, { kind: 'entity' }>,
+ attrs: Map<string, string> | null,
+): boolean {
+ if (!attrs) return true;
+ const val = attrs.get(vw.attribute.toLowerCase());
+ if (vw.op === 'eq') return val !== undefined && val.toLowerCase() === vw.value.toLowerCase();
+ return val !== undefined; // exists (map already excludes empties)
+}
+
+/** Normalize a widget's gate — overlay-sourced widgets may still carry a
+ * legacy string; anything that isn't the structured object is no gate. */
+export function vwOf(w: DashboardWidget): VisibleWhen | undefined {
+ const vw = w.visibleWhen as unknown;
+ return vw && typeof vw === 'object' && 'kind' in (vw as object) ? (vw as VisibleWhen) : undefined;
+}
+
+/** A `mqe` gate whose expression the widget already queries — evaluated
+ * from the widget's own batch result (no extra probe, no skip). */
+export function isSelfGate(w: DashboardWidget, vw: VisibleWhen): boolean {
+ return vw.kind === 'mqe' && w.expressions.includes(vw.expression);
+}
+
+/** Expand `tab` containers to their leaf children so the pipeline only sees
+ * queryable leaves (a tab carries no MQE). Covers the template-resolved
+ * fallback + direct API callers; the SPA already flattens to the active tab.
+ * Emits only the FIRST (default-active) panel — matching the lazy contract,
+ * so a tab group never fans into a larger OAP request than the UI issues. */
+export function flattenTabWidgets(widgets: DashboardWidget[]): DashboardWidget[] {
+ const out: DashboardWidget[] = [];
+ for (const w of widgets) {
+ if (w.type === 'tab') {
+ const firstPanel = (w.tabs ?? [])[0];
+ for (const child of firstPanel?.widgets ?? []) {
+ if (child.type !== 'tab') out.push(child);
+ }
+ } else {
+ out.push(w);
+ }
+ }
+ return out;
+}
diff --git a/apps/bff/src/logic/dashboard/mqe.ts b/apps/bff/src/logic/dashboard/mqe.ts
new file mode 100644
index 0000000..937d8f4
--- /dev/null
+++ b/apps/bff/src/logic/dashboard/mqe.ts
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * MQE (`execExpression`) wire-shape types + the per-widget GraphQL fragment
+ * builder shared by the dashboard query route and its parsers.
+ */
+
+import type { Window } from '../../util/window.js';
+
+interface MqeOwner {
+ scope?: string | null;
+ serviceName?: string | null;
+ serviceInstanceName?: string | null;
+ endpointName?: string | null;
+}
+interface MqeValueShape {
+ id?: string | null;
+ value?: string | null;
+ /** Trace id of a RECORD_LIST sample (slow SQL / slow statements) —
+ * powers the jump-to-trace icon on a `record` widget. Null on
+ * non-record results. */
+ traceID?: string | null;
+ owner?: MqeOwner | null;
+}
+interface MqeLabelShape {
+ key: string;
+ value: string;
+}
+interface MqeMetadataShape {
+ labels?: MqeLabelShape[] | null;
+}
+interface MqeValuesShape {
+ metric?: MqeMetadataShape | null;
+ values?: MqeValueShape[];
+}
+export interface MqeResultShape {
+ type: string;
+ error?: string | null;
+ results?: MqeValuesShape[];
+}
+
+/** Build one aliased `execExpression` GraphQL fragment for a single
+ * widget expression. The entity scope flips based on opts:
+ * - `layerScope: true` → `{ scope: All }` (no service filter — GLOBAL,
+ * not layer-restricted; use with care since OAP's Entity has no
+ * `layer` field, so this leaks across layers if the metric is
+ * shared between layers)
+ * - `serviceInstanceName` set → ServiceInstance scope
+ * - `endpointName` set → Endpoint scope
+ * - otherwise → Service scope with the supplied serviceName
+ *
+ * Exported for unit testing (see dashboard.test.ts). */
+export function buildFragment(
+ alias: string,
+ expression: string,
+ serviceName: string,
+ normal: boolean,
+ w: Window,
+ opts: {
+ layerScope?: boolean;
+ serviceInstanceName?: string | null;
+ endpointName?: string | null;
+ /** When true, splice `coldStage: true` into the Duration literal.
+ * OAP ignores it for non-BanyanDB backends, so callers can pass it
+ * unconditionally when the request asked for cold-stage data. */
+ coldStage?: boolean;
+ } = {},
+): string {
+ // The selection set fetches metric.labels (multi-series Line widgets —
+ // relabels() returns one labeled result per percentile) and value.id /
+ // owner.endpointName (TopList widgets — top_n() returns a sorted list of
+ // entities + values).
+ let entity: string;
+ if (opts.layerScope) {
+ entity = '{ scope: All }';
+ } else if (opts.serviceInstanceName) {
+ entity =
+ `{ scope: ServiceInstance, serviceName: ${JSON.stringify(serviceName)},` +
+ ` serviceInstanceName: ${JSON.stringify(opts.serviceInstanceName)},` +
+ ` normal: ${normal ? 'true' : 'false'} }`;
+ } else if (opts.endpointName) {
+ entity =
+ `{ scope: Endpoint, serviceName: ${JSON.stringify(serviceName)},` +
+ ` endpointName: ${JSON.stringify(opts.endpointName)},` +
+ ` normal: ${normal ? 'true' : 'false'} }`;
+ } else {
+ entity = `{ scope: Service, serviceName: ${JSON.stringify(serviceName)}, normal: ${normal ? 'true' : 'false'} }`;
+ }
+ const coldFrag = opts.coldStage ? ', coldStage: true' : '';
+ return (
+ `${alias}: execExpression(\n` +
+ ` expression: ${JSON.stringify(expression)},\n` +
+ ` entity: ${entity},\n` +
+ ` duration: { start: ${JSON.stringify(w.start)}, end: ${JSON.stringify(w.end)}, step: ${w.step}${coldFrag} }\n` +
+ ` ) {\n` +
+ ` type error\n` +
+ ` results {\n` +
+ ` metric { labels { key value } }\n` +
+ ` values { id value traceID owner { scope serviceName serviceInstanceName endpointName } }\n` +
+ ` }\n` +
+ ` }`
+ );
+}
diff --git a/apps/bff/src/logic/dashboard/parsers.ts b/apps/bff/src/logic/dashboard/parsers.ts
new file mode 100644
index 0000000..14d432c
--- /dev/null
+++ b/apps/bff/src/logic/dashboard/parsers.ts
@@ -0,0 +1,181 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Pure parsers that turn an `execExpression` (MQE) result into each widget
+ * type's render shape. Stateless and exported for unit testing.
+ */
+
+import type { MqeResultShape } from './mqe.js';
+
+export function parseSeries(r: MqeResultShape | undefined): Array<number | null> | null {
+ if (!r || r.error) return null;
+ const values = r.results?.[0]?.values ?? [];
+ if (values.length === 0) return null;
+ return values.map((v) => {
+ if (v.value === null || v.value === undefined) return null;
+ const n = Number(v.value);
+ return Number.isFinite(n) ? n : null;
+ });
+}
+export function avgOf(series: Array<number | null> | null): number | null {
+ if (!series) return null;
+ const xs = series.filter((v): v is number => v !== null);
+ if (xs.length === 0) return null;
+ return xs.reduce((a, b) => a + b, 0) / xs.length;
+}
+
+/**
+ * Time-series MQE responses can carry multiple labeled results (one
+ * relabel() call returns 5 results, one per percentile). Convert each
+ * to a `DashboardSeries`. The label preference order:
+ * - explicit `relabels(..., key='...')` from metric.labels (multi-series)
+ * - fallback to the caller's expression text (single-series)
+ *
+ * Do NOT use `values[0].id` as a label — for time-series MQEs, OAP
+ * returns the per-bucket timestamp/index as the value id, which is
+ * useless as a series label.
+ */
+export function parseLabeledSeries(
+ r: MqeResultShape | undefined,
+ fallbackLabel: string,
+): Array<{ label: string; data: Array<number | null> }> | null {
+ if (!r || r.error) return null;
+ const out: Array<{ label: string; data: Array<number | null> }> = [];
+ for (const rs of r.results ?? []) {
+ const values = rs.values ?? [];
+ if (values.length === 0) continue;
+ const data = values.map((v) => {
+ if (v.value === null || v.value === undefined) return null;
+ const n = Number(v.value);
+ return Number.isFinite(n) ? n : null;
+ });
+ // For relabels() results OAP returns multi-result responses with
+ // metric.labels populated — take the last (most-derived) label
+ // value, e.g. `percentile='99'`. Single-series results have no
+ // labels; fall back to the operator's expression text.
+ const labels = rs.metric?.labels ?? [];
+ const lbl = labels.length > 0 ? labels[labels.length - 1].value : fallbackLabel;
+ out.push({ label: lbl, data });
+ }
+ return out.length > 0 ? out : null;
+}
+
+/**
+ * Extract a sorted list from a `top_n(...)` MQE response. Names follow
+ * an entity-scope priority:
+ * Endpoint → "<service> · <endpoint>" or just "<endpoint>"
+ * Instance → "<service> · <instance>" or just "<instance>"
+ * Service → service
+ * fallback → raw id
+ *
+ * The `<service> ·` prefix is only added when the list actually spans
+ * MULTIPLE services (layer-wide top lists, where the same endpoint can
+ * appear under different services and needs disambiguation). On a
+ * single-service dashboard ("Top 20 APIs" under one service) every row
+ * carries the same service, so the prefix is pure noise — drop it and
+ * show just the endpoint / instance.
+ */
+export function parseTopList(
+ r: MqeResultShape | undefined,
+): Array<{ name: string; value: number | null }> | null {
+ if (!r || r.error) return null;
+ const values = r.results?.[0]?.values ?? [];
+ if (values.length === 0) return null;
+ const services = new Set<string>();
+ for (const v of values) {
+ if (v.owner?.serviceName) services.add(v.owner.serviceName);
+ }
+ const multiService = services.size > 1;
+ return values.map((v) => {
+ const o = v.owner;
+ let name = '—';
+ if (o?.endpointName) {
+ name = multiService && o.serviceName ? `${o.serviceName} · ${o.endpointName}` : o.endpointName;
+ } else if (o?.serviceInstanceName) {
+ name = multiService && o.serviceName
+ ? `${o.serviceName} · ${o.serviceInstanceName}`
+ : o.serviceInstanceName;
+ } else if (o?.serviceName) {
+ name = o.serviceName;
+ } else if (v.id) {
+ name = v.id;
+ }
+ const num = v.value !== null && v.value !== undefined ? Number(v.value) : null;
+ return { name, value: Number.isFinite(num as number) ? (num as number) : null };
+ });
+}
+
+/**
+ * Extract slow-SQL / slow-statement samples from a RECORD_LIST MQE
+ * response (e.g. `top_n(top_n_database_statement, …)`). Each entry is one
+ * sampled statement execution: `name` is the statement text (the MQE
+ * value `id`), `value` the latency, and `traceId` the originating trace —
+ * which the `record` widget surfaces as a jump-to-trace icon per row.
+ */
+export function parseRecords(
+ r: MqeResultShape | undefined,
+): Array<{ name: string; value: number | null; traceId: string | null }> | null {
+ if (!r || r.error) return null;
+ const values = r.results?.[0]?.values ?? [];
+ if (values.length === 0) return null;
+ return values.map((v) => {
+ const num = v.value !== null && v.value !== undefined ? Number(v.value) : null;
+ return {
+ name: v.id ?? '—',
+ value: Number.isFinite(num as number) ? (num as number) : null,
+ traceId: v.traceID ?? null,
+ };
+ });
+}
+
+/**
+ * Extract `table` rows from a LABELED `latest(...)` MQE response. Each
+ * result is one label combination (e.g. `{phase: Running, service: x}`
+ * or `{condition: Ready, node: y}`); the row name joins the label
+ * VALUES (the status/phase/condition/entity dimensions) and the value
+ * is the latest non-null bucket. Mirrors booster-ui's Table for
+ * label-dimensioned meters that a scalar card / time-series line can't
+ * represent. Rows are sorted by name for a stable render.
+ */
+export function parseTable(
+ r: MqeResultShape | undefined,
+): Array<{ labels: Array<{ key: string; value: string }>; value: number | null }> | null {
+ if (!r || r.error) return null;
+ const results = r.results ?? [];
+ if (results.length === 0) return null;
+ const rows = results.map((rs) => {
+ const labels = (rs.metric?.labels ?? []).map((l) => ({ key: l.key, value: l.value }));
+ // `latest(...)` yields one bucket, but be defensive: take the last
+ // non-null value across the result's buckets.
+ let value: number | null = null;
+ for (const v of rs.values ?? []) {
+ if (v.value === null || v.value === undefined) continue;
+ const n = Number(v.value);
+ if (Number.isFinite(n)) value = n;
+ }
+ // No labels (degenerate) → fall back to the value id as a single column.
+ if (labels.length === 0 && rs.values?.[0]?.id) {
+ labels.push({ key: 'name', value: rs.values[0].id as string });
+ }
+ return { labels, value };
+ });
+ rows.sort((a, b) =>
+ a.labels.map((l) => l.value).join('·').localeCompare(b.labels.map((l) => l.value).join('·')),
+ );
+ return rows;
+}
diff --git a/apps/bff/src/logic/dashboard/schema.ts b/apps/bff/src/logic/dashboard/schema.ts
new file mode 100644
index 0000000..b607004
--- /dev/null
+++ b/apps/bff/src/logic/dashboard/schema.ts
@@ -0,0 +1,157 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Request-body + widget validation schemas for the dashboard query route.
+ * `scopeSchema` is also consumed by the GET-config handler (config/dashboard.ts).
+ */
+
+import { z } from 'zod';
+
+/** A leaf widget — the five queryable kinds, used both at the top level and
+ * inside a tab panel. `widgetSchema` below extends it to add the `tab`
+ * container (one level deep: a tab's children are leaves). */
+const leafWidgetSchema = z.object({
+ id: z.string().min(1),
+ title: z.string(),
+ tip: z.string().optional(),
+ type: z.enum(['card', 'line', 'top', 'record', 'table']),
+ // Cap is 16: JVM Memory Detail carries 11 pool metrics (code cache +
+ // young/old/survivor/permgen/metaspace + z-heap + compressed class space
+ // + 3 segmented codeheaps), and a few language families approach the same
+ // range; 16 leaves headroom for future relabeled bundles.
+ expressions: z.array(z.string().min(1)).min(1).max(16),
+ expressionLabels: z.array(z.string()).max(16).optional(),
+ expressionUnits: z.array(z.string()).max(16).optional(),
+ expressionAxes: z.array(z.number().int().min(0).max(1)).max(16).optional(),
+ unit: z.string().optional(),
+ tableHeaders: z.tuple([z.string(), z.string()]).optional(),
+ showTableValues: z.boolean().optional(),
+ span: z.number().int().min(1).max(12).optional(),
+ rowSpan: z.number().int().min(1).max(64).optional(),
+ // Card value formatting + enum maps. The resolver gates colored status
+ // chips on format:'enum' + valueColors, so both must survive validation.
+ format: z.enum(['int', 'decimal', 'compact', 'duration', 'enum']).optional(),
+ valueMap: z.record(z.string()).optional(),
+ valueColors: z.record(z.string()).optional(),
+ labelTopN: z.number().int().min(1).max(50).optional(),
+ // Structured visibility gate. `.catch(undefined)` makes the parse
+ // TOLERANT: a legacy free-text predicate (`"<metric> has value"` /
+ // `#entity.x`) left over in an OAP-stored dashboard resolves to
+ // `undefined` (ungated) instead of failing the whole widget/template
+ // parse. New gates are authored as the structured object.
+ visibleWhen: z
+ .union([
+ z.object({ kind: z.literal('mqe'), expression: z.string().min(1), op: z.literal('exists') }),
+ z.object({
+ kind: z.literal('mqe'),
+ expression: z.string().min(1),
+ op: z.enum(['gt', 'lt']),
+ value: z.number(),
+ }),
+ z.object({ kind: z.literal('entity'), attribute: z.string().min(1), op: z.literal('exists') }),
+ z.object({
+ kind: z.literal('entity'),
+ attribute: z.string().min(1),
+ op: z.literal('eq'),
+ value: z.string(),
+ }),
+ ])
+ .optional()
+ .catch(undefined),
+ layerScope: z.boolean().optional(),
+ // Legacy x/y/w/h kept optional for back-compat.
+ x: z.number().int().min(0).optional(),
+ y: z.number().int().min(0).optional(),
+ w: z.number().int().positive().optional(),
+ h: z.number().int().positive().optional(),
+});
+
+/** Full widget schema: a leaf, plus the `tab` container. A `tab` carries no MQE
+ * of its own (so `expressions` may be empty) and holds named panels of leaf
+ * widgets in `tabs`. The SPA flattens to the active tab before posting; the
+ * BFF also flattens (see `flattenTabWidgets`) so the pipeline only sees leaves. */
+export const widgetSchema = leafWidgetSchema
+ .extend({
+ type: z.enum(['card', 'line', 'top', 'record', 'table', 'tab']),
+ // Relaxed to allow the empty array a `tab` container carries; the refine
+ // below keeps every NON-tab leaf at ≥1 expression (an empty-MQE leaf would
+ // otherwise pass here and render blank).
+ expressions: z.array(z.string().min(1)).max(16),
+ tabs: z
+ .array(z.object({ name: z.string(), widgets: z.array(leafWidgetSchema).max(40) }))
+ .max(20)
+ .optional(),
+ })
+ .superRefine((w, ctx) => {
+ if (w.type !== 'tab' && w.expressions.length === 0) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['expressions'],
+ message: 'a non-tab widget requires at least one expression',
+ });
+ }
+ });
+
+/** Shared with config/dashboard.ts (GET-config handler). */
+export const scopeSchema = z.enum([
+ 'service',
+ 'instance',
+ 'endpoint',
+ 'dependency',
+ 'topology',
+ 'trace',
+ 'logs',
+ 'traceProfiling',
+ 'ebpfProfiling',
+ 'asyncProfiling',
+]);
+
+/** Per-request queryable-widget cap (mirrors the SPA's chunk size). Enforced on
+ * the body pre-expansion (zod) AND on the leaf count after tab flattening. */
+export const MAX_REQUEST_WIDGETS = 40;
+
+export const bodySchema = z.object({
+ service: z.string().optional(),
+ /** Selected instance name. Honored only when `scope === 'instance'`
+ * (or any instance-derived scope) — the BFF flips the MQE entity to
+ * `{ scope: ServiceInstance, serviceName, serviceInstanceName }` so
+ * every widget on the Instance page evaluates against the chosen
+ * pair instead of the parent service. */
+ serviceInstance: z.string().optional(),
+ /** Selected endpoint name, analogous to `serviceInstance` but for
+ * the Endpoint page. Switches the entity to
+ * `{ scope: Endpoint, serviceName, endpointName }`. */
+ endpoint: z.string().optional(),
+ // Hard cap per request — protects OAP's storage page-size cliffs
+ // (CLAUDE.md warns about backend-specific thresholds). The UI is
+ // responsible for chunking widget sets larger than this across
+ // multiple requests; the BFF refuses oversized bodies up-front so
+ // an accidentally-huge template never reaches OAP. The cap is
+ // re-checked AFTER tab expansion (a container counts as 1 here but
+ // flattens to many leaves) — see the handler.
+ widgets: z.array(widgetSchema).max(MAX_REQUEST_WIDGETS).optional(),
+ scope: scopeSchema.optional(),
+ /** Global time-range, forwarded by the SPA's time picker. When all
+ * three are present the BFF queries OAP at the requested precision
+ * and window; otherwise it falls back to the last-hour MINUTE
+ * default. `step` must match OAP's downsampling tiers and drives the
+ * date-string format (verifyDateTimeString rejects a mismatch). */
+ step: z.enum(['MINUTE', 'HOUR', 'DAY']).optional(),
+ startMs: z.number().int().positive().optional(),
+ endMs: z.number().int().positive().optional(),
+});
diff --git a/apps/bff/src/logic/inspect/attribution.ts b/apps/bff/src/logic/inspect/attribution.ts
index c32c6c2..1100cb6 100644
--- a/apps/bff/src/logic/inspect/attribution.ts
+++ b/apps/bff/src/logic/inspect/attribution.ts
@@ -170,7 +170,6 @@ async function buildIndex(deps: AttributionDeps): Promise<AttributionIndex> {
),
]);
- // OAL: fetch every file's content and extract LHS metric names.
// Per-file getFileContent errors are tolerated.
const oalContents = await Promise.all(
filesEnvSafe.files.map(async (name) => {
@@ -213,8 +212,8 @@ async function buildIndex(deps: AttributionDeps): Promise<AttributionIndex> {
const malContents = [...malRuntimeContents, ...malBundledContents];
- // Build the index. Detect conflicts (one metric claimed by multiple
- // files) so the SPA can surface them.
+ // Detect conflicts (one metric claimed by multiple files) so the SPA
+ // can surface them.
const byMetric = new Map<string, MetricAttribution>();
const claims = new Map<string, { source: AttributionSource; file: string }[]>();
diff --git a/apps/bff/src/logic/inspect/parser-oal.ts b/apps/bff/src/logic/inspect/parser-oal.ts
index ef72e02..cd26aef 100644
--- a/apps/bff/src/logic/inspect/parser-oal.ts
+++ b/apps/bff/src/logic/inspect/parser-oal.ts
@@ -32,9 +32,7 @@ const METRIC_NAME_RE = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/;
/** Strip C-style line and block comments from a source string. */
function stripComments(src: string): string {
- // Block comments first — non-greedy, multiline.
const noBlock = src.replace(/\/\*[\s\S]*?\*\//g, '');
- // Line comments next.
return noBlock.replace(/\/\/[^\n]*/g, '');
}
diff --git a/apps/bff/src/logic/layers/loader.ts b/apps/bff/src/logic/layers/loader.ts
index e7652f8..8d6d8fd 100644
--- a/apps/bff/src/logic/layers/loader.ts
+++ b/apps/bff/src/logic/layers/loader.ts
@@ -404,7 +404,7 @@ function locateConfigDir(): string {
readdirSync(dir);
return dir;
} catch {
- /* try next */
+ // try next
}
}
// Last-resort default — first candidate. The first readdir of an
diff --git a/apps/bff/src/logic/oap/hierarchy.ts b/apps/bff/src/logic/oap/hierarchy.ts
index e33530b..8c301c4 100644
--- a/apps/bff/src/logic/oap/hierarchy.ts
+++ b/apps/bff/src/logic/oap/hierarchy.ts
@@ -165,7 +165,6 @@ function groupPeers(
}
}
- // Inject self under its own layer.
ensure(focusLayer).set(serviceId, {
id: serviceId,
name: selfName ?? serviceId,
diff --git a/apps/bff/src/logic/templates/global-defaults-bundled.ts b/apps/bff/src/logic/templates/global-defaults-bundled.ts
index 384747d..c2ab2df 100644
--- a/apps/bff/src/logic/templates/global-defaults-bundled.ts
+++ b/apps/bff/src/logic/templates/global-defaults-bundled.ts
@@ -69,14 +69,9 @@ export function invalidateGlobalDefaultsBundledCache(): void {
function locate(rel: string): string {
// Same probe order as the alert + layer + overview loaders:
- // 1. <HERE>/bundled_templates/... — bundled BFF (esbuild rolls
- // this loader into dist/server.js; HERE = .../dist and the
- // bundled_templates folder sits as a sibling). In the container
- // this resolves to /app/bundled_templates/.
- // 2. <HERE>/../../bundled_templates/... — dev (tsx). Source is at
- // apps/bff/src/logic/templates/, bundled_templates is two levels
- // up at apps/bff/src/bundled_templates/.
- // 3. <cwd>/bundled_templates/... — operator-relocated dist/.
+ // 1. <HERE>/bundled_templates/... — packaged dist (HERE = dist/).
+ // 2. <HERE>/../../bundled_templates/... — dev source tree (tsx).
+ // 3. <cwd>/bundled_templates/... — relocated dist/.
const candidates = [
resolve(HERE, `bundled_templates/${rel}`),
resolve(HERE, `../../bundled_templates/${rel}`),
diff --git a/apps/bff/src/rbac/route-policy.ts b/apps/bff/src/rbac/route-policy.ts
index 257a74b..0327871 100644
--- a/apps/bff/src/rbac/route-policy.ts
+++ b/apps/bff/src/rbac/route-policy.ts
@@ -155,6 +155,7 @@ export const ROUTE_POLICY: Record<string, RoutePolicy> = {
'GET /api/layer/:key/ebpf/network/tasks': 'profile:read',
'GET /api/ebpf/network/tasks': 'profile:read',
'GET /api/ebpf/network/topology': 'profile:read',
+ 'GET /api/ebpf/network/processes': 'profile:read',
'POST /api/layer/:key/ebpf/network/process-relation-metrics': 'profile:read',
'GET /api/overview/dashboards': 'overview:read',
diff --git a/apps/bff/src/rbac/verbs.ts b/apps/bff/src/rbac/verbs.ts
index 43ce4a8..6661d87 100644
--- a/apps/bff/src/rbac/verbs.ts
+++ b/apps/bff/src/rbac/verbs.ts
@@ -33,7 +33,6 @@ export const VERBS = {
profileRead: 'profile:read',
infra3dRead: 'infra-3d:read',
- // Operate writes
ruleRead: 'rule:read',
ruleWrite: 'rule:write',
ruleWriteStructural: 'rule:write:structural',
@@ -64,7 +63,6 @@ export const VERBS = {
ttlRead: 'ttl:read',
configRead: 'config:read',
- // Admin surface
userRead: 'user:read',
userWrite: 'user:write',
roleRead: 'role:read',
diff --git a/apps/bff/src/util/dns-fanout.ts b/apps/bff/src/util/dns-fanout.ts
index 4456e81..4669c67 100644
--- a/apps/bff/src/util/dns-fanout.ts
+++ b/apps/bff/src/util/dns-fanout.ts
@@ -19,8 +19,7 @@
* DNS-resolve a hostname-based URL into one URL per resolved IP, so the
* caller can fan out per-node requests against a single configured URL.
*
- * Replaces the previous "list every admin URL in horizon.yaml" approach
- * for the per-node features (live-debug status). The user configures
+ * Used by the per-node features (live-debug status): the user configures
* one URL pointing at a DNS name (or k8s Service / headless Service);
* this helper turns it into N URLs the BFF can probe individually.
*
diff --git a/apps/bff/src/util/window.ts b/apps/bff/src/util/window.ts
index dfd9ae1..39313cf 100644
--- a/apps/bff/src/util/window.ts
+++ b/apps/bff/src/util/window.ts
@@ -55,8 +55,7 @@ function pad(n: number): string {
/** Shift an epoch-ms into the OAP server's local wall-clock by adding the
* offset, then read the UTC fields off the shifted Date — which are now
- * the OAP-local components. This is the same trick as `alarms.ts`'s
- * original `fmtSecond`; it works because `Date` is an absolute instant
+ * the OAP-local components. Works because `Date` is an absolute instant
* and `getUTC*` doesn't apply the BFF process's TZ. */
function shifted(epochMs: number, offsetMinutes: number): Date {
return new Date(epochMs + offsetMinutes * 60_000);
@@ -128,8 +127,6 @@ export function windowFromRange<S extends TimeStep>(
};
}
-// ── Server timezone discovery ─────────────────────────────────────────
-
interface TzCacheEntry {
offsetMinutes: number;
fetchedAt: number;
@@ -152,10 +149,8 @@ const TIME_INFO_QUERY = /* GraphQL */ `
/** Look up the OAP server's UTC offset in minutes. Cached 60s.
*
* Returns 0 (UTC fallback) if the probe fails — same behavior as
- * booster-ui, and matches the fallback alarms.ts has carried since
- * the original shared-offset implementation. The 60s TTL bounds how
- * long a misconfigured BFF would keep sending bad-TZ strings after
- * the operator fixes their OAP. */
+ * booster-ui. The 60s TTL bounds how long a misconfigured BFF would
+ * keep sending bad-TZ strings after the operator fixes their OAP. */
export async function getServerOffsetMinutes(
config: ConfigSource,
fetchImpl?: FetchLike,
diff --git a/apps/ui/eslint.config.mjs b/apps/ui/eslint.config.mjs
index 8dda499..d8b006d 100644
Binary files a/apps/ui/eslint.config.mjs and b/apps/ui/eslint.config.mjs differ
diff --git a/apps/ui/src/api/client.ts b/apps/ui/src/api/client.ts
index aff6ab5..f17c912 100644
--- a/apps/ui/src/api/client.ts
+++ b/apps/ui/src/api/client.ts
@@ -221,6 +221,8 @@ export type {
ProcessRelationEndpointRef,
ProcessRelationMetric,
ProcessRelationMetricsResponse,
+ NetworkProcess,
+ NetworkProcessesResponse,
NetworkProfilingSampling,
NetworkProfilingCreateRequest,
NetworkProfilingCreateResponse,
diff --git a/apps/ui/src/api/scopes/layer-template.ts b/apps/ui/src/api/scopes/layer-template.ts
index 20f41fb..d94d879 100644
--- a/apps/ui/src/api/scopes/layer-template.ts
+++ b/apps/ui/src/api/scopes/layer-template.ts
@@ -28,7 +28,4 @@ export class LayerTemplatesApi {
'/api/admin/layer-templates',
);
}
-
- // save() removed — LayerDashboardsAdmin now saves via
- // `bff.templateSync.save('horizon.layer.<KEY>', content)`.
}
diff --git a/apps/ui/src/api/scopes/network-profile.ts b/apps/ui/src/api/scopes/network-profile.ts
index 4db25e5..1944491 100644
--- a/apps/ui/src/api/scopes/network-profile.ts
+++ b/apps/ui/src/api/scopes/network-profile.ts
@@ -17,6 +17,7 @@
import type {
EBPFTaskListResponse,
+ NetworkProcessesResponse,
NetworkProfilingCreateRequest,
NetworkProfilingCreateResponse,
NetworkProfilingKeepAliveResponse,
@@ -65,6 +66,16 @@ export class NetworkProfileApi {
);
}
+ /** Rover-monitored processes on an instance — the create modal confirms
+ * the instance has profilable processes before Create. */
+ processes(serviceInstance: string, windowMinutes = 30): Promise<NetworkProcessesResponse> {
+ const qs = new URLSearchParams({ serviceInstance, windowMinutes: String(windowMinutes) });
+ return this.bff.request<NetworkProcessesResponse>(
+ 'GET',
+ `/api/ebpf/network/processes?${qs.toString()}`,
+ );
+ }
+
create(body: NetworkProfilingCreateRequest): Promise<NetworkProfilingCreateResponse> {
return this.bff.request<NetworkProfilingCreateResponse>(
'POST',
diff --git a/apps/ui/src/api/scopes/overview.ts b/apps/ui/src/api/scopes/overview.ts
index 94ec685..560c720 100644
--- a/apps/ui/src/api/scopes/overview.ts
+++ b/apps/ui/src/api/scopes/overview.ts
@@ -64,8 +64,6 @@ export class OverviewApi {
`/api/admin/overview-templates/${encodeURIComponent(id)}`,
);
}
- // adminSave removed — OverviewTemplatesAdmin now saves via
- // `bff.templateSync.save('horizon.overview.<id>', content)`.
adminCreate(body: OverviewDashboard): Promise<{ ok: true; id: string }> {
return this.bff.request<{ ok: true; id: string }>(
'POST',
diff --git a/apps/ui/src/components/charts/AlarmsTimeline.vue b/apps/ui/src/components/charts/AlarmsTimeline.vue
index c4457aa..62f347c 100644
--- a/apps/ui/src/components/charts/AlarmsTimeline.vue
+++ b/apps/ui/src/components/charts/AlarmsTimeline.vue
@@ -38,6 +38,7 @@ import {
BrushComponent,
GridComponent,
MarkLineComponent,
+ ToolboxComponent,
TooltipComponent,
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
@@ -50,6 +51,7 @@ echarts.use([
BrushComponent,
GridComponent,
MarkLineComponent,
+ ToolboxComponent,
TooltipComponent,
CanvasRenderer,
]);
@@ -161,7 +163,7 @@ function buildOption(): echarts.EChartsCoreOption {
xAxisIndex: 0,
brushType: 'lineX',
brushMode: 'single',
- brushStyle: { color: 'rgba(249,115,22,0.18)', borderColor: 'rgba(249,115,22,0.6)' },
+ brushStyle: { color: 'rgba(226,232,240,0.10)', borderColor: 'rgba(226,232,240,0.7)' },
transformable: false,
throttleType: 'debounce',
throttleDelay: 200,
@@ -359,27 +361,49 @@ watch(
{ deep: true },
);
-/* Parent-driven brush clear: when the operator hits the "clear
- * selection" button in the list header, the parent sets its
- * `selectedRange` ref to null. Mirror that into the chart by
- * wiping the brush rectangle. We only act on the null transition —
- * a non-null selection on this side is either echoed from a drag we
- * just did (no-op needed) or from a click on a flag (no rectangle
- * needed; the row list narrowing is the visual feedback). */
-watch(
- () => props.selectedRange,
- (next) => {
- if (next === null || next === undefined) clearBrush();
- },
-);
+/** Draw the orange selection band for a range (or wipe it when null).
+ * Keeps the chart's rectangle in sync with the parent's `selectedRange`
+ * whatever the source — a drag (snaps to the whole-minute range), a flag
+ * click (a single-minute band, so the operator sees which slice is
+ * active, not just the narrowed list), or the parent's clear button. */
+function drawBrush(range: { startTime: number; endTime: number } | null | undefined): void {
+ if (!chart) return;
+ if (range === null || range === undefined) {
+ clearBrush();
+ return;
+ }
+ chart.dispatchAction({
+ type: 'brush',
+ areas: [{ brushType: 'lineX', xAxisIndex: 0, coordRange: [range.startTime, range.endTime] }],
+ });
+}
+watch(() => props.selectedRange, (next) => drawBrush(next));
</script>
<template>
- <div ref="container" class="alarms-timeline" :style="{ height: `${height ?? 110}px` }" />
+ <div class="alarms-timeline-wrap">
+ <div ref="container" class="alarms-timeline" :style="{ height: `${height ?? 110}px` }" />
+ <!-- Legend — the stack is firing (red) on the bottom, recovered (green)
+ on top; without this the colored areas / pins read ambiguously. -->
+ <div class="atl-legend">
+ <span class="atl-leg"><i class="atl-swatch firing" /> firing</span>
+ <span class="atl-leg"><i class="atl-swatch recovered" /> recovered</span>
+ </div>
+ </div>
</template>
<style scoped>
-.alarms-timeline {
- width: 100%;
+.alarms-timeline-wrap { width: 100%; }
+.alarms-timeline { width: 100%; }
+.atl-legend {
+ display: flex;
+ gap: 16px;
+ padding: 2px 4px 0;
+ font-size: 10.5px;
+ color: var(--sw-fg-3);
}
+.atl-leg { display: inline-flex; align-items: center; gap: 5px; }
+.atl-swatch { width: 9px; height: 9px; border-radius: 2px; display: inline-block; }
+.atl-swatch.firing { background: #ef4444; }
+.atl-swatch.recovered { background: #22c55e; }
</style>
diff --git a/apps/ui/src/components/charts/TopList.vue b/apps/ui/src/components/charts/TopList.vue
index a6265c8..e147c40 100644
--- a/apps/ui/src/components/charts/TopList.vue
+++ b/apps/ui/src/components/charts/TopList.vue
@@ -68,7 +68,6 @@ const effectiveGroups = computed<TopGroup[]>(() => {
});
const activeIdx = ref(0);
watch(effectiveGroups, (g) => {
- // Reset to first tab when the group set changes shape.
if (activeIdx.value >= g.length) activeIdx.value = 0;
});
const activeGroup = computed(() => effectiveGroups.value[activeIdx.value] ?? null);
@@ -350,7 +349,6 @@ const tipStyle = computed(() => {
pointer-events: none;
}
-/* ── Pop-out modal ───────────────────────────────────────────────── */
.tl-modal {
position: fixed;
inset: 0;
diff --git a/apps/ui/src/components/primitives/CatalogNav.vue b/apps/ui/src/components/primitives/CatalogNav.vue
index 8e12f9f..b240209 100644
--- a/apps/ui/src/components/primitives/CatalogNav.vue
+++ b/apps/ui/src/components/primitives/CatalogNav.vue
@@ -116,9 +116,6 @@ const sections: NavSection[] = [
],
},
{
- /* "DSL Management" was a misleading label — the page is just a
- * static read-out of the operator's own RBAC verbs. Renamed
- * "Permissions" so its purpose is obvious. */
kicker: 'account',
links: [
{
diff --git a/apps/ui/src/components/primitives/TagInput.vue b/apps/ui/src/components/primitives/TagInput.vue
index 2cb7a36..1268439 100644
--- a/apps/ui/src/components/primitives/TagInput.vue
+++ b/apps/ui/src/components/primitives/TagInput.vue
@@ -56,7 +56,6 @@ const winMinutes = computed<number>(() =>
props.windowMinutes && props.windowMinutes > 0 ? props.windowMinutes : 30,
);
-// ── Fragment parsing ─────────────────────────────────────────────
// Suggestions operate on the text after the last comma; everything
// before it is preserved verbatim when a suggestion is applied.
const lastComma = computed<number>(() => props.modelValue.lastIndexOf(','));
@@ -115,7 +114,6 @@ function scheduleValueFetch(key: string): void {
valueDebounce = setTimeout(() => void ensureValues(key), 180);
}
-// ── Suggestion list ──────────────────────────────────────────────
// Before `=`: matching keys rendered `key=`. After `=`: matching values
// rendered `key=value`. Filter is case-insensitive prefix on the typed part.
const suggestions = computed<string[]>(() => {
@@ -163,7 +161,6 @@ function applySuggestion(s: string): void {
});
}
-// ── Input / keyboard ─────────────────────────────────────────────
function onInput(e: Event): void {
emit('update:modelValue', (e.target as HTMLInputElement).value);
open.value = true;
diff --git a/apps/ui/src/components/primitives/useEscapeToClose.ts b/apps/ui/src/components/primitives/useEscapeToClose.ts
new file mode 100644
index 0000000..590c400
--- /dev/null
+++ b/apps/ui/src/components/primitives/useEscapeToClose.ts
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { onBeforeUnmount, onMounted } from 'vue';
+
+/**
+ * Close a dismissible box (popout / modal / drawer / side panel / popover)
+ * on the Escape key — the keyboard counterpart to its × / backdrop click.
+ *
+ * Pass an `isOpen` getter so the listener is a no-op while the box is shut
+ * (and so it reads the LATEST open state on every keypress — a prop, a
+ * ref, a store flag); `close` runs only when open. The window listener is
+ * torn down on unmount.
+ *
+ * useEscapeToClose(() => props.show, () => emit('close'));
+ * useEscapeToClose(() => openStage.value !== null, () => (openStage.value = null));
+ *
+ * Boxes that nest another dismissible box (a span panel inside a trace
+ * popout) own a bespoke two-level handler instead — this is for the common
+ * single-level case.
+ */
+export function useEscapeToClose(isOpen: () => boolean, close: () => void): void {
+ function onKey(e: KeyboardEvent): void {
+ if (e.key !== 'Escape') return;
+ if (!isOpen()) return;
+ close();
+ }
+ onMounted(() => window.addEventListener('keydown', onKey));
+ onBeforeUnmount(() => window.removeEventListener('keydown', onKey));
+}
diff --git a/apps/ui/src/controls/debugPanel.ts b/apps/ui/src/controls/debugPanel.ts
index f29f94a..1b8e217 100644
--- a/apps/ui/src/controls/debugPanel.ts
+++ b/apps/ui/src/controls/debugPanel.ts
@@ -35,8 +35,6 @@ function detectInitial(): boolean {
if (raw === '1') return true;
if (raw === '0') return false;
}
- // No stored preference → off. Was previously on for localhost; now
- // uniform so operator-reported behavior matches what developers see.
return false;
}
diff --git a/apps/ui/src/features/admin/_shared/TranslationEditor.vue b/apps/ui/src/features/admin/_shared/TranslationEditor.vue
deleted file mode 100644
index eae6e8e..0000000
--- a/apps/ui/src/features/admin/_shared/TranslationEditor.vue
+++ /dev/null
@@ -1,334 +0,0 @@
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<!--
- Per-template translation editor. Single target language at a time;
- EN column is fixed; saves embed the new translations into the
- template's configuration as a sibling `i18n` block. The BFF's
- localizeContent merges them at render time.
-
- The editor doesn't own template content — it receives the EN source
- + current i18n state from the parent admin view and emits a save
- request with the updated map. The parent owns the save path
- (templateSync.save / save-local).
--->
-<script setup lang="ts">
-import { computed, nextTick, ref, watch } from 'vue';
-import { useI18n } from 'vue-i18n';
-import { SUPPORTED_LOCALES, LOCALE_NATIVE_LABEL, type Locale } from '@/i18n';
-
-const { t } = useI18n({ useScope: 'global' });
-import {
- walkTranslatable,
- getAtPath,
- setAtPath,
- type TranslatableField,
-} from './translatableFields';
-
-const props = defineProps<{
- /** English source content (whatever the parent currently has as the
- * authoritative copy — local draft, remote, or bundled). */
- source: unknown;
- /** Current i18n overlays embedded in the template, keyed by locale.
- * Loaded from `source.i18n` if present. */
- i18n?: Record<string, unknown>;
- /** True while the parent is publishing this editor's edits. Disables
- * the save button + greys the inputs. */
- saving?: boolean;
- /** When set, rows whose path starts with this prefix get a `.focused`
- * highlight and the first match scrolls into view. Driven by the
- * preview pane's click-to-focus signal. */
- focusPrefix?: string;
-}>();
-
-const emit = defineEmits<{
- /** Emitted when the operator clicks Save. Payload is the COMPLETE
- * i18n map (all locales, including unchanged ones), ready to splice
- * into the source's configuration.i18n. */
- save: [next: Record<string, unknown>];
-}>();
-
-const targetLocales = SUPPORTED_LOCALES.filter((l) => l !== 'en');
-const target = ref<Locale>(targetLocales[0]);
-
-/** Editor draft, indexed by path string → operator-entered value.
- * Loaded from the embedded i18n on locale switch; saved back into a
- * full structural overlay on emit. */
-const draft = ref<Record<string, string>>({});
-
-const fields = computed<TranslatableField[]>(() => walkTranslatable(props.source));
-const targetOverlay = computed<unknown>(() => props.i18n?.[target.value] ?? null);
-
-watch(
- [target, targetOverlay],
- ([loc, overlay]) => {
- const next: Record<string, string> = {};
- for (const f of fields.value) {
- const existing = getAtPath(overlay, f.segments);
- if (existing !== undefined) next[f.path] = existing;
- }
- draft.value = next;
- void loc;
- },
- { immediate: true },
-);
-
-const showLexicon = ref(false);
-
-/** Fields that need translator attention (operator has typed nothing
- * and no overlay value exists). The lexicon doesn't reach here —
- * this view is per-template prose only. */
-const needsTranslation = computed<TranslatableField[]>(() =>
- fields.value.filter((f) => !draft.value[f.path] || draft.value[f.path].length === 0),
-);
-const filledCount = computed<number>(() => fields.value.length - needsTranslation.value.length);
-
-const groupedFields = computed<Array<{ section: string; rows: TranslatableField[] }>>(() => {
- const visible = showLexicon.value ? fields.value : fields.value;
- const groups = new Map<string, TranslatableField[]>();
- for (const f of visible) {
- const list = groups.get(f.section) ?? [];
- list.push(f);
- groups.set(f.section, list);
- }
- return Array.from(groups, ([section, rows]) => ({ section, rows }));
-});
-
-function isFocused(f: TranslatableField): boolean {
- const p = props.focusPrefix;
- return !!p && (f.path === p || f.path.startsWith(`${p}.`) || f.path.startsWith(`${p}[`));
-}
-
-const rowRefs = ref<Map<string, HTMLElement>>(new Map());
-function setRowRef(path: string, el: HTMLElement | null): void {
- if (el) rowRefs.value.set(path, el);
- else rowRefs.value.delete(path);
-}
-
-watch(
- () => props.focusPrefix,
- async (prefix) => {
- if (!prefix) return;
- await nextTick();
- const first = fields.value.find((f) => isFocused(f));
- if (!first) return;
- const el = rowRefs.value.get(first.path);
- if (el) el.scrollIntoView({ block: 'center', behavior: 'smooth' });
- },
-);
-
-function onSave(): void {
- const overlay: Record<string, unknown> = {};
- for (const f of fields.value) {
- const v = draft.value[f.path];
- if (!v || v.length === 0) continue;
- setAtPath(overlay, f.segments, v);
- }
- const next: Record<string, unknown> = { ...(props.i18n ?? {}) };
- if (Object.keys(overlay).length === 0) {
- delete next[target.value];
- } else {
- next[target.value] = overlay;
- }
- emit('save', next);
-}
-
-const isDirty = computed<boolean>(() => {
- const overlay = targetOverlay.value;
- for (const f of fields.value) {
- const existing = getAtPath(overlay, f.segments) ?? '';
- const current = draft.value[f.path] ?? '';
- if (existing !== current) return true;
- }
- return false;
-});
-</script>
-
-<template>
- <div class="te">
- <div class="te__head">
- <label class="te__lang">
- <span>{{ t('Target language') }}</span>
- <select v-model="target">
- <option v-for="loc in targetLocales" :key="loc" :value="loc">
- {{ LOCALE_NATIVE_LABEL[loc] }} ({{ loc }})
- </option>
- </select>
- </label>
- <span class="te__progress">
- {{ t('{filled} / {total} translated', { filled: filledCount, total: fields.length }) }}
- </span>
- <button
- type="button"
- class="sw-btn is-primary"
- :disabled="!isDirty || saving"
- @click="onSave"
- >
- {{ saving ? t('Saving…') : t('Save translations') }}
- </button>
- </div>
-
- <div v-if="fields.length === 0" class="te__empty">
- {{ t('No translatable fields in this template.') }}
- </div>
-
- <div v-else class="te__list">
- <div v-for="g in groupedFields" :key="g.section" class="te__group">
- <h4 class="te__section">{{ g.section }}</h4>
- <div class="te__row te__row--header">
- <span class="te__col-path">{{ t('Field') }}</span>
- <span class="te__col-src">{{ t('English (source)') }}</span>
- <span class="te__col-tgt">{{ LOCALE_NATIVE_LABEL[target] }}</span>
- </div>
- <div
- v-for="f in g.rows"
- :key="f.path"
- :ref="(el) => setRowRef(f.path, el as HTMLElement | null)"
- class="te__row"
- :class="{ 'te__row--focus': isFocused(f) }"
- >
- <code class="te__col-path" :title="f.path">{{ f.path }}</code>
- <span class="te__col-src">{{ f.source }}</span>
- <input
- v-model="draft[f.path]"
- type="text"
- class="te__col-tgt te__input"
- :placeholder="f.source"
- :disabled="saving"
- />
- </div>
- </div>
- </div>
- </div>
-</template>
-
-<style scoped>
-.te {
- display: flex;
- flex-direction: column;
- gap: 10px;
- min-height: 0;
-}
-.te__head {
- display: flex;
- align-items: center;
- gap: 14px;
- padding: 8px 12px;
- background: var(--sw-bg-1);
- border: 1px solid var(--sw-line-2);
- border-radius: 6px;
-}
-.te__lang {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- font-size: 11.5px;
- color: var(--sw-fg-3);
-}
-.te__lang select {
- background: var(--sw-bg-2);
- color: var(--sw-fg-1);
- border: 1px solid var(--sw-line-2);
- border-radius: 4px;
- padding: 2px 6px;
- font-size: 12px;
-}
-.te__progress {
- font-size: 12px;
- color: var(--sw-fg-2);
-}
-.te__head .sw-btn {
- margin-left: auto;
-}
-.te__empty {
- padding: 24px;
- text-align: center;
- color: var(--sw-fg-3);
- font-size: 12.5px;
-}
-.te__list {
- display: flex;
- flex-direction: column;
- gap: 16px;
-}
-.te__group {
- border: 1px solid var(--sw-line-2);
- border-radius: 6px;
- overflow: hidden;
-}
-.te__section {
- margin: 0;
- padding: 8px 12px;
- font-size: 11px;
- letter-spacing: 0.04em;
- text-transform: uppercase;
- color: var(--sw-fg-3);
- background: var(--sw-bg-1);
- border-bottom: 1px solid var(--sw-line-2);
-}
-.te__row {
- display: grid;
- grid-template-columns: minmax(140px, 1fr) minmax(160px, 1.4fr) minmax(160px, 1.4fr);
- gap: 10px;
- align-items: center;
- padding: 7px 12px;
- border-bottom: 1px solid var(--sw-line-2);
- min-height: 32px;
-}
-.te__row:last-child { border-bottom: none; }
-.te__row--focus {
- background: rgba(255, 152, 0, 0.08);
- border-left: 2px solid var(--sw-accent);
- padding-left: 10px;
-}
-.te__row--header {
- font-size: 10.5px;
- text-transform: uppercase;
- letter-spacing: 0.06em;
- color: var(--sw-fg-3);
-}
-.te__col-path {
- font-family: var(--sw-mono);
- font-size: 11px;
- color: var(--sw-fg-3);
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-.te__col-src {
- font-size: 12.5px;
- color: var(--sw-fg-2);
- white-space: pre-wrap;
- word-break: break-word;
-}
-.te__col-tgt {
- font-size: 12.5px;
- color: var(--sw-fg-1);
-}
-.te__input {
- width: 100%;
- background: var(--sw-bg-2);
- color: var(--sw-fg-1);
- border: 1px solid var(--sw-line-2);
- border-radius: 4px;
- padding: 4px 6px;
- font-size: 12.5px;
-}
-.te__input:focus {
- outline: none;
- border-color: var(--sw-accent);
-}
-</style>
diff --git a/apps/ui/src/features/admin/_shared/useSingletonTemplateEditor.ts b/apps/ui/src/features/admin/_shared/useSingletonTemplateEditor.ts
new file mode 100644
index 0000000..f7c3036
--- /dev/null
+++ b/apps/ui/src/features/admin/_shared/useSingletonTemplateEditor.ts
@@ -0,0 +1,319 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * The load / save / push / reset / import / export state machine shared by
+ * SINGLETON admin templates — template kinds backed by exactly one row
+ * (`horizon.<kind>.<key>`, e.g. `horizon.infra-3d.config`). They ride the
+ * same bundled → local(browser) → remote(OAP) machinery as the layer /
+ * overview dashboards, but without a picker: there's one document, so the
+ * page binds a structured editor straight at the working `draft`.
+ *
+ * The host SFC owns only the section markup that edits `draft.value`; this
+ * composable owns everything around it:
+ *
+ * - `draft` — the working copy the editor mutates (cloned from a source).
+ * - source selection (`editorSource`, `loadFrom`, `syncDraft`) — local
+ * draft if present, else remote, else bundled.
+ * - `save` — persist the editor state as a browser-local draft (the only
+ * "save"; it never writes OAP).
+ * - push (`openPushDiff`, `pushToOap`, the diff pretties + error list) —
+ * the publish to OAP, the only thing whose failure means "not saved".
+ * - `resetTo` — discard edits + drop the local draft, reload a clean source.
+ * - import / export — file ⇄ local-draft round-trip.
+ * - `dirty` / `ready` / `loadError` / `badge` / `readOnly` — the derived
+ * flags the header + banner render.
+ *
+ * `normalize` is the per-kind hook for collapsing legacy wire shapes into
+ * the one the editor edits (e.g. infra-3d's topology/load → metric). It runs
+ * on every clone that lands in the editor AND on the dirty-baseline, so an
+ * old-shape remote never reads as "dirty" the moment it loads. Defaults to
+ * a structural clone with no transform.
+ */
+
+import { computed, onMounted, ref, watch, type ComputedRef, type Ref } from 'vue';
+import { bff } from '@/api/client';
+import type { TemplateKind, TemplateStatus } from '@/api/scopes/configs';
+import { useTemplateSources } from '@/features/admin/_shared/useTemplateSources';
+import { useTemplateSync, type SyncBanner } from '@/features/admin/_shared/useTemplateSync';
+import { useLocalTemplateEdits } from '@/controls/localTemplateEdits';
+import { buildExportEnvelope, downloadJson, pickJsonFile, validateImport } from '@/features/admin/_shared/templatePortability';
+import { refreshConfigBundle } from '@/controls/configBundle';
+import { stableStringify } from '@/utils/stableJson';
+
+type Source = 'local' | 'bundled' | 'remote';
+
+export interface SingletonTemplateEditorOptions<T> {
+ /** Template kind — drives the sync badges + the source rows fetch. */
+ kind: TemplateKind;
+ /** The single canonical row name, `horizon.<kind>.<key>`. */
+ name: string;
+ /** Collapse legacy wire shapes into the editor's shape. Mutates in place;
+ * called on a fresh clone (never the live source). Optional. */
+ normalize?: (content: T) => void;
+ /** Best-effort refresh of the live (rendered) view after a successful
+ * publish — e.g. re-read the 3D-map config a page renders from. A failure
+ * here never surfaces as a push error (the publish already committed). */
+ afterPush?: () => Promise<void>;
+ /** Transient note shown after an Import succeeds. A getter so it
+ * re-resolves against the live locale at import time, not setup time. */
+ importedNote: () => string;
+}
+
+export interface SingletonTemplateEditorReturn<T> {
+ /** Working copy the structured editor mutates. */
+ draft: Ref<T | null>;
+ /** Which of the three sources the editor is currently showing. */
+ editorSource: Ref<Source>;
+ /** Sources have settled but produced no working doc (BFF unreachable). */
+ loadError: Ref<boolean>;
+ ready: ComputedRef<boolean>;
+ readOnly: ComputedRef<boolean>;
+ hasLocalDraft: ComputedRef<boolean>;
+ hasRemote: ComputedRef<boolean>;
+ /** Per-row sync badge (synced / diverged / …) for the source pill. */
+ badge: ComputedRef<TemplateStatus | null>;
+ /** Bundled byte-equals OAP-live — resetting to bundled is then a no-op. */
+ isSynced: ComputedRef<boolean>;
+ /** Editor diverges from its baseline — drives the Save button. */
+ dirty: ComputedRef<boolean>;
+ banner: ComputedRef<SyncBanner>;
+
+ /** Server-side issue list from a failed push / import (or null). */
+ pushErr: Ref<string[] | null>;
+ pushing: Ref<boolean>;
+ pushDiffOpen: Ref<boolean>;
+ resetMenuOpen: Ref<boolean>;
+ importMsg: Ref<string | null>;
+ /** Pretty-printed draft / remote for the push diff. */
+ pushLocalPretty: ComputedRef<string>;
+ pushRemotePretty: ComputedRef<string>;
+
+ loadFrom: (src: Source) => void;
+ save: () => void;
+ openPushDiff: () => void;
+ pushToOap: () => Promise<void>;
+ resetTo: (src: 'bundled' | 'remote') => void;
+ onExport: () => void;
+ onImportFile: () => Promise<void>;
+}
+
+function clone<T>(v: T): T {
+ return JSON.parse(JSON.stringify(v)) as T;
+}
+
+export function useSingletonTemplateEditor<T>(
+ opts: SingletonTemplateEditorOptions<T>,
+): SingletonTemplateEditorReturn<T> {
+ const { kind, name, normalize, afterPush, importedNote } = opts;
+ const sources = useTemplateSources(kind);
+ const sync = useTemplateSync({ kind });
+ const localEdits = useLocalTemplateEdits();
+
+ const draft = ref<T | null>(null) as Ref<T | null>;
+ const editorSource = ref<Source>('remote');
+ const pushing = ref(false);
+ const pushErr = ref<string[] | null>(null);
+ const pushDiffOpen = ref(false);
+ const resetMenuOpen = ref(false);
+ const importMsg = ref<string | null>(null);
+ const loadError = ref(false);
+
+ const readOnly = computed(() => sync.readOnly.value);
+ const ready = computed(() => !sources.isLoading.value && draft.value !== null);
+ const hasLocalDraft = computed(() => localEdits.has(name));
+ const hasRemote = computed(() => sources.hasRemote(name));
+ const badge = computed(() => sync.badgeFor(name));
+ const isSynced = computed(() => badge.value === 'synced');
+
+ /** Cloned + normalized — used as a comparison baseline so an old-shape
+ * remote doesn't read as "dirty" the moment it loads. */
+ function normalizedClone(cfg: T | null): T | null {
+ if (!cfg) return null;
+ const c = clone(cfg);
+ normalize?.(c);
+ return c;
+ }
+
+ function loadFrom(src: Source): void {
+ let next: T | null = null;
+ if (src === 'local') next = localEdits.get<T>(name) ?? null;
+ else if (src === 'remote') next = sources.remote<T>(name);
+ else next = sources.bundled<T>(name);
+ // Bundled always exists; remote/local may be null — fall back so the
+ // editor always has a working doc.
+ if (!next) next = sources.bundled<T>(name);
+ draft.value = normalizedClone(next);
+ editorSource.value = src;
+ }
+
+ /** Pick the source on (re)load: local draft if present, else remote (the
+ * runtime source of truth), else bundled. */
+ function syncDraft(): void {
+ if (hasLocalDraft.value) loadFrom('local');
+ else if (hasRemote.value) loadFrom('remote');
+ else loadFrom('bundled');
+ }
+
+ onMounted(async () => {
+ // Force a fresh OAP read so badges + remote content are current.
+ await refreshConfigBundle({ force: true });
+ await sources.refetch();
+ syncDraft();
+ loadError.value = draft.value === null;
+ });
+
+ // Cold-cache arrival — hydrate once the sources land if mount raced ahead.
+ watch(
+ () => sources.isLoading.value,
+ (loading) => {
+ if (loading) return;
+ if (!draft.value) syncDraft();
+ loadError.value = draft.value === null;
+ },
+ );
+
+ const localContent = computed<T | null>(() => localEdits.get<T>(name) ?? null);
+ const remoteContent = computed<T | null>(() => sources.remote<T>(name));
+
+ /** Dirty = the editor diverges from its baseline (the local draft when
+ * one exists, otherwise remote / bundled). Drives the Save button. */
+ const dirty = computed(() => {
+ if (!draft.value) return false;
+ const baseline = hasLocalDraft.value
+ ? localContent.value
+ : (remoteContent.value ?? sources.bundled<T>(name));
+ // Normalize the baseline so an old-shape remote doesn't read as dirty
+ // against the normalized draft.
+ return stableStringify(draft.value) !== stableStringify(normalizedClone(baseline ?? null));
+ });
+
+ /** Save the current editor state as a browser-local draft. The only
+ * "save" — it never writes OAP. Publish via "Check diff & push". */
+ function save(): void {
+ if (!draft.value) return;
+ localEdits.set(name, clone(draft.value));
+ editorSource.value = 'local';
+ }
+
+ const pushLocalPretty = computed(() => (draft.value ? stableStringify(draft.value, 2) : ''));
+ const pushRemotePretty = computed(() => stableStringify(remoteContent.value ?? null, 2));
+
+ function openPushDiff(): void {
+ if (!draft.value) return;
+ // Persist the editor state first so the diff reflects exactly what
+ // would be pushed.
+ save();
+ pushErr.value = null;
+ pushDiffOpen.value = true;
+ }
+
+ async function pushToOap(): Promise<void> {
+ if (!draft.value || pushing.value) return;
+ pushing.value = true;
+ pushErr.value = null;
+ // 1) The publish — the only thing whose failure means "not saved".
+ try {
+ await bff.templateSync.save(name, draft.value);
+ } catch (err) {
+ const anyErr = err as { body?: { issues?: string[] }; message?: string };
+ pushErr.value = anyErr.body?.issues ?? [anyErr.message ?? String(err)];
+ pushing.value = false;
+ return; // keep the modal open with the error; nothing was committed
+ }
+ // Committed. Clear the local draft + close the modal regardless of the
+ // post-write cache refresh outcome below.
+ localEdits.remove(name);
+ pushDiffOpen.value = false;
+ // 2) Best-effort cache refreshes. A failure here does NOT undo the
+ // publish, so it must never surface as a "push failed".
+ try {
+ await bff.templateSync.resync();
+ await Promise.all([sources.refetch(), refreshConfigBundle({ force: true })]);
+ await afterPush?.();
+ loadFrom('remote');
+ } catch (err) {
+ console.warn(`[${kind}] post-push refresh failed (the publish already committed):`, err);
+ } finally {
+ pushing.value = false;
+ }
+ }
+
+ /** Reset the editor to a clean source and drop any local draft. */
+ function resetTo(src: 'bundled' | 'remote'): void {
+ loadFrom(src);
+ localEdits.remove(name);
+ pushErr.value = null;
+ resetMenuOpen.value = false;
+ }
+
+ // Export downloads the IN-USE config (remote, else bundled) — what the
+ // page renders — not the editor draft. Import stages a file as a local
+ // draft; `loadFrom('local')` normalizes any legacy shapes. Errors reuse
+ // the push-issue list; success shows a transient note.
+ function onExport(): void {
+ const inUse = sources.remote<T>(name) ?? sources.bundled<T>(name);
+ if (!inUse) return;
+ downloadJson(`${name}.json`, buildExportEnvelope(kind, name, inUse));
+ }
+
+ async function onImportFile(): Promise<void> {
+ const text = await pickJsonFile();
+ if (text === null) return;
+ const res = validateImport(kind, text);
+ if (!res.ok) {
+ pushErr.value = [res.error];
+ importMsg.value = null;
+ return;
+ }
+ localEdits.set(name, res.content);
+ loadFrom('local');
+ pushErr.value = null;
+ importMsg.value = importedNote();
+ setTimeout(() => {
+ importMsg.value = null;
+ }, 6000);
+ }
+
+ return {
+ draft,
+ editorSource,
+ loadError,
+ ready,
+ readOnly,
+ hasLocalDraft,
+ hasRemote,
+ badge,
+ isSynced,
+ dirty,
+ banner: sync.banner,
+ pushErr,
+ pushing,
+ pushDiffOpen,
+ resetMenuOpen,
+ importMsg,
+ pushLocalPretty,
+ pushRemotePretty,
+ loadFrom,
+ save,
+ openPushDiff,
+ pushToOap,
+ resetTo,
+ onExport,
+ onImportFile,
+ };
+}
diff --git a/apps/ui/src/features/admin/auth-status/AuthStatusView.vue b/apps/ui/src/features/admin/auth-status/AuthStatusView.vue
index 1b77a81..2d54bc9 100644
--- a/apps/ui/src/features/admin/auth-status/AuthStatusView.vue
+++ b/apps/ui/src/features/admin/auth-status/AuthStatusView.vue
@@ -119,7 +119,6 @@ function fmtAgo(ms: number | null): string {
<div v-if="loading" class="loading">{{ t('Loading auth status…') }}</div>
<div v-else-if="probeError" class="error">{{ t('Failed to load: {err}', { err: probeError }) }}</div>
<template v-else-if="status">
- <!-- Headline -->
<div class="head-card">
<div class="head-left">
<div class="status-glyph" :class="{ ok: healthy, err: !healthy }">
@@ -179,7 +178,6 @@ function fmtAgo(ms: number | null): string {
</div>
<div class="grid-2col">
- <!-- Backend identity -->
<section class="sw-card">
<header class="card-head">
<h3>{{ t('Backend') }}</h3>
@@ -256,7 +254,6 @@ function fmtAgo(ms: number | null): string {
</table>
</section>
- <!-- Local users -->
<section class="sw-card">
<header class="card-head">
<h3>{{ t('Local users') }}</h3>
@@ -301,7 +298,6 @@ function fmtAgo(ms: number | null): string {
</section>
</div>
- <!-- LDAP details -->
<section v-if="status.ldap" class="sw-card">
<header class="card-head">
<h3>{{ t('LDAP probe') }}</h3>
@@ -367,7 +363,6 @@ function fmtAgo(ms: number | null): string {
</table>
</section>
- <!-- Group -> role mapping -->
<section v-if="status.ldap && status.ldap.groupMappings.length" class="sw-card">
<header class="card-head">
<h3>{{ t('Group → role mapping') }}</h3>
@@ -404,7 +399,6 @@ function fmtAgo(ms: number | null): string {
</table>
</section>
- <!-- Resolver -->
<section v-if="status.ldap" class="sw-card">
<header class="card-head">
<h3>{{ t('Test a username') }}</h3>
diff --git a/apps/ui/src/features/admin/global-defaults/GlobalDefaultsAdmin.vue b/apps/ui/src/features/admin/global-defaults/GlobalDefaultsAdmin.vue
index 18ca244..4b85e34 100644
--- a/apps/ui/src/features/admin/global-defaults/GlobalDefaultsAdmin.vue
+++ b/apps/ui/src/features/admin/global-defaults/GlobalDefaultsAdmin.vue
@@ -61,7 +61,6 @@ const timeStatus = computed(() => timeSync.badgeFor('horizon.time-defaults.globa
const themeDiverged = computed(() => themeStatus.value === 'diverged');
const timeDiverged = computed(() => timeStatus.value === 'diverged');
-// ── Drafts ─────────────────────────────────────────────────────────
// We hydrate from the bundle's syncStatus (badge tells us what's there,
// but not the value); call sync-status once on mount to get the live
// values. After save, refetch.
@@ -122,7 +121,6 @@ watch(
() => { void loadFromOap(); },
);
-// ── Save ───────────────────────────────────────────────────────────
const saving = ref(false);
const flash = ref<string | null>(null);
function setFlash(msg: string): void {
@@ -169,7 +167,6 @@ function onReset(): void {
}
}
-// ── Time picker presets ───────────────────────────────────────────
// A small whitelist — operators can pick from these or type a custom
// number. Step precision (the OAP `Duration.step` value) is derived
// from the window size automatically: ≤ 4h → MINUTE, 6h…14d → HOUR,
@@ -204,7 +201,6 @@ const draftBucketCount = computed(() => {
return Math.round(m / 60 / 24);
});
-// ── Diff modal state ──────────────────────────────────────────────
const themeDiffOpen = ref(false);
const timeDiffOpen = ref(false);
async function onDiffReset(): Promise<void> {
@@ -231,7 +227,6 @@ async function onDiffReset(): Promise<void> {
<div v-else-if="loadError" class="gd__err">{{ loadError }}</div>
<template v-else>
- <!-- ── Theme ───────────────────────────────────────────────── -->
<section class="gd__section">
<header class="gd__sec-head">
<h2>{{ t('Theme') }}</h2>
@@ -258,7 +253,6 @@ async function onDiffReset(): Promise<void> {
</div>
</section>
- <!-- ── Time defaults ──────────────────────────────────────── -->
<section class="gd__section">
<header class="gd__sec-head">
<h2>{{ t('Default time window') }}</h2>
@@ -333,7 +327,6 @@ async function onDiffReset(): Promise<void> {
</p>
</section>
- <!-- ── Actions ────────────────────────────────────────────── -->
<footer class="gd__actions">
<span v-if="flash" class="gd__flash">{{ flash }}</span>
<span v-else-if="dirty" class="gd__dirty">{{ t('unsaved changes') }}</span>
diff --git a/apps/ui/src/features/admin/infra-3d/Infra3dAdminView.vue b/apps/ui/src/features/admin/infra-3d/Infra3dAdminView.vue
index 7022448..761f6f4 100644
--- a/apps/ui/src/features/admin/infra-3d/Infra3dAdminView.vue
+++ b/apps/ui/src/features/admin/infra-3d/Infra3dAdminView.vue
@@ -41,30 +41,24 @@
3D-map content before it reaches OAP); issues land in the push error list.
-->
<script setup lang="ts">
-import { computed, onMounted, ref, watch } from 'vue';
+import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useLayers } from '@/shell/useLayers';
import {
- bff,
type Infra3dConfig,
type InfraGroupSpec,
type InfraLayerSpec,
- type InfraLevelSpec,
type InfraMqe,
} from '@/api/client';
import { refresh as refreshLiveInfraConfig } from '@/features/infra-3d/composables/useInfra3dConfig';
-import { useTemplateSources } from '@/features/admin/_shared/useTemplateSources';
-import { useTemplateSync } from '@/features/admin/_shared/useTemplateSync';
-import { useLocalTemplateEdits } from '@/controls/localTemplateEdits';
-import { buildExportEnvelope, downloadJson, pickJsonFile, validateImport } from '@/features/admin/_shared/templatePortability';
-import { refreshConfigBundle } from '@/controls/configBundle';
-import { stableStringify } from '@/utils/stableJson';
+import { useSingletonTemplateEditor } from '@/features/admin/_shared/useSingletonTemplateEditor';
+import { useInfra3dLevels, type ResolvedLevel } from './useInfra3dLevels';
import SyncStatusBanner from '@/features/admin/_shared/SyncStatusBanner.vue';
import TemplateStatusBadge from '@/features/admin/_shared/TemplateStatusBadge.vue';
+import Infra3dLayerRow, { type LayerRow } from './Infra3dLayerRow.vue';
import Modal from '@/features/operate/_shared/Modal.vue';
import MonacoDiff from '@/features/operate/_shared/MonacoDiff.vue';
-// ── Live OAP layer catalog ────────────────────────────────────────────
// We hydrate the Layers section from the catalog union'd with config
// keys, so an OAP layer the admin hasn't classified yet shows up here
// and an out-of-tree layer (config exists, OAP no longer reports it)
@@ -72,39 +66,12 @@ import MonacoDiff from '@/features/operate/_shared/MonacoDiff.vue';
const { availableLayers } = useLayers();
const { t } = useI18n();
-// ── Template-sync state ───────────────────────────────────────────────
// The 3D-map config is a singleton template kind — ONE row,
-// `horizon.infra-3d.config`. It rides the same bundled → local(browser)
-// → remote(OAP) machinery as the layer / overview dashboards: edits save
-// to a browser-local draft, "Check diff & push" publishes to OAP, and
-// the map renders the remote (with bundled as fallback).
+// `horizon.infra-3d.config`. The shared editor owns the bundled →
+// local(browser) → remote(OAP) load/save/push/reset/import/export machine;
+// `normalizeSpecs` folds the legacy topology/load shapes into the single
+// `metric` the editor edits, and `afterPush` re-reads the live /3d/map view.
const NAME = 'horizon.infra-3d.config';
-const sources = useTemplateSources('infra-3d');
-const sync = useTemplateSync({ kind: 'infra-3d' });
-const localEdits = useLocalTemplateEdits();
-
-/** Working copy the structured editor below mutates. */
-const draft = ref<Infra3dConfig | null>(null);
-const layerSearch = ref('');
-/** Which of the three sources the editor is currently showing. */
-const editorSource = ref<'local' | 'bundled' | 'remote'>('remote');
-const pushing = ref(false);
-const pushErr = ref<string[] | null>(null);
-const pushDiffOpen = ref(false);
-const resetMenuOpen = ref(false);
-
-const readOnly = computed(() => sync.readOnly.value);
-const ready = computed(() => !sources.isLoading.value && draft.value !== null);
-const hasLocalDraft = computed(() => localEdits.has(NAME));
-const hasRemote = computed(() => sources.hasRemote(NAME));
-/** Per-row sync badge (synced / diverged / …) for the source pill. */
-const badge = computed(() => sync.badgeFor(NAME));
-/** Bundled byte-equals OAP-live — resetting to bundled is then a no-op. */
-const isSynced = computed(() => badge.value === 'synced');
-
-function clone<T>(v: T): T {
- return JSON.parse(JSON.stringify(v)) as T;
-}
/** Collapse the deprecated `topology` / `load` shapes into the single
* `metric` the editor edits, so an OAP row saved before the single-metric
@@ -120,218 +87,44 @@ function normalizeSpecs(cfg: Infra3dConfig): void {
}
}
-/** Cloned + normalized — used as a comparison baseline so an old-shape
- * remote doesn't read as "dirty" the moment it loads. */
-function normalizedClone(cfg: Infra3dConfig | null): Infra3dConfig | null {
- if (!cfg) return null;
- const c = clone(cfg);
- normalizeSpecs(c);
- return c;
-}
-
-function loadFrom(src: 'local' | 'bundled' | 'remote'): void {
- let next: Infra3dConfig | null = null;
- if (src === 'local') next = localEdits.get<Infra3dConfig>(NAME) ?? null;
- else if (src === 'remote') next = sources.remote<Infra3dConfig>(NAME);
- else next = sources.bundled<Infra3dConfig>(NAME);
- // Bundled always exists; remote/local may be null — fall back so the
- // editor always has a working doc.
- if (!next) next = sources.bundled<Infra3dConfig>(NAME);
- draft.value = normalizedClone(next);
- editorSource.value = src;
-}
-
-/** Pick the source on (re)load: local draft if present, else remote (the
- * runtime source of truth), else bundled. */
-function syncDraft(): void {
- if (hasLocalDraft.value) loadFrom('local');
- else if (hasRemote.value) loadFrom('remote');
- else loadFrom('bundled');
-}
-
-/** Set when the sources settle but still produce no working doc (the BFF
- * itself is unreachable — bundled rows are absent, so there's nothing to
- * edit). Surfaces an error instead of an indefinite spinner. */
-const loadError = ref(false);
-
-onMounted(async () => {
- // Force a fresh OAP read so badges + remote content are current.
- await refreshConfigBundle({ force: true });
- await sources.refetch();
- syncDraft();
- loadError.value = draft.value === null;
-});
-
-// Cold-cache arrival — hydrate once the sources land if mount raced ahead.
-watch(
- () => sources.isLoading.value,
- (loading) => {
- if (loading) return;
- if (!draft.value) syncDraft();
- loadError.value = draft.value === null;
- },
-);
-
-const localContent = computed<Infra3dConfig | null>(
- () => localEdits.get<Infra3dConfig>(NAME) ?? null,
-);
-const remoteContent = computed<Infra3dConfig | null>(() => sources.remote<Infra3dConfig>(NAME));
-
-/** Dirty = the editor diverges from its baseline (the local draft when
- * one exists, otherwise remote / bundled). Drives the Save button. */
-const dirty = computed(() => {
- if (!draft.value) return false;
- const baseline = hasLocalDraft.value
- ? localContent.value
- : (remoteContent.value ?? sources.bundled<Infra3dConfig>(NAME));
- // Normalize the baseline to the single-metric shape so an old-shape
- // remote (topology/load) doesn't read as dirty against the normalized draft.
- return stableStringify(draft.value) !== stableStringify(normalizedClone(baseline ?? null));
+const editor = useSingletonTemplateEditor<Infra3dConfig>({
+ kind: 'infra-3d',
+ name: NAME,
+ normalize: normalizeSpecs,
+ afterPush: () => refreshLiveInfraConfig().then(() => undefined),
+ importedNote: () => t('Imported as a local draft — preview, then “Check diff & push”.'),
});
+const {
+ draft,
+ editorSource,
+ loadError,
+ ready,
+ readOnly,
+ hasLocalDraft,
+ hasRemote,
+ badge,
+ isSynced,
+ dirty,
+ banner,
+ pushErr,
+ pushing,
+ pushDiffOpen,
+ resetMenuOpen,
+ importMsg,
+ pushLocalPretty,
+ pushRemotePretty,
+ save,
+ openPushDiff,
+ pushToOap,
+ resetTo,
+ onExport,
+ onImportFile,
+} = editor;
-/** Save the current editor state as a browser-local draft. The only
- * "save" — it never writes OAP. Publish via "Check diff & push". */
-function save(): void {
- if (!draft.value) return;
- localEdits.set(NAME, clone(draft.value));
- editorSource.value = 'local';
-}
-
-const pushLocalPretty = computed(() => (draft.value ? stableStringify(draft.value, 2) : ''));
-const pushRemotePretty = computed(() => stableStringify(remoteContent.value ?? null, 2));
-
-function openPushDiff(): void {
- if (!draft.value) return;
- // Persist the editor state first so the diff reflects exactly what
- // would be pushed.
- save();
- pushErr.value = null;
- pushDiffOpen.value = true;
-}
-
-async function pushToOap(): Promise<void> {
- if (!draft.value || pushing.value) return;
- pushing.value = true;
- pushErr.value = null;
- // 1) The publish — the only thing whose failure means "not saved".
- try {
- await bff.templateSync.save(NAME, draft.value);
- } catch (err) {
- const anyErr = err as { body?: { issues?: string[] }; message?: string };
- pushErr.value = anyErr.body?.issues ?? [anyErr.message ?? String(err)];
- pushing.value = false;
- return; // keep the modal open with the error; nothing was committed
- }
- // Committed. Clear the local draft + close the modal regardless of the
- // post-write cache refresh outcome below.
- localEdits.remove(NAME);
- pushDiffOpen.value = false;
- // 2) Best-effort cache refreshes. A failure here (e.g. the /3d/map read
- // cache pop 403-ing for a role without infra-3d:read) does NOT undo the
- // publish, so it must never surface as a "push failed".
- try {
- await bff.templateSync.resync();
- await Promise.all([sources.refetch(), refreshConfigBundle({ force: true })]);
- await refreshLiveInfraConfig();
- loadFrom('remote');
- } catch (err) {
- console.warn('[infra-3d] post-push refresh failed (the publish already committed):', err);
- } finally {
- pushing.value = false;
- }
-}
-
-/** Reset the editor to a clean source and drop any local draft. */
-function resetTo(src: 'bundled' | 'remote'): void {
- loadFrom(src);
- localEdits.remove(NAME);
- pushErr.value = null;
- resetMenuOpen.value = false;
-}
-
-// ── Import / Export ────────────────────────────────────────────────
-// Export downloads the IN-USE config (remote, else bundled) — what the map
-// renders — not the editor draft. Import stages a file as a local draft;
-// `loadFrom('local')` normalizes any legacy topology/load shapes. Errors
-// reuse the push-issue list; success shows a transient note.
-const importMsg = ref<string | null>(null);
-function onExport(): void {
- const inUse = sources.remote<Infra3dConfig>(NAME) ?? sources.bundled<Infra3dConfig>(NAME);
- if (!inUse) return;
- downloadJson(`${NAME}.json`, buildExportEnvelope('infra-3d', NAME, inUse));
-}
-async function onImportFile(): Promise<void> {
- const text = await pickJsonFile();
- if (text === null) return;
- const res = validateImport('infra-3d', text);
- if (!res.ok) {
- pushErr.value = [res.error];
- importMsg.value = null;
- return;
- }
- localEdits.set(NAME, res.content);
- loadFrom('local');
- pushErr.value = null;
- importMsg.value = t('Imported as a local draft — preview, then “Check diff & push”.');
- setTimeout(() => {
- importMsg.value = null;
- }, 6000);
-}
-
-// ── Levels editing ────────────────────────────────────────────────────
-function addLevel(): void {
- if (!draft.value) return;
- const maxOrder = Math.max(-1, ...draft.value.levels.map((l) => l.order));
- // Unique id — a length-based id collides after add-then-remove editing
- // (and a duplicate level id aliases tier buckets + fails save validation).
- const taken = new Set(draft.value.levels.map((l) => l.id));
- let n = draft.value.levels.length + 1;
- let id = `level-${n}`;
- while (taken.has(id)) id = `level-${++n}`;
- draft.value.levels.push({ id, order: maxOrder + 1, label: 'New level', layers: [] });
-}
-function removeLevel(id: string): void {
- if (!draft.value) return;
- draft.value.levels = draft.value.levels.filter((l) => l.id !== id);
- if (draft.value.unknownLayer.level === id && draft.value.levels.length > 0) {
- draft.value.unknownLayer.level = draft.value.levels[0]!.id;
- }
-}
-const levelsSorted = computed<InfraLevelSpec[]>(() => {
- if (!draft.value) return [];
- return [...draft.value.levels].sort((a, b) => a.order - b.order);
-});
-
-/** `idx` is the index in `levelsSorted` (what the template renders) — NOT
- * the unsorted `draft.levels` array, whose order can differ from the sort
- * (bundled has mesh order 2 before middleware order 1). Swap the `order`
- * values of the two SORTED neighbours so ↑/↓ moves the intended tier. */
-function moveLevel(idx: number, delta: number): void {
- const sorted = levelsSorted.value;
- const target = idx + delta;
- if (target < 0 || target >= sorted.length) return;
- const a = sorted[idx]!;
- const b = sorted[target]!;
- const ao = a.order;
- a.order = b.order;
- b.order = ao;
-}
-
-// ── Layer ⇄ level resolution ──────────────────────────────────────────
-// Level membership is edited in ONE place — the Levels section's member
-// chips. The Layers section only DISPLAYS where each layer lands, using
-// the same resolution order the BFF applies, so the two surfaces never
-// drift into the old "edit the same array twice" redundancy.
+const layerSearch = ref('');
-/** Compile that never throws — a half-typed regex in an input just stops
- * matching rather than blowing up the page. */
-function safeRegex(src: string): RegExp | null {
- try {
- return new RegExp(src);
- } catch {
- return null;
- }
-}
+const { levelsSorted, addLevel, removeLevel, moveLevel, resolveLevel, levelLabel } =
+ useInfra3dLevels(draft);
/** Union of OAP-reported + config-declared layer keys (canonical upper). */
const allLayerKeys = computed<string[]>(() => {
@@ -341,42 +134,6 @@ const allLayerKeys = computed<string[]>(() => {
return [...s].sort((a, b) => a.localeCompare(b));
});
-type LevelVia = 'group' | 'explicit' | 'default' | 'filtered';
-
-/** Mirror the BFF's layer→level resolution (see useInfra3dConfig): global
- * filter → group membership → explicit list → unknownLayer fallback.
- * Returns HOW it resolved so the unpinned rows can flag fallback / filtered
- * layers the operator didn't pin by hand. */
-function resolveLevel(key: string): { levelId: string | null; via: LevelVia } {
- if (!draft.value) return { levelId: null, via: 'default' };
- const u = key.toUpperCase();
- const gf = safeRegex(draft.value.filter.layer);
- if (gf && !gf.test(u)) return { levelId: null, via: 'filtered' };
- for (const g of draft.value.groups ?? []) {
- if (g.layers.some((k) => k.toUpperCase() === u)) return { levelId: g.level, via: 'group' };
- }
- for (const lvl of draft.value.levels) {
- if (lvl.layers.some((k) => k.toUpperCase() === u)) return { levelId: lvl.id, via: 'explicit' };
- }
- return { levelId: draft.value.unknownLayer.level, via: 'default' };
-}
-
-function levelLabel(levelId: string | null): string {
- if (!levelId) return '—';
- return draft.value?.levels.find((l) => l.id === levelId)?.label ?? levelId;
-}
-
-// ── Layers editing ────────────────────────────────────────────────────
-/** Union of OAP-known + config-known layers. The keys are canonical
- * upper-case; the entry's `inOap`/`inConfig` flags drive the row badges. */
-interface LayerRow {
- key: string;
- inOap: boolean;
- inConfig: boolean;
- hasTopology: boolean;
- spec: InfraLayerSpec | null;
-}
-
const layerRows = computed<LayerRow[]>(() => {
if (!draft.value) return [];
const oap = new Map<string, { hasTopology: boolean }>();
@@ -422,8 +179,8 @@ const serviceMapLayers = computed<string[]>(() =>
/** Resolved level per layer-key — drives the read-only "via" qualifier on
* UNPINNED rows so the operator sees how a layer lands when no tier pins
* it (regex / fallback / filtered). */
-const resolvedLevels = computed<Record<string, { levelId: string | null; via: LevelVia }>>(() => {
- const out: Record<string, { levelId: string | null; via: LevelVia }> = {};
+const resolvedLevels = computed<Record<string, ResolvedLevel>>(() => {
+ const out: Record<string, ResolvedLevel> = {};
for (const r of layerRows.value) out[r.key] = resolveLevel(r.key);
return out;
});
@@ -526,7 +283,13 @@ function clearMetric(key: string): void {
if (spec) spec.metric = undefined;
}
-// ── Groups editing ────────────────────────────────────────────────────
+/** Write one metric field — the row component edits via events (it can't
+ * mutate the row prop directly), so the parent owns the draft write. */
+function setMetricField(key: string, field: 'mqe' | 'label' | 'unit', value: string): void {
+ const metric = draft.value?.layers[key.toUpperCase()]?.metric;
+ if (metric) metric[field] = value;
+}
+
// Logic groups (e.g. Self-Observability) cluster several layers into one
// block on a tier. The icon set is the bakeable subset the 3D stamp
// renderer knows (useLayerIconTexture.LayerIconName); an unknown name
@@ -661,7 +424,7 @@ const stats = computed(() => {
</div>
</header>
- <SyncStatusBanner :banner="sync.banner.value" />
+ <SyncStatusBanner :banner="banner" />
<ul v-if="pushErr && pushErr.length" class="issues">
<li v-for="(it, i) in pushErr" :key="i"><code>{{ it }}</code></li>
</ul>
@@ -672,7 +435,6 @@ const stats = computed(() => {
</div>
<div v-else-if="!ready" class="loading">{{ t('Loading config…') }}</div>
<template v-else-if="draft">
- <!-- ── Global filter ─────────────────────────────────────────── -->
<section class="sect">
<header class="sect-head">
<h2>{{ t('Global layer filter') }}</h2>
@@ -690,7 +452,6 @@ const stats = computed(() => {
</div>
</section>
- <!-- ── Tiers & layers ─────────────────────────────────────────── -->
<section class="sect">
<header class="sect-head">
<h2>{{ t('Tiers & layers (top → bottom)') }}</h2>
@@ -720,23 +481,20 @@ const stats = computed(() => {
</header>
<div class="tier-body">
<div class="layer-rows">
- <div v-for="row in layersByTier[lvl.id]" :key="row.key" class="layer-row">
- <input type="color" class="color-pick" :value="row.spec?.color ?? '#8a8a8a'" @input="(e) => (ensureLayerSpec(row.key).color = (e.target as HTMLInputElement).value)" />
- <span class="layer-key">{{ row.key }}</span>
- <template v-if="row.spec?.metric">
- <input class="inp mono metric-mqe" v-model="row.spec.metric.mqe" :placeholder="t('mqe e.g. service_cpm')" />
- <input class="inp metric-lbl" v-model="row.spec.metric.label" :placeholder="t('label')" />
- <input class="inp metric-unit" v-model="row.spec.metric.unit" :placeholder="t('unit')" />
- <button class="btn tiny danger" type="button" :title="t('remove metric')" @click="clearMetric(row.key)">⊘</button>
- </template>
- <button v-else class="btn tiny ghost" type="button" @click="ensureMetric(row.key)">{{ t('+ metric') }}</button>
- <div class="row-spacer" />
- <select class="inp tier-select" :value="explicitTier[row.key] ?? ''" @change="(e) => onMoveTier(row.key, e)">
- <option value="">{{ t('— unpinned —') }}</option>
- <option v-for="tier in levelsSorted" :key="tier.id" :value="tier.id">{{ tier.label }}</option>
- </select>
- <button class="btn tiny ghost" type="button" :title="t('Remove from this tier (moves to Unpinned)')" @click="assignLayerToLevel(row.key, null)">×</button>
- </div>
+ <Infra3dLayerRow
+ v-for="row in layersByTier[lvl.id]"
+ :key="row.key"
+ :row="row"
+ variant="tier"
+ :levels="levelsSorted"
+ :pinned-tier="explicitTier[row.key] ?? ''"
+ @set-color="(c) => (ensureLayerSpec(row.key).color = c)"
+ @update-metric="(f, v) => setMetricField(row.key, f, v)"
+ @change-tier="(e) => onMoveTier(row.key, e)"
+ @ensure-metric="ensureMetric(row.key)"
+ @clear-metric="clearMetric(row.key)"
+ @remove="assignLayerToLevel(row.key, null)"
+ />
<div v-if="(layersByTier[lvl.id]?.length ?? 0) === 0" class="tier-empty">{{ t('No layers pinned — use a layer\'s tier dropdown to move one here.') }}</div>
</div>
</div>
@@ -744,7 +502,6 @@ const stats = computed(() => {
</div>
</section>
- <!-- ── Unpinned → failover ────────────────────────────────────── -->
<section class="sect">
<header class="sect-head">
<h2>{{ t('Unpinned layers') }}</h2>
@@ -756,37 +513,28 @@ const stats = computed(() => {
</header>
<div class="sect-body">
<div class="layer-rows">
- <div
+ <Infra3dLayerRow
v-for="row in unpinnedRows"
:key="row.key"
- class="layer-row"
- :class="{ unclassified: isUnclassified(row.key) }"
- >
- <input type="color" class="color-pick" :value="row.spec?.color ?? '#8a8a8a'" @input="(e) => (ensureLayerSpec(row.key).color = (e.target as HTMLInputElement).value)" />
- <span class="layer-key">{{ row.key }}</span>
- <template v-if="row.spec?.metric">
- <input class="inp mono metric-mqe" v-model="row.spec.metric.mqe" placeholder="mqe" />
- <input class="inp metric-lbl" v-model="row.spec.metric.label" :placeholder="t('label')" />
- <input class="inp metric-unit" v-model="row.spec.metric.unit" :placeholder="t('unit')" />
- <button class="btn tiny danger" type="button" :title="t('remove metric')" @click="clearMetric(row.key)">⊘</button>
- </template>
- <button v-else class="btn tiny ghost" type="button" @click="ensureMetric(row.key)">{{ t('+ metric') }}</button>
- <div class="row-spacer" />
- <span class="via-tag" :data-via="resolvedLevels[row.key]?.via" :title="t('falls to {via}', { via: resolvedLevels[row.key]?.via })">
- {{ resolvedLevels[row.key]?.via === 'filtered' ? t('filtered out') : '→ ' + levelLabel(resolvedLevels[row.key]?.levelId ?? null) }}
- </span>
- <select class="inp tier-select" :value="explicitTier[row.key] ?? ''" @change="(e) => onMoveTier(row.key, e)">
- <option value="">{{ t('— pin to tier —') }}</option>
- <option v-for="tier in levelsSorted" :key="tier.id" :value="tier.id">{{ tier.label }}</option>
- </select>
- <button class="btn tiny danger" type="button" :title="t('Delete this layer from the config entirely')" @click="removeLayerFromConfig(row.key)">×</button>
- </div>
+ :row="row"
+ variant="unpinned"
+ :levels="levelsSorted"
+ :pinned-tier="explicitTier[row.key] ?? ''"
+ :resolved="resolvedLevels[row.key]"
+ :resolved-label="levelLabel(resolvedLevels[row.key]?.levelId ?? null)"
+ :unclassified="isUnclassified(row.key)"
+ @set-color="(c) => (ensureLayerSpec(row.key).color = c)"
+ @update-metric="(f, v) => setMetricField(row.key, f, v)"
+ @change-tier="(e) => onMoveTier(row.key, e)"
+ @ensure-metric="ensureMetric(row.key)"
+ @clear-metric="clearMetric(row.key)"
+ @remove="removeLayerFromConfig(row.key)"
+ />
<div v-if="unpinnedRows.length === 0" class="empty">{{ t('No unpinned layers.') }}</div>
</div>
</div>
</section>
- <!-- ── Groups ────────────────────────────────────────────────── -->
<section class="sect">
<header class="sect-head">
<h2>{{ t('Logic groups') }}</h2>
@@ -844,7 +592,6 @@ const stats = computed(() => {
</div>
</section>
- <!-- ── Service-map layers ─────────────────────────────────────── -->
<section class="sect">
<header class="sect-head">
<h2>{{ t('Service-map layers') }}</h2>
@@ -860,7 +607,6 @@ const stats = computed(() => {
</div>
</section>
- <!-- ── Unknown layer fallback ─────────────────────────────────── -->
<section class="sect">
<header class="sect-head">
<h2>{{ t('Failover tier') }}</h2>
@@ -878,7 +624,6 @@ const stats = computed(() => {
</template>
- <!-- ── Check diff & push ──────────────────────────────────────────── -->
<Modal :open="pushDiffOpen" :title="t('Push 3D-map config to OAP')" width="min(1100px, 94vw)" fit-body @close="pushDiffOpen = false">
<div class="push-modal">
<p class="push-lede">
@@ -925,7 +670,6 @@ export { parseHexColor };
overflow-y: auto;
}
-/* Header */
.hd {
display: flex;
align-items: center;
@@ -943,7 +687,6 @@ export { parseHexColor };
.lede code { background: var(--sw-bg-3); padding: 1px 4px; border-radius: 3px; }
.hd-actions { display: flex; align-items: center; gap: 8px; flex: 0 0 auto; }
-/* Source pill + reset menu */
.src-pill {
display: inline-flex;
align-items: center;
@@ -988,13 +731,11 @@ export { parseHexColor };
.reset-item[disabled] { opacity: 0.45; cursor: default; }
.reset-suffix { color: var(--sw-fg-3); font-size: 10px; }
-/* Push diff modal */
.push-modal { display: flex; flex-direction: column; gap: 10px; min-width: min(1040px, 90vw); flex: 1; min-height: 0; }
/* Definite height for the Monaco diff to fill (else it collapses). */
.push-diff { flex: 1; min-height: 0; }
.push-lede { font-size: 11.5px; color: var(--sw-fg-2); margin: 0; }
-/* Buttons */
.btn {
height: 26px;
padding: 0 12px;
@@ -1015,7 +756,6 @@ export { parseHexColor };
.btn.danger { border-color: rgba(239, 68, 68, 0.6); color: #f87171; }
.btn.danger:hover:not([disabled]) { background: rgba(239, 68, 68, 0.15); color: #fca5a5; }
-/* Banners */
.issues {
margin: 8px 20px 0;
padding: 8px 12px;
@@ -1040,7 +780,6 @@ export { parseHexColor };
}
.loading { padding: 20px; color: var(--sw-fg-3); font-size: 12px; }
-/* Sections */
.sect {
margin: 12px 20px;
border: 1px solid var(--sw-line);
@@ -1061,7 +800,6 @@ export { parseHexColor };
.sect-body { padding: 12px 14px; }
.fallback-level { max-width: 260px; }
-/* Inputs */
.field { display: flex; flex-direction: column; gap: 4px; margin-bottom: 8px; }
.field.row { flex-direction: row; align-items: center; gap: 6px; }
.lbl { font-size: 10.5px; letter-spacing: 0.04em; text-transform: uppercase; color: var(--sw-fg-3); }
@@ -1081,7 +819,6 @@ export { parseHexColor };
.inp.search { height: 22px; width: 180px; margin-left: auto; }
.inp:focus { outline: 1px solid var(--sw-accent); }
-/* Tiers */
.tier-card {
border: 1px solid var(--sw-line);
border-radius: 4px;
@@ -1146,19 +883,9 @@ export { parseHexColor };
.add-layer:hover { border-color: var(--sw-accent); color: var(--sw-fg-0); }
.add-layer:focus { outline: 1px solid var(--sw-accent); }
-/* Layer rows — one dense line per layer (inside a tier or the unpinned
- bucket): colour · key · badges · metric (mqe/label/unit) · tier · remove. */
+/* Layer-row container (the rows themselves are Infra3dLayerRow). The colour
+ picker is reused in the group head, so its rule stays here too. */
.layer-rows { display: flex; flex-direction: column; gap: 4px; }
-.layer-row {
- display: flex;
- align-items: center;
- gap: 6px;
- padding: 4px 6px;
- border: 1px solid var(--sw-line);
- border-radius: 4px;
- background: var(--sw-bg-1);
-}
-.layer-row.unclassified { border-color: rgba(239, 158, 68, 0.5); }
.color-pick {
width: 24px;
height: 20px;
@@ -1169,26 +896,6 @@ export { parseHexColor };
cursor: pointer;
flex: 0 0 auto;
}
-.layer-key {
- font-family: var(--sw-mono-font, monospace);
- font-size: 11.5px;
- font-weight: 600;
- color: var(--sw-fg-0);
- /* Fixed column so the metric fields line up across every row regardless
- of key length (GENERAL … BYTEDANCE_MINI_PROGRAM). */
- flex: 0 0 190px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-.via-tag { font-size: 10px; color: var(--sw-fg-3); white-space: nowrap; flex: 0 0 auto; }
-.via-tag[data-via='default'],
-.via-tag[data-via='filtered'] { color: #f0a04b; }
-.metric-mqe { flex: 0 1 200px; min-width: 110px; }
-.metric-lbl { flex: 0 0 110px; }
-.metric-unit { flex: 0 0 72px; }
-.row-spacer { flex: 1 1 auto; min-width: 8px; }
-.tier-select { flex: 0 0 130px; }
.tier-empty { font-size: 11px; color: var(--sw-fg-3); font-style: italic; padding: 2px 2px 4px; }
.warn-count { color: #f0a04b; }
.row-2 { display: flex; gap: 8px; }
@@ -1196,7 +903,6 @@ export { parseHexColor };
.hint-sm { font-size: 10.5px; color: var(--sw-fg-3); margin: 0; }
.empty { padding: 14px; text-align: center; color: var(--sw-fg-3); font-size: 11.5px; }
-/* Groups */
.groups-grid { display: flex; flex-direction: column; gap: 8px; }
.group-card {
border: 1px solid var(--sw-line);
@@ -1215,6 +921,4 @@ export { parseHexColor };
.group-body { padding: 10px 12px; display: flex; flex-direction: column; gap: 8px; }
.group-body .row-2 { max-width: 420px; }
.hint-sm.warn { color: #f0a04b; }
-
-/* Advanced */
</style>
diff --git a/apps/ui/src/features/admin/infra-3d/Infra3dLayerRow.vue b/apps/ui/src/features/admin/infra-3d/Infra3dLayerRow.vue
new file mode 100644
index 0000000..90cb0da
--- /dev/null
+++ b/apps/ui/src/features/admin/infra-3d/Infra3dLayerRow.vue
@@ -0,0 +1,209 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<!--
+ One dense per-layer line for the 3D-map admin: colour · key · metric
+ (mqe/label/unit) · tier-select · trailing action. Two variants share this
+ markup:
+
+ - `tier` — rendered inside a tier card; trailing action UNPINS the
+ layer (× → moves it to the Unpinned bucket).
+ - `unpinned` — rendered in the Unpinned section; shows the resolved
+ `via` tag (→ <failover tier> / "filtered out"), highlights an
+ unclassified row, and the trailing action DELETES the layer from the
+ config entirely.
+
+ The metric inputs bind straight at `row.spec.metric` (a live reference
+ into the editor draft) so two-way editing stays in the parent's `draft`;
+ structural mutations (colour, tier, +/⊘ metric, remove) go up as events.
+-->
+<script setup lang="ts">
+import { useI18n } from 'vue-i18n';
+import type { InfraLayerSpec, InfraLevelSpec } from '@/api/client';
+import type { LevelVia } from './useInfra3dLevels';
+
+/** Union of OAP-known + config-known layers. Keys are canonical upper-case;
+ * `inOap`/`inConfig` drive the row badges. */
+export interface LayerRow {
+ key: string;
+ inOap: boolean;
+ inConfig: boolean;
+ hasTopology: boolean;
+ spec: InfraLayerSpec | null;
+}
+
+defineProps<{
+ row: LayerRow;
+ variant: 'tier' | 'unpinned';
+ levels: InfraLevelSpec[];
+ /** Tier id this layer is explicitly pinned to, or '' when unpinned. */
+ pinnedTier: string;
+ /** Unpinned variant only — how the layer resolves when no tier pins it. */
+ resolved?: { levelId: string | null; via: LevelVia };
+ /** Unpinned variant only — resolved level's display label (for the via tag). */
+ resolvedLabel?: string;
+ /** Unpinned variant only — highlights a layer nothing places. */
+ unclassified?: boolean;
+}>();
+
+const emit = defineEmits<{
+ (e: 'set-color', value: string): void;
+ (e: 'update-metric', field: 'mqe' | 'label' | 'unit', value: string): void;
+ (e: 'change-tier', event: Event): void;
+ (e: 'ensure-metric'): void;
+ (e: 'clear-metric'): void;
+ (e: 'remove'): void;
+}>();
+
+const { t } = useI18n();
+
+function onColor(e: Event): void {
+ emit('set-color', (e.target as HTMLInputElement).value);
+}
+function onMetric(field: 'mqe' | 'label' | 'unit', e: Event): void {
+ emit('update-metric', field, (e.target as HTMLInputElement).value);
+}
+</script>
+
+<template>
+ <div class="layer-row" :class="{ unclassified: variant === 'unpinned' && unclassified }">
+ <input type="color" class="color-pick" :value="row.spec?.color ?? '#8a8a8a'" @input="onColor" />
+ <span class="layer-key">{{ row.key }}</span>
+ <template v-if="row.spec?.metric">
+ <input
+ class="inp mono metric-mqe"
+ :value="row.spec.metric.mqe"
+ :placeholder="variant === 'tier' ? t('mqe e.g. service_cpm') : 'mqe'"
+ @input="(e) => onMetric('mqe', e)"
+ />
+ <input class="inp metric-lbl" :value="row.spec.metric.label" :placeholder="t('label')" @input="(e) => onMetric('label', e)" />
+ <input class="inp metric-unit" :value="row.spec.metric.unit" :placeholder="t('unit')" @input="(e) => onMetric('unit', e)" />
+ <button class="btn tiny danger" type="button" :title="t('remove metric')" @click="emit('clear-metric')">⊘</button>
+ </template>
+ <button v-else class="btn tiny ghost" type="button" @click="emit('ensure-metric')">{{ t('+ metric') }}</button>
+ <div class="row-spacer" />
+ <span
+ v-if="variant === 'unpinned'"
+ class="via-tag"
+ :data-via="resolved?.via"
+ :title="t('falls to {via}', { via: resolved?.via })"
+ >
+ {{ resolved?.via === 'filtered' ? t('filtered out') : '→ ' + (resolvedLabel ?? '—') }}
+ </span>
+ <select class="inp tier-select" :value="pinnedTier" @change="emit('change-tier', $event)">
+ <option value="">{{ variant === 'tier' ? t('— unpinned —') : t('— pin to tier —') }}</option>
+ <option v-for="tier in levels" :key="tier.id" :value="tier.id">{{ tier.label }}</option>
+ </select>
+ <button
+ v-if="variant === 'tier'"
+ class="btn tiny ghost"
+ type="button"
+ :title="t('Remove from this tier (moves to Unpinned)')"
+ @click="emit('remove')"
+ >
+ ×
+ </button>
+ <button
+ v-else
+ class="btn tiny danger"
+ type="button"
+ :title="t('Delete this layer from the config entirely')"
+ @click="emit('remove')"
+ >
+ ×
+ </button>
+ </div>
+</template>
+
+<style scoped>
+.layer-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 4px 6px;
+ border: 1px solid var(--sw-line);
+ border-radius: 4px;
+ background: var(--sw-bg-1);
+}
+.layer-row.unclassified { border-color: rgba(239, 158, 68, 0.5); }
+.color-pick {
+ width: 24px;
+ height: 20px;
+ padding: 0;
+ border: 1px solid var(--sw-line-2);
+ border-radius: 3px;
+ background: transparent;
+ cursor: pointer;
+ flex: 0 0 auto;
+}
+.layer-key {
+ font-family: var(--sw-mono-font, monospace);
+ font-size: 11.5px;
+ font-weight: 600;
+ color: var(--sw-fg-0);
+ /* Fixed column so the metric fields line up across every row regardless
+ of key length (GENERAL … BYTEDANCE_MINI_PROGRAM). */
+ flex: 0 0 190px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.via-tag { font-size: 10px; color: var(--sw-fg-3); white-space: nowrap; flex: 0 0 auto; }
+.via-tag[data-via='default'],
+.via-tag[data-via='filtered'] { color: #f0a04b; }
+.metric-mqe { flex: 0 1 200px; min-width: 110px; }
+.metric-lbl { flex: 0 0 110px; }
+.metric-unit { flex: 0 0 72px; }
+.row-spacer { flex: 1 1 auto; min-width: 8px; }
+.tier-select { flex: 0 0 130px; }
+
+.inp {
+ height: 24px;
+ padding: 0 8px;
+ background: var(--sw-bg-2);
+ border: 1px solid var(--sw-line-2);
+ border-radius: 4px;
+ color: var(--sw-fg-0);
+ font-size: 11.5px;
+ font-family: inherit;
+}
+.inp.mono { font-family: var(--sw-mono-font, ui-monospace, monospace); font-size: 11px; }
+.inp:focus { outline: 1px solid var(--sw-accent); }
+
+.btn {
+ height: 26px;
+ padding: 0 12px;
+ font-size: 11.5px;
+ border: 1px solid var(--sw-line-2);
+ border-radius: 4px;
+ background: var(--sw-bg-2);
+ color: var(--sw-fg-1);
+ cursor: pointer;
+ white-space: nowrap;
+}
+.btn:hover:not([disabled]) { background: var(--sw-bg-3); color: var(--sw-fg-0); }
+.btn[disabled] { opacity: 0.45; cursor: default; }
+.btn.tiny { height: 20px; padding: 0 8px; font-size: 10px; }
+.btn.danger { border-color: rgba(239, 68, 68, 0.6); color: #f87171; }
+.btn.danger:hover:not([disabled]) { background: rgba(239, 68, 68, 0.15); color: #fca5a5; }
+.btn.ghost {
+ align-self: flex-start;
+ background: transparent;
+ border-style: dashed;
+ color: var(--sw-fg-3);
+}
+.btn.ghost:hover:not([disabled]) { color: var(--sw-fg-1); border-color: var(--sw-accent); background: transparent; }
+</style>
diff --git a/apps/ui/src/features/admin/infra-3d/useInfra3dLevels.ts b/apps/ui/src/features/admin/infra-3d/useInfra3dLevels.ts
new file mode 100644
index 0000000..fb45e16
--- /dev/null
+++ b/apps/ui/src/features/admin/infra-3d/useInfra3dLevels.ts
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Tier (level) editing + layer→level resolution for the 3D-map admin.
+ *
+ * Level membership is edited in ONE place — the Levels section's member
+ * chips. The Layers section only DISPLAYS where each layer lands, using
+ * the same resolution order the BFF applies (see useInfra3dConfig): global
+ * filter → group membership → explicit list → unknownLayer fallback. Both
+ * surfaces share `resolveLevel` here so they never drift into the old
+ * "edit the same array twice" redundancy.
+ *
+ * Bound to the editor `draft`; every mutation writes through it.
+ */
+
+import { computed, type ComputedRef, type Ref } from 'vue';
+import type { Infra3dConfig, InfraLevelSpec } from '@/api/client';
+
+export type LevelVia = 'group' | 'explicit' | 'default' | 'filtered';
+
+export interface ResolvedLevel {
+ levelId: string | null;
+ via: LevelVia;
+}
+
+/** Compile that never throws — a half-typed regex in an input just stops
+ * matching rather than blowing up the page. */
+export function safeRegex(src: string): RegExp | null {
+ try {
+ return new RegExp(src);
+ } catch {
+ return null;
+ }
+}
+
+export function useInfra3dLevels(draft: Ref<Infra3dConfig | null>): {
+ levelsSorted: ComputedRef<InfraLevelSpec[]>;
+ addLevel: () => void;
+ removeLevel: (id: string) => void;
+ moveLevel: (idx: number, delta: number) => void;
+ resolveLevel: (key: string) => ResolvedLevel;
+ levelLabel: (levelId: string | null) => string;
+} {
+ function addLevel(): void {
+ if (!draft.value) return;
+ const maxOrder = Math.max(-1, ...draft.value.levels.map((l) => l.order));
+ // Unique id — a length-based id collides after add-then-remove editing
+ // (and a duplicate level id aliases tier buckets + fails save validation).
+ const taken = new Set(draft.value.levels.map((l) => l.id));
+ let n = draft.value.levels.length + 1;
+ let id = `level-${n}`;
+ while (taken.has(id)) id = `level-${++n}`;
+ draft.value.levels.push({ id, order: maxOrder + 1, label: 'New level', layers: [] });
+ }
+
+ function removeLevel(id: string): void {
+ if (!draft.value) return;
+ draft.value.levels = draft.value.levels.filter((l) => l.id !== id);
+ if (draft.value.unknownLayer.level === id && draft.value.levels.length > 0) {
+ draft.value.unknownLayer.level = draft.value.levels[0]!.id;
+ }
+ }
+
+ const levelsSorted = computed<InfraLevelSpec[]>(() => {
+ if (!draft.value) return [];
+ return [...draft.value.levels].sort((a, b) => a.order - b.order);
+ });
+
+ /** `idx` is the index in `levelsSorted` (what the template renders) — NOT
+ * the unsorted `draft.levels` array, whose order can differ from the sort
+ * (bundled has mesh order 2 before middleware order 1). Swap the `order`
+ * values of the two SORTED neighbours so ↑/↓ moves the intended tier. */
+ function moveLevel(idx: number, delta: number): void {
+ const sorted = levelsSorted.value;
+ const target = idx + delta;
+ if (target < 0 || target >= sorted.length) return;
+ const a = sorted[idx]!;
+ const b = sorted[target]!;
+ const ao = a.order;
+ a.order = b.order;
+ b.order = ao;
+ }
+
+ /** Mirror the BFF's layer→level resolution: global filter → group
+ * membership → explicit list → unknownLayer fallback. Returns HOW it
+ * resolved so the unpinned rows can flag fallback / filtered layers the
+ * operator didn't pin by hand. */
+ function resolveLevel(key: string): ResolvedLevel {
+ if (!draft.value) return { levelId: null, via: 'default' };
+ const u = key.toUpperCase();
+ const gf = safeRegex(draft.value.filter.layer);
+ if (gf && !gf.test(u)) return { levelId: null, via: 'filtered' };
+ for (const g of draft.value.groups ?? []) {
+ if (g.layers.some((k) => k.toUpperCase() === u)) return { levelId: g.level, via: 'group' };
+ }
+ for (const lvl of draft.value.levels) {
+ if (lvl.layers.some((k) => k.toUpperCase() === u)) return { levelId: lvl.id, via: 'explicit' };
+ }
+ return { levelId: draft.value.unknownLayer.level, via: 'default' };
+ }
+
+ function levelLabel(levelId: string | null): string {
+ if (!levelId) return '—';
+ return draft.value?.levels.find((l) => l.id === levelId)?.label ?? levelId;
+ }
+
+ return { levelsSorted, addLevel, removeLevel, moveLevel, resolveLevel, levelLabel };
+}
diff --git a/apps/ui/src/features/admin/layer-templates/LayerDashboardsAdmin.vue b/apps/ui/src/features/admin/layer-templates/LayerDashboardsAdmin.vue
index 9c54a47..d4b895e 100644
--- a/apps/ui/src/features/admin/layer-templates/LayerDashboardsAdmin.vue
+++ b/apps/ui/src/features/admin/layer-templates/LayerDashboardsAdmin.vue
@@ -16,15 +16,18 @@
-->
<!--
Admin / Layer dashboards. List every loaded layer template, pick one
- on the left, edit its per-scope widget set on the right. Saves write
- the JSON file back via POST /api/admin/layer-templates/:key so the
- BFF refreshes its in-memory cache.
+ on the left, edit its per-scope widget set on the right. Saves go
+ through the template-sync store (bff.templateSync.save) which persists
+ to OAP and refreshes the BFF's in-memory cache.
Widget editor presents the new span-based fields (12-col flow
layout): operator picks a column span, optional row span, MQE
expressions, type, title, unit, and an optional visibility predicate.
Legacy x/y/w/h are NOT shown — they're kept on the wire for
back-compat with older JSONs but operators don't edit them.
+
+ XL file; decomposition is staged — geometry helpers are extracted
+ (layer-dashboards.geometry.ts); MetricDefinitionRow + composables pending.
-->
<script setup lang="ts">
import { computed, reactive, ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';
@@ -46,6 +49,17 @@ import type {
TopologyMetricDef,
} from '@skywalking-horizon-ui/api-client';
import { collectWidgetIds } from '@skywalking-horizon-ui/api-client';
+import {
+ CANVAS_COLS,
+ CANVAS_ROW_PX,
+ CANVAS_GAP_PX,
+ SUBGRID_ROW_PX,
+ SUBGRID_GAP_PX,
+ DRAWER_COL,
+ widgetSpan,
+ widgetRowSpan,
+ widgetGridStyle,
+} from '@/features/admin/layer-templates/layer-dashboards.geometry';
/** Admin-only scopes that aren't dashboard-widget scopes. `networkProfiling`
* is the process-topology edge editor; `deployment` is the
@@ -440,10 +454,9 @@ function persistLocal(content: AdminLayerTemplate): void {
// "Reset to ▾" dropdown — discard the current local draft and reload the
// editor from the picked source. The op-facing tooltip says "Discard
// current edits and reload …", so the action must DROP the local draft
-// rather than re-stage the new content as a fresh draft (which the
-// previous implementation did via persistLocal, triggering the
-// TemplateConflictPrompt right after every reset). Subsequent edits in
-// the editor re-create a local draft naturally on the next change.
+// rather than re-stage the new content as a fresh draft — re-staging would
+// trigger the TemplateConflictPrompt right after every reset. Subsequent
+// edits in the editor re-create a local draft naturally on the next change.
const resetDropdownOpen = ref(false);
function resetTo(src: 'bundled' | 'remote'): void {
loadFrom(src);
@@ -559,7 +572,7 @@ watch(visibleScopes, (scopes) => {
void nextTick(updateScopeScroll);
});
-// ── Scope-tab strip horizontal scroll. The strip can hold ~11 scopes;
+// Scope-tab strip horizontal scroll. The strip can hold ~11 scopes;
// on a narrow editor it overflows, so we let it scroll and surface
// chevron buttons that appear only on the side(s) with hidden tabs.
const scopeNav = ref<HTMLElement | null>(null);
@@ -603,7 +616,7 @@ watch(
watch([visibleScopes, activeScope], () => void nextTick(updateScopeScroll));
function onWinResizeScope(): void { updateScopeScroll(); }
-// ── Editor drawer position. The drawer edits the selected widget. A sticky
+// Editor drawer position. The drawer edits the selected widget. A sticky
// drawer gets clipped once you scroll past the bottom of the tall widget canvas
// (its containing block), so a bottom-row widget opens with the editor's top
// off-screen. Pin it to the viewport with `position: fixed` instead, overlaying
@@ -614,7 +627,6 @@ function onWinResizeScope(): void { updateScopeScroll(); }
// viewport below the topbar.
const drawerEl = ref<HTMLElement | null>(null);
const editorCardEl = ref<HTMLElement | null>(null);
-const DRAWER_COL = 360;
function positionDrawer(): void {
const el = drawerEl.value;
const card = editorCardEl.value;
@@ -867,23 +879,6 @@ const resize = reactive<{
cellH: 1,
});
-const CANVAS_COLS = 12;
-const CANVAS_ROW_PX = 120;
-const CANVAS_GAP_PX = 8;
-
-function widgetSpan(w: DashboardWidget): number {
- return Math.min(CANVAS_COLS, Math.max(1, w.span ?? 4));
-}
-function widgetRowSpan(w: DashboardWidget): number {
- return Math.max(1, w.rowSpan ?? 2);
-}
-function widgetGridStyle(w: DashboardWidget): Record<string, string> {
- return {
- gridColumn: `span ${widgetSpan(w)}`,
- gridRow: `span ${widgetRowSpan(w)}`,
- };
-}
-
function onResizeStart(e: MouseEvent, i: number): void {
e.preventDefault();
e.stopPropagation();
@@ -907,8 +902,6 @@ function onResizeStart(e: MouseEvent, i: number): void {
window.addEventListener('mousemove', onResizeMove);
window.addEventListener('mouseup', onResizeEnd);
}
-const SUBGRID_ROW_PX = 84;
-const SUBGRID_GAP_PX = 6;
/** Resize a widget INSIDE a tab — same drag as the top level, but snapped to
* the tab's own 12-col sub-grid pitch (measured from the .cw-subgrid). */
function onSubResizeStart(e: MouseEvent, widgetId: string, tabIdx: number, subIdx: number): void {
@@ -1072,7 +1065,6 @@ function onReorderDrop(e: DragEvent, i: number): void {
setWidgetsFor(activeScope.value, widgets);
selectedIdx.value = tIdx;
} else {
- // Plain reorder.
widgets.splice(from, 1);
widgets.splice(to, 0, dragged);
setWidgetsFor(activeScope.value, widgets);
@@ -1221,6 +1213,10 @@ function setValueMapKey(oldKey: string, newKey: string): void {
const label = w.valueMap[oldKey];
delete w.valueMap[oldKey];
w.valueMap[newKey] = label;
+ if (w.valueColors && oldKey in w.valueColors) {
+ w.valueColors[newKey] = w.valueColors[oldKey];
+ delete w.valueColors[oldKey];
+ }
}
function addValueMapRow(): void {
const w = editingWidget.value;
@@ -1235,6 +1231,30 @@ function removeValueMapRow(key: string): void {
if (!w || !w.valueMap) return;
delete w.valueMap[key];
if (Object.keys(w.valueMap).length === 0) delete w.valueMap;
+ if (w.valueColors) {
+ delete w.valueColors[key];
+ if (Object.keys(w.valueColors).length === 0) delete w.valueColors;
+ }
+}
+
+// Optional color per valueMap key → `valueColors`, turning the enum card into
+// colored status chips (one per matched value/label). Empty = no chip color.
+const CHIP_COLORS = ['', 'ok', 'warn', 'err', 'info', 'neutral'] as const;
+function valueColorFor(key: string): string {
+ return editingWidget.value?.valueColors?.[key] ?? '';
+}
+function setValueColor(key: string, color: string): void {
+ const w = editingWidget.value;
+ if (!w) return;
+ if (!color) {
+ if (w.valueColors) {
+ delete w.valueColors[key];
+ if (Object.keys(w.valueColors).length === 0) delete w.valueColors;
+ }
+ return;
+ }
+ if (!w.valueColors) w.valueColors = {};
+ w.valueColors[key] = color;
}
/** Drawer commits edits in place on the live draft via v-model — no
@@ -1462,7 +1482,6 @@ async function pushToOap(): Promise<void> {
}
}
-// ── Import / Export ────────────────────────────────────────────────
function flashMsg(msg: string): void {
saveMsg.value = msg;
setTimeout(() => {
@@ -1506,7 +1525,7 @@ async function onImportFile(): Promise<void> {
flashMsg(`Imported “${key}” as a local draft. Preview, then “Check diff & push”.`);
}
-// ── Disable / reactivate (OAP has no hard DELETE) ──────────────────
+// Disable / reactivate — OAP has no hard DELETE.
// Disabling soft-disables the layer on OAP: a disabled template drops out
// of the bundle AND the menu, so the layer disappears from the sidebar.
// Reactivating re-pushes the bundled default to OAP, which clears the
@@ -2392,7 +2411,7 @@ function setVisibility(v: 'public' | 'operate'): void {
}
}
-// ── Topology cluster setup — rule editor + live tester.
+// Topology cluster setup — rule editor + live tester.
// The rule is a named-capture regex run against every service name in
// the topology + service pickers. Operators bind which capture maps to
// the display label vs the cluster value (e.g. k8s namespace), and
@@ -2637,7 +2656,6 @@ const namingTest = computed<NamingTestResult>(() => {
</template>
</div>
</div>
- <!-- Identity strip + save controls -->
<section class="sw-card identity-card">
<div class="identity-row">
<span class="dot inline" :style="{ background: selectedTpl.color || 'var(--sw-fg-3)' }" />
@@ -2725,7 +2743,6 @@ const namingTest = computed<NamingTestResult>(() => {
title="Import a layer dashboard JSON file as a local draft — preview, then publish."
@click="onImportFile"
>Import</button>
- <!-- Reset the editor to a source (discard current content). -->
<div class="reset-dd">
<button class="sw-btn" type="button" @click="resetDropdownOpen = !resetDropdownOpen">
Reset to <span class="caret" :class="{ open: resetDropdownOpen }">›</span>
@@ -2763,7 +2780,6 @@ const namingTest = computed<NamingTestResult>(() => {
</div>
</template>
</div>
- <!-- Preview the real page rendering a chosen source. -->
<div class="reset-dd">
<button class="sw-btn" type="button" @click="previewDropdownOpen = !previewDropdownOpen">
Preview <span class="caret" :class="{ open: previewDropdownOpen }">›</span>
@@ -3031,7 +3047,6 @@ const namingTest = computed<NamingTestResult>(() => {
</div>
</section>
- <!-- Scope tabs -->
<div id="scope-editor" class="scope-tabs-wrap sw-card">
<button
v-show="canScrollScopeLeft"
@@ -4051,7 +4066,6 @@ const namingTest = computed<NamingTestResult>(() => {
>+ Add widget ▾</button>
<div v-if="addMenuOpen" class="add-menu-backdrop" @click="addMenuOpen = false" />
<div v-if="addMenuOpen" class="add-menu" role="menu">
- <!-- Container first, then a divider, then the five leaf kinds. -->
<button type="button" class="add-menu-item" role="menuitem" @click="pickAddKind('tab')">
<span class="ami-type t-tab">tab</span>
<span class="ami-text">
@@ -4344,11 +4358,10 @@ const namingTest = computed<NamingTestResult>(() => {
</div>
</template>
- <!-- NORMAL widget: the content form. -->
<template v-else>
<template v-if="editingWidget">
<div v-if="editingWidget.format === 'enum'" class="d-section">
- <span class="d-label">Value map (enum → label)</span>
+ <span class="d-label">Value map (enum → label, color)</span>
<div class="vm-rows">
<div v-for="(row, i) in valueMapEntries" :key="i" class="vm-row">
<input
@@ -4364,11 +4377,19 @@ const namingTest = computed<NamingTestResult>(() => {
@input="setValueMapLabel(row[0], ($event.target as HTMLInputElement).value)"
placeholder="Failed"
/>
+ <select
+ class="vm-color"
+ :value="valueColorFor(row[0])"
+ title="Chip color"
+ @change="setValueColor(row[0], ($event.target as HTMLSelectElement).value)"
+ >
+ <option v-for="c in CHIP_COLORS" :key="c" :value="c">{{ c || '—' }}</option>
+ </select>
<button type="button" class="expr-del" title="Remove" @click="removeValueMapRow(row[0])">×</button>
</div>
</div>
<button type="button" class="sw-btn ghost small" @click="addValueMapRow">+ value</button>
- <p class="d-hint">Map a coded value to a label (e.g. 1 → OK). Card widgets only; labels are translatable per locale.</p>
+ <p class="d-hint">Map a coded value — or a metric label such as a K8s node condition — to a label and an optional chip color (<code>ok</code> green / <code>warn</code> amber / <code>err</code> red / <code>info</code> blue / <code>neutral</code> grey). With a color set, the card renders colored status chips, one per matched value. Card widgets only; labels are translatable per locale.</p>
</div>
<div class="d-section">
<span class="d-label">MQE expressions</span>
@@ -6443,6 +6464,7 @@ const namingTest = computed<NamingTestResult>(() => {
.vm-row .vm-key { width: 64px; flex: 0 0 auto; }
.vm-row .vm-arrow { color: var(--sw-fg-3); }
.vm-row .vm-label { flex: 1 1 auto; min-width: 0; }
+.vm-row .vm-color { width: 84px; flex: 0 0 auto; }
.expr-rows { display: flex; flex-direction: column; gap: 4px; }
.expr-row { display: flex; gap: 6px; align-items: center; }
.expr-row .expr-mqe { flex: 1 1 auto; min-width: 0; }
diff --git a/apps/ui/src/features/admin/layer-templates/layer-dashboards.geometry.ts b/apps/ui/src/features/admin/layer-templates/layer-dashboards.geometry.ts
new file mode 100644
index 0000000..647fe75
--- /dev/null
+++ b/apps/ui/src/features/admin/layer-templates/layer-dashboards.geometry.ts
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Grid geometry for the layer-dashboard admin canvas — shared by the
+ * widget grid-style helpers and the drag/resize handlers in
+ * `LayerDashboardsAdmin.vue`.
+ */
+
+import type { DashboardWidget } from '@skywalking-horizon-ui/api-client';
+
+/** Top-level canvas grid: 12 columns, fixed row height + gap (px). */
+export const CANVAS_COLS = 12;
+export const CANVAS_ROW_PX = 120;
+export const CANVAS_GAP_PX = 8;
+/** Nested tab-widget sub-grid (same column count, tighter rows). */
+export const SUBGRID_ROW_PX = 84;
+export const SUBGRID_GAP_PX = 6;
+/** Width (px) of the floating widget-edit drawer, anchored to the canvas. */
+export const DRAWER_COL = 360;
+
+export function widgetSpan(w: DashboardWidget): number {
+ return Math.min(CANVAS_COLS, Math.max(1, w.span ?? 4));
+}
+export function widgetRowSpan(w: DashboardWidget): number {
+ return Math.max(1, w.rowSpan ?? 2);
+}
+export function widgetGridStyle(w: DashboardWidget): Record<string, string> {
+ return {
+ gridColumn: `span ${widgetSpan(w)}`,
+ gridRow: `span ${widgetRowSpan(w)}`,
+ };
+}
diff --git a/apps/ui/src/features/admin/overview-templates/NewOverviewDashboardModal.vue b/apps/ui/src/features/admin/overview-templates/NewOverviewDashboardModal.vue
new file mode 100644
index 0000000..731b167
--- /dev/null
+++ b/apps/ui/src/features/admin/overview-templates/NewOverviewDashboardModal.vue
@@ -0,0 +1,104 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<!--
+ New-overview-dashboard composer. A self-contained form (id / title /
+ description) that emits `submit` with the typed values; the parent owns
+ uniqueness validation and pushes any failure back via the `error` prop.
+ Create mirrors edit — the parent writes a LOCAL browser draft, never the
+ server, so this modal carries no persistence of its own.
+-->
+<script setup lang="ts">
+import { ref, watch } from 'vue';
+import Modal from '@/features/operate/_shared/Modal.vue';
+
+const props = defineProps<{
+ open: boolean;
+ /** Validation error pushed back by the parent (uniqueness / shape). */
+ error: string | null;
+}>();
+
+const emit = defineEmits<{
+ close: [];
+ submit: [payload: { id: string; title: string; description: string }];
+}>();
+
+const id = ref('');
+const title = ref('');
+const description = ref('');
+
+// Reset the fields each time the composer (re)opens so a prior cancel
+// doesn't leak its half-typed values into the next create.
+watch(
+ () => props.open,
+ (open) => {
+ if (open) {
+ id.value = '';
+ title.value = '';
+ description.value = '';
+ }
+ },
+);
+
+function submit(): void {
+ emit('submit', { id: id.value, title: title.value, description: description.value });
+}
+</script>
+
+<template>
+ <Modal :open="open" title="New dashboard" width="min(520px, 92vw)" @close="emit('close')">
+ <div class="nod">
+ <label class="nod__field">
+ <span>Id (used as the name — must be unique)</span>
+ <input v-model="id" type="text" class="nod__in nod__in--mono" placeholder="my-overview" @keyup.enter="submit" />
+ </label>
+ <label class="nod__field">
+ <span>Title</span>
+ <input v-model="title" type="text" class="nod__in" placeholder="My overview" @keyup.enter="submit" />
+ </label>
+ <label class="nod__field">
+ <span>Description (optional)</span>
+ <textarea v-model="description" class="nod__in nod__in--ta" rows="2" placeholder="Short, one-paragraph description shown under the dashboard title." />
+ </label>
+ <div v-if="error" class="nod__err">{{ error }}</div>
+ </div>
+ <template #footer>
+ <button class="sw-btn" type="button" @click="emit('close')">Cancel</button>
+ <button class="sw-btn is-primary" type="button" @click="submit">Create</button>
+ </template>
+ </Modal>
+</template>
+
+<style scoped>
+.nod { display: flex; flex-direction: column; gap: 10px; }
+.nod__field { display: flex; flex-direction: column; gap: 3px; }
+.nod__field > span {
+ font-size: 9.5px; text-transform: uppercase; letter-spacing: 0.08em;
+ color: var(--sw-fg-3); font-weight: 600;
+}
+.nod__in {
+ background: var(--sw-bg-1); border: 1px solid var(--sw-line);
+ color: var(--sw-fg-0); font: inherit; font-size: 11.5px;
+ padding: 4px 6px; border-radius: 4px;
+}
+.nod__in--mono { font-family: var(--sw-mono); }
+.nod__in--ta {
+ width: 100%; box-sizing: border-box; min-height: 56px;
+ padding: 8px 10px; resize: vertical; line-height: 1.5;
+ font-family: var(--sw-sans); font-size: 12px;
+}
+.nod__err { font-size: 11px; color: var(--sw-err); }
+</style>
diff --git a/apps/ui/src/features/admin/overview-templates/OverviewEditCanvas.vue b/apps/ui/src/features/admin/overview-templates/OverviewEditCanvas.vue
new file mode 100644
index 0000000..d13a430
--- /dev/null
+++ b/apps/ui/src/features/admin/overview-templates/OverviewEditCanvas.vue
@@ -0,0 +1,670 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<!--
+ Interactive edit canvas — the LEFT pane of the overview editor. Renders
+ the dashboard's section-broken widget grid with the REAL overview widget
+ primitives (Metric / KpiTile / MetricComposite) fed deterministic mock
+ data, so the layout reads pixel-for-pixel like the live page. On top of
+ that read-only preview it layers the editor affordances the live page
+ doesn't have:
+
+ - click a cell / section-break / page header to SELECT it (the drawer
+ edits the selection); the inner preview is pointer-events:none so a
+ click selects rather than following a widget's link.
+ - HTML5 drag to REORDER widgets within the flat widgets array.
+ - a corner handle to RESIZE (drag updates span / rowSpan).
+ - an inline "+ Add widget" composer that gates a new widget on
+ (type, width, height) before appending it with per-type defaults.
+
+ Mutations that reorder / add reassign the whole dashboard via
+ `update:modelValue`; resize mutates the widget object in place (it's the
+ same reactive reference the parent holds).
+-->
+<script setup lang="ts">
+import { computed, reactive, ref } from 'vue';
+import type { OverviewDashboard, OverviewWidget } from '@skywalking-horizon-ui/api-client';
+import KpiTileWidget from '@/render/widgets/KpiTileWidget.vue';
+import MetricWidget from '@/render/widgets/MetricWidget.vue';
+import MetricCompositeWidget from '@/render/widgets/MetricCompositeWidget.vue';
+import { mockAlarms, mockKpiValues, mockNumber } from './widget-mock';
+import { META_SEL } from './constants';
+
+const props = defineProps<{
+ modelValue: OverviewDashboard;
+ selectedWidgetId: string | null;
+}>();
+
+const emit = defineEmits<{
+ 'update:modelValue': [dash: OverviewDashboard];
+ 'select-widget': [id: string];
+}>();
+
+function selectWidget(id: string): void {
+ emit('select-widget', id);
+}
+
+interface PreviewSection {
+ cols: number;
+ /** The section-break widget that opened this section (its id + title),
+ * or null for the implicit first section. Lets the canvas render the
+ * section-break as a selectable header. */
+ sb: OverviewWidget | null;
+ widgets: OverviewWidget[];
+}
+const previewSections = computed<PreviewSection[]>(() => {
+ const out: PreviewSection[] = [];
+ let cur: PreviewSection | null = null;
+ for (const w of props.modelValue.widgets) {
+ if (w.type === 'section-break') {
+ cur = { cols: w.cols ?? 12, sb: w, widgets: [] };
+ out.push(cur);
+ continue;
+ }
+ if (!cur) {
+ cur = { cols: 12, sb: null, widgets: [] };
+ out.push(cur);
+ }
+ cur.widgets.push(w);
+ }
+ return out;
+});
+
+function widgetKindLabel(type: OverviewWidget['type']): string {
+ switch (type) {
+ case 'metric-composite': return 'Composite metrics';
+ case 'section-break': return 'Section break';
+ case 'metric': return 'Metric';
+ case 'topology': return 'Topology';
+ case 'alarms': return 'Alarms';
+ case 'kpi-tile': return 'KPI tile';
+ default: return type;
+ }
+}
+
+/** Grid placement for one preview cell — span/rowSpan within the
+ * section's column count. Same clamps as the live renderer
+ * (OverviewDashboardView.widgetStyle): span ∈ [1, cols], rowSpan ∈ [1, 8]. */
+function previewCellStyle(w: OverviewWidget, cols: number): Record<string, string> {
+ return {
+ gridColumn: `span ${Math.min(cols, Math.max(1, w.span ?? cols))}`,
+ gridRow: `span ${Math.min(8, Math.max(1, w.rowSpan ?? 1))}`,
+ };
+}
+
+const dragId = ref<string | null>(null);
+function onWidgetDragStart(e: DragEvent, id: string): void {
+ dragId.value = id;
+ if (e.dataTransfer) e.dataTransfer.effectAllowed = 'move';
+}
+function onWidgetDrop(targetId: string): void {
+ const d = props.modelValue;
+ if (!d || !dragId.value || dragId.value === targetId) {
+ dragId.value = null;
+ return;
+ }
+ const ws = [...d.widgets];
+ const from = ws.findIndex((w) => w.id === dragId.value);
+ const to = ws.findIndex((w) => w.id === targetId);
+ dragId.value = null;
+ if (from < 0 || to < 0) return;
+ const [moved] = ws.splice(from, 1);
+ ws.splice(to, 0, moved!);
+ emit('update:modelValue', { ...d, widgets: ws });
+}
+
+const resize = reactive({ active: false, id: '', startX: 0, startY: 0, startSpan: 4, startRowSpan: 1, cellW: 1, cellH: 96, cols: 12 });
+function onResizeStart(e: MouseEvent, w: OverviewWidget, cols: number): void {
+ e.preventDefault();
+ e.stopPropagation();
+ const grid = (e.target as HTMLElement).closest('.ot__pv-grid') as HTMLElement | null;
+ if (!grid) return;
+ const gap = 6;
+ const cellW = (grid.getBoundingClientRect().width - gap * (cols - 1)) / cols;
+ resize.active = true;
+ resize.id = w.id;
+ resize.startX = e.clientX;
+ resize.startY = e.clientY;
+ resize.startSpan = w.span ?? 4;
+ resize.startRowSpan = w.rowSpan ?? 1;
+ resize.cellW = cellW + gap;
+ resize.cellH = 96 + gap;
+ resize.cols = cols;
+ selectWidget(w.id);
+ window.addEventListener('mousemove', onResizeMove);
+ window.addEventListener('mouseup', onResizeEnd);
+}
+function onResizeMove(e: MouseEvent): void {
+ if (!resize.active || !props.modelValue) return;
+ const span = Math.max(1, Math.min(resize.cols, resize.startSpan + Math.round((e.clientX - resize.startX) / resize.cellW)));
+ const rowSpan = Math.max(1, Math.min(8, resize.startRowSpan + Math.round((e.clientY - resize.startY) / resize.cellH)));
+ const w = props.modelValue.widgets.find((x) => x.id === resize.id);
+ if (w && (w.span !== span || w.rowSpan !== rowSpan)) {
+ w.span = span;
+ w.rowSpan = rowSpan;
+ }
+}
+function onResizeEnd(): void {
+ resize.active = false;
+ window.removeEventListener('mousemove', onResizeMove);
+ window.removeEventListener('mouseup', onResizeEnd);
+}
+
+/* Small inline form that gates a new widget on (type, width, height)
+ * — the operator picks those first per the spec, then the widget
+ * is appended with sensible defaults and the existing per-widget
+ * editor handles everything else. */
+const WIDGET_TYPE_OPTIONS: ReadonlyArray<{ type: OverviewWidget['type']; label: string }> = [
+ { type: 'section-break', label: 'Section break' },
+ { type: 'metric', label: 'Metric' },
+ { type: 'topology', label: 'Topology' },
+ { type: 'alarms', label: 'Alarms' },
+ { type: 'kpi-tile', label: 'KPI tile (number + metrics)' },
+ { type: 'metric-composite', label: 'Composite metrics (mixed)' },
+];
+
+const composerOpen = ref(false);
+const composerType = ref<OverviewWidget['type']>('metric');
+const composerSpan = ref<number>(3);
+const composerRowSpan = ref<number>(1);
+
+function openComposer(): void {
+ composerOpen.value = true;
+ /* Default sizing matches the most common shape per type so the
+ * operator doesn't have to remember "topology wants 9x6" etc. */
+ composerType.value = 'metric';
+ composerSpan.value = 3;
+ composerRowSpan.value = 1;
+}
+function cancelComposer(): void {
+ composerOpen.value = false;
+}
+
+/** Auto-id: `<type>_<n>` where n increments to avoid collisions with
+ * any existing widget id in the dashboard. */
+function nextWidgetId(type: string): string {
+ const existing = new Set(props.modelValue.widgets.map((w) => w.id));
+ let n = 1;
+ while (existing.has(`${type}_${n}`)) n++;
+ return `${type}_${n}`;
+}
+
+/** Per-type seed values — title + any required type-specific fields
+ * so the new widget renders something sensible immediately and the
+ * save round-trip passes the BFF's zod schema. */
+function widgetDefaults(type: OverviewWidget['type']): Partial<OverviewWidget> {
+ switch (type) {
+ case 'section-break':
+ return { title: 'New section', cols: 12 };
+ case 'metric':
+ return { title: 'New metric', mqe: '', aggregation: 'avg' };
+ case 'topology':
+ return { title: 'Topology' };
+ case 'alarms':
+ return { title: 'Active alarms', limit: 10 };
+ case 'kpi-tile':
+ return { title: 'KPI tile', kpis: [], showCount: false };
+ case 'metric-composite':
+ return { title: 'Composite metrics', kpis: [] };
+ default:
+ return { title: 'New widget' };
+ }
+}
+
+function createWidget(): void {
+ const type = composerType.value;
+ const defaults = widgetDefaults(type);
+ const widget: OverviewWidget = {
+ id: nextWidgetId(type),
+ title: defaults.title ?? 'New widget',
+ type,
+ span: type === 'section-break' ? undefined : composerSpan.value,
+ rowSpan: type === 'section-break' ? undefined : composerRowSpan.value,
+ ...defaults,
+ };
+ emit('update:modelValue', { ...props.modelValue, widgets: [...props.modelValue.widgets, widget] });
+ composerOpen.value = false;
+ selectWidget(widget.id);
+}
+</script>
+
+<template>
+ <!-- Canvas: mock-data widget grid. Click a widget to edit it in the
+ drawer; only the live "Preview ▾" page uses real OAP data. -->
+ <div class="ot__canvas-pane ot__preview">
+ <div class="ot__canvas-hint">layout + mock data · click a widget to edit · the live page uses real data</div>
+ <!-- Page heading preview — the dashboard title + description as
+ they render on the live overview page. Click to edit the
+ dashboard meta in the drawer, like any widget. -->
+ <header
+ class="ot__canvas-title"
+ :class="{ 'ot__cw--sel': selectedWidgetId === META_SEL }"
+ @click="selectWidget(META_SEL)"
+ >
+ <h2>{{ modelValue.title || modelValue.id }}</h2>
+ <p v-if="modelValue.description" class="ot__canvas-desc">{{ modelValue.description }}</p>
+ </header>
+ <div
+ v-for="(sec, si) in previewSections"
+ :key="si"
+ class="ot__pv-section"
+ >
+ <!-- Section break (a.k.a. line-break / text header) — a real
+ selectable widget; click to edit its title + columns. -->
+ <div
+ v-if="sec.sb"
+ class="ot__pv-section-head ot__pv-sb"
+ :class="{ 'ot__cw--sel': selectedWidgetId === sec.sb.id, 'ot__cw--drag': dragId === sec.sb.id }"
+ draggable="true"
+ @click="selectWidget(sec.sb.id)"
+ @dragstart="onWidgetDragStart($event, sec.sb.id)"
+ @dragend="dragId = null"
+ @dragover.prevent
+ @drop.prevent="onWidgetDrop(sec.sb.id)"
+ >
+ <span class="ot__pv-sb-tag">section</span>
+ <span class="ot__pv-sb-title">{{ sec.sb.title || '(untitled section)' }}</span>
+ <span class="ot__pv-sb-cols">{{ sec.cols }} cols</span>
+ </div>
+ <div
+ class="ot__pv-grid"
+ :style="{ gridTemplateColumns: `repeat(${sec.cols}, minmax(0, 1fr))` }"
+ >
+ <!-- Each widget is wrapped in a selectable cell. The inner
+ preview (the real overview component, mock data) is
+ pointer-events:none so a click selects the widget for
+ editing instead of following KpiTileWidget's link. -->
+ <div
+ v-for="w in sec.widgets"
+ :key="w.id"
+ class="ot__cw"
+ :class="{ 'ot__cw--sel': selectedWidgetId === w.id, 'ot__cw--drag': dragId === w.id }"
+ :style="previewCellStyle(w, sec.cols)"
+ draggable="true"
+ @click="selectWidget(w.id)"
+ @dragstart="onWidgetDragStart($event, w.id)"
+ @dragend="dragId = null"
+ @dragover.prevent
+ @drop.prevent="onWidgetDrop(w.id)"
+ >
+ <MetricWidget
+ v-if="w.type === 'metric'"
+ :title="w.title"
+ :tip="w.tip"
+ :value="mockNumber(w.id)"
+ :unit="w.unit"
+ />
+ <KpiTileWidget
+ v-else-if="w.type === 'kpi-tile'"
+ :title="w.title"
+ :tip="w.tip"
+ :layer="w.layer"
+ :show-count="w.showCount ?? false"
+ :count="mockNumber(w.id, 30)"
+ :kpis="w.kpis ?? []"
+ :kpi-values="mockKpiValues(w)"
+ />
+ <MetricCompositeWidget
+ v-else-if="w.type === 'metric-composite'"
+ :title="w.title"
+ :tip="w.tip"
+ :layer="w.layer"
+ :kpis="w.kpis ?? []"
+ :kpi-values="mockKpiValues(w)"
+ />
+ <article v-else class="ot__pv-card">
+ <div class="ot__pv-card-head">
+ <span class="ot__pv-kind">{{ widgetKindLabel(w.type) }}</span>
+ <span v-if="w.layer" class="ot__pv-layer">{{ w.layer }}</span>
+ </div>
+ <div class="ot__pv-title">{{ w.title }}</div>
+ <template v-if="w.type === 'alarms'">
+ <!-- Mock alarm rows — same shape as AlarmsWidget so
+ the operator sees the rail layout, not just a
+ count. Severity / message / scope all mocked. -->
+ <ul class="ot__pv-alarms">
+ <li
+ v-for="row in mockAlarms(w.id, Math.min(w.limit ?? 10, 3))"
+ :key="row.key"
+ class="ot__pv-alarm"
+ >
+ <span class="ot__pv-alarm-dot" :class="row.firing ? 'is-err' : 'is-ok'" />
+ <div class="ot__pv-alarm-text">
+ <div class="ot__pv-alarm-msg">{{ row.msg }}</div>
+ <div class="ot__pv-alarm-scope">{{ row.scope }}</div>
+ </div>
+ <span class="ot__pv-alarm-time mono">{{ row.since }}</span>
+ </li>
+ </ul>
+ <div class="ot__pv-sub">
+ mock · max {{ w.limit ?? 10 }} rows
+ </div>
+ </template>
+ <template v-else-if="w.type === 'topology'">
+ <!-- Mock topology SVG: a small graph of circles + edges
+ so the operator sees the shape of a topology tile
+ in this widget's slot. -->
+ <svg class="ot__pv-topo-svg" viewBox="0 0 220 100" preserveAspectRatio="xMidYMid meet">
+ <line x1="40" y1="20" x2="110" y2="50" />
+ <line x1="40" y1="80" x2="110" y2="50" />
+ <line x1="110" y1="50" x2="180" y2="25" />
+ <line x1="110" y1="50" x2="180" y2="75" />
+ <line x1="180" y1="25" x2="180" y2="75" />
+ <circle cx="40" cy="20" r="8" />
+ <circle cx="40" cy="80" r="8" />
+ <circle cx="110" cy="50" r="10" class="hub" />
+ <circle cx="180" cy="25" r="8" />
+ <circle cx="180" cy="75" r="8" />
+ </svg>
+ <div class="ot__pv-sub">topology · {{ w.layer ?? '—' }}</div>
+ </template>
+ </article>
+ <!-- Corner resize handle (drag to change span / rowSpan). -->
+ <span
+ class="ot__cw-resize"
+ title="Drag to resize"
+ @mousedown="onResizeStart($event, w, sec.cols)"
+ />
+ </div>
+ </div>
+ </div>
+ <div v-if="previewSections.length === 0" class="ot__pv-empty">
+ No widgets yet — add one below.
+ </div>
+ <!-- Add-widget composer, on the canvas (the drawer only shows
+ when a widget is selected). -->
+ <div class="ot__add-widget">
+ <button
+ v-if="!composerOpen"
+ type="button"
+ class="ot__add-trigger"
+ @click="openComposer"
+ >
+ + Add widget
+ </button>
+ <article v-else class="ot__widget ot__composer">
+ <header class="ot__widget-head">
+ <span class="ot__widget-kind">New widget</span>
+ </header>
+ <div class="ot__row">
+ <label class="ot__field">
+ <span>Type</span>
+ <select v-model="composerType" class="ot__in ot__in--narrow">
+ <option v-for="opt in WIDGET_TYPE_OPTIONS" :key="opt.type" :value="opt.type">
+ {{ opt.label }}
+ </option>
+ </select>
+ </label>
+ <label v-if="composerType !== 'section-break'" class="ot__field">
+ <span>Width (span)</span>
+ <input v-model.number="composerSpan" type="number" min="1" max="12" class="ot__in ot__in--num" />
+ </label>
+ <label v-if="composerType !== 'section-break'" class="ot__field">
+ <span>Height (rows)</span>
+ <input v-model.number="composerRowSpan" type="number" min="1" max="12" class="ot__in ot__in--num" />
+ </label>
+ </div>
+ <div class="ot__composer-foot">
+ <span class="ot__composer-hint">
+ A default title + content scaffold is generated; you can edit everything after creating.
+ </span>
+ <button type="button" class="ot__btn" @click="cancelComposer">cancel</button>
+ <button type="button" class="ot__btn ot__btn--primary" @click="createWidget">create</button>
+ </div>
+ </article>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.ot__preview {
+ margin-top: 14px;
+ padding: 12px;
+ background: var(--sw-bg-2);
+ border: 1px solid var(--sw-line);
+ border-radius: 6px;
+}
+.ot__canvas-pane { order: 1; flex: 1 1 0; min-width: 0; }
+.ot__canvas-hint { font-size: 10.5px; color: var(--sw-fg-3); margin-bottom: 8px; }
+.ot__canvas-title {
+ margin-bottom: 12px; padding: 4px 6px 10px; cursor: pointer; border-radius: 6px;
+ /* Same selectable hint as the canvas cells. */
+ outline: 1px dashed var(--sw-line-2); outline-offset: 2px;
+}
+.ot__canvas-title:hover { background: var(--sw-bg-2); outline-color: var(--sw-fg-3); }
+.ot__canvas-title h2 { margin: 0; font-size: 17px; font-weight: 600; color: var(--sw-fg-0); }
+.ot__canvas-desc { margin: 4px 0 0; font-size: 12px; color: var(--sw-fg-2); line-height: 1.5; max-width: 760px; }
+
+.ot__pv-section { margin-bottom: 10px; }
+.ot__pv-section-head {
+ font-size: 10.5px;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: var(--sw-fg-2);
+ padding-bottom: 6px;
+ border-bottom: 1px dashed var(--sw-line);
+ margin-bottom: 6px;
+}
+/* Mirror the live renderer's section grid (OverviewDashboardView): fixed
+ 72px auto-rows so `rowSpan` is real height and `span` columns sit
+ side-by-side, instead of collapsing to content height (which stacks a
+ span-9 topology above a span-3 alarms rather than beside it). */
+.ot__pv-grid { display: grid; grid-auto-rows: 72px; gap: 8px; }
+/* Inner widget fills its spanned cell, like the live page (grid items
+ stretch by default; the inner component must take the full height). */
+.ot__cw > *:not(.ot__cw-resize) { height: 100%; box-sizing: border-box; }
+.ot__pv-card {
+ background: var(--sw-bg-1);
+ border: 1px solid var(--sw-line);
+ border-radius: 4px;
+ padding: 6px 8px;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ min-height: 60px;
+ overflow: hidden;
+}
+.ot__pv-card-head { display: flex; gap: 6px; align-items: baseline; }
+.ot__pv-kind {
+ font-size: 9px;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--sw-accent);
+ font-weight: 600;
+}
+.ot__pv-layer {
+ font-family: var(--sw-mono);
+ font-size: 9px;
+ color: var(--sw-fg-3);
+ margin-left: auto;
+}
+.ot__pv-title { font-size: 11px; color: var(--sw-fg-0); font-weight: 500; }
+.ot__pv-sub { font-size: 10px; color: var(--sw-fg-3); }
+/* Topology mock — SVG of a few nodes + edges. Uses currentColor /
+ * design tokens so the graph reads against the card background. */
+.ot__pv-topo-svg {
+ width: 100%;
+ flex: 1;
+ min-height: 80px;
+ max-height: 140px;
+}
+.ot__pv-topo-svg line {
+ stroke: var(--sw-line-2);
+ stroke-width: 1;
+ opacity: 0.7;
+}
+.ot__pv-topo-svg circle {
+ fill: var(--sw-bg-2);
+ stroke: var(--sw-fg-2);
+ stroke-width: 1.5;
+}
+.ot__pv-topo-svg circle.hub {
+ fill: var(--sw-accent-soft);
+ stroke: var(--sw-accent);
+}
+
+.ot__pv-alarms { list-style: none; margin: 0; padding: 0; }
+.ot__pv-alarm {
+ display: flex; align-items: flex-start; gap: 6px;
+ padding: 4px 0;
+ border-top: 1px solid var(--sw-line);
+ font-size: 10.5px;
+}
+.ot__pv-alarm:first-child { border-top: none; }
+.ot__pv-alarm-dot {
+ width: 5px; height: 5px; border-radius: 50%; margin-top: 4px; flex-shrink: 0;
+}
+.ot__pv-alarm-dot.is-err { background: var(--sw-err); }
+.ot__pv-alarm-dot.is-ok { background: var(--sw-ok); }
+.ot__pv-alarm-text { flex: 1; min-width: 0; }
+.ot__pv-alarm-msg {
+ color: var(--sw-fg-1); white-space: nowrap;
+ overflow: hidden; text-overflow: ellipsis;
+}
+.ot__pv-alarm-scope {
+ font-family: var(--sw-mono); font-size: 9px;
+ color: var(--sw-fg-3); white-space: nowrap;
+ overflow: hidden; text-overflow: ellipsis;
+}
+.ot__pv-alarm-time { color: var(--sw-fg-3); font-size: 9px; flex-shrink: 0; }
+.ot__pv-empty {
+ padding: 14px; text-align: center;
+ font-size: 11px; color: var(--sw-fg-3); font-style: italic;
+}
+
+/* Canvas cell: selectable wrapper. The inner preview is pointer-events:none
+ so clicking selects the widget (instead of following its link). */
+.ot__cw {
+ position: relative;
+ min-width: 0;
+ cursor: grab;
+ border-radius: 8px;
+ /* Dashed hint that the tile is selectable; firms up on hover, becomes a
+ solid accent outline when selected. */
+ outline: 1px dashed var(--sw-line-2);
+ outline-offset: 2px;
+}
+.ot__cw:hover { outline-color: var(--sw-fg-3); }
+.ot__cw:active { cursor: grabbing; }
+.ot__cw > * { pointer-events: none; }
+.ot__cw--sel { outline: 2px solid var(--sw-accent) !important; outline-offset: 1px; border-radius: 8px; }
+.ot__cw--drag { opacity: 0.45; }
+/* Corner resize handle — overrides the cell's pointer-events:none so it
+ can capture its own mousedown. */
+.ot__cw-resize {
+ pointer-events: auto;
+ position: absolute;
+ right: 2px;
+ bottom: 2px;
+ width: 14px;
+ height: 14px;
+ cursor: nwse-resize;
+ border-right: 2px solid var(--sw-fg-3);
+ border-bottom: 2px solid var(--sw-fg-3);
+ border-bottom-right-radius: 3px;
+ opacity: 0.5;
+}
+.ot__cw:hover .ot__cw-resize { opacity: 0.9; }
+/* Section-break rendered as a selectable header in the canvas. */
+.ot__pv-sb {
+ display: flex; align-items: center; gap: 8px; cursor: pointer;
+ border-radius: 5px; padding: 5px 8px; margin-bottom: 6px;
+ /* Same selectable hint as the canvas cells. */
+ outline: 1px dashed var(--sw-line-2); outline-offset: 2px;
+}
+.ot__pv-sb:hover { background: var(--sw-bg-2); outline-color: var(--sw-fg-3); }
+.ot__pv-sb-tag {
+ font-size: 8.5px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em;
+ color: var(--sw-accent); border: 1px solid var(--sw-accent-line, var(--sw-accent));
+ border-radius: 3px; padding: 0 4px;
+}
+.ot__pv-sb-title { flex: 1; font-weight: 600; color: var(--sw-fg-0); text-transform: none; letter-spacing: 0; }
+.ot__pv-sb-cols { font-size: 9.5px; color: var(--sw-fg-3); font-family: var(--sw-mono); }
+
+/* Field primitives reused by the composer. */
+.ot__widget {
+ background: var(--sw-bg-2);
+ border: 1px solid var(--sw-line);
+ border-radius: 6px;
+ padding: 10px 12px;
+}
+.ot__widget-head {
+ display: flex; align-items: baseline; gap: 8px;
+ margin-bottom: 8px;
+}
+.ot__widget-kind {
+ font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em;
+ color: var(--sw-accent); font-weight: 600;
+}
+.ot__row { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 6px; }
+.ot__field {
+ display: flex; flex-direction: column; gap: 3px;
+ min-width: 140px;
+}
+.ot__field > span {
+ font-size: 9.5px; text-transform: uppercase; letter-spacing: 0.08em;
+ color: var(--sw-fg-3); font-weight: 600;
+}
+.ot__in {
+ background: var(--sw-bg-1); border: 1px solid var(--sw-line);
+ color: var(--sw-fg-0); font: inherit; font-size: 11.5px;
+ padding: 4px 6px; border-radius: 4px;
+}
+.ot__in--narrow { width: 160px; }
+.ot__in--num { width: 80px; font-variant-numeric: tabular-nums; }
+
+.ot__add-widget { margin-top: 8px; }
+.ot__add-trigger {
+ width: 100%;
+ background: transparent;
+ border: 1px dashed var(--sw-line-2);
+ color: var(--sw-fg-2);
+ font: inherit;
+ font-size: 12px;
+ padding: 10px;
+ border-radius: 6px;
+ cursor: pointer;
+}
+.ot__add-trigger:hover {
+ border-color: var(--sw-accent);
+ color: var(--sw-fg-0);
+ background: var(--sw-bg-2);
+}
+.ot__composer { border-color: var(--sw-accent); }
+.ot__composer-foot {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-top: 10px;
+}
+.ot__composer-hint {
+ font-size: 10.5px;
+ color: var(--sw-fg-3);
+ flex: 1;
+ font-style: italic;
+}
+.ot__btn {
+ background: var(--sw-bg-1); border: 1px solid var(--sw-line-2);
+ color: var(--sw-fg-0); font: inherit; font-size: 12px;
+ padding: 6px 14px; border-radius: 4px; cursor: pointer;
+}
+.ot__btn:not(:disabled):hover { background: var(--sw-bg-2); }
+.ot__btn--primary {
+ background: var(--sw-accent); border-color: var(--sw-accent);
+ color: #0a0d12; font-weight: 600;
+}
+.ot__btn--primary:not(:disabled):hover { background: var(--sw-accent-light, #fb923c); }
+</style>
diff --git a/apps/ui/src/features/admin/overview-templates/OverviewTemplatesAdmin.vue b/apps/ui/src/features/admin/overview-templates/OverviewTemplatesAdmin.vue
index 8fb7ef8..0cd15cd 100644
--- a/apps/ui/src/features/admin/overview-templates/OverviewTemplatesAdmin.vue
+++ b/apps/ui/src/features/admin/overview-templates/OverviewTemplatesAdmin.vue
@@ -36,15 +36,11 @@
decisions, not config tweaks.
-->
<script setup lang="ts">
-import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, watch, watchEffect } from 'vue';
+import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch, watchEffect } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { useQuery } from '@tanstack/vue-query';
-import type {
- OverviewDashboard,
- OverviewKpi,
- OverviewWidget,
-} from '@skywalking-horizon-ui/api-client';
+import type { OverviewDashboard } from '@skywalking-horizon-ui/api-client';
import { bff, BffApiError } from '@/api/client';
import type { OverviewTemplateSummary } from '@/api/scopes/overview';
import { useLocalTemplateEdits, overviewEditName } from '@/controls/localTemplateEdits';
@@ -55,16 +51,13 @@ import { useLayers } from '@/shell/useLayers';
import SyncStatusBanner from '@/features/admin/_shared/SyncStatusBanner.vue';
import { refreshConfigBundle } from '@/controls/configBundle';
import { stableStringify } from '@/utils/stableJson';
-import TemplateStatusBadge from '@/features/admin/_shared/TemplateStatusBadge.vue';
-import MqeExpressionInput from '@/features/admin/_shared/MqeExpressionInput.vue';
+import TemplatePicker, { type TemplatePickerEntry } from '@/features/admin/_shared/TemplatePicker.vue';
import { useTemplateSync } from '@/features/admin/_shared/useTemplateSync';
-// Real overview widget primitives — the preview renders these with mock
-// data so it matches the live page pixel-for-pixel (no bespoke copy).
-import KpiTileWidget from '@/render/widgets/KpiTileWidget.vue';
-import MetricWidget from '@/render/widgets/MetricWidget.vue';
-import MetricCompositeWidget from '@/render/widgets/MetricCompositeWidget.vue';
import Modal from '@/features/operate/_shared/Modal.vue';
import MonacoDiff from '@/features/operate/_shared/MonacoDiff.vue';
+import OverviewEditCanvas from './OverviewEditCanvas.vue';
+import OverviewWidgetDrawer from './OverviewWidgetDrawer.vue';
+import NewOverviewDashboardModal from './NewOverviewDashboardModal.vue';
// OAP UI-template sync status for the Overview kind. Drives the
// page-level banner + read-only mode + per-row badge lookup.
@@ -151,7 +144,6 @@ const dashboards = computed(() => [
]);
const selectedId = ref<string>('');
-const selectedDash = computed(() => dashboards.value.find((d) => d.id === selectedId.value) ?? null);
// True when the selected dashboard exists on the server (disk/remote) — a
// local-only draft has no server detail to fetch, so the detail query must
// stay disabled for it (it would 404).
@@ -159,45 +151,28 @@ const isServerBacked = computed(() =>
serverDashboards.value.some((d) => d.id === selectedId.value),
);
-// Top dropdown picker (replaces the left list — same pattern as the layer
-// dashboards switcher). Filterable; "+ New dashboard" lives inside it.
-const listDropdownOpen = ref(false);
-const listSearch = ref('');
-const divergedOnly = ref(false);
-const localOnly = ref(false);
+// Top dashboard picker — the shared TemplatePicker chip + dropdown (same
+// component the Translations page uses). Filterable + Diverged / Local
+// filters live inside it; "+ New dashboard" sits beside it.
function isDivergedRow(id: string): boolean {
const s = sync.badgeFor(`horizon.overview.${id}`);
return s === 'diverged' || s === 'bundled-fallback';
}
-const divergedCount = computed(() => dashboards.value.filter((d) => isDivergedRow(d.id)).length);
-const localDraftCount = computed(() => dashboards.value.filter((d) => hasLocalDraftFor(d.id)).length);
-
-// Auto-uncheck the picker filter when its underlying set drops to
-// zero. Without this the operator can hit Reset / Push / Sync — which
-// removes the matching row from the filtered set — and end up stuck
-// on an empty list with the checkbox itself disabled (since
-// divergedCount / localDraftCount === 0). Same guard as the Layer
-// Dashboards admin page.
-watch(divergedCount, (n) => { if (n === 0) divergedOnly.value = false; });
-watch(localDraftCount, (n) => { if (n === 0) localOnly.value = false; });
-const filteredDashboards = computed(() => {
- const q = listSearch.value.trim().toLowerCase();
- return dashboards.value.filter((d) => {
- if (divergedOnly.value && !isDivergedRow(d.id)) return false;
- if (localOnly.value && !hasLocalDraftFor(d.id)) return false;
- if (!q) return true;
- return d.title.toLowerCase().includes(q) || d.id.toLowerCase().includes(q);
- });
-});
-function pickDashboard(id: string): void {
- selectedId.value = id;
- listDropdownOpen.value = false;
-}
/** Whether a dashboard id has an unpublished local browser draft — drives
* the "local" badge in the picker. */
function hasLocalDraftFor(id: string): boolean {
return localEdits.has(overviewEditName(id));
}
+const pickerEntries = computed<TemplatePickerEntry[]>(() =>
+ dashboards.value.map((d) => ({
+ value: d.id,
+ label: d.title,
+ key: d.id,
+ syncBadge: sync.badgeFor(`horizon.overview.${d.id}`),
+ hasLocalDraft: hasLocalDraftFor(d.id),
+ isDiverged: isDivergedRow(d.id),
+ })),
+);
/* Auto-select rule: if nothing is selected (cold start), pick the
* first dashboard. If the currently-selected id disappears from the
* list (just deleted by the operator), fall back to the new first.
@@ -219,27 +194,20 @@ watchEffect(() => {
}
});
-// ── New-dashboard composer ─────────────────────────────────────────
const newDashOpen = ref(false);
-const newDashId = ref('');
-const newDashTitle = ref('');
-const newDashDescription = ref('');
const newDashError = ref<string | null>(null);
function openNewDash(): void {
newDashOpen.value = true;
- newDashId.value = '';
- newDashTitle.value = '';
- newDashDescription.value = '';
newDashError.value = null;
}
function cancelNewDash(): void {
newDashOpen.value = false;
newDashError.value = null;
}
-function createDash(): void {
- const id = newDashId.value.trim();
- const title = newDashTitle.value.trim();
+function createDash(payload: { id: string; title: string; description: string }): void {
+ const id = payload.id.trim();
+ const title = payload.title.trim();
if (!id) {
newDashError.value = 'id is required';
return;
@@ -263,7 +231,7 @@ function createDash(): void {
// Create mirrors edit: write a LOCAL browser draft, don't touch the
// server. The dashboard is immediately selectable + previewable; "Check
// diff & push" publishes it to OAP (create-or-update, server-side).
- const description = newDashDescription.value.trim();
+ const description = payload.description.trim();
const dash: OverviewDashboard = {
id,
title,
@@ -276,7 +244,6 @@ function createDash(): void {
setFlash(`created local draft · ${id} — edit, preview, then “Check diff & push”.`);
}
-// ── Preview pane ──────────────────────────────────────────────────
/* Lightweight layout preview — recreates the dashboard's grid + a
* summary card per widget (kind / title / KPI labels) so the
* operator can see "is the layout right?" without saving + tab-
@@ -286,16 +253,14 @@ function createDash(): void {
* widget components — that would require running the orchestrator
* against mock OAP data — but enough to validate placement + scope. */
// Canvas selection: the editor is one page now — a mock-data widget grid
-// (canvas, left) + a drawer (right) that edits the clicked widget. Mirrors
-// the layer dashboards editor.
-// Sentinel id for the dashboard-meta "widget" (title + description). Real
-// widget ids never collide with it.
-const META_SEL = '__meta__';
+// (OverviewEditCanvas, left) + a drawer (OverviewWidgetDrawer, right) that
+// edits the clicked widget. The canvas owns its own drag / resize / add-
+// widget composer; the parent owns only the shared selection + the array-
+// level reorder / remove the drawer reaches back into.
const selectedWidgetId = ref<string | null>(null);
function selectWidget(id: string): void {
selectedWidgetId.value = id;
}
-// Drop the selection when the dashboard changes.
watch(selectedId, () => {
selectedWidgetId.value = null;
});
@@ -316,162 +281,6 @@ onBeforeUnmount(() => window.removeEventListener('keydown', onEditorKey));
// cache so even a fresh fetch sees live OAP state.
onMounted(() => void refreshConfigBundle({ force: true }));
-// ── Canvas drag-reorder (HTML5 DnD over the flat widgets array) ─────
-const dragId = ref<string | null>(null);
-function onWidgetDragStart(e: DragEvent, id: string): void {
- dragId.value = id;
- if (e.dataTransfer) e.dataTransfer.effectAllowed = 'move';
-}
-function onWidgetDrop(targetId: string): void {
- const d = draft.value;
- if (!d || !dragId.value || dragId.value === targetId) {
- dragId.value = null;
- return;
- }
- const ws = [...d.widgets];
- const from = ws.findIndex((w) => w.id === dragId.value);
- const to = ws.findIndex((w) => w.id === targetId);
- dragId.value = null;
- if (from < 0 || to < 0) return;
- const [moved] = ws.splice(from, 1);
- ws.splice(to, 0, moved!);
- draft.value = { ...d, widgets: ws };
-}
-
-// ── Canvas corner-resize (drag updates span / rowSpan) ──────────────
-const resize = reactive({ active: false, id: '', startX: 0, startY: 0, startSpan: 4, startRowSpan: 1, cellW: 1, cellH: 96, cols: 12 });
-function onResizeStart(e: MouseEvent, w: OverviewWidget, cols: number): void {
- e.preventDefault();
- e.stopPropagation();
- const grid = (e.target as HTMLElement).closest('.ot__pv-grid') as HTMLElement | null;
- if (!grid) return;
- const gap = 6;
- const cellW = (grid.getBoundingClientRect().width - gap * (cols - 1)) / cols;
- resize.active = true;
- resize.id = w.id;
- resize.startX = e.clientX;
- resize.startY = e.clientY;
- resize.startSpan = w.span ?? 4;
- resize.startRowSpan = w.rowSpan ?? 1;
- resize.cellW = cellW + gap;
- resize.cellH = 96 + gap;
- resize.cols = cols;
- selectWidget(w.id);
- window.addEventListener('mousemove', onResizeMove);
- window.addEventListener('mouseup', onResizeEnd);
-}
-function onResizeMove(e: MouseEvent): void {
- if (!resize.active || !draft.value) return;
- const span = Math.max(1, Math.min(resize.cols, resize.startSpan + Math.round((e.clientX - resize.startX) / resize.cellW)));
- const rowSpan = Math.max(1, Math.min(8, resize.startRowSpan + Math.round((e.clientY - resize.startY) / resize.cellH)));
- const w = draft.value.widgets.find((x) => x.id === resize.id);
- if (w && (w.span !== span || w.rowSpan !== rowSpan)) {
- w.span = span;
- w.rowSpan = rowSpan;
- }
-}
-function onResizeEnd(): void {
- resize.active = false;
- window.removeEventListener('mousemove', onResizeMove);
- window.removeEventListener('mouseup', onResizeEnd);
-}
-
-interface PreviewSection {
- cols: number;
- /** The section-break widget that opened this section (its id + title),
- * or null for the implicit first section. Lets the canvas render the
- * section-break as a selectable header. */
- sb: OverviewWidget | null;
- widgets: OverviewWidget[];
-}
-const previewSections = computed<PreviewSection[]>(() => {
- if (!draft.value) return [];
- const out: PreviewSection[] = [];
- let cur: PreviewSection | null = null;
- for (const w of draft.value.widgets) {
- if (w.type === 'section-break') {
- cur = { cols: w.cols ?? 12, sb: w, widgets: [] };
- out.push(cur);
- continue;
- }
- if (!cur) {
- cur = { cols: 12, sb: null, widgets: [] };
- out.push(cur);
- }
- cur.widgets.push(w);
- }
- return out;
-});
-
-/* Cheap deterministic mock values — keyed by widget id + KPI label
- * so re-renders return the same number (no jitter while editing).
- * Hash-based so different ids look different but each is stable. */
-function hash(s: string): number {
- let h = 0;
- for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0;
- return h;
-}
-function mockNumber(seed: string, max = 999): number {
- return hash(seed) % max;
-}
-function mockPercent(seed: string): number {
- return 10 + (hash(seed) % 85);
-}
-/** Mock alarm rows for the preview's alarms widget. Deterministic
- * per widget id so the rows don't churn while editing. */
-const MOCK_ALARM_MSGS = [
- 'Response time of service mesh-svr::cart is more than 20ms.',
- 'JVM old-gen GC > 5s/min on agent::orders',
- 'p95 SLA below threshold for service mesh-svr::reviews',
-];
-const MOCK_ALARM_SCOPES = ['Service · mesh-svr::cart', 'Instance · pod-2 of agent::orders', 'Service · reviews'];
-const MOCK_ALARM_AGES = ['2m', '14m', '47m'];
-function mockAlarms(seed: string, n: number): Array<{
- key: string;
- firing: boolean;
- msg: string;
- scope: string;
- since: string;
-}> {
- const out: Array<{ key: string; firing: boolean; msg: string; scope: string; since: string }> = [];
- const cap = Math.max(0, Math.min(n, MOCK_ALARM_MSGS.length));
- for (let i = 0; i < cap; i++) {
- out.push({
- key: `${seed}::${i}`,
- firing: (hash(seed + i) % 4) !== 0, // ~3/4 firing
- msg: MOCK_ALARM_MSGS[i]!,
- scope: MOCK_ALARM_SCOPES[i]!,
- since: MOCK_ALARM_AGES[i]!,
- });
- }
- return out;
-}
-
-/** Mock value per KPI label for the real widget components — percent /
- * progress-bar rows get a 0-100 value, everything else a plain number.
- * Keyed by widget id + label so it's stable across re-renders. */
-function mockKpiValues(w: OverviewWidget): Record<string, number | null> {
- const out: Record<string, number | null> = {};
- for (const k of w.kpis ?? []) {
- out[k.label] =
- k.unit === '%' || k.style === 'progress-bar'
- ? mockPercent(w.id + k.label)
- : mockNumber(w.id + k.label, k.max ?? 999);
- }
- return out;
-}
-/** Grid placement for one preview cell — span/rowSpan within the
- * section's column count. */
-function previewCellStyle(w: OverviewWidget, cols: number): Record<string, string> {
- // Same clamps as the live renderer (OverviewDashboardView.widgetStyle):
- // span ∈ [1, cols], rowSpan ∈ [1, 8].
- return {
- gridColumn: `span ${Math.min(cols, Math.max(1, w.span ?? cols))}`,
- gridRow: `span ${Math.min(8, Math.max(1, w.rowSpan ?? 1))}`,
- };
-}
-
-// ── Delete current dashboard ───────────────────────────────────────
// A local-only draft (never pushed) is truly removed from the browser —
// a real hard delete, it was never on OAP. Anything on OAP (bundled or
// remote-only) is soft-disabled, because OAP has no hard DELETE; a
@@ -830,7 +639,6 @@ async function pushToOap(): Promise<void> {
}
}
-// ── Import / Export ────────────────────────────────────────────────
// Export downloads the IN-USE version (what end users render: remote,
// else bundled) — never the editor draft. A never-published local-only
// draft has no in-use version, so Export is disabled there.
@@ -870,32 +678,7 @@ async function onImportFile(): Promise<void> {
);
}
-// ── KPI row helpers (kpi-tile only) ────────────────────────────────
-function addKpi(w: OverviewWidget): void {
- const next = [...(w.kpis ?? []), { label: 'new KPI', mqe: '' } as OverviewKpi];
- w.kpis = next;
-}
-function removeKpi(w: OverviewWidget, idx: number): void {
- if (!w.kpis) return;
- w.kpis = w.kpis.filter((_, i) => i !== idx);
-}
-function moveKpi(w: OverviewWidget, idx: number, dir: -1 | 1): void {
- if (!w.kpis) return;
- const next = [...w.kpis];
- const j = idx + dir;
- if (j < 0 || j >= next.length) return;
- [next[idx], next[j]] = [next[j], next[idx]];
- w.kpis = next;
-}
-/* Switching a KPI to progress-bar makes `max` mandatory — seed a
- * sensible default if it isn't set so the BFF doesn't 400 on save. */
-function onKpiStyleChange(k: OverviewKpi): void {
- if (k.style === 'progress-bar' && (k.max === undefined || k.max === null)) {
- k.max = 100;
- }
-}
-
-// ── Widget reorder + delete ────────────────────────────────────────
+// Widget reorder + delete — the drawer reaches back into these.
function moveWidget(idx: number, dir: -1 | 1): void {
if (!draft.value) return;
const next = [...draft.value.widgets];
@@ -911,98 +694,6 @@ function removeWidget(idx: number): void {
draft.value = { ...draft.value, widgets: next };
if (removed && removed.id === selectedWidgetId.value) selectedWidgetId.value = null;
}
-
-// ── Add-widget composer ────────────────────────────────────────────
-/* Small inline form that gates a new widget on (type, width, height)
- * — the operator picks those first per the spec, then the widget
- * is appended with sensible defaults and the existing per-widget
- * editor handles everything else. */
-const composerOpen = ref(false);
-const composerType = ref<OverviewWidget['type']>('metric');
-const composerSpan = ref<number>(3);
-const composerRowSpan = ref<number>(1);
-
-function openComposer(): void {
- composerOpen.value = true;
- /* Default sizing matches the most common shape per type so the
- * operator doesn't have to remember "topology wants 9x6" etc. */
- composerType.value = 'metric';
- composerSpan.value = 3;
- composerRowSpan.value = 1;
-}
-function cancelComposer(): void {
- composerOpen.value = false;
-}
-
-/** Auto-id: `<type>_<n>` where n increments to avoid collisions with
- * any existing widget id in the dashboard. */
-function nextWidgetId(type: string): string {
- const existing = new Set(draft.value?.widgets.map((w) => w.id) ?? []);
- let n = 1;
- while (existing.has(`${type}_${n}`)) n++;
- return `${type}_${n}`;
-}
-
-/** Per-type seed values — title + any required type-specific fields
- * so the new widget renders something sensible immediately and the
- * save round-trip passes the BFF's zod schema. */
-function widgetDefaults(type: OverviewWidget['type']): Partial<OverviewWidget> {
- switch (type) {
- case 'section-break':
- return { title: 'New section', cols: 12 };
- case 'metric':
- return { title: 'New metric', mqe: '', aggregation: 'avg' };
- case 'topology':
- return { title: 'Topology' };
- case 'alarms':
- return { title: 'Active alarms', limit: 10 };
- case 'kpi-tile':
- return { title: 'KPI tile', kpis: [], showCount: false };
- case 'metric-composite':
- return { title: 'Composite metrics', kpis: [] };
- default:
- return { title: 'New widget' };
- }
-}
-
-function createWidget(): void {
- if (!draft.value) return;
- const type = composerType.value;
- const defaults = widgetDefaults(type);
- const widget: OverviewWidget = {
- id: nextWidgetId(type),
- title: defaults.title ?? 'New widget',
- type,
- span: type === 'section-break' ? undefined : composerSpan.value,
- rowSpan: type === 'section-break' ? undefined : composerRowSpan.value,
- ...defaults,
- };
- draft.value = { ...draft.value, widgets: [...draft.value.widgets, widget] };
- composerOpen.value = false;
- selectedWidgetId.value = widget.id; // open the drawer to finish editing it
-}
-
-// ── Widget meta ────────────────────────────────────────────────────
-const WIDGET_TYPE_OPTIONS: ReadonlyArray<{ type: OverviewWidget['type']; label: string }> = [
- { type: 'section-break', label: 'Section break' },
- { type: 'metric', label: 'Metric' },
- { type: 'topology', label: 'Topology' },
- { type: 'alarms', label: 'Alarms' },
- { type: 'kpi-tile', label: 'KPI tile (number + metrics)' },
- { type: 'metric-composite', label: 'Composite metrics (mixed)' },
-];
-
-function widgetKindLabel(type: OverviewWidget['type']): string {
- switch (type) {
- case 'metric-composite': return 'Composite metrics';
- case 'section-break': return 'Section break';
- case 'metric': return 'Metric';
- case 'topology': return 'Topology';
- case 'alarms': return 'Alarms';
- case 'kpi-tile': return 'KPI tile';
- default: return type;
- }
-}
</script>
<template>
@@ -1028,101 +719,25 @@ function widgetKindLabel(type: OverviewWidget['type']): string {
<div v-if="listQuery.isPending.value" class="ot__empty">loading…</div>
<div v-else class="ot__main">
- <!-- Top dashboard picker — filterable dropdown (same pattern as the
- layer dashboards switcher); "+ New" lives inside it. -->
+ <!-- Top dashboard picker — shared TemplatePicker chip + dropdown
+ (search + Diverged / Local filters + refresh live inside it);
+ "+ New dashboard" sits beside it. -->
<div class="ot__picker-bar">
- <div class="ot__dd">
- <button type="button" class="ot__dd-btn" @click="listDropdownOpen = !listDropdownOpen">
- <span class="ot__dd-title">{{ selectedDash?.title || 'Select dashboard' }}</span>
- <code v-if="selectedDash" class="ot__dd-id">{{ selectedDash.id }}</code>
- <span v-if="selectedId && hasLocalDraftFor(selectedId)" class="ot__local-badge" title="Unpublished local draft">local</span>
- <TemplateStatusBadge v-if="selectedId" :status="sync.badgeFor(`horizon.overview.${selectedId}`)" />
- <span class="caret" :class="{ open: listDropdownOpen }">›</span>
- </button>
- <template v-if="listDropdownOpen">
- <div class="ot__dd-backdrop" @click="listDropdownOpen = false" />
- <div class="ot__dd-pop">
- <!-- Browse mode: search + filters + list. Hidden while the
- New-dashboard composer is open so the form stands alone. -->
- <template v-if="!newDashOpen">
- <div class="ot__dd-search">
- <input v-model="listSearch" type="text" placeholder="Search dashboards…" autocomplete="off" spellcheck="false" />
- </div>
- <div class="ot__dd-filters">
- <label class="ot__dd-filter" :class="{ on: divergedOnly }">
- <input v-model="divergedOnly" type="checkbox" :disabled="divergedCount === 0" />
- Diverged<span v-if="divergedCount" class="ot__dd-fc">{{ divergedCount }}</span>
- </label>
- <label class="ot__dd-filter" :class="{ on: localOnly }">
- <input v-model="localOnly" type="checkbox" :disabled="localDraftCount === 0" />
- Local<span v-if="localDraftCount" class="ot__dd-fc local">{{ localDraftCount }}</span>
- </label>
- </div>
- <div class="ot__dd-list">
- <button
- v-for="d in filteredDashboards"
- :key="d.id"
- type="button"
- class="ot__dd-item"
- :class="{ active: d.id === selectedId }"
- @click="pickDashboard(d.id)"
- >
- <span class="ot__dd-item-title">{{ d.title }}</span>
- <code>{{ d.id }}</code>
- <span class="ot__dd-item-count">{{ d.widgetCount }}w</span>
- <span v-if="!d.editable" class="ot__readonly-tag">no source</span>
- <span v-if="hasLocalDraftFor(d.id)" class="ot__local-badge" title="Unpublished local draft">local</span>
- <TemplateStatusBadge :status="sync.badgeFor(`horizon.overview.${d.id}`)" />
- </button>
- <p v-if="filteredDashboards.length === 0" class="ot__dd-empty">No dashboards match.</p>
- </div>
- <div class="ot__dd-new">
- <button
- type="button"
- class="ot__btn"
- :disabled="sync.readOnly.value"
- :title="sync.readOnly.value ? 'OAP unreachable — cannot create' : ''"
- @click="openNewDash"
- >+ New dashboard</button>
- </div>
- <div class="ot__dd-foot">
- <span class="ot__picker-count">{{ dashboards.length }} dashboard{{ dashboards.length === 1 ? '' : 's' }}</span>
- <button
- type="button"
- class="ot__btn ot__refresh-btn"
- :disabled="refreshingFromRemote || sync.readOnly.value"
- :title="sync.readOnly.value
- ? 'OAP unreachable — cannot refresh'
- : 'Force the BFF to re-read every UI-template from OAP (clears the 30s cache)'"
- @click="refreshFromRemote"
- >{{ refreshingFromRemote ? 'refreshing…' : 'refresh from remote' }}</button>
- </div>
- </template>
-
- <!-- Create mode: self-contained form (replaces the list). -->
- <div v-else class="ot__newdash">
- <div class="ot__newdash-head">New dashboard</div>
- <label class="ot__field ot__field--wide">
- <span>Id (used as the name — must be unique)</span>
- <input v-model="newDashId" type="text" class="ot__in ot__in--mono" placeholder="my-overview" @keyup.enter="createDash" />
- </label>
- <label class="ot__field ot__field--wide">
- <span>Title</span>
- <input v-model="newDashTitle" type="text" class="ot__in" placeholder="My overview" @keyup.enter="createDash" />
- </label>
- <label class="ot__field ot__field--wide">
- <span>Description (optional)</span>
- <textarea v-model="newDashDescription" class="ot__in ot__in--ta" rows="2" placeholder="Short, one-paragraph description shown under the dashboard title." />
- </label>
- <div v-if="newDashError" class="ot__newdash-err">{{ newDashError }}</div>
- <div class="ot__newdash-foot">
- <button type="button" class="ot__btn" @click="cancelNewDash">cancel</button>
- <button type="button" class="ot__btn ot__btn--primary" @click="createDash">create</button>
- </div>
- </div>
- </div>
- </template>
- </div>
+ <TemplatePicker
+ :model-value="selectedId"
+ :entries="pickerEntries"
+ kind-label="dashboards"
+ :refreshing="refreshingFromRemote"
+ @update:model-value="(v) => (selectedId = v)"
+ @refresh="refreshFromRemote"
+ />
+ <button
+ type="button"
+ class="ot__btn"
+ :disabled="sync.readOnly.value"
+ :title="sync.readOnly.value ? 'OAP unreachable — cannot create' : ''"
+ @click="openNewDash"
+ >+ New dashboard</button>
</div>
<section class="ot__detail">
@@ -1266,431 +881,38 @@ function widgetKindLabel(type: OverviewWidget['type']): string {
<!-- One-page editor: mock-data widget grid (canvas, left) +
drawer (right) that edits the clicked widget. -->
<div class="ot__editor-split" :class="{ 'has-sel': !!selectedWidgetId }">
-
- <aside v-if="selectedWidgetId" class="ot__drawer-pane ot__widgets">
- <div class="ot__drawer-head">
- <span class="ot__drawer-title">{{ selectedWidgetId === META_SEL ? 'Dashboard meta' : 'Edit widget' }}</span>
- <button type="button" class="ot__drawer-close" title="Close (Esc)" @click="selectedWidgetId = null">✕</button>
- </div>
- <!-- Dashboard-level meta: title + description. -->
- <section v-if="selectedWidgetId === META_SEL" class="ot__meta">
- <header class="ot__meta-head">
- <span class="ot__meta-kicker">Dashboard meta</span>
- <span class="ot__meta-hint">Shown in the sidebar and as the page sub-heading.</span>
- </header>
- <label class="ot__field">
- <span>Title</span>
- <input v-model="draft.title" type="text" class="ot__in" />
- </label>
- <label class="ot__field ot__field--wide">
- <span>Description</span>
- <textarea
- v-model="draft.description"
- class="ot__in ot__in--ta"
- rows="3"
- placeholder="Short, one-paragraph description shown under the dashboard title."
- />
- </label>
- </section>
-
- <article
- v-for="(w, wi) in draft.widgets"
- v-show="w.id === selectedWidgetId"
- :key="w.id"
- class="ot__widget"
- :class="`ot__widget--${w.type}`"
- >
- <!-- Header: type kicker + widget id + move/delete row actions. -->
- <header class="ot__widget-head">
- <span class="ot__widget-kind">{{ widgetKindLabel(w.type) }}</span>
- <code class="ot__widget-id">{{ w.id }}</code>
- <span class="ot__widget-actions">
- <button
- type="button"
- class="ot__arrow"
- :disabled="wi === 0"
- title="Move up"
- @click="moveWidget(wi, -1)"
- >‹</button>
- <button
- type="button"
- class="ot__arrow"
- :disabled="wi === draft.widgets.length - 1"
- title="Move down"
- @click="moveWidget(wi, 1)"
- >›</button>
- <button
- type="button"
- class="ot__del"
- title="Remove widget"
- @click="removeWidget(wi)"
- >×</button>
- </span>
- </header>
-
- <!-- 1. Size (width / height) first per the spec — layout
- decisions before content. section-break has no
- per-cell span (it spans the whole row), so we show
- the grid `cols` field there instead. -->
- <div class="ot__row">
- <label v-if="w.type === 'section-break'" class="ot__field">
- <span>Columns (grid)</span>
- <input v-model.number="w.cols" type="number" min="1" max="12" class="ot__in ot__in--num" />
- </label>
- <template v-else>
- <label class="ot__field">
- <span>Width (span)</span>
- <input v-model.number="w.span" type="number" min="1" max="12" class="ot__in ot__in--num" />
- </label>
- <label class="ot__field">
- <span>Height (rows)</span>
- <input v-model.number="w.rowSpan" type="number" min="1" max="12" class="ot__in ot__in--num" />
- </label>
- </template>
- </div>
-
- <!-- 2. Title + tip. -->
- <div class="ot__row">
- <label class="ot__field ot__field--wide">
- <span>Title</span>
- <input v-model="w.title" type="text" class="ot__in" />
- </label>
- <label v-if="w.type !== 'section-break'" class="ot__field ot__field--wide">
- <span>Tip</span>
- <input v-model="w.tip" type="text" class="ot__in" placeholder="(optional)" />
- </label>
- </div>
-
- <!-- 3. Layer — universal for data widgets. -->
- <div v-if="w.type !== 'section-break'" class="ot__row">
- <label class="ot__field">
- <span>Layer</span>
- <select v-model="w.layer" class="ot__in ot__in--narrow">
- <option :value="undefined">— any —</option>
- <option v-for="k in layerOptions" :key="k" :value="k">{{ k }}</option>
- </select>
- </label>
- </div>
-
- <!-- metric: mqe + unit + aggregation -->
- <div v-if="w.type === 'metric'" class="ot__row">
- <label class="ot__field ot__field--wide">
- <span>MQE</span>
- <MqeExpressionInput v-model="w.mqe" placeholder="service_cpm" title="Widget MQE" />
- </label>
- <label class="ot__field">
- <span>Unit</span>
- <input v-model="w.unit" type="text" class="ot__in ot__in--narrow" placeholder="rpm / ms / %" />
- </label>
- <label class="ot__field">
- <span>Aggregation</span>
- <select v-model="w.aggregation" class="ot__in ot__in--narrow">
- <option :value="undefined">—</option>
- <option value="avg">avg</option>
- <option value="sum">sum</option>
- </select>
- </label>
- </div>
-
- <!-- alarms: limit -->
- <div v-if="w.type === 'alarms'" class="ot__row">
- <label class="ot__field">
- <span>Row limit</span>
- <input v-model.number="w.limit" type="number" min="1" max="100" class="ot__in ot__in--num" />
- </label>
- </div>
-
- <!-- kpi-tile / metric-composite: KPI rows. -->
- <template v-if="w.type === 'kpi-tile' || w.type === 'metric-composite'">
- <div v-if="w.type === 'kpi-tile'" class="ot__row">
- <label class="ot__field">
- <span>Show service count</span>
- <input type="checkbox" v-model="w.showCount" />
- </label>
- </div>
- <div class="ot__kpis">
- <div class="ot__kpis-head">
- <span>KPI rows ({{ (w.kpis ?? []).length }})</span>
- <button type="button" class="ot__add-btn" @click="addKpi(w)">+ add row</button>
- </div>
- <div v-if="(w.kpis ?? []).length === 0" class="ot__kpis-empty">
- No KPI rows. Add one to surface a metric on the tile.
- </div>
- <!-- One card per KPI. The drawer is narrow (sidebar-only),
- so fields stack vertically instead of a wide table
- row that truncates every column. -->
- <ul v-else class="ot__kpi-cards">
- <li v-for="(k, i) in w.kpis ?? []" :key="i" class="ot__kpi-card">
- <div class="ot__kpi-card-head">
- <span class="ot__kpi-card-idx">#{{ i + 1 }}</span>
- <div class="ot__kpi-card-ord">
- <button
- type="button"
- class="ot__arrow"
- title="Move up"
- :disabled="i === 0"
- @click="moveKpi(w, i, -1)"
- >↑</button>
- <button
- type="button"
- class="ot__arrow"
- title="Move down"
- :disabled="i === (w.kpis ?? []).length - 1"
- @click="moveKpi(w, i, 1)"
- >↓</button>
- </div>
- <button type="button" class="ot__del" title="Remove row" @click="removeKpi(w, i)">×</button>
- </div>
- <label class="ot__field ot__field--full">
- <span>Label</span>
- <input v-model="k.label" type="text" class="ot__in" />
- </label>
- <label class="ot__field ot__field--full">
- <span>Source</span>
- <select v-model="k.source" class="ot__in">
- <option :value="undefined">mqe</option>
- <option value="mqe">mqe</option>
- <option value="service-count">service-count</option>
- </select>
- </label>
- <label v-if="(k.source ?? 'mqe') === 'mqe'" class="ot__field ot__field--full">
- <span>MQE</span>
- <MqeExpressionInput v-model="k.mqe" title="KPI MQE" />
- </label>
- <p v-else class="ot__none">Value comes from the service count (listServices) — no MQE.</p>
- <div class="ot__kpi-card-grid">
- <label class="ot__field">
- <span>Unit</span>
- <input v-model="k.unit" type="text" class="ot__in" />
- </label>
- <label class="ot__field">
- <span>Aggr</span>
- <select v-model="k.aggregation" class="ot__in">
- <option :value="undefined">—</option>
- <option value="avg">avg</option>
- <option value="sum">sum</option>
- </select>
- </label>
- <label class="ot__field">
- <span>Style</span>
- <select v-model="k.style" class="ot__in" @change="onKpiStyleChange(k)">
- <option :value="undefined">number</option>
- <option value="number">number</option>
- <option value="progress-bar">progress-bar</option>
- </select>
- </label>
- <label v-if="k.style === 'progress-bar'" class="ot__field">
- <span>Max</span>
- <input
- v-model.number="k.max"
- type="number"
- min="0"
- step="any"
- class="ot__in"
- placeholder="100"
- />
- </label>
- </div>
- </li>
- </ul>
- </div>
- </template>
- </article>
-
- </aside>
-
- <!-- Canvas: mock-data widget grid (left). Click a widget to edit
- it in the drawer; only the live "Preview ▾" page uses real
- OAP data. -->
- <div class="ot__canvas-pane ot__preview">
- <div class="ot__canvas-hint">layout + mock data · click a widget to edit · the live page uses real data</div>
- <!-- Page heading preview — the dashboard title + description as
- they render on the live overview page. Click to edit the
- dashboard meta in the drawer, like any widget. -->
- <header
- class="ot__canvas-title"
- :class="{ 'ot__cw--sel': selectedWidgetId === META_SEL }"
- @click="selectWidget(META_SEL)"
- >
- <h2>{{ draft.title || draft.id }}</h2>
- <p v-if="draft.description" class="ot__canvas-desc">{{ draft.description }}</p>
- </header>
- <div
- v-for="(sec, si) in previewSections"
- :key="si"
- class="ot__pv-section"
- >
- <!-- Section break (a.k.a. line-break / text header) — a real
- selectable widget; click to edit its title + columns. -->
- <div
- v-if="sec.sb"
- class="ot__pv-section-head ot__pv-sb"
- :class="{ 'ot__cw--sel': selectedWidgetId === sec.sb.id, 'ot__cw--drag': dragId === sec.sb.id }"
- draggable="true"
- @click="selectWidget(sec.sb.id)"
- @dragstart="onWidgetDragStart($event, sec.sb.id)"
- @dragend="dragId = null"
- @dragover.prevent
- @drop.prevent="onWidgetDrop(sec.sb.id)"
- >
- <span class="ot__pv-sb-tag">section</span>
- <span class="ot__pv-sb-title">{{ sec.sb.title || '(untitled section)' }}</span>
- <span class="ot__pv-sb-cols">{{ sec.cols }} cols</span>
- </div>
- <div
- class="ot__pv-grid"
- :style="{ gridTemplateColumns: `repeat(${sec.cols}, minmax(0, 1fr))` }"
- >
- <!-- Each widget is wrapped in a selectable cell. The inner
- preview (the real overview component, mock data) is
- pointer-events:none so a click selects the widget for
- editing instead of following KpiTileWidget's link. -->
- <div
- v-for="w in sec.widgets"
- :key="w.id"
- class="ot__cw"
- :class="{ 'ot__cw--sel': selectedWidgetId === w.id, 'ot__cw--drag': dragId === w.id }"
- :style="previewCellStyle(w, sec.cols)"
- draggable="true"
- @click="selectWidget(w.id)"
- @dragstart="onWidgetDragStart($event, w.id)"
- @dragend="dragId = null"
- @dragover.prevent
- @drop.prevent="onWidgetDrop(w.id)"
- >
- <MetricWidget
- v-if="w.type === 'metric'"
- :title="w.title"
- :tip="w.tip"
- :value="mockNumber(w.id)"
- :unit="w.unit"
- />
- <KpiTileWidget
- v-else-if="w.type === 'kpi-tile'"
- :title="w.title"
- :tip="w.tip"
- :layer="w.layer"
- :show-count="w.showCount ?? false"
- :count="mockNumber(w.id, 30)"
- :kpis="w.kpis ?? []"
- :kpi-values="mockKpiValues(w)"
- />
- <MetricCompositeWidget
- v-else-if="w.type === 'metric-composite'"
- :title="w.title"
- :tip="w.tip"
- :layer="w.layer"
- :kpis="w.kpis ?? []"
- :kpi-values="mockKpiValues(w)"
- />
- <article v-else class="ot__pv-card">
- <div class="ot__pv-card-head">
- <span class="ot__pv-kind">{{ widgetKindLabel(w.type) }}</span>
- <span v-if="w.layer" class="ot__pv-layer">{{ w.layer }}</span>
- </div>
- <div class="ot__pv-title">{{ w.title }}</div>
- <!-- Per-type mock body. -->
- <template v-if="w.type === 'alarms'">
- <!-- Mock alarm rows — same shape as AlarmsWidget so
- the operator sees the rail layout, not just a
- count. Severity / message / scope all mocked. -->
- <ul class="ot__pv-alarms">
- <li
- v-for="row in mockAlarms(w.id, Math.min(w.limit ?? 10, 3))"
- :key="row.key"
- class="ot__pv-alarm"
- >
- <span class="ot__pv-alarm-dot" :class="row.firing ? 'is-err' : 'is-ok'" />
- <div class="ot__pv-alarm-text">
- <div class="ot__pv-alarm-msg">{{ row.msg }}</div>
- <div class="ot__pv-alarm-scope">{{ row.scope }}</div>
- </div>
- <span class="ot__pv-alarm-time mono">{{ row.since }}</span>
- </li>
- </ul>
- <div class="ot__pv-sub">
- mock · max {{ w.limit ?? 10 }} rows
- </div>
- </template>
- <template v-else-if="w.type === 'topology'">
- <!-- Mock topology SVG: a small graph of circles + edges
- so the operator sees the shape of a topology tile
- in this widget's slot. -->
- <svg class="ot__pv-topo-svg" viewBox="0 0 220 100" preserveAspectRatio="xMidYMid meet">
- <line x1="40" y1="20" x2="110" y2="50" />
- <line x1="40" y1="80" x2="110" y2="50" />
- <line x1="110" y1="50" x2="180" y2="25" />
- <line x1="110" y1="50" x2="180" y2="75" />
- <line x1="180" y1="25" x2="180" y2="75" />
- <circle cx="40" cy="20" r="8" />
- <circle cx="40" cy="80" r="8" />
- <circle cx="110" cy="50" r="10" class="hub" />
- <circle cx="180" cy="25" r="8" />
- <circle cx="180" cy="75" r="8" />
- </svg>
- <div class="ot__pv-sub">topology · {{ w.layer ?? '—' }}</div>
- </template>
- </article>
- <!-- Corner resize handle (drag to change span / rowSpan). -->
- <span
- class="ot__cw-resize"
- title="Drag to resize"
- @mousedown="onResizeStart($event, w, sec.cols)"
- />
- </div>
- </div>
- </div>
- <div v-if="previewSections.length === 0" class="ot__pv-empty">
- No widgets yet — add one below.
- </div>
- <!-- Add-widget composer, on the canvas (the drawer only shows
- when a widget is selected). -->
- <div class="ot__add-widget">
- <button
- v-if="!composerOpen"
- type="button"
- class="ot__add-trigger"
- @click="openComposer"
- >
- + Add widget
- </button>
- <article v-else class="ot__widget ot__composer">
- <header class="ot__widget-head">
- <span class="ot__widget-kind">New widget</span>
- </header>
- <div class="ot__row">
- <label class="ot__field">
- <span>Type</span>
- <select v-model="composerType" class="ot__in ot__in--narrow">
- <option v-for="opt in WIDGET_TYPE_OPTIONS" :key="opt.type" :value="opt.type">
- {{ opt.label }}
- </option>
- </select>
- </label>
- <label v-if="composerType !== 'section-break'" class="ot__field">
- <span>Width (span)</span>
- <input v-model.number="composerSpan" type="number" min="1" max="12" class="ot__in ot__in--num" />
- </label>
- <label v-if="composerType !== 'section-break'" class="ot__field">
- <span>Height (rows)</span>
- <input v-model.number="composerRowSpan" type="number" min="1" max="12" class="ot__in ot__in--num" />
- </label>
- </div>
- <div class="ot__composer-foot">
- <span class="ot__composer-hint">
- A default title + content scaffold is generated; you can edit everything after creating.
- </span>
- <button type="button" class="ot__btn" @click="cancelComposer">cancel</button>
- <button type="button" class="ot__btn ot__btn--primary" @click="createWidget">create</button>
- </div>
- </article>
- </div>
- </div>
+ <OverviewWidgetDrawer
+ v-if="selectedWidgetId"
+ :draft="draft"
+ :selected-widget-id="selectedWidgetId"
+ :layer-options="layerOptions"
+ @close="selectedWidgetId = null"
+ @move="moveWidget"
+ @remove="removeWidget"
+ @update:title="(v) => { if (draft) draft.title = v; }"
+ @update:description="(v) => { if (draft) draft.description = v; }"
+ />
+ <OverviewEditCanvas
+ :model-value="draft"
+ :selected-widget-id="selectedWidgetId"
+ @update:model-value="(d) => (draft = d)"
+ @select-widget="selectWidget"
+ />
</div>
</template>
</section>
</div>
+ <!-- New-dashboard composer. Create mirrors edit — the parent writes a
+ LOCAL browser draft and validates uniqueness, pushing any failure
+ back via :error. -->
+ <NewOverviewDashboardModal
+ :open="newDashOpen"
+ :error="newDashError"
+ @close="cancelNewDash"
+ @submit="createDash"
+ />
+
<!-- Push confirm: shows the remote → local diff before publishing. -->
<Modal :open="pushDiffOpen" title="Publish local → OAP?" width="min(1100px, 94vw)" @close="pushDiffOpen = false">
<p class="ot__push-lede">
@@ -1759,6 +981,7 @@ function widgetKindLabel(type: OverviewWidget['type']): string {
.ot__push-diff { height: 50vh; min-height: 320px; border: 1px solid var(--sw-line); border-radius: 6px; overflow: hidden; }
</style>
+
<style scoped>
.ot { padding: 20px 20px 60px; max-width: 1400px; margin: 0 auto; }
.ot__head { margin-bottom: 18px; }
@@ -1776,94 +999,10 @@ function widgetKindLabel(type: OverviewWidget['type']): string {
.ot__no-remote { text-align: left; max-width: 600px; padding: 24px; }
.ot__no-remote h3 { margin: 0 0 8px; font-size: 14px; color: var(--sw-fg-0); }
.ot__no-remote p { margin: 0 0 16px; font-size: 12px; line-height: 1.6; color: var(--sw-fg-2); }
-.ot__toolbar { display: flex; justify-content: flex-end; margin: 8px 0; }
.ot__main { display: flex; flex-direction: column; gap: 12px; }
.ot__picker-bar { display: flex; align-items: center; gap: 10px; }
-.ot__picker-count { font-size: 10.5px; color: var(--sw-fg-3); }
-.ot__dd-foot {
- display: flex;
- align-items: center;
- gap: 10px;
- padding: 8px 10px;
- border-top: 1px solid var(--sw-line-2);
-}
-.ot__dd-foot .ot__refresh-btn { margin-left: auto; font-size: 11px; height: 24px; padding: 0 8px; }
-.ot__dd { position: relative; display: flex; }
-.ot__dd-btn {
- display: inline-flex; align-items: center; gap: 8px;
- height: 32px; padding: 0 12px;
- background: var(--sw-bg-2); border: 1px solid var(--sw-line-2); border-radius: 6px;
- color: var(--sw-fg-0); font: inherit; font-size: 13px; font-weight: 600; cursor: pointer; min-width: 240px;
-}
-.ot__dd-btn:hover { background: var(--sw-bg-3); }
-.ot__dd-btn .ot__dd-title { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 280px; }
-.ot__dd-btn .ot__dd-id { font-family: var(--sw-mono); font-size: 10px; color: var(--sw-fg-3); background: var(--sw-bg-1); padding: 1px 5px; border-radius: 3px; }
-.ot__dd-btn .caret { margin-left: auto; transform: rotate(90deg); transition: transform 0.15s; font-size: 12px; }
-.ot__dd-btn .caret.open { transform: rotate(-90deg); }
-.ot__dd-backdrop { position: fixed; inset: 0; z-index: 40; }
-.ot__dd-pop {
- position: absolute; top: calc(100% + 4px); left: 0; z-index: 41;
- width: min(80vw, 560px); max-height: 60vh; display: flex; flex-direction: column;
- background: var(--sw-bg-1); border: 1px solid var(--sw-line); border-radius: 8px;
- box-shadow: 0 12px 32px -8px rgba(0,0,0,0.5); padding: 6px;
-}
-.ot__dd-filters { display: flex; gap: 12px; padding: 2px 4px 8px; border-bottom: 1px solid var(--sw-line); margin-bottom: 4px; }
-.ot__dd-filter { display: inline-flex; align-items: center; gap: 5px; font-size: 11px; color: var(--sw-fg-2); cursor: pointer; }
-.ot__dd-filter.on { color: var(--sw-fg-0); }
-.ot__dd-filter input:disabled { cursor: not-allowed; }
-.ot__dd-fc { padding: 0 5px; border-radius: 8px; background: var(--sw-warn, var(--sw-accent)); color: #1a1a1a; font-size: 9.5px; font-weight: 700; }
-.ot__dd-search { padding: 2px 2px 6px; }
-.ot__dd-search input {
- width: 100%; box-sizing: border-box; height: 30px; padding: 0 8px;
- background: var(--sw-bg-2); border: 1px solid var(--sw-line-2); border-radius: 5px; color: var(--sw-fg-0); font: inherit; font-size: 12px;
-}
-.ot__dd-search input:focus { outline: none; border-color: var(--sw-accent); }
-.ot__dd-list { overflow-y: auto; display: flex; flex-direction: column; gap: 2px; }
-.ot__dd-item {
- display: flex; align-items: center; gap: 8px; width: 100%;
- padding: 7px 9px; border: none; background: transparent; border-radius: 5px;
- color: var(--sw-fg-1); font: inherit; font-size: 12px; text-align: left; cursor: pointer;
-}
-.ot__dd-item:hover { background: var(--sw-bg-2); color: var(--sw-fg-0); }
-.ot__dd-item.active { background: var(--sw-accent-soft); color: var(--sw-accent-2); box-shadow: inset 2px 0 0 var(--sw-accent); }
-.ot__dd-item-title { flex: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
-.ot__dd-item code { font-family: var(--sw-mono); font-size: 10px; color: var(--sw-fg-3); }
-.ot__dd-item-count { font-family: var(--sw-mono); font-size: 10px; color: var(--sw-fg-3); }
-.ot__dd-empty { padding: 10px; font-size: 11px; color: var(--sw-fg-3); }
-.ot__local-badge {
- flex: 0 0 auto; font-size: 9px; font-weight: 700; letter-spacing: 0.06em;
- text-transform: uppercase; color: #1a1a1a; background: var(--sw-warn, #f59e0b);
- padding: 1px 6px; border-radius: 8px;
-}
-.ot__dd-new { border-top: 1px solid var(--sw-line); margin-top: 4px; padding: 8px 2px 2px; }
-.ot__split { display: grid; grid-template-columns: 280px 1fr; gap: 16px; align-items: start; }
-.ot__list {
- list-style: none; margin: 0; padding: 0;
- background: var(--sw-bg-1); border: 1px solid var(--sw-line); border-radius: 8px; overflow: hidden;
-}
-.ot__list-item { padding: 10px 14px; border-bottom: 1px solid var(--sw-line); cursor: pointer; }
-.ot__list-item:last-child { border-bottom: none; }
-.ot__list-item:hover { background: var(--sw-bg-2); }
-.ot__list-item.active { background: var(--sw-bg-3); box-shadow: inset 2px 0 0 var(--sw-accent); }
-.ot__list-item.readonly { opacity: 0.6; cursor: not-allowed; }
-.ot__list-title { font-size: 12.5px; font-weight: 500; color: var(--sw-fg-0); }
-.ot__list-meta { margin-top: 4px; display: flex; gap: 8px; font-size: 10.5px; color: var(--sw-fg-3); }
-.ot__list-meta code { font-family: var(--sw-mono); color: var(--sw-fg-2); }
-.ot__readonly-tag { color: var(--sw-warn); font-style: italic; }
-.ot__list-empty { padding: 24px; text-align: center; font-size: 12px; color: var(--sw-fg-3); }
-.ot__list-add { padding: 8px; border-top: 1px solid var(--sw-line); }
-.ot__add-trigger--list { font-size: 11.5px; padding: 6px; }
-.ot__newdash { display: flex; flex-direction: column; gap: 10px; padding: 10px 12px; }
-.ot__newdash-head {
- font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.08em;
- color: var(--sw-fg-2); padding-bottom: 8px; border-bottom: 1px solid var(--sw-line);
-}
-.ot__newdash-err { font-size: 11px; color: var(--sw-err); }
-.ot__newdash-foot {
- display: flex; gap: 8px; justify-content: flex-end;
- padding-top: 8px; border-top: 1px solid var(--sw-line);
-}
+
.ot__head-btn {
background: transparent;
border: 1px solid var(--sw-line-2);
@@ -1877,492 +1016,20 @@ function widgetKindLabel(type: OverviewWidget['type']): string {
cursor: pointer;
}
.ot__head-btn:hover { background: var(--sw-bg-2); color: var(--sw-fg-0); }
-.ot__head-btn.active { background: var(--sw-bg-3); color: var(--sw-fg-0); border-color: var(--sw-accent); }
.ot__head-btn--danger:hover {
background: transparent; color: var(--sw-err); border-color: rgba(239,68,68,0.4);
}
-/* Config / Preview tab strip. Sits between the dashboard id + the
- * delete action; consumes flex space so the delete button lands at
- * the right edge. */
-.ot__tabs {
- display: inline-flex;
- background: var(--sw-bg-2);
- border: 1px solid var(--sw-line);
- border-radius: 5px;
- padding: 2px;
- margin-left: 12px;
-}
-.ot__tab {
- background: transparent;
- border: 0;
- color: var(--sw-fg-2);
- font: inherit;
- font-size: 11px;
- font-weight: 500;
- padding: 4px 14px;
- border-radius: 3px;
- cursor: pointer;
-}
-.ot__tab:hover { color: var(--sw-fg-0); }
-.ot__tab.active {
- background: var(--sw-bg-3);
- color: var(--sw-fg-0);
- font-weight: 600;
-}
-
-/* Preview pane */
-.ot__preview {
- margin-top: 14px;
- padding: 12px;
- background: var(--sw-bg-2);
- border: 1px solid var(--sw-line);
- border-radius: 6px;
-}
-.ot__preview-head {
- display: flex; align-items: baseline; gap: 8px;
- margin-bottom: 10px;
-}
-.ot__preview-head h3 {
- font-size: 11px;
- text-transform: uppercase;
- letter-spacing: 0.08em;
- color: var(--sw-fg-2);
- margin: 0;
-}
-.ot__preview-hint { font-size: 10.5px; color: var(--sw-fg-3); font-style: italic; }
-.ot__pv-section { margin-bottom: 10px; }
-.ot__pv-section-head {
- font-size: 10.5px;
- text-transform: uppercase;
- letter-spacing: 0.08em;
- color: var(--sw-fg-2);
- padding-bottom: 6px;
- border-bottom: 1px dashed var(--sw-line);
- margin-bottom: 6px;
-}
-/* Mirror the live renderer's section grid (OverviewDashboardView): fixed
- 72px auto-rows so `rowSpan` is real height and `span` columns sit
- side-by-side, instead of collapsing to content height (which stacks a
- span-9 topology above a span-3 alarms rather than beside it). */
-.ot__pv-grid { display: grid; grid-auto-rows: 72px; gap: 8px; }
-/* Inner widget fills its spanned cell, like the live page (grid items
- stretch by default; the inner component must take the full height). */
-.ot__cw > *:not(.ot__cw-resize) { height: 100%; box-sizing: border-box; }
-.ot__pv-card {
- background: var(--sw-bg-1);
- border: 1px solid var(--sw-line);
- border-radius: 4px;
- padding: 6px 8px;
- display: flex;
- flex-direction: column;
- gap: 4px;
- min-height: 60px;
- overflow: hidden;
-}
-.ot__pv-card-head { display: flex; gap: 6px; align-items: baseline; }
-.ot__pv-kind {
- font-size: 9px;
- text-transform: uppercase;
- letter-spacing: 0.06em;
- color: var(--sw-accent);
- font-weight: 600;
-}
-.ot__pv-layer {
- font-family: var(--sw-mono);
- font-size: 9px;
- color: var(--sw-fg-3);
- margin-left: auto;
-}
-.ot__pv-title { font-size: 11px; color: var(--sw-fg-0); font-weight: 500; }
-.ot__pv-bignum {
- font-size: 20px; font-weight: 600; color: var(--sw-fg-0);
- font-variant-numeric: tabular-nums; margin-top: auto;
-}
-.ot__pv-bignum--err { color: var(--sw-err); }
-.ot__pv-unit { font-size: 11px; color: var(--sw-fg-3); margin-left: 4px; }
-.ot__pv-sub { font-size: 10px; color: var(--sw-fg-3); }
-.ot__pv-mqe {
- font-family: var(--sw-mono); font-size: 9px;
- color: var(--sw-fg-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
-}
-/* Topology mock — SVG of a few nodes + edges. Uses currentColor /
- * design tokens so the graph reads against the card background. */
-.ot__pv-topo-svg {
- width: 100%;
- flex: 1;
- min-height: 80px;
- max-height: 140px;
-}
-.ot__pv-topo-svg line {
- stroke: var(--sw-line-2);
- stroke-width: 1;
- opacity: 0.7;
-}
-.ot__pv-topo-svg circle {
- fill: var(--sw-bg-2);
- stroke: var(--sw-fg-2);
- stroke-width: 1.5;
-}
-.ot__pv-topo-svg circle.hub {
- fill: var(--sw-accent-soft);
- stroke: var(--sw-accent);
-}
-
-/* Alarms mock rows */
-.ot__pv-alarms { list-style: none; margin: 0; padding: 0; }
-.ot__pv-alarm {
- display: flex; align-items: flex-start; gap: 6px;
- padding: 4px 0;
- border-top: 1px solid var(--sw-line);
- font-size: 10.5px;
-}
-.ot__pv-alarm:first-child { border-top: none; }
-.ot__pv-alarm-dot {
- width: 5px; height: 5px; border-radius: 50%; margin-top: 4px; flex-shrink: 0;
-}
-.ot__pv-alarm-dot.is-err { background: var(--sw-err); }
-.ot__pv-alarm-dot.is-ok { background: var(--sw-ok); }
-.ot__pv-alarm-text { flex: 1; min-width: 0; }
-.ot__pv-alarm-msg {
- color: var(--sw-fg-1); white-space: nowrap;
- overflow: hidden; text-overflow: ellipsis;
-}
-.ot__pv-alarm-scope {
- font-family: var(--sw-mono); font-size: 9px;
- color: var(--sw-fg-3); white-space: nowrap;
- overflow: hidden; text-overflow: ellipsis;
-}
-.ot__pv-alarm-time { color: var(--sw-fg-3); font-size: 9px; flex-shrink: 0; }
-
-/* Composite metrics mock — same number-grid + bar-grid split the
- * real MetricCompositeWidget uses. */
-.ot__pv-num-grid {
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(72px, 1fr));
- gap: 4px;
-}
-.ot__pv-num-tile {
- display: flex; flex-direction: column; gap: 1px;
- padding: 5px 7px;
- background: var(--sw-bg-2);
- border: 1px solid var(--sw-line);
- border-radius: 4px;
-}
-.ot__pv-num-val {
- font-size: 14px; font-weight: 600; color: var(--sw-fg-0);
- font-variant-numeric: tabular-nums;
-}
-.ot__pv-num-unit { font-size: 9px; color: var(--sw-fg-3); margin-left: 2px; }
-.ot__pv-num-label {
- font-size: 9px; color: var(--sw-fg-3);
- text-transform: uppercase; letter-spacing: 0.05em;
-}
-.ot__pv-bar-grid {
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
- gap: 6px;
- margin-top: 6px;
-}
-.ot__pv-bar-row { display: flex; flex-direction: column; gap: 3px; }
-.ot__pv-bar-head { display: flex; justify-content: space-between; align-items: baseline; }
-.ot__pv-bar-label { font-size: 10px; color: var(--sw-fg-2); }
-.ot__pv-bar-val {
- font-size: 10.5px; font-weight: 600; color: var(--sw-fg-0);
- font-variant-numeric: tabular-nums;
-}
-.ot__pv-bar {
- height: 3px; background: var(--sw-bg-2);
- border-radius: 2px; overflow: hidden;
-}
-.ot__pv-bar-fill { display: block; height: 100%; background: var(--sw-accent); }
-.ot__pv-empty {
- padding: 14px; text-align: center;
- font-size: 11px; color: var(--sw-fg-3); font-style: italic;
-}
-
.ot__detail { background: var(--sw-bg-1); border: 1px solid var(--sw-line); border-radius: 8px; padding: 16px; }
/* One-page editor: canvas (left, mock-data grid) + drawer (right, editor).
- DOM order is drawer-then-canvas; `order` flips them visually. */
+ The panes set their own `order` / `flex` from inside their components. */
.ot__editor-split { display: flex; gap: 14px; align-items: flex-start; }
-.ot__canvas-pane { order: 1; flex: 1 1 0; min-width: 0; }
-.ot__drawer-pane {
- order: 2;
- flex: 0 0 380px;
- max-width: 380px;
- position: sticky;
- top: 12px;
- max-height: calc(100vh - 90px);
- overflow-y: auto;
- border-left: 1px solid var(--sw-line);
- padding-left: 14px;
-}
-.ot__canvas-hint { font-size: 10.5px; color: var(--sw-fg-3); margin-bottom: 8px; }
-.ot__canvas-title {
- margin-bottom: 12px; padding: 4px 6px 10px; cursor: pointer; border-radius: 6px;
- /* Same selectable hint as the canvas cells. */
- outline: 1px dashed var(--sw-line-2); outline-offset: 2px;
-}
-.ot__canvas-title:hover { background: var(--sw-bg-2); outline-color: var(--sw-fg-3); }
-.ot__canvas-title h2 { margin: 0; font-size: 17px; font-weight: 600; color: var(--sw-fg-0); }
-.ot__canvas-desc { margin: 4px 0 0; font-size: 12px; color: var(--sw-fg-2); line-height: 1.5; max-width: 760px; }
-.ot__drawer-head { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; padding-bottom: 8px; border-bottom: 1px solid var(--sw-line); }
-.ot__drawer-title { font-size: 11px; text-transform: uppercase; letter-spacing: 0.08em; color: var(--sw-fg-2); font-weight: 600; }
-.ot__drawer-close { margin-left: auto; background: transparent; border: none; color: var(--sw-fg-3); font-size: 14px; cursor: pointer; width: 22px; height: 22px; border-radius: 4px; }
-.ot__drawer-close:hover { background: var(--sw-bg-2); color: var(--sw-fg-0); }
-/* Canvas cell: selectable wrapper. The inner preview is pointer-events:none
- so clicking selects the widget (instead of following its link). */
-.ot__cw {
- position: relative;
- min-width: 0;
- cursor: grab;
- border-radius: 8px;
- /* Dashed hint that the tile is selectable; firms up on hover, becomes a
- solid accent outline when selected. */
- outline: 1px dashed var(--sw-line-2);
- outline-offset: 2px;
-}
-.ot__cw:hover { outline-color: var(--sw-fg-3); }
-.ot__cw:active { cursor: grabbing; }
-.ot__cw > * { pointer-events: none; }
-.ot__cw--sel { outline: 2px solid var(--sw-accent) !important; outline-offset: 1px; border-radius: 8px; }
-.ot__cw--drag { opacity: 0.45; }
-/* Corner resize handle — overrides the cell's pointer-events:none so it
- can capture its own mousedown. */
-.ot__cw-resize {
- pointer-events: auto;
- position: absolute;
- right: 2px;
- bottom: 2px;
- width: 14px;
- height: 14px;
- cursor: nwse-resize;
- border-right: 2px solid var(--sw-fg-3);
- border-bottom: 2px solid var(--sw-fg-3);
- border-bottom-right-radius: 3px;
- opacity: 0.5;
-}
-.ot__cw:hover .ot__cw-resize { opacity: 0.9; }
-/* Section-break rendered as a selectable header in the canvas. */
-.ot__pv-sb {
- display: flex; align-items: center; gap: 8px; cursor: pointer;
- border-radius: 5px; padding: 5px 8px; margin-bottom: 6px;
- /* Same selectable hint as the canvas cells. */
- outline: 1px dashed var(--sw-line-2); outline-offset: 2px;
-}
-.ot__pv-sb:hover { background: var(--sw-bg-2); outline-color: var(--sw-fg-3); }
-.ot__pv-sb-tag {
- font-size: 8.5px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em;
- color: var(--sw-accent); border: 1px solid var(--sw-accent-line, var(--sw-accent));
- border-radius: 3px; padding: 0 4px;
-}
-.ot__pv-sb-title { flex: 1; font-weight: 600; color: var(--sw-fg-0); text-transform: none; letter-spacing: 0; }
-.ot__pv-sb-cols { font-size: 9.5px; color: var(--sw-fg-3); font-family: var(--sw-mono); }
.ot__detail-head { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; flex-wrap: wrap; }
.ot__head-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
-.ot__detail-subhead { display: flex; align-items: center; justify-content: flex-end; gap: 10px; margin-bottom: 12px; }
-.ot__del-note { font-size: 10.5px; color: var(--sw-fg-3); font-style: italic; }
.ot__detail-head h2 { margin: 0; font-size: 13px; font-weight: 600; }
.ot__detail-head h2 code { font-family: var(--sw-mono); color: var(--sw-fg-0); }
.ot__count { font-size: 11px; color: var(--sw-fg-3); }
-/* Per-widget card */
-.ot__widgets { display: flex; flex-direction: column; gap: 10px; }
-.ot__widget {
- background: var(--sw-bg-2);
- border: 1px solid var(--sw-line);
- border-radius: 6px;
- padding: 10px 12px;
-}
-.ot__widget--section-break { border-left: 3px solid var(--sw-accent); }
-.ot__widget-head {
- display: flex; align-items: baseline; gap: 8px;
- margin-bottom: 8px;
-}
-.ot__widget-kind {
- font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em;
- color: var(--sw-accent); font-weight: 600;
-}
-.ot__widget-id {
- font-family: var(--sw-mono); font-size: 10.5px; color: var(--sw-fg-3);
- margin-left: auto;
-}
-.ot__widget-actions { display: inline-flex; gap: 2px; }
-.ot__widget-actions .ot__arrow { width: 22px; height: 22px; }
-.ot__widget-actions .ot__del { font-size: 16px; }
-
-.ot__row { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 6px; }
-.ot__row--tight { gap: 4px; align-items: center; }
-.ot__field {
- display: flex; flex-direction: column; gap: 3px;
- min-width: 140px;
-}
-.ot__field--wide { flex: 1 1 220px; }
-.ot__field > span {
- font-size: 9.5px; text-transform: uppercase; letter-spacing: 0.08em;
- color: var(--sw-fg-3); font-weight: 600;
-}
-.ot__in {
- background: var(--sw-bg-1); border: 1px solid var(--sw-line);
- color: var(--sw-fg-0); font: inherit; font-size: 11.5px;
- padding: 4px 6px; border-radius: 4px;
-}
-.ot__in--narrow { width: 160px; }
-.ot__in--xnarrow { width: 70px; }
-.ot__in--mono { font-family: var(--sw-mono); }
-.ot__in--num { width: 80px; font-variant-numeric: tabular-nums; }
-.ot__in--xnum { width: 48px; font-variant-numeric: tabular-nums; }
-.ot__in--ta {
- /* Textarea variant of `.ot__in`. Three lines is the sweet spot for a
- description paragraph — enough to read the whole sentence without
- scrolling, not so tall it pushes the widget list down. The base
- `.ot__in` 4px vertical padding is cramped for multi-line text;
- restore comfortable line-height + padding here. */
- width: 100%;
- min-height: 72px;
- padding: 8px 10px;
- resize: vertical;
- line-height: 1.5;
- font-family: var(--sw-sans);
- font-size: 12px;
-}
-.ot__field input[type='checkbox'] { width: 14px; height: 14px; margin: 4px 0 0; cursor: pointer; }
-.ot__none { color: var(--sw-fg-3); font-size: 11px; }
-
-/* Dashboard-level meta card (sits above the widget list). */
-.ot__meta {
- background: var(--sw-bg-2);
- border: 1px solid var(--sw-line);
- border-radius: 6px;
- padding: 12px 14px;
- display: flex;
- flex-direction: column;
- gap: 10px;
-}
-.ot__meta-head {
- display: flex;
- align-items: baseline;
- gap: 10px;
-}
-.ot__meta-kicker {
- font-size: 9.5px;
- text-transform: uppercase;
- letter-spacing: 0.1em;
- color: var(--sw-fg-3);
- font-weight: 700;
-}
-.ot__meta-hint {
- font-size: 10.5px;
- color: var(--sw-fg-3);
-}
-
-/* Sub-title (description preview) in the dashboard list. */
-.ot__list-desc {
- margin-top: 3px;
- color: var(--sw-fg-2);
- font-size: 11px;
- line-height: 1.4;
- /* Clamp to two lines so long descriptions don't push the meta row
- off-screen. Falls back gracefully on browsers without -webkit-line-clamp. */
- display: -webkit-box;
- -webkit-line-clamp: 2;
- -webkit-box-orient: vertical;
- overflow: hidden;
-}
-
-/* KPI sub-table */
-.ot__kpis {
- margin-top: 8px;
- background: var(--sw-bg-1);
- border: 1px solid var(--sw-line);
- border-radius: 5px;
- padding: 8px;
-}
-.ot__kpis-head {
- display: flex; align-items: center; gap: 8px;
- font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em;
- color: var(--sw-fg-3); font-weight: 600;
- margin-bottom: 6px;
-}
-.ot__kpis-empty {
- padding: 14px; text-align: center;
- font-size: 11.5px; color: var(--sw-fg-3);
-}
-.ot__add-btn {
- margin-left: auto;
- background: transparent; border: 1px dashed var(--sw-line-2);
- color: var(--sw-fg-2); font: inherit; font-size: 11px;
- padding: 2px 10px; border-radius: 4px; cursor: pointer;
-}
-.ot__add-btn:hover { color: var(--sw-fg-0); border-style: solid; }
-/* KPI rows as stacked cards (the drawer is sidebar-narrow — a wide table
- row truncates every column). One bordered card per row; full-width
- Label/Source/MQE, then a 2-col Unit/Aggr/Style/Max grid. */
-.ot__kpi-cards { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }
-.ot__kpi-card {
- background: var(--sw-bg-2); border: 1px solid var(--sw-line);
- border-radius: 5px; padding: 8px 10px;
- display: flex; flex-direction: column; gap: 8px;
-}
-.ot__kpi-card-head { display: flex; align-items: center; gap: 6px; }
-.ot__kpi-card-idx {
- font-size: 10px; font-weight: 700; font-family: var(--sw-mono);
- color: var(--sw-fg-3);
-}
-.ot__kpi-card-ord { display: inline-flex; gap: 2px; margin-left: auto; }
-.ot__kpi-card-grid {
- display: grid; grid-template-columns: 1fr 1fr; gap: 8px;
-}
-.ot__kpi-card .ot__field { min-width: 0; }
-.ot__kpi-card .ot__field--full { grid-column: 1 / -1; }
-.ot__kpi-card .ot__in { width: 100%; box-sizing: border-box; }
-.ot__kpi-card .ot__none { margin: 0; }
-.ot__arrow {
- background: transparent; border: 0;
- color: var(--sw-fg-2); font: inherit; font-size: 12px;
- width: 20px; height: 22px; cursor: pointer;
-}
-.ot__arrow:disabled { opacity: 0.3; cursor: not-allowed; }
-.ot__arrow:not(:disabled):hover { color: var(--sw-fg-0); }
-.ot__del {
- background: transparent; border: 0;
- color: var(--sw-fg-3); font: inherit; font-size: 14px; line-height: 1;
- width: 22px; height: 22px; cursor: pointer; border-radius: 3px;
-}
-.ot__del:hover { color: var(--sw-err); background: var(--sw-bg-2); }
-
-/* Add-widget composer */
-.ot__add-widget { margin-top: 8px; }
-.ot__add-trigger {
- width: 100%;
- background: transparent;
- border: 1px dashed var(--sw-line-2);
- color: var(--sw-fg-2);
- font: inherit;
- font-size: 12px;
- padding: 10px;
- border-radius: 6px;
- cursor: pointer;
-}
-.ot__add-trigger:hover {
- border-color: var(--sw-accent);
- color: var(--sw-fg-0);
- background: var(--sw-bg-2);
-}
-.ot__composer { border-color: var(--sw-accent); }
-.ot__composer-foot {
- display: flex;
- align-items: center;
- gap: 8px;
- margin-top: 10px;
-}
-.ot__composer-hint {
- font-size: 10.5px;
- color: var(--sw-fg-3);
- flex: 1;
- font-style: italic;
-}
-
.ot__flash-row { display: flex; justify-content: flex-end; padding: 4px 0 0; }
.ot__flash { font-size: 11px; color: var(--sw-ok); }
.ot__dirty { font-size: 11px; color: var(--sw-warn); }
diff --git a/apps/ui/src/features/admin/overview-templates/OverviewWidgetDrawer.vue b/apps/ui/src/features/admin/overview-templates/OverviewWidgetDrawer.vue
new file mode 100644
index 0000000..ebc2e6d
--- /dev/null
+++ b/apps/ui/src/features/admin/overview-templates/OverviewWidgetDrawer.vue
@@ -0,0 +1,482 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<!--
+ Per-widget editor drawer (the right rail of the overview editor). The
+ editor is TYPE-AWARE — each widget kind exposes only the fields it
+ actually consumes. The drawer mutates widget objects (and their KPI rows)
+ IN PLACE — those objects are the same reactive references the parent holds
+ in `draft.widgets`, so an in-field edit reflects on the canvas live.
+ Array-level operations (reorder / remove a whole widget) reassign the
+ widgets array and are owned by the parent, reached via `move` / `remove`.
+
+ A sentinel id (`META_SEL`) selects the dashboard-meta "widget" (title +
+ description) instead of a real one.
+-->
+<script setup lang="ts">
+import type { OverviewDashboard, OverviewKpi, OverviewWidget } from '@skywalking-horizon-ui/api-client';
+import MqeExpressionInput from '@/features/admin/_shared/MqeExpressionInput.vue';
+import { useEscapeToClose } from '@/components/primitives/useEscapeToClose';
+import { META_SEL } from './constants';
+
+defineProps<{
+ draft: OverviewDashboard;
+ selectedWidgetId: string | null;
+ /** Live layers + any layer already referenced by the draft. */
+ layerOptions: string[];
+}>();
+
+const emit = defineEmits<{
+ close: [];
+ move: [idx: number, dir: -1 | 1];
+ remove: [idx: number];
+ 'update:title': [v: string];
+ 'update:description': [v: string];
+}>();
+
+useEscapeToClose(() => true, () => emit('close'));
+
+function widgetKindLabel(type: OverviewWidget['type']): string {
+ switch (type) {
+ case 'metric-composite': return 'Composite metrics';
+ case 'section-break': return 'Section break';
+ case 'metric': return 'Metric';
+ case 'topology': return 'Topology';
+ case 'alarms': return 'Alarms';
+ case 'kpi-tile': return 'KPI tile';
+ default: return type;
+ }
+}
+
+// KPI row helpers — kpi-tile / metric-composite only.
+function addKpi(w: OverviewWidget): void {
+ const next = [...(w.kpis ?? []), { label: 'new KPI', mqe: '' } as OverviewKpi];
+ w.kpis = next;
+}
+function removeKpi(w: OverviewWidget, idx: number): void {
+ if (!w.kpis) return;
+ w.kpis = w.kpis.filter((_, i) => i !== idx);
+}
+function moveKpi(w: OverviewWidget, idx: number, dir: -1 | 1): void {
+ if (!w.kpis) return;
+ const next = [...w.kpis];
+ const j = idx + dir;
+ if (j < 0 || j >= next.length) return;
+ [next[idx], next[j]] = [next[j], next[idx]];
+ w.kpis = next;
+}
+/* Switching a KPI to progress-bar makes `max` mandatory — seed a
+ * sensible default if it isn't set so the BFF doesn't 400 on save. */
+function onKpiStyleChange(k: OverviewKpi): void {
+ if (k.style === 'progress-bar' && (k.max === undefined || k.max === null)) {
+ k.max = 100;
+ }
+}
+</script>
+
+<template>
+ <aside class="ot__drawer-pane ot__widgets">
+ <div class="ot__drawer-head">
+ <span class="ot__drawer-title">{{ selectedWidgetId === META_SEL ? 'Dashboard meta' : 'Edit widget' }}</span>
+ <button type="button" class="ot__drawer-close" title="Close (Esc)" @click="emit('close')">✕</button>
+ </div>
+ <section v-if="selectedWidgetId === META_SEL" class="ot__meta">
+ <header class="ot__meta-head">
+ <span class="ot__meta-kicker">Dashboard meta</span>
+ <span class="ot__meta-hint">Shown in the sidebar and as the page sub-heading.</span>
+ </header>
+ <label class="ot__field">
+ <span>Title</span>
+ <input
+ :value="draft.title"
+ type="text"
+ class="ot__in"
+ @input="emit('update:title', ($event.target as HTMLInputElement).value)"
+ />
+ </label>
+ <label class="ot__field ot__field--wide">
+ <span>Description</span>
+ <textarea
+ :value="draft.description"
+ class="ot__in ot__in--ta"
+ rows="3"
+ placeholder="Short, one-paragraph description shown under the dashboard title."
+ @input="emit('update:description', ($event.target as HTMLTextAreaElement).value)"
+ />
+ </label>
+ </section>
+
+ <article
+ v-for="(w, wi) in draft.widgets"
+ v-show="w.id === selectedWidgetId"
+ :key="w.id"
+ class="ot__widget"
+ :class="`ot__widget--${w.type}`"
+ >
+ <header class="ot__widget-head">
+ <span class="ot__widget-kind">{{ widgetKindLabel(w.type) }}</span>
+ <code class="ot__widget-id">{{ w.id }}</code>
+ <span class="ot__widget-actions">
+ <button
+ type="button"
+ class="ot__arrow"
+ :disabled="wi === 0"
+ title="Move up"
+ @click="emit('move', wi, -1)"
+ >‹</button>
+ <button
+ type="button"
+ class="ot__arrow"
+ :disabled="wi === draft.widgets.length - 1"
+ title="Move down"
+ @click="emit('move', wi, 1)"
+ >›</button>
+ <button
+ type="button"
+ class="ot__del"
+ title="Remove widget"
+ @click="emit('remove', wi)"
+ >×</button>
+ </span>
+ </header>
+
+ <!-- 1. Size (width / height) first per the spec — layout
+ decisions before content. section-break has no
+ per-cell span (it spans the whole row), so we show
+ the grid `cols` field there instead. -->
+ <div class="ot__row">
+ <label v-if="w.type === 'section-break'" class="ot__field">
+ <span>Columns (grid)</span>
+ <input v-model.number="w.cols" type="number" min="1" max="12" class="ot__in ot__in--num" />
+ </label>
+ <template v-else>
+ <label class="ot__field">
+ <span>Width (span)</span>
+ <input v-model.number="w.span" type="number" min="1" max="12" class="ot__in ot__in--num" />
+ </label>
+ <label class="ot__field">
+ <span>Height (rows)</span>
+ <input v-model.number="w.rowSpan" type="number" min="1" max="12" class="ot__in ot__in--num" />
+ </label>
+ </template>
+ </div>
+
+ <div class="ot__row">
+ <label class="ot__field ot__field--wide">
+ <span>Title</span>
+ <input v-model="w.title" type="text" class="ot__in" />
+ </label>
+ <label v-if="w.type !== 'section-break'" class="ot__field ot__field--wide">
+ <span>Tip</span>
+ <input v-model="w.tip" type="text" class="ot__in" placeholder="(optional)" />
+ </label>
+ </div>
+
+ <div v-if="w.type !== 'section-break'" class="ot__row">
+ <label class="ot__field">
+ <span>Layer</span>
+ <select v-model="w.layer" class="ot__in ot__in--narrow">
+ <option :value="undefined">— any —</option>
+ <option v-for="k in layerOptions" :key="k" :value="k">{{ k }}</option>
+ </select>
+ </label>
+ </div>
+
+ <div v-if="w.type === 'metric'" class="ot__row">
+ <label class="ot__field ot__field--wide">
+ <span>MQE</span>
+ <MqeExpressionInput v-model="w.mqe" placeholder="service_cpm" title="Widget MQE" />
+ </label>
+ <label class="ot__field">
+ <span>Unit</span>
+ <input v-model="w.unit" type="text" class="ot__in ot__in--narrow" placeholder="rpm / ms / %" />
+ </label>
+ <label class="ot__field">
+ <span>Aggregation</span>
+ <select v-model="w.aggregation" class="ot__in ot__in--narrow">
+ <option :value="undefined">—</option>
+ <option value="avg">avg</option>
+ <option value="sum">sum</option>
+ </select>
+ </label>
+ </div>
+
+ <div v-if="w.type === 'alarms'" class="ot__row">
+ <label class="ot__field">
+ <span>Row limit</span>
+ <input v-model.number="w.limit" type="number" min="1" max="100" class="ot__in ot__in--num" />
+ </label>
+ </div>
+
+ <template v-if="w.type === 'kpi-tile' || w.type === 'metric-composite'">
+ <div v-if="w.type === 'kpi-tile'" class="ot__row">
+ <label class="ot__field">
+ <span>Show service count</span>
+ <input type="checkbox" v-model="w.showCount" />
+ </label>
+ </div>
+ <div class="ot__kpis">
+ <div class="ot__kpis-head">
+ <span>KPI rows ({{ (w.kpis ?? []).length }})</span>
+ <button type="button" class="ot__add-btn" @click="addKpi(w)">+ add row</button>
+ </div>
+ <div v-if="(w.kpis ?? []).length === 0" class="ot__kpis-empty">
+ No KPI rows. Add one to surface a metric on the tile.
+ </div>
+ <!-- One card per KPI. The drawer is narrow (sidebar-only),
+ so fields stack vertically instead of a wide table
+ row that truncates every column. -->
+ <ul v-else class="ot__kpi-cards">
+ <li v-for="(k, i) in w.kpis ?? []" :key="i" class="ot__kpi-card">
+ <div class="ot__kpi-card-head">
+ <span class="ot__kpi-card-idx">#{{ i + 1 }}</span>
+ <div class="ot__kpi-card-ord">
+ <button
+ type="button"
+ class="ot__arrow"
+ title="Move up"
+ :disabled="i === 0"
+ @click="moveKpi(w, i, -1)"
+ >↑</button>
+ <button
+ type="button"
+ class="ot__arrow"
+ title="Move down"
+ :disabled="i === (w.kpis ?? []).length - 1"
+ @click="moveKpi(w, i, 1)"
+ >↓</button>
+ </div>
+ <button type="button" class="ot__del" title="Remove row" @click="removeKpi(w, i)">×</button>
+ </div>
+ <label class="ot__field ot__field--full">
+ <span>Label</span>
+ <input v-model="k.label" type="text" class="ot__in" />
+ </label>
+ <label class="ot__field ot__field--full">
+ <span>Source</span>
+ <select v-model="k.source" class="ot__in">
+ <option :value="undefined">mqe</option>
+ <option value="mqe">mqe</option>
+ <option value="service-count">service-count</option>
+ </select>
+ </label>
+ <label v-if="(k.source ?? 'mqe') === 'mqe'" class="ot__field ot__field--full">
+ <span>MQE</span>
+ <MqeExpressionInput v-model="k.mqe" title="KPI MQE" />
+ </label>
+ <p v-else class="ot__none">Value comes from the service count (listServices) — no MQE.</p>
+ <div class="ot__kpi-card-grid">
+ <label class="ot__field">
+ <span>Unit</span>
+ <input v-model="k.unit" type="text" class="ot__in" />
+ </label>
+ <label class="ot__field">
+ <span>Aggr</span>
+ <select v-model="k.aggregation" class="ot__in">
+ <option :value="undefined">—</option>
+ <option value="avg">avg</option>
+ <option value="sum">sum</option>
+ </select>
+ </label>
+ <label class="ot__field">
+ <span>Style</span>
+ <select v-model="k.style" class="ot__in" @change="onKpiStyleChange(k)">
+ <option :value="undefined">number</option>
+ <option value="number">number</option>
+ <option value="progress-bar">progress-bar</option>
+ </select>
+ </label>
+ <label v-if="k.style === 'progress-bar'" class="ot__field">
+ <span>Max</span>
+ <input
+ v-model.number="k.max"
+ type="number"
+ min="0"
+ step="any"
+ class="ot__in"
+ placeholder="100"
+ />
+ </label>
+ </div>
+ </li>
+ </ul>
+ </div>
+ </template>
+ </article>
+ </aside>
+</template>
+
+<style scoped>
+.ot__widgets { display: flex; flex-direction: column; gap: 10px; }
+.ot__drawer-pane {
+ order: 2;
+ flex: 0 0 380px;
+ max-width: 380px;
+ position: sticky;
+ top: 12px;
+ max-height: calc(100vh - 90px);
+ overflow-y: auto;
+ border-left: 1px solid var(--sw-line);
+ padding-left: 14px;
+}
+.ot__drawer-head { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; padding-bottom: 8px; border-bottom: 1px solid var(--sw-line); }
+.ot__drawer-title { font-size: 11px; text-transform: uppercase; letter-spacing: 0.08em; color: var(--sw-fg-2); font-weight: 600; }
+.ot__drawer-close { margin-left: auto; background: transparent; border: none; color: var(--sw-fg-3); font-size: 14px; cursor: pointer; width: 22px; height: 22px; border-radius: 4px; }
+.ot__drawer-close:hover { background: var(--sw-bg-2); color: var(--sw-fg-0); }
+
+.ot__widget {
+ background: var(--sw-bg-2);
+ border: 1px solid var(--sw-line);
+ border-radius: 6px;
+ padding: 10px 12px;
+}
+.ot__widget--section-break { border-left: 3px solid var(--sw-accent); }
+.ot__widget-head {
+ display: flex; align-items: baseline; gap: 8px;
+ margin-bottom: 8px;
+}
+.ot__widget-kind {
+ font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em;
+ color: var(--sw-accent); font-weight: 600;
+}
+.ot__widget-id {
+ font-family: var(--sw-mono); font-size: 10.5px; color: var(--sw-fg-3);
+ margin-left: auto;
+}
+.ot__widget-actions { display: inline-flex; gap: 2px; }
+.ot__widget-actions .ot__arrow { width: 22px; height: 22px; }
+.ot__widget-actions .ot__del { font-size: 16px; }
+
+.ot__row { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 6px; }
+.ot__field {
+ display: flex; flex-direction: column; gap: 3px;
+ min-width: 140px;
+}
+.ot__field--wide { flex: 1 1 220px; }
+.ot__field > span {
+ font-size: 9.5px; text-transform: uppercase; letter-spacing: 0.08em;
+ color: var(--sw-fg-3); font-weight: 600;
+}
+.ot__in {
+ background: var(--sw-bg-1); border: 1px solid var(--sw-line);
+ color: var(--sw-fg-0); font: inherit; font-size: 11.5px;
+ padding: 4px 6px; border-radius: 4px;
+}
+.ot__in--narrow { width: 160px; }
+.ot__in--num { width: 80px; font-variant-numeric: tabular-nums; }
+.ot__in--ta {
+ /* Textarea variant of `.ot__in`. Three lines is the sweet spot for a
+ description paragraph — enough to read the whole sentence without
+ scrolling, not so tall it pushes the widget list down. The base
+ `.ot__in` 4px vertical padding is cramped for multi-line text;
+ restore comfortable line-height + padding here. */
+ width: 100%;
+ min-height: 72px;
+ padding: 8px 10px;
+ resize: vertical;
+ line-height: 1.5;
+ font-family: var(--sw-sans);
+ font-size: 12px;
+}
+.ot__field input[type='checkbox'] { width: 14px; height: 14px; margin: 4px 0 0; cursor: pointer; }
+.ot__none { color: var(--sw-fg-3); font-size: 11px; }
+
+.ot__meta {
+ background: var(--sw-bg-2);
+ border: 1px solid var(--sw-line);
+ border-radius: 6px;
+ padding: 12px 14px;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+.ot__meta-head {
+ display: flex;
+ align-items: baseline;
+ gap: 10px;
+}
+.ot__meta-kicker {
+ font-size: 9.5px;
+ text-transform: uppercase;
+ letter-spacing: 0.1em;
+ color: var(--sw-fg-3);
+ font-weight: 700;
+}
+.ot__meta-hint {
+ font-size: 10.5px;
+ color: var(--sw-fg-3);
+}
+
+.ot__kpis {
+ margin-top: 8px;
+ background: var(--sw-bg-1);
+ border: 1px solid var(--sw-line);
+ border-radius: 5px;
+ padding: 8px;
+}
+.ot__kpis-head {
+ display: flex; align-items: center; gap: 8px;
+ font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em;
+ color: var(--sw-fg-3); font-weight: 600;
+ margin-bottom: 6px;
+}
+.ot__kpis-empty {
+ padding: 14px; text-align: center;
+ font-size: 11.5px; color: var(--sw-fg-3);
+}
+.ot__add-btn {
+ margin-left: auto;
+ background: transparent; border: 1px dashed var(--sw-line-2);
+ color: var(--sw-fg-2); font: inherit; font-size: 11px;
+ padding: 2px 10px; border-radius: 4px; cursor: pointer;
+}
+.ot__add-btn:hover { color: var(--sw-fg-0); border-style: solid; }
+/* KPI rows as stacked cards (the drawer is sidebar-narrow — a wide table
+ row truncates every column). One bordered card per row; full-width
+ Label/Source/MQE, then a 2-col Unit/Aggr/Style/Max grid. */
+.ot__kpi-cards { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }
+.ot__kpi-card {
+ background: var(--sw-bg-2); border: 1px solid var(--sw-line);
+ border-radius: 5px; padding: 8px 10px;
+ display: flex; flex-direction: column; gap: 8px;
+}
+.ot__kpi-card-head { display: flex; align-items: center; gap: 6px; }
+.ot__kpi-card-idx {
+ font-size: 10px; font-weight: 700; font-family: var(--sw-mono);
+ color: var(--sw-fg-3);
+}
+.ot__kpi-card-ord { display: inline-flex; gap: 2px; margin-left: auto; }
+.ot__kpi-card-grid {
+ display: grid; grid-template-columns: 1fr 1fr; gap: 8px;
+}
+.ot__kpi-card .ot__field { min-width: 0; }
+.ot__kpi-card .ot__field--full { grid-column: 1 / -1; }
+.ot__kpi-card .ot__in { width: 100%; box-sizing: border-box; }
+.ot__kpi-card .ot__none { margin: 0; }
+.ot__arrow {
+ background: transparent; border: 0;
+ color: var(--sw-fg-2); font: inherit; font-size: 12px;
+ width: 20px; height: 22px; cursor: pointer;
+}
+.ot__arrow:disabled { opacity: 0.3; cursor: not-allowed; }
+.ot__arrow:not(:disabled):hover { color: var(--sw-fg-0); }
+.ot__del {
+ background: transparent; border: 0;
+ color: var(--sw-fg-3); font: inherit; font-size: 14px; line-height: 1;
+ width: 22px; height: 22px; cursor: pointer; border-radius: 3px;
+}
+.ot__del:hover { color: var(--sw-err); background: var(--sw-bg-2); }
+</style>
diff --git a/apps/ui/src/api/scopes/layer-template.ts b/apps/ui/src/features/admin/overview-templates/constants.ts
similarity index 57%
copy from apps/ui/src/api/scopes/layer-template.ts
copy to apps/ui/src/features/admin/overview-templates/constants.ts
index 20f41fb..8d40e8e 100644
--- a/apps/ui/src/api/scopes/layer-template.ts
+++ b/apps/ui/src/features/admin/overview-templates/constants.ts
@@ -15,20 +15,9 @@
* limitations under the License.
*/
-import type { AdminLayerTemplate, BffClient } from '../client';
-
-/** `bff.layerTemplates` — admin CRUD for the bundled per-layer JSON
- * templates that drive dashboards / service lists / overview tiles. */
-export class LayerTemplatesApi {
- constructor(private readonly bff: BffClient) {}
-
- list(): Promise<{ templates: AdminLayerTemplate[] }> {
- return this.bff.request<{ templates: AdminLayerTemplate[] }>(
- 'GET',
- '/api/admin/layer-templates',
- );
- }
-
- // save() removed — LayerDashboardsAdmin now saves via
- // `bff.templateSync.save('horizon.layer.<KEY>', content)`.
-}
+/**
+ * Sentinel id for the dashboard-meta "widget" (title + description).
+ * Selecting it opens the meta editor in the drawer instead of a real
+ * widget. Real widget ids never collide with it.
+ */
+export const META_SEL = '__meta__';
diff --git a/apps/ui/src/features/admin/overview-templates/widget-mock.ts b/apps/ui/src/features/admin/overview-templates/widget-mock.ts
new file mode 100644
index 0000000..6fe785b
--- /dev/null
+++ b/apps/ui/src/features/admin/overview-templates/widget-mock.ts
@@ -0,0 +1,91 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Deterministic mock-data generators for the OverviewTemplates admin edit
+ * canvas. The canvas renders the REAL overview widget primitives (Metric /
+ * KpiTile / MetricComposite) so the preview matches the live page, but with
+ * fabricated values — the operator is designing layout + scope, not browsing
+ * live data, so a BFF round-trip per keystroke would be wasteful.
+ *
+ * Everything is keyed off the widget id (+ KPI label) so a single widget's
+ * preview stays stable as the operator tweaks it — flipping span / rowSpan or
+ * editing a sibling shouldn't jiggle the numbers under their cursor.
+ */
+
+import type { OverviewWidget } from '@skywalking-horizon-ui/api-client';
+
+function hash(s: string): number {
+ let h = 0;
+ for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0;
+ return h;
+}
+
+export function mockNumber(seed: string, max = 999): number {
+ return hash(seed) % max;
+}
+
+export function mockPercent(seed: string): number {
+ return 10 + (hash(seed) % 85);
+}
+
+/** Mock alarm rows for the preview's alarms widget. Deterministic
+ * per widget id so the rows don't churn while editing. */
+const MOCK_ALARM_MSGS = [
+ 'Response time of service mesh-svr::cart is more than 20ms.',
+ 'JVM old-gen GC > 5s/min on agent::orders',
+ 'p95 SLA below threshold for service mesh-svr::reviews',
+];
+const MOCK_ALARM_SCOPES = ['Service · mesh-svr::cart', 'Instance · pod-2 of agent::orders', 'Service · reviews'];
+const MOCK_ALARM_AGES = ['2m', '14m', '47m'];
+
+export interface MockAlarmRow {
+ key: string;
+ firing: boolean;
+ msg: string;
+ scope: string;
+ since: string;
+}
+
+export function mockAlarms(seed: string, n: number): MockAlarmRow[] {
+ const out: MockAlarmRow[] = [];
+ const cap = Math.max(0, Math.min(n, MOCK_ALARM_MSGS.length));
+ for (let i = 0; i < cap; i++) {
+ out.push({
+ key: `${seed}::${i}`,
+ firing: (hash(seed + i) % 4) !== 0, // ~3/4 firing
+ msg: MOCK_ALARM_MSGS[i]!,
+ scope: MOCK_ALARM_SCOPES[i]!,
+ since: MOCK_ALARM_AGES[i]!,
+ });
+ }
+ return out;
+}
+
+/** Mock value per KPI label for the real widget components — percent /
+ * progress-bar rows get a 0-100 value, everything else a plain number.
+ * Keyed by widget id + label so it's stable across re-renders. */
+export function mockKpiValues(w: OverviewWidget): Record<string, number | null> {
+ const out: Record<string, number | null> = {};
+ for (const k of w.kpis ?? []) {
+ out[k.label] =
+ k.unit === '%' || k.style === 'progress-bar'
+ ? mockPercent(w.id + k.label)
+ : mockNumber(w.id + k.label, k.max ?? 999);
+ }
+ return out;
+}
diff --git a/apps/ui/src/features/admin/roles/RolesView.vue b/apps/ui/src/features/admin/roles/RolesView.vue
index d1d6bb0..d5c67b0 100644
--- a/apps/ui/src/features/admin/roles/RolesView.vue
+++ b/apps/ui/src/features/admin/roles/RolesView.vue
@@ -322,7 +322,6 @@ function grantsOf(role: string): string[] {
<div v-if="loading" class="loading">{{ t('Loading roles…') }}</div>
<div v-else-if="error" class="error">{{ t('Failed to load:') }} {{ error }}</div>
<template v-else-if="status">
- <!-- Intro -->
<section class="sw-card intro">
<h2 class="intro-title">{{ t('What each role can do') }}</h2>
<i18n-t
@@ -375,14 +374,12 @@ function grantsOf(role: string): string[] {
</div>
</section>
- <!-- Per-group cards: Menu scope (left) + Actions (right) -->
<section v-for="g in groupedVerbs" :key="g.title" class="sw-card group-card">
<header class="card-head">
<h3>{{ g.title }}</h3>
<span class="muted">{{ g.blurb }}</span>
</header>
<div class="group-body">
- <!-- Left: mock menu bar showing what this area covers -->
<aside class="scope" :aria-label="t('Menu scope')">
<div class="col-head">
<span class="col-num">1</span>
@@ -398,10 +395,8 @@ function grantsOf(role: string): string[] {
</ul>
</aside>
- <!-- Connector arrow makes the relationship visible -->
<div class="connector" aria-hidden="true">→</div>
- <!-- Right: per-role permission grid for the actions in this area -->
<div class="grid-wrap">
<div class="col-head">
<span class="col-num">2</span>
@@ -475,7 +470,6 @@ function grantsOf(role: string): string[] {
color: var(--sw-fg-0);
}
-/* ── Intro ───────────────────────────────────────────────────────── */
.intro { padding: 14px 18px; }
.intro-title { margin: 0; font-size: var(--sw-fs-lg); color: var(--sw-fg-0); font-weight: var(--sw-fw-semibold); }
.intro-body {
@@ -503,7 +497,6 @@ function grantsOf(role: string): string[] {
line-height: var(--sw-lh-normal);
}
-/* ── Group card ──────────────────────────────────────────────────── */
.muted { color: var(--sw-fg-3); font-size: var(--sw-fs-sm); font-weight: var(--sw-fw-regular); }
.card-head h3 + .muted { margin-left: 6px; }
@@ -651,7 +644,6 @@ function grantsOf(role: string): string[] {
font-size: var(--sw-fs-lg);
}
-/* ── Pills ───────────────────────────────────────────────────────── */
.pill {
display: inline-flex;
align-items: center;
@@ -668,7 +660,6 @@ function grantsOf(role: string): string[] {
.pill-info { color: var(--sw-info); background: rgba(56,189,248,0.16); border-color: rgba(56,189,248,0.33); }
.pill-cyan { color: var(--sw-cyan, #22d3ee); background: rgba(34,211,238,0.14); border-color: rgba(34,211,238,0.33); }
-/* ── Rules card ──────────────────────────────────────────────────── */
.rules-card { padding: 0; }
.rules-grid {
display: grid;
diff --git a/apps/ui/src/features/admin/translations/TranslationFieldPanel.vue b/apps/ui/src/features/admin/translations/TranslationFieldPanel.vue
new file mode 100644
index 0000000..93ed356
--- /dev/null
+++ b/apps/ui/src/features/admin/translations/TranslationFieldPanel.vue
@@ -0,0 +1,170 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<!--
+ Click-anchored translation editor for the Translations page. A
+ FloatingPanel positioned next to the clicked widget, listing only that
+ widget's translatable fields. Each row shows the EN source and a draft
+ textarea; typing emits `update-field`, Stage emits `stage`. The wire
+ path (e.g. `kpis[0].label`) is internal — the operator sees the field's
+ structural KIND (title, tip, …) instead.
+-->
+<script setup lang="ts">
+import { useI18n } from 'vue-i18n';
+import FloatingPanel from '@/components/primitives/FloatingPanel.vue';
+import { vAutosize } from '@/utils/autosize';
+import type { TranslatableField } from '@/features/admin/_shared/translatableFields';
+
+defineProps<{
+ open: boolean;
+ anchor: HTMLElement | null;
+ point: { x: number; y: number } | null;
+ label: string;
+ /** Native label of the target locale, shown in the panel kicker. */
+ targetLabel: string;
+ fields: TranslatableField[];
+ saving: boolean;
+ dirty: boolean;
+ /** Reader for the draft value of a field path. */
+ draftValue: (path: string) => string;
+}>();
+
+const emit = defineEmits<{
+ close: [];
+ 'update-field': [path: string, value: string];
+ stage: [];
+}>();
+
+const { t } = useI18n({ useScope: 'global' });
+
+/** Human label for a translatable field shown next to the EN source.
+ * The wire path (e.g. `kpis[0].label`) is internal — translators
+ * shouldn't see it; they should see what KIND of string they're
+ * translating (title, tip, tab label, …). EN source identifies
+ * which one. */
+const FIELD_LABELS: Record<string, string> = {
+ title: 'Title',
+ tip: 'Tip',
+ description: 'Description',
+ label: 'Label',
+ group: 'Group',
+ alias: 'Alias',
+ expressionLabels: 'Series label',
+ tableHeaders: 'Column header',
+ slots: 'Term',
+ aliases: 'Layer alias',
+};
+function leafLabel(segments: Array<string | number>): string {
+ // Walk back to the last non-index segment — that's the field's
+ // structural name. For `kpis[3].label` it's "label"; for
+ // `expressionLabels[2]` it's "expressionLabels".
+ for (let i = segments.length - 1; i >= 0; i--) {
+ const s = segments[i];
+ if (typeof s === 'string') return FIELD_LABELS[s] ?? s;
+ }
+ return '';
+}
+</script>
+
+<template>
+ <FloatingPanel
+ :open="open"
+ :anchor="anchor"
+ :point="point"
+ :width="520"
+ @close="emit('close')"
+ >
+ <div class="fp">
+ <header class="fp__head">
+ <div class="fp__head-text">
+ <span class="fp__kicker">EN → {{ targetLabel }}</span>
+ <h4>{{ label }}</h4>
+ </div>
+ <button type="button" class="fp__close" @click="emit('close')">✕</button>
+ </header>
+ <div class="fp__rows">
+ <div v-for="f in fields" :key="f.path" class="fp__row">
+ <div class="fp__row-meta">
+ <span class="fp__tag">{{ leafLabel(f.segments) }}</span>
+ <span class="fp__src">{{ f.source }}</span>
+ </div>
+ <textarea
+ v-autosize="draftValue(f.path) || f.source"
+ :value="draftValue(f.path)"
+ :placeholder="f.source"
+ rows="1"
+ class="fp__input"
+ @input="emit('update-field', f.path, ($event.target as HTMLTextAreaElement).value)"
+ ></textarea>
+ </div>
+ </div>
+ <footer class="fp__foot">
+ <button type="button" class="sw-btn" @click="emit('close')">{{ t('Close') }}</button>
+ <button type="button" class="sw-btn is-primary" :disabled="saving || !dirty" @click="emit('stage')">
+ {{ t('Stage local') }}
+ </button>
+ </footer>
+ </div>
+ </FloatingPanel>
+</template>
+
+<style scoped>
+/* Floating panel (per-widget translation popover) */
+.fp { display: flex; flex-direction: column; max-height: calc(100vh - 16px); }
+.fp__head {
+ display: flex; align-items: flex-start; gap: 10px;
+ padding: 10px 12px;
+ border-bottom: 1px solid var(--sw-line-2);
+ background: var(--sw-bg-2);
+}
+.fp__head-text { flex: 1; min-width: 0; }
+.fp__kicker {
+ font-size: 9.5px; letter-spacing: 0.06em; text-transform: uppercase;
+ color: var(--sw-accent); display: block; margin-bottom: 2px;
+}
+.fp__head h4 { margin: 0; font-size: 13px; color: var(--sw-fg-0); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.fp__close {
+ background: none; border: none; color: var(--sw-fg-3);
+ cursor: pointer; font-size: 14px; padding: 0 4px;
+}
+.fp__close:hover { color: var(--sw-fg-1); }
+.fp__rows { flex: 1; min-height: 0; overflow-y: auto; padding: 8px 12px; }
+.fp__row { padding: 8px 0; border-bottom: 1px dashed var(--sw-line); }
+.fp__row:last-child { border-bottom: none; }
+.fp__row-meta { display: flex; align-items: baseline; gap: 8px; margin-bottom: 4px; }
+.fp__tag {
+ flex: 0 0 auto;
+ font-size: 9.5px; letter-spacing: 0.06em; text-transform: uppercase;
+ color: var(--sw-fg-3);
+ background: var(--sw-bg-2); border: 1px solid var(--sw-line-2);
+ padding: 1px 6px; border-radius: 3px;
+}
+.fp__src { font-size: 12px; color: var(--sw-fg-1); font-weight: 500; }
+.fp__input {
+ width: 100%; box-sizing: border-box;
+ background: var(--sw-bg-2); color: var(--sw-fg-1);
+ border: 1px solid var(--sw-line-2); border-radius: 3px;
+ padding: 4px 6px; font-size: 12.5px; resize: vertical;
+ font-family: inherit;
+}
+.fp__input:focus { outline: none; border-color: var(--sw-accent); }
+.fp__foot {
+ padding: 8px 12px;
+ border-top: 1px solid var(--sw-line-2);
+ display: flex; gap: 6px; justify-content: flex-end;
+ background: var(--sw-bg-2);
+}
+</style>
diff --git a/apps/ui/src/features/admin/translations/TranslationPreview.vue b/apps/ui/src/features/admin/translations/TranslationPreview.vue
deleted file mode 100644
index 5981643..0000000
--- a/apps/ui/src/features/admin/translations/TranslationPreview.vue
+++ /dev/null
@@ -1,402 +0,0 @@
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<!--
- Translation-time preview pane. Renders the picked template with the
- in-progress overlay applied; no live MQE — chart bodies come from
- the same deterministic mock generators the LayerDashboards admin
- editor uses, so the preview here matches that view's chart shapes.
-
- Overview kind reuses the actual overview widget primitives with empty
- data. Layer kind renders per-scope widgets via TimeChart / TopList /
- inline card / record, all mock-fed. Clicking any widget emits
- `select-widget` so the parent can focus the corresponding row in the
- editor.
-
- Nothing in this pane navigates — RouterLink isn't used and clicks
- don't escape the preview surface.
--->
-<script setup lang="ts">
-import { computed } from 'vue';
-import { useI18n } from 'vue-i18n';
-import type { AdminLayerTemplate, DashboardWidget } from '@/api/client';
-
-const { t } = useI18n({ useScope: 'global' });
-import type {
- OverviewDashboard,
- OverviewWidget,
-} from '@skywalking-horizon-ui/api-client';
-import SectionBreak from '@/render/widgets/SectionBreak.vue';
-import MetricWidget from '@/render/widgets/MetricWidget.vue';
-import KpiTileWidget from '@/render/widgets/KpiTileWidget.vue';
-import AlarmsWidget from '@/render/widgets/AlarmsWidget.vue';
-import MetricCompositeWidget from '@/render/widgets/MetricCompositeWidget.vue';
-import TimeChart from '@/components/charts/TimeChart.vue';
-import TopList from '@/components/charts/TopList.vue';
-import { fmtMetric } from '@/utils/formatters';
-import {
- mockCardValue,
- mockLineSeries,
- mockRecordRows,
- mockTopGroups,
-} from '@/features/admin/layer-templates/widget-mock';
-
-type AdminScope = 'service' | 'instance' | 'endpoint';
-
-const props = defineProps<{
- kind: 'overview' | 'layer';
- overview?: OverviewDashboard;
- layer?: AdminLayerTemplate;
- scope?: AdminScope;
-}>();
-
-const emit = defineEmits<{
- /** Operator clicked a widget — the parent should focus the
- * corresponding row in the editor. */
- 'select-widget': [widgetId: string];
-}>();
-
-interface OverviewSection {
- title: string;
- cols: number;
- widgets: OverviewWidget[];
-}
-
-const overviewSections = computed<OverviewSection[]>(() => {
- const dash = props.overview;
- if (!dash) return [];
- const out: OverviewSection[] = [];
- let current: OverviewSection | null = null;
- for (const w of dash.widgets) {
- if (w.type === 'section-break') {
- current = { title: w.title, cols: w.cols ?? 12, widgets: [] };
- out.push(current);
- } else {
- if (!current) {
- current = { title: '', cols: 12, widgets: [] };
- out.push(current);
- }
- current.widgets.push(w);
- }
- }
- return out;
-});
-
-function gridStyle(span?: number, rowSpan?: number, cols = 12): Record<string, string> {
- const out: Record<string, string> = {};
- if (span) out.gridColumn = `span ${Math.min(cols, Math.max(1, span))}`;
- if (rowSpan) out.gridRow = `span ${Math.min(8, Math.max(1, rowSpan))}`;
- return out;
-}
-
-const scopeWidgets = computed<DashboardWidget[]>(() => {
- const tpl = props.layer as (AdminLayerTemplate & { dashboards?: Record<string, DashboardWidget[]> }) | undefined;
- if (!tpl) return [];
- const s: AdminScope = props.scope ?? 'service';
- return tpl.dashboards?.[s] ?? tpl.widgets ?? [];
-});
-
-const headerColumns = computed(() => props.layer?.metrics?.columns ?? []);
-const overviewGroups = computed(() => {
- const ov = props.layer?.overview as
- | { groups?: Array<{ title: string; metrics: Array<{ label: string; tip?: string; unit?: string }> }> }
- | undefined;
- return ov?.groups ?? [];
-});
-
-function widgetRowSpan(w: DashboardWidget): number {
- return Math.min(8, Math.max(1, w.rowSpan ?? 1));
-}
-</script>
-
-<template>
- <div class="prev">
- <template v-if="kind === 'overview' && overview">
- <header class="prev-head">
- <h2>{{ overview.title }}</h2>
- <p v-if="overview.description" class="lede">{{ overview.description }}</p>
- </header>
- <div class="sections">
- <section v-for="(sec, si) in overviewSections" :key="si" class="section">
- <SectionBreak v-if="sec.title" :title="sec.title" />
- <div
- class="section-grid"
- :style="{ gridTemplateColumns: `repeat(${sec.cols}, minmax(0, 1fr))` }"
- >
- <template v-for="w in sec.widgets" :key="w.id">
- <!-- Intercept clicks in the CAPTURE phase. The overview
- widget primitives (KpiTileWidget,
- MetricCompositeWidget, AlarmsWidget) contain
- RouterLinks that would navigate to /layer/... or
- /alarms. We don't want any navigation off this page;
- capture-prevent stops the inner link from firing
- and lets us emit `select-widget` instead. -->
- <div
- class="ovw-cell"
- :style="gridStyle(w.span, w.rowSpan, sec.cols)"
- @click.capture.prevent.stop="emit('select-widget', w.id)"
- >
- <MetricWidget
- v-if="w.type === 'metric'"
- :title="w.title"
- :tip="w.tip"
- :value="null"
- :unit="w.unit"
- />
- <KpiTileWidget
- v-else-if="w.type === 'kpi-tile'"
- :title="w.title"
- :tip="w.tip"
- :layer="w.layer"
- :show-count="w.showCount"
- :count="null"
- :kpis="w.kpis ?? []"
- :kpi-values="{}"
- />
- <AlarmsWidget
- v-else-if="w.type === 'alarms'"
- :title="w.title"
- :tip="w.tip"
- :limit="w.limit"
- :layer="w.layer"
- />
- <div v-else-if="w.type === 'topology'" class="topo-host sw-card">
- <span class="topo-host__label">{{ w.title || t('Topology') }}</span>
- </div>
- <MetricCompositeWidget
- v-else-if="w.type === 'metric-composite'"
- :title="w.title"
- :tip="w.tip"
- :layer="w.layer"
- :kpis="w.kpis"
- :kpi-values="{}"
- />
- </div>
- </template>
- </div>
- </section>
- </div>
- </template>
-
- <template v-else-if="kind === 'layer' && layer">
- <header class="prev-head">
- <h2>{{ layer.alias || layer.key }}</h2>
- <span class="key-tag">{{ layer.key }}</span>
- </header>
-
- <section v-if="headerColumns.length > 0" class="section">
- <div class="prev-subhead">{{ t('Service header') }}</div>
- <div class="hdr-strip">
- <div v-for="c in headerColumns" :key="c.metric" class="hdr-col" @click="emit('select-widget', `header:${c.metric}`)">
- <span class="hdr-label">{{ c.label }}</span>
- <span class="hdr-unit">{{ c.unit ?? '—' }}</span>
- </div>
- </div>
- </section>
-
- <section v-if="overviewGroups.length > 0" class="section">
- <div class="prev-subhead">{{ t('Overview tiles') }}</div>
- <div class="ov-grid">
- <div
- v-for="(g, gi) in overviewGroups"
- :key="gi"
- class="ov-group sw-card"
- @click="emit('select-widget', `ovgroup:${gi}`)"
- >
- <div class="ov-title">{{ g.title || ' ' }}</div>
- <div class="ov-metrics">
- <div
- v-for="(m, mi) in g.metrics"
- :key="m.label"
- class="ov-metric"
- @click.stop="emit('select-widget', `ovmetric:${gi}:${mi}`)"
- >
- <span class="ov-label">{{ m.label }}</span>
- <span class="ov-value">—</span>
- </div>
- </div>
- </div>
- </div>
- </section>
-
- <section v-if="scopeWidgets.length > 0" class="section">
- <div class="prev-subhead">{{ t('{scope} dashboard widgets', { scope: scope ?? '' }) }}</div>
- <div class="widget-grid">
- <div
- v-for="w in scopeWidgets"
- :key="w.id"
- class="canvas-widget"
- :style="gridStyle(w.span, w.rowSpan, 12)"
- @click="emit('select-widget', w.id)"
- >
- <header class="cw-head">
- <h5>{{ w.title }}</h5>
- <span class="cw-type" :class="`t-${w.type}`">{{ w.type }}</span>
- </header>
- <div class="cw-body">
- <template v-if="w.type === 'line' && w.expressions.length > 0">
- <TimeChart
- :series="mockLineSeries(w)"
- :unit="w.unit"
- :height="Math.max(60, widgetRowSpan(w) * 120 - 50)"
- />
- </template>
- <template v-else-if="w.type === 'top' && w.expressions.length > 0">
- <TopList
- :groups="mockTopGroups(w, Math.max(4, widgetRowSpan(w) * 3))"
- :unit="w.unit"
- />
- </template>
- <template v-else-if="w.type === 'card'">
- <div class="cw-card-value">
- <span class="num">{{ fmtMetric(mockCardValue(w)) }}</span>
- <span v-if="w.unit" class="unit">{{ w.unit }}</span>
- </div>
- </template>
- <template v-else-if="w.type === 'record' && w.expressions.length > 0">
- <ul class="cw-records">
- <li
- v-for="(r, ri) in mockRecordRows(w, Math.max(3, widgetRowSpan(w) * 2))"
- :key="ri"
- class="cw-record-row"
- >
- <span class="rec-name">{{ r.name }}</span>
- <span class="rec-value">
- {{ fmtMetric(r.value ?? null) }}<span v-if="w.unit" class="unit">{{ w.unit }}</span>
- </span>
- </li>
- </ul>
- </template>
- <p v-else class="cw-empty">{{ t('No preview shape for this widget type.') }}</p>
- </div>
- </div>
- </div>
- </section>
- </template>
-
- <div v-else class="empty">{{ t('Pick a template to preview.') }}</div>
- </div>
-</template>
-
-<style scoped>
-.prev { padding: 12px 14px; display: flex; flex-direction: column; gap: 14px; overflow: auto; }
-.prev-head { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
-.prev-head h2 { margin: 0; font-size: 18px; font-weight: 600; color: var(--sw-fg-0); }
-.prev-head .lede { width: 100%; margin: 4px 0 0; font-size: 12px; color: var(--sw-fg-2); line-height: 1.5; }
-.key-tag {
- font-family: var(--sw-mono); font-size: 10.5px;
- padding: 2px 6px; border-radius: 3px; background: var(--sw-bg-2); color: var(--sw-fg-3);
-}
-.prev-subhead {
- font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em; color: var(--sw-fg-3);
- margin-bottom: 6px;
-}
-.sections { display: flex; flex-direction: column; gap: 14px; }
-.section { display: flex; flex-direction: column; gap: 6px; }
-.section-grid { display: grid; grid-auto-rows: 72px; gap: 10px; }
-
-/* Each cell wraps the real widget primitive. Capture-phase click
- handler on the wrapper swallows nav clicks before they reach
- the widget's inner RouterLink. The wrapper also forwards the
- grid-position style so the layout matches OverviewDashboardView. */
-.ovw-cell { cursor: pointer; display: contents; }
-.ovw-cell > * { cursor: pointer; }
-/* Restore the grid placement on the actual widget (display:contents
- above means the inner element is the grid item). */
-.ovw-cell { display: block; }
-
-.hdr-strip { display: flex; gap: 8px; flex-wrap: wrap; }
-.hdr-col {
- flex: 1 1 auto; min-width: 90px;
- background: var(--sw-bg-1); border: 1px solid var(--sw-line-2); border-radius: 4px;
- padding: 6px 10px; display: flex; flex-direction: column; gap: 2px;
- cursor: pointer;
-}
-.hdr-col:hover { border-color: var(--sw-accent); }
-.hdr-label { font-size: 11px; font-weight: 600; color: var(--sw-fg-1); }
-.hdr-unit { font-size: 10px; color: var(--sw-fg-3); font-family: var(--sw-mono); }
-
-.ov-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 10px; }
-.ov-group { padding: 10px 12px; display: flex; flex-direction: column; gap: 6px; cursor: pointer; }
-.ov-title { font-size: 11px; font-weight: 600; color: var(--sw-fg-1); }
-.ov-metrics { display: flex; flex-direction: column; gap: 3px; }
-.ov-metric { display: flex; justify-content: space-between; font-size: 11.5px; }
-.ov-label { color: var(--sw-fg-2); }
-.ov-value { color: var(--sw-fg-3); font-family: var(--sw-mono); }
-
-/* Layer widget cards — copy of LayerDashboardsAdmin's `.canvas-widget`
- visual vocabulary so this preview looks indistinguishable from the
- admin editor's canvas. Mock data via the shared widget-mock helpers. */
-.widget-grid {
- display: grid;
- grid-template-columns: repeat(12, minmax(0, 1fr));
- /* `auto` rather than a fixed track height so the grid grows to fit
- widgets with longer content (long top-N lists, dense record
- widgets, wide line charts). Each widget's `rowSpan` still spans
- the right number of rows, but each row sizes to its largest
- occupant rather than to a hard-coded 120 px. */
- grid-auto-rows: minmax(120px, auto);
- gap: 10px;
-}
-.canvas-widget {
- background: var(--sw-bg-1);
- border: 1px solid var(--sw-line-2);
- border-radius: 6px;
- padding: 8px 10px;
- display: flex;
- flex-direction: column;
- gap: 6px;
- cursor: pointer;
- overflow: hidden;
- min-height: 0;
-}
-.canvas-widget:hover { border-color: var(--sw-accent); }
-.cw-head { display: flex; align-items: center; gap: 8px; }
-.cw-head h5 { margin: 0; font-size: 12px; font-weight: 600; color: var(--sw-fg-1); flex: 1; }
-.cw-type {
- font-size: 9.5px; padding: 1px 6px; border-radius: 3px; text-transform: uppercase;
- background: var(--sw-bg-2); color: var(--sw-fg-3);
- letter-spacing: 0.05em;
-}
-.cw-body { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
-.cw-card-value { display: flex; align-items: baseline; gap: 6px; padding: 12px 4px; }
-.cw-card-value .num { font-size: 22px; font-weight: 600; color: var(--sw-fg-0); }
-.cw-card-value .unit { font-size: 11px; color: var(--sw-fg-3); }
-.cw-records { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 3px; overflow: auto; }
-.cw-record-row { display: flex; justify-content: space-between; gap: 8px; font-size: 11.5px; }
-.rec-name { color: var(--sw-fg-2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
-.rec-value { color: var(--sw-fg-1); font-family: var(--sw-mono); }
-.rec-value .unit { color: var(--sw-fg-3); margin-left: 2px; }
-.cw-empty { color: var(--sw-fg-3); font-size: 11px; padding: 16px; text-align: center; margin: 0; }
-
-.topo-host {
- padding: 12px;
- display: flex;
- align-items: center;
- justify-content: center;
- color: var(--sw-fg-3);
- font-size: 12px;
- cursor: pointer;
-}
-.topo-host__label { font-style: italic; }
-
-.empty {
- padding: 60px 20px;
- text-align: center;
- color: var(--sw-fg-3);
- font-size: 13px;
-}
-</style>
diff --git a/apps/ui/src/features/admin/translations/TranslationsView.vue b/apps/ui/src/features/admin/translations/TranslationsView.vue
index 333881e..98f8b1c 100644
--- a/apps/ui/src/features/admin/translations/TranslationsView.vue
+++ b/apps/ui/src/features/admin/translations/TranslationsView.vue
@@ -33,34 +33,28 @@
<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
-import { useTemplateSources } from '@/features/admin/_shared/useTemplateSources';
import {
buildOverlayExportEnvelope,
downloadJson,
parseOverlayImport,
pickJsonFile,
} from '@/features/admin/_shared/templatePortability';
-import { useTemplateSync } from '@/features/admin/_shared/useTemplateSync';
import SyncStatusBanner from '@/features/admin/_shared/SyncStatusBanner.vue';
import LayerDashboardCanvas from '@/features/admin/_shared/LayerDashboardCanvas.vue';
import OverviewDashboardCanvas from '@/features/admin/_shared/OverviewDashboardCanvas.vue';
-import TemplatePicker, { type TemplatePickerEntry } from '@/features/admin/_shared/TemplatePicker.vue';
+import TemplatePicker from '@/features/admin/_shared/TemplatePicker.vue';
import TypeaheadSelect from '@/components/primitives/TypeaheadSelect.vue';
-import FloatingPanel from '@/components/primitives/FloatingPanel.vue';
import Modal from '@/features/operate/_shared/Modal.vue';
import MonacoDiff from '@/features/operate/_shared/MonacoDiff.vue';
+import TranslationFieldPanel from './TranslationFieldPanel.vue';
+import { useTranslationPicker } from './useTranslationPicker';
+import { useTranslationDraft, type EffectiveSource } from './useTranslationDraft';
import { useLocalTranslationEdits } from '@/controls/localTranslationEdits';
import { refreshConfigBundle } from '@/controls/configBundle';
import { bff, BffApiError } from '@/api/client';
import { stableStringify } from '@/utils/stableJson';
-import {
- walkTranslatable,
- setAtPath,
- getAtPath,
- type TranslatableField,
-} from '@/features/admin/_shared/translatableFields';
+import { type TranslatableField } from '@/features/admin/_shared/translatableFields';
import { SUPPORTED_LOCALES, LOCALE_NATIVE_LABEL, type Locale } from '@/i18n';
-import { vAutosize } from '@/utils/autosize';
import type { AdminLayerTemplate } from '@/api/client';
import type {
OverviewDashboard,
@@ -73,102 +67,21 @@ const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms
const { t } = useI18n({ useScope: 'global' });
-const overviewSources = useTemplateSources('overview');
-const layerSources = useTemplateSources('layer');
-const layerSync = useTemplateSync({ kind: 'layer' });
-const overviewSync = useTemplateSync({ kind: 'overview' });
const localEdits = useLocalTranslationEdits();
-// ── Picker state ───────────────────────────────────────────────────
const selectedKind = ref<'overview' | 'layer'>('overview');
const selectedName = ref<string>('');
const scope = ref<DashboardScope>('service');
-// Bundled-only entries (overview / layer rows the operator may not
-// have pushed yet) come off the sync-status badge list.
-const bundledOverviewNames = computed<string[]>(() => {
- const s = overviewSync.status.value;
- return s ? s.badges.filter((b) => b.kind === 'overview').map((b) => b.name) : [];
-});
-const layerNames = computed<string[]>(() => {
- const s = layerSync.status.value;
- return s ? s.badges.filter((b) => b.kind === 'layer').map((b) => b.name) : [];
-});
-
-function metaFor(name: string, kind: 'overview' | 'layer'): {
- syncBadge: ReturnType<typeof layerSync.badgeFor>;
- hasLocalDraft: boolean;
- isDiverged: boolean;
- localeBadges: TemplatePickerEntry['localeBadges'];
-} {
- const sync = kind === 'overview' ? overviewSync : layerSync;
- const sources = kind === 'overview' ? overviewSources : layerSources;
- const badge = sync.badgeFor(name);
- // Per-locale status chips: derived from the overlay sibling rows
- // already present in sync-status, with the operator's unstaged
- // browser draft taking precedence ('local' wins over any sync state).
- const localeBadges = SUPPORTED_LOCALES.filter((l) => l !== 'en').map((locale) => {
- if (localEdits.has(name, locale)) {
- return { locale, status: 'local' as const };
- }
- const s = sources.overlayStatus(name, locale);
- return { locale, status: s ?? ('empty' as const) };
- });
- return {
- syncBadge: badge,
- // Picker chip lights up when ANY locale has an unstaged draft for
- // this template.
- hasLocalDraft: localEdits.localesFor(name).length > 0,
- isDiverged: badge === 'diverged',
- localeBadges,
- };
-}
-
-const overviewEntries = computed<TemplatePickerEntry[]>(() => {
- const out: TemplatePickerEntry[] = [];
- const seen = new Set<string>();
- const push = (name: string, content: OverviewDashboard | null): void => {
- if (!content || seen.has(name)) return;
- seen.add(name);
- out.push({
- value: name,
- label: content.title || content.id,
- key: content.id,
- ...metaFor(name, 'overview'),
- });
- };
- for (const name of overviewSources.remoteNames()) {
- push(name, overviewSources.remote<OverviewDashboard>(name));
- }
- for (const name of bundledOverviewNames.value) {
- push(name, overviewSources.bundled<OverviewDashboard>(name));
- }
- out.sort((a, b) => a.label.localeCompare(b.label));
- return out;
-});
-
-const layerEntries = computed<TemplatePickerEntry[]>(() => {
- const out: TemplatePickerEntry[] = [];
- for (const name of layerNames.value) {
- const content =
- layerSources.remote<AdminLayerTemplate>(name) ??
- layerSources.bundled<AdminLayerTemplate>(name);
- if (!content) continue;
- out.push({
- value: name,
- label: content.alias || content.key,
- key: content.key,
- color: content.color,
- ...metaFor(name, 'layer'),
- });
- }
- out.sort((a, b) => a.label.localeCompare(b.label));
- return out;
-});
-
-const activeEntries = computed<TemplatePickerEntry[]>(() =>
- selectedKind.value === 'overview' ? overviewEntries.value : layerEntries.value,
-);
+const {
+ overviewSources,
+ layerSources,
+ layerSync,
+ overviewSync,
+ overviewEntries,
+ layerEntries,
+ activeEntries,
+} = useTranslationPicker(selectedKind);
const refreshing = ref(false);
async function onRefreshTemplates(): Promise<void> {
@@ -197,8 +110,6 @@ watch(
{ immediate: true },
);
-// ── Source + draft state ───────────────────────────────────────────
-
/** Effective SOURCE for the picked template — strictly REMOTE (the
* version published to OAP). We translate the PUBLISHED template's
* fields, not the bundled disk copy: the runtime localizes against the
@@ -207,7 +118,7 @@ watch(
* no OAP row therefore isn't translatable until it's published (the
* editor shows the empty state). Embedded `i18n` is no longer written by
* this page; any historical embedded block is stripped defensively. */
-const effective = computed<{ source: Record<string, unknown> } | null>(() => {
+const effective = computed<EffectiveSource | null>(() => {
const name = selectedName.value;
const kind = selectedKind.value;
if (!name) return null;
@@ -219,145 +130,28 @@ const effective = computed<{ source: Record<string, unknown> } | null>(() => {
return { source: rest };
});
-/** Operator's in-progress overlay, keyed by template-name → locale →
- * field-path → translation. Editor reads/writes here; Push serializes
- * the per-locale map back into the sibling OAP overlay row. */
-const draft = ref<Record<string, Record<string, Record<string, string>>>>({});
-
-/** OAP + disk overlay snapshots we've already fetched from the BFF,
- * keyed by `${name}:${locale}`. Used to seed the draft AND to compute
- * the diff for the push modal. */
-interface OverlaySnapshot { disk: unknown; oap: unknown }
-const fetchedOverlays = ref<Record<string, OverlaySnapshot>>({});
-
-function overlayKey(name: string, locale: string): string {
- return `${name}:${locale}`;
-}
-
-/** Walk an overlay into the draft for (name, locale). Translatable
- * leaves only; existing draft values are NEVER clobbered (preserves
- * the operator's in-progress typing across locale switches). */
-function applyOverlayToDraft(name: string, loc: string, overlay: unknown, eff: { source: Record<string, unknown> }): void {
- if (!overlay) return;
- const fields = walkTranslatable(eff.source);
- const m: Record<string, string> = {};
- for (const f of fields) {
- const v = getAtPath(overlay, f.segments);
- if (typeof v === 'string' && v.length > 0) m[f.path] = v;
- }
- const tplMap = { ...(draft.value[name] ?? {}) };
- const cur = tplMap[loc] ?? {};
- tplMap[loc] = { ...m, ...cur };
- draft.value = { ...draft.value, [name]: tplMap };
-}
-
-/** Seed the draft for one (template, locale) from:
- * 1. disk overlay (BFF-shipped sibling catalog)
- * 2. OAP overlay row (previously-pushed translations) — wins over disk
- * 3. local-staged draft (operator's in-progress) — wins over both
- * Existing draft values still take precedence over (1) and (2) so
- * active typing isn't disturbed. */
-async function ensureOverlayFetched(name: string, loc: Locale, eff: NonNullable<typeof effective.value>): Promise<void> {
- if (loc === 'en') return;
- const k = overlayKey(name, loc);
- if (Object.prototype.hasOwnProperty.call(fetchedOverlays.value, k)) return;
- try {
- const { disk, oap } = await bff.templateSync.overlay(name, loc);
- fetchedOverlays.value = { ...fetchedOverlays.value, [k]: { disk, oap } };
- // Disk first, then OAP on top — OAP wins per-leaf where set.
- applyOverlayToDraft(name, loc, disk, eff);
- applyOverlayToDraft(name, loc, oap, eff);
- } catch {
- fetchedOverlays.value = { ...fetchedOverlays.value, [k]: { disk: null, oap: null } };
- }
- // Local stage wins over everything — apply last so it survives the
- // seed even when an OAP row exists.
- const staged = localEdits.get<unknown>(name, loc);
- if (staged) applyOverlayToDraft(name, loc, staged, eff);
-}
-
-// `target` MUST be declared above the `watch(effective, ...)` below
-// because that watch uses `{ immediate: true }` and reads `target.value`
-// in its callback — which fires DURING setup. Declaring `target` after
-// the watch leaves it in the TDZ at the moment the immediate callback
-// runs, producing a silent ReferenceError that aborts setup and renders
-// the page blank with no console trace (CLAUDE.md flags this as a
-// recurring failure mode for `immediate: true` watchers).
-const target = ref<Locale>(
- (SUPPORTED_LOCALES.find((l) => l !== 'en') as Locale) ?? 'zh-CN',
-);
-const targetLocales = SUPPORTED_LOCALES.filter((l) => l !== 'en');
-
-watch(
- effective,
- (eff) => {
- if (!eff) return;
- const name = selectedName.value;
- if (!draft.value[name]) {
- draft.value = { ...draft.value, [name]: {} };
- }
- void ensureOverlayFetched(name, target.value, eff);
- },
- { immediate: true },
-);
-
-// When the operator switches target language, lazy-fetch its overlays.
-watch([target, effective], ([loc, eff]) => {
- if (!eff || !selectedName.value) return;
- void ensureOverlayFetched(selectedName.value, loc, eff);
-});
-
-/** Build the overlay object (source-shape mirror) for one (name, locale)
- * from the in-memory draft. Returns null when the draft is empty. */
-function buildOverlayContent(name: string, loc: string, eff: NonNullable<typeof effective.value>): Record<string, unknown> | null {
- const fields = walkTranslatable(eff.source);
- const overlay: Record<string, unknown> = {};
- const m = draft.value[name]?.[loc] ?? {};
- for (const f of fields) {
- const v = m[f.path];
- if (v && v.length > 0) setAtPath(overlay, f.segments, v);
- }
- return Object.keys(overlay).length === 0 ? null : overlay;
-}
-
-/** The source as the preview should render it — the target locale's
- * current draft is merged onto English. */
-const localizedSource = computed<unknown>(() => {
- const eff = effective.value;
- if (!eff) return null;
- const overlay = buildOverlayContent(selectedName.value, target.value, eff);
- if (!overlay) return eff.source;
- return deepMerge(eff.source, overlay);
-});
-
-function deepMerge(src: unknown, ovl: unknown): unknown {
- if (Array.isArray(src)) {
- if (!Array.isArray(ovl)) return src;
- return src.map((item, i) => deepMerge(item, ovl[i]));
- }
- if (src !== null && typeof src === 'object') {
- if (!ovl || typeof ovl !== 'object' || Array.isArray(ovl)) return src;
- const ovlMap = ovl as Record<string, unknown>;
- const out: Record<string, unknown> = {};
- for (const [k, v] of Object.entries(src as Record<string, unknown>)) {
- out[k] = deepMerge(v, ovlMap[k]);
- }
- return out;
- }
- if (typeof src === 'string' && typeof ovl === 'string' && ovl.length > 0) return ovl;
- return src;
-}
-
-const localizedOverview = computed<OverviewDashboard | null>(() => {
- if (selectedKind.value !== 'overview') return null;
- return (localizedSource.value as OverviewDashboard) ?? null;
-});
-const localizedLayer = computed<AdminLayerTemplate | null>(() => {
- if (selectedKind.value !== 'layer') return null;
- return (localizedSource.value as AdminLayerTemplate) ?? null;
-});
-
-// ── Scope (Component) selector for layer kind ──────────────────────
+const {
+ target,
+ targetLocales,
+ fetchedOverlays,
+ editorSource,
+ localizedOverview,
+ localizedLayer,
+ allFields,
+ filledCount,
+ oapOverlayForTarget,
+ draftOverlayForTarget,
+ inUseOverlayForTarget,
+ dirty,
+ hasStagedLocal,
+ overlayKey,
+ draftValue,
+ setDraftValue,
+ applyOverlayToDraft,
+ buildOverlayContent,
+ rebuildDraftForLocale,
+ clearDraftLocale,
+} = useTranslationDraft({ selectedKind, selectedName, effective });
const scopeOptions = computed<Array<{ value: DashboardScope; label: string }>>(() => {
const eff = effective.value;
@@ -369,19 +163,6 @@ const scopeOptions = computed<Array<{ value: DashboardScope; label: string }>>((
];
});
-// ── Translation progress counter ───────────────────────────────────
-
-const allFields = computed<TranslatableField[]>(() => {
- const eff = effective.value;
- return eff ? walkTranslatable(eff.source) : [];
-});
-const filledCount = computed<number>(() => {
- const m = draft.value[selectedName.value]?.[target.value] ?? {};
- return allFields.value.filter((f) => (m[f.path] ?? '').length > 0).length;
-});
-
-// ── Click-widget → floating panel ──────────────────────────────────
-
interface PanelState {
open: boolean;
/** Anchor element for outside-click detection. */
@@ -471,25 +252,6 @@ function onSelectLayerHeader(payload: { el: HTMLElement; event: MouseEvent }): v
openPanel(fields, 'Layer header', payload.el, pointFromEvent(payload.event));
}
-const currentPanelFields = computed<TranslatableField[]>(() => panel.value.fields);
-
-// ── Editing inside the floating panel ──────────────────────────────
-
-function draftValue(path: string): string {
- return draft.value[selectedName.value]?.[target.value]?.[path] ?? '';
-}
-function setDraftValue(path: string, value: string): void {
- const name = selectedName.value;
- const loc = target.value;
- const tplMap = { ...(draft.value[name] ?? {}) };
- const locMap = { ...(tplMap[loc] ?? {}) };
- if (value.length === 0) delete locMap[path];
- else locMap[path] = value;
- tplMap[loc] = locMap;
- draft.value = { ...draft.value, [name]: tplMap };
-}
-
-// ── Stage to local + Push to OAP ───────────────────────────────────
// Per-locale model: stage / push acts on the CURRENT target locale.
// Operator switches Target to translate another language; each locale
// is its own OAP overlay row.
@@ -498,69 +260,9 @@ const banner = computed(() =>
selectedKind.value === 'overview' ? overviewSync.banner.value : layerSync.banner.value,
);
-/** OAP overlay row content for (selected template, target locale).
- * Used as the LEFT side of the push diff. */
-const oapOverlayForTarget = computed<unknown>(() => {
- const snap = fetchedOverlays.value[overlayKey(selectedName.value, target.value)];
- return snap?.oap ?? null;
-});
-
-/** Operator's would-be next OAP overlay for (selected template, target
- * locale) — built from the in-memory draft. */
-const draftOverlayForTarget = computed<Record<string, unknown> | null>(() => {
- const eff = effective.value;
- if (!eff || !selectedName.value) return null;
- return buildOverlayContent(selectedName.value, target.value, eff);
-});
-
-/** Diff state — true when the draft differs from what's on OAP. The
- * push modal's stage / push buttons gate on this. */
-const dirty = computed<boolean>(() => {
- const a = draftOverlayForTarget.value;
- const b = oapOverlayForTarget.value;
- return stableStringify(a ?? null) !== stableStringify(b ?? null);
-});
-
const saveMsg = ref<string | null>(null);
const saving = ref(false);
-/* ── Editor source tracking ────────────────────────────────────────
- * Matches the Layer Dashboards + Overview Templates admin editors:
- * the pill always shows one of three states (`from local` / `from
- * bundled` / `from remote`) and the dropdown lets the operator reset
- * to the disk-shipped overlay only ("bundled") or to whatever OAP
- * currently has ("remote"). Local edits flip the pill to "from
- * local"; discard flips it back to "from remote". */
-const editorSource = ref<'local' | 'bundled' | 'remote'>('remote');
-
-// Switching template or target locale recomputes the source from
-// whether the operator has unstaged local edits for that (name, loc).
-// Don't clobber an explicitly-set source (bundled) inside the same
-// locale — the watcher only fires when name/locale changes.
-watch([selectedName, target], () => {
- editorSource.value = hasStagedLocal.value ? 'local' : 'remote';
-});
-
-/** Rebuild the draft for one (name, locale) from a specific source.
- * - `remote` reproduces the default layering (disk overlay first, OAP
- * overlay wins per leaf) — the canonical baseline the operator
- * sees in the live UI.
- * - `bundled` shows ONLY the disk-shipped overlay, ignoring OAP. Use
- * this to compare against the on-disk seed without OAP overrides. */
-function rebuildDraftForLocale(name: string, loc: string, src: 'remote' | 'bundled'): void {
- const eff = effective.value;
- if (!eff) return;
- const tplMap = { ...(draft.value[name] ?? {}) };
- delete tplMap[loc];
- draft.value = { ...draft.value, [name]: tplMap };
- const snap = fetchedOverlays.value[overlayKey(name, loc)];
- if (!snap) return;
- applyOverlayToDraft(name, loc, snap.disk, eff);
- if (src === 'remote') {
- applyOverlayToDraft(name, loc, snap.oap, eff);
- }
-}
-
/** Reset to dropdown — discard the current local draft and reload the
* draft from the picked source. Symmetric with the layer / overview
* editors. */
@@ -670,13 +372,10 @@ function discardLocal(): void {
setTimeout(() => (saveMsg.value = null), 3000);
}
-const hasStagedLocal = computed<boolean>(() => localEdits.has(selectedName.value, target.value));
-
const readOnly = computed<boolean>(() =>
selectedKind.value === 'overview' ? overviewSync.readOnly.value : layerSync.readOnly.value,
);
-// ── Import / Export ────────────────────────────────────────────────
// Translations are their own OAP rows on their own page, so their
// import/export is separate from the source-template pages. Both act on
// the CURRENT (template, target locale) — the same unit Stage / Push use.
@@ -686,14 +385,6 @@ function flashMsg(msg: string): void {
if (saveMsg.value === msg) saveMsg.value = null;
}, 6000);
}
-/** The in-use overlay for (selected template, target locale): the OAP row
- * (what's published) wins, else the disk-shipped seed. A pushed row is
- * already the full merged overlay, so this is the complete in-use copy. */
-const inUseOverlayForTarget = computed<Record<string, unknown> | null>(() => {
- const snap = fetchedOverlays.value[overlayKey(selectedName.value, target.value)];
- const v = snap?.oap ?? snap?.disk ?? null;
- return v && typeof v === 'object' ? (v as Record<string, unknown>) : null;
-});
const canExport = computed<boolean>(() => inUseOverlayForTarget.value !== null);
function onExport(): void {
const overlay = inUseOverlayForTarget.value;
@@ -741,9 +432,7 @@ async function onImportFile(): Promise<void> {
}
// Overwrite the (template, locale) draft from the imported overlay, then
// stage it locally so Push publishes exactly the imported translation.
- const tplMap = { ...(draft.value[name] ?? {}) };
- delete tplMap[loc];
- draft.value = { ...draft.value, [name]: tplMap };
+ clearDraftLocale(name, loc);
applyOverlayToDraft(name, loc, res.content, eff);
const overlay = buildOverlayContent(name, loc, eff);
if (overlay) localEdits.set(name, loc, overlay);
@@ -756,34 +445,6 @@ async function onImportFile(): Promise<void> {
}),
);
}
-
-/** Human label for a translatable field shown next to the EN source.
- * The wire path (e.g. `kpis[0].label`) is internal — translators
- * shouldn't see it; they should see what KIND of string they're
- * translating (title, tip, tab label, …). EN source identifies
- * which one. */
-const FIELD_LABELS: Record<string, string> = {
- title: 'Title',
- tip: 'Tip',
- description: 'Description',
- label: 'Label',
- group: 'Group',
- alias: 'Alias',
- expressionLabels: 'Series label',
- tableHeaders: 'Column header',
- slots: 'Term',
- aliases: 'Layer alias',
-};
-function leafLabel(segments: Array<string | number>): string {
- // Walk back to the last non-index segment — that's the field's
- // structural name. For `kpis[3].label` it's "label"; for
- // `expressionLabels[2]` it's "expressionLabels".
- for (let i = segments.length - 1; i >= 0; i--) {
- const s = segments[i];
- if (typeof s === 'string') return FIELD_LABELS[s] ?? s;
- }
- return '';
-}
</script>
<template>
@@ -959,45 +620,20 @@ function leafLabel(segments: Array<string | number>): string {
/>
</div>
- <FloatingPanel
+ <TranslationFieldPanel
:open="panel.open"
:anchor="panel.anchor"
:point="panel.point"
- :width="520"
+ :label="panel.label"
+ :target-label="LOCALE_NATIVE_LABEL[target]"
+ :fields="panel.fields"
+ :saving="saving"
+ :dirty="dirty"
+ :draft-value="draftValue"
@close="closePanel"
- >
- <div class="fp">
- <header class="fp__head">
- <div class="fp__head-text">
- <span class="fp__kicker">EN → {{ LOCALE_NATIVE_LABEL[target] }}</span>
- <h4>{{ panel.label }}</h4>
- </div>
- <button type="button" class="fp__close" @click="closePanel">✕</button>
- </header>
- <div class="fp__rows">
- <div v-for="f in currentPanelFields" :key="f.path" class="fp__row">
- <div class="fp__row-meta">
- <span class="fp__tag">{{ leafLabel(f.segments) }}</span>
- <span class="fp__src">{{ f.source }}</span>
- </div>
- <textarea
- v-autosize="draftValue(f.path) || f.source"
- :value="draftValue(f.path)"
- :placeholder="f.source"
- rows="1"
- class="fp__input"
- @input="setDraftValue(f.path, ($event.target as HTMLTextAreaElement).value)"
- ></textarea>
- </div>
- </div>
- <footer class="fp__foot">
- <button type="button" class="sw-btn" @click="closePanel">{{ t('Close') }}</button>
- <button type="button" class="sw-btn is-primary" :disabled="saving || !dirty" @click="stageLocal">
- {{ t('Stage local') }}
- </button>
- </footer>
- </div>
- </FloatingPanel>
+ @update-field="setDraftValue"
+ @stage="stageLocal"
+ />
<Modal
:open="pushOpen"
@@ -1111,52 +747,6 @@ function leafLabel(segments: Array<string | number>): string {
background: var(--sw-bg-1);
}
-/* Floating panel (per-widget translation popover) */
-.fp { display: flex; flex-direction: column; max-height: calc(100vh - 16px); }
-.fp__head {
- display: flex; align-items: flex-start; gap: 10px;
- padding: 10px 12px;
- border-bottom: 1px solid var(--sw-line-2);
- background: var(--sw-bg-2);
-}
-.fp__head-text { flex: 1; min-width: 0; }
-.fp__kicker {
- font-size: 9.5px; letter-spacing: 0.06em; text-transform: uppercase;
- color: var(--sw-accent); display: block; margin-bottom: 2px;
-}
-.fp__head h4 { margin: 0; font-size: 13px; color: var(--sw-fg-0); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
-.fp__close {
- background: none; border: none; color: var(--sw-fg-3);
- cursor: pointer; font-size: 14px; padding: 0 4px;
-}
-.fp__close:hover { color: var(--sw-fg-1); }
-.fp__rows { flex: 1; min-height: 0; overflow-y: auto; padding: 8px 12px; }
-.fp__row { padding: 8px 0; border-bottom: 1px dashed var(--sw-line); }
-.fp__row:last-child { border-bottom: none; }
-.fp__row-meta { display: flex; align-items: baseline; gap: 8px; margin-bottom: 4px; }
-.fp__tag {
- flex: 0 0 auto;
- font-size: 9.5px; letter-spacing: 0.06em; text-transform: uppercase;
- color: var(--sw-fg-3);
- background: var(--sw-bg-2); border: 1px solid var(--sw-line-2);
- padding: 1px 6px; border-radius: 3px;
-}
-.fp__src { font-size: 12px; color: var(--sw-fg-1); font-weight: 500; }
-.fp__input {
- width: 100%; box-sizing: border-box;
- background: var(--sw-bg-2); color: var(--sw-fg-1);
- border: 1px solid var(--sw-line-2); border-radius: 3px;
- padding: 4px 6px; font-size: 12.5px; resize: vertical;
- font-family: inherit;
-}
-.fp__input:focus { outline: none; border-color: var(--sw-accent); }
-.fp__foot {
- padding: 8px 12px;
- border-top: 1px solid var(--sw-line-2);
- display: flex; gap: 6px; justify-content: flex-end;
- background: var(--sw-bg-2);
-}
-
.tv__push-lede {
margin: 0 0 10px; font-size: 12.5px; color: var(--sw-fg-2); line-height: 1.5;
}
diff --git a/apps/ui/src/features/admin/translations/useTranslationDraft.ts b/apps/ui/src/features/admin/translations/useTranslationDraft.ts
new file mode 100644
index 0000000..c583e2f
--- /dev/null
+++ b/apps/ui/src/features/admin/translations/useTranslationDraft.ts
@@ -0,0 +1,351 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Draft / overlay state machine for the Translations page.
+ *
+ * Owns the per-template in-memory translation draft and the disk→oap→local
+ * seeding precedence: for one (template, locale) the draft is seeded from the
+ * BFF-shipped disk overlay, then the OAP overlay row (wins per leaf), then the
+ * operator's local-staged draft (wins over both) — while existing draft values
+ * are never clobbered so active typing survives a locale switch. Exposes the
+ * localized preview source (target draft merged onto English), the per-target
+ * dirty/diff state, the editor-source pill state, and the field-level draft
+ * accessors the floating editor reads/writes.
+ *
+ * The caller passes the picker refs (kind / name) and the strictly-REMOTE
+ * `effective` source; this composable owns `target`, the draft, the fetched
+ * overlay snapshots, and the seeding watches.
+ */
+
+import { computed, ref, watch, type ComputedRef, type Ref } from 'vue';
+import { useLocalTranslationEdits } from '@/controls/localTranslationEdits';
+import { bff } from '@/api/client';
+import { stableStringify } from '@/utils/stableJson';
+import {
+ walkTranslatable,
+ setAtPath,
+ getAtPath,
+ type TranslatableField,
+} from '@/features/admin/_shared/translatableFields';
+import { SUPPORTED_LOCALES, type Locale } from '@/i18n';
+import type { AdminLayerTemplate } from '@/api/client';
+import type { OverviewDashboard } from '@skywalking-horizon-ui/api-client';
+
+/** Effective SOURCE for the picked template — strictly REMOTE. */
+export interface EffectiveSource { source: Record<string, unknown> }
+
+/** OAP + disk overlay snapshots already fetched from the BFF. */
+interface OverlaySnapshot { disk: unknown; oap: unknown }
+
+export interface UseTranslationDraftArgs {
+ selectedKind: Ref<'overview' | 'layer'>;
+ selectedName: Ref<string>;
+ effective: ComputedRef<EffectiveSource | null>;
+}
+
+export interface UseTranslationDraftReturn {
+ target: Ref<Locale>;
+ targetLocales: Locale[];
+ fetchedOverlays: Ref<Record<string, OverlaySnapshot>>;
+ editorSource: Ref<'local' | 'bundled' | 'remote'>;
+ localizedOverview: ComputedRef<OverviewDashboard | null>;
+ localizedLayer: ComputedRef<AdminLayerTemplate | null>;
+ allFields: ComputedRef<TranslatableField[]>;
+ filledCount: ComputedRef<number>;
+ oapOverlayForTarget: ComputedRef<unknown>;
+ draftOverlayForTarget: ComputedRef<Record<string, unknown> | null>;
+ inUseOverlayForTarget: ComputedRef<Record<string, unknown> | null>;
+ dirty: ComputedRef<boolean>;
+ hasStagedLocal: ComputedRef<boolean>;
+ overlayKey: (name: string, locale: string) => string;
+ draftValue: (path: string) => string;
+ setDraftValue: (path: string, value: string) => void;
+ applyOverlayToDraft: (name: string, loc: string, overlay: unknown, eff: EffectiveSource) => void;
+ buildOverlayContent: (name: string, loc: string, eff: EffectiveSource) => Record<string, unknown> | null;
+ rebuildDraftForLocale: (name: string, loc: string, src: 'remote' | 'bundled') => void;
+ clearDraftLocale: (name: string, loc: string) => void;
+}
+
+export function useTranslationDraft(args: UseTranslationDraftArgs): UseTranslationDraftReturn {
+ const { selectedKind, selectedName, effective } = args;
+ const localEdits = useLocalTranslationEdits();
+
+ /** Operator's in-progress overlay, keyed by template-name → locale →
+ * field-path → translation. Editor reads/writes here; Push serializes
+ * the per-locale map back into the sibling OAP overlay row. */
+ const draft = ref<Record<string, Record<string, Record<string, string>>>>({});
+
+ /** OAP + disk overlay snapshots we've already fetched from the BFF,
+ * keyed by `${name}:${locale}`. Used to seed the draft AND to compute
+ * the diff for the push modal. */
+ const fetchedOverlays = ref<Record<string, OverlaySnapshot>>({});
+
+ function overlayKey(name: string, locale: string): string {
+ return `${name}:${locale}`;
+ }
+
+ /** Walk an overlay into the draft for (name, locale). Translatable
+ * leaves only; existing draft values are NEVER clobbered (preserves
+ * the operator's in-progress typing across locale switches). */
+ function applyOverlayToDraft(name: string, loc: string, overlay: unknown, eff: EffectiveSource): void {
+ if (!overlay) return;
+ const fields = walkTranslatable(eff.source);
+ const m: Record<string, string> = {};
+ for (const f of fields) {
+ const v = getAtPath(overlay, f.segments);
+ if (typeof v === 'string' && v.length > 0) m[f.path] = v;
+ }
+ const tplMap = { ...(draft.value[name] ?? {}) };
+ const cur = tplMap[loc] ?? {};
+ tplMap[loc] = { ...m, ...cur };
+ draft.value = { ...draft.value, [name]: tplMap };
+ }
+
+ /** Seed the draft for one (template, locale) from:
+ * 1. disk overlay (BFF-shipped sibling catalog)
+ * 2. OAP overlay row (previously-pushed translations) — wins over disk
+ * 3. local-staged draft (operator's in-progress) — wins over both
+ * Existing draft values still take precedence over (1) and (2) so
+ * active typing isn't disturbed. */
+ async function ensureOverlayFetched(name: string, loc: Locale, eff: EffectiveSource): Promise<void> {
+ if (loc === 'en') return;
+ const k = overlayKey(name, loc);
+ if (Object.prototype.hasOwnProperty.call(fetchedOverlays.value, k)) return;
+ try {
+ const { disk, oap } = await bff.templateSync.overlay(name, loc);
+ fetchedOverlays.value = { ...fetchedOverlays.value, [k]: { disk, oap } };
+ // Disk first, then OAP on top — OAP wins per-leaf where set.
+ applyOverlayToDraft(name, loc, disk, eff);
+ applyOverlayToDraft(name, loc, oap, eff);
+ } catch {
+ fetchedOverlays.value = { ...fetchedOverlays.value, [k]: { disk: null, oap: null } };
+ }
+ // Local stage wins over everything — apply last so it survives the
+ // seed even when an OAP row exists.
+ const staged = localEdits.get<unknown>(name, loc);
+ if (staged) applyOverlayToDraft(name, loc, staged, eff);
+ }
+
+ // `target` MUST be declared above the `watch(effective, ...)` below
+ // because that watch uses `{ immediate: true }` and reads `target.value`
+ // in its callback — which fires DURING setup. Declaring `target` after
+ // the watch leaves it in the TDZ at the moment the immediate callback
+ // runs, producing a silent ReferenceError that aborts setup and renders
+ // the page blank with no console trace (CLAUDE.md flags this as a
+ // recurring failure mode for `immediate: true` watchers).
+ const target = ref<Locale>(
+ (SUPPORTED_LOCALES.find((l) => l !== 'en') as Locale) ?? 'zh-CN',
+ );
+ const targetLocales = SUPPORTED_LOCALES.filter((l) => l !== 'en');
+
+ watch(
+ effective,
+ (eff) => {
+ if (!eff) return;
+ const name = selectedName.value;
+ if (!draft.value[name]) {
+ draft.value = { ...draft.value, [name]: {} };
+ }
+ void ensureOverlayFetched(name, target.value, eff);
+ },
+ { immediate: true },
+ );
+
+ // When the operator switches target language, lazy-fetch its overlays.
+ watch([target, effective], ([loc, eff]) => {
+ if (!eff || !selectedName.value) return;
+ void ensureOverlayFetched(selectedName.value, loc, eff);
+ });
+
+ /** Build the overlay object (source-shape mirror) for one (name, locale)
+ * from the in-memory draft. Returns null when the draft is empty. */
+ function buildOverlayContent(name: string, loc: string, eff: EffectiveSource): Record<string, unknown> | null {
+ const fields = walkTranslatable(eff.source);
+ const overlay: Record<string, unknown> = {};
+ const m = draft.value[name]?.[loc] ?? {};
+ for (const f of fields) {
+ const v = m[f.path];
+ if (v && v.length > 0) setAtPath(overlay, f.segments, v);
+ }
+ return Object.keys(overlay).length === 0 ? null : overlay;
+ }
+
+ /** The source as the preview should render it — the target locale's
+ * current draft is merged onto English. */
+ const localizedSource = computed<unknown>(() => {
+ const eff = effective.value;
+ if (!eff) return null;
+ const overlay = buildOverlayContent(selectedName.value, target.value, eff);
+ if (!overlay) return eff.source;
+ return deepMerge(eff.source, overlay);
+ });
+
+ function deepMerge(src: unknown, ovl: unknown): unknown {
+ if (Array.isArray(src)) {
+ if (!Array.isArray(ovl)) return src;
+ return src.map((item, i) => deepMerge(item, ovl[i]));
+ }
+ if (src !== null && typeof src === 'object') {
+ if (!ovl || typeof ovl !== 'object' || Array.isArray(ovl)) return src;
+ const ovlMap = ovl as Record<string, unknown>;
+ const out: Record<string, unknown> = {};
+ for (const [k, v] of Object.entries(src as Record<string, unknown>)) {
+ out[k] = deepMerge(v, ovlMap[k]);
+ }
+ return out;
+ }
+ if (typeof src === 'string' && typeof ovl === 'string' && ovl.length > 0) return ovl;
+ return src;
+ }
+
+ const localizedOverview = computed<OverviewDashboard | null>(() => {
+ if (selectedKind.value !== 'overview') return null;
+ return (localizedSource.value as OverviewDashboard) ?? null;
+ });
+ const localizedLayer = computed<AdminLayerTemplate | null>(() => {
+ if (selectedKind.value !== 'layer') return null;
+ return (localizedSource.value as AdminLayerTemplate) ?? null;
+ });
+
+ // ── Translation progress counter ─────────────────────────────────
+ const allFields = computed<TranslatableField[]>(() => {
+ const eff = effective.value;
+ return eff ? walkTranslatable(eff.source) : [];
+ });
+ const filledCount = computed<number>(() => {
+ const m = draft.value[selectedName.value]?.[target.value] ?? {};
+ return allFields.value.filter((f) => (m[f.path] ?? '').length > 0).length;
+ });
+
+ // ── Field-level draft accessors ──────────────────────────────────
+ function draftValue(path: string): string {
+ return draft.value[selectedName.value]?.[target.value]?.[path] ?? '';
+ }
+ function setDraftValue(path: string, value: string): void {
+ const name = selectedName.value;
+ const loc = target.value;
+ const tplMap = { ...(draft.value[name] ?? {}) };
+ const locMap = { ...(tplMap[loc] ?? {}) };
+ if (value.length === 0) delete locMap[path];
+ else locMap[path] = value;
+ tplMap[loc] = locMap;
+ draft.value = { ...draft.value, [name]: tplMap };
+ }
+
+ /** OAP overlay row content for (selected template, target locale).
+ * Used as the LEFT side of the push diff. */
+ const oapOverlayForTarget = computed<unknown>(() => {
+ const snap = fetchedOverlays.value[overlayKey(selectedName.value, target.value)];
+ return snap?.oap ?? null;
+ });
+
+ /** Operator's would-be next OAP overlay for (selected template, target
+ * locale) — built from the in-memory draft. */
+ const draftOverlayForTarget = computed<Record<string, unknown> | null>(() => {
+ const eff = effective.value;
+ if (!eff || !selectedName.value) return null;
+ return buildOverlayContent(selectedName.value, target.value, eff);
+ });
+
+ /** The in-use overlay for (selected template, target locale): the OAP row
+ * (what's published) wins, else the disk-shipped seed. A pushed row is
+ * already the full merged overlay, so this is the complete in-use copy. */
+ const inUseOverlayForTarget = computed<Record<string, unknown> | null>(() => {
+ const snap = fetchedOverlays.value[overlayKey(selectedName.value, target.value)];
+ const v = snap?.oap ?? snap?.disk ?? null;
+ return v && typeof v === 'object' ? (v as Record<string, unknown>) : null;
+ });
+
+ /** Diff state — true when the draft differs from what's on OAP. The
+ * push modal's stage / push buttons gate on this. */
+ const dirty = computed<boolean>(() => {
+ const a = draftOverlayForTarget.value;
+ const b = oapOverlayForTarget.value;
+ return stableStringify(a ?? null) !== stableStringify(b ?? null);
+ });
+
+ const hasStagedLocal = computed<boolean>(() => localEdits.has(selectedName.value, target.value));
+
+ /* ── Editor source tracking ──────────────────────────────────────
+ * Matches the Layer Dashboards + Overview Templates admin editors:
+ * the pill always shows one of three states (`from local` / `from
+ * bundled` / `from remote`) and the dropdown lets the operator reset
+ * to the disk-shipped overlay only ("bundled") or to whatever OAP
+ * currently has ("remote"). Local edits flip the pill to "from
+ * local"; discard flips it back to "from remote". */
+ const editorSource = ref<'local' | 'bundled' | 'remote'>('remote');
+
+ // Switching template or target locale recomputes the source from
+ // whether the operator has unstaged local edits for that (name, loc).
+ // Don't clobber an explicitly-set source (bundled) inside the same
+ // locale — the watcher only fires when name/locale changes.
+ watch([selectedName, target], () => {
+ editorSource.value = hasStagedLocal.value ? 'local' : 'remote';
+ });
+
+ /** Rebuild the draft for one (name, locale) from a specific source.
+ * - `remote` reproduces the default layering (disk overlay first, OAP
+ * overlay wins per leaf) — the canonical baseline the operator
+ * sees in the live UI.
+ * - `bundled` shows ONLY the disk-shipped overlay, ignoring OAP. Use
+ * this to compare against the on-disk seed without OAP overrides. */
+ function rebuildDraftForLocale(name: string, loc: string, src: 'remote' | 'bundled'): void {
+ const eff = effective.value;
+ if (!eff) return;
+ const tplMap = { ...(draft.value[name] ?? {}) };
+ delete tplMap[loc];
+ draft.value = { ...draft.value, [name]: tplMap };
+ const snap = fetchedOverlays.value[overlayKey(name, loc)];
+ if (!snap) return;
+ applyOverlayToDraft(name, loc, snap.disk, eff);
+ if (src === 'remote') {
+ applyOverlayToDraft(name, loc, snap.oap, eff);
+ }
+ }
+
+ /** Drop the (name, locale) draft slot entirely — used before overwriting
+ * it from an imported overlay. */
+ function clearDraftLocale(name: string, loc: string): void {
+ const tplMap = { ...(draft.value[name] ?? {}) };
+ delete tplMap[loc];
+ draft.value = { ...draft.value, [name]: tplMap };
+ }
+
+ return {
+ target,
+ targetLocales,
+ fetchedOverlays,
+ editorSource,
+ localizedOverview,
+ localizedLayer,
+ allFields,
+ filledCount,
+ oapOverlayForTarget,
+ draftOverlayForTarget,
+ inUseOverlayForTarget,
+ dirty,
+ hasStagedLocal,
+ overlayKey,
+ draftValue,
+ setDraftValue,
+ applyOverlayToDraft,
+ buildOverlayContent,
+ rebuildDraftForLocale,
+ clearDraftLocale,
+ };
+}
diff --git a/apps/ui/src/features/admin/translations/useTranslationPicker.ts b/apps/ui/src/features/admin/translations/useTranslationPicker.ts
new file mode 100644
index 0000000..b33bc85
--- /dev/null
+++ b/apps/ui/src/features/admin/translations/useTranslationPicker.ts
@@ -0,0 +1,149 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Entry-list assembly for the Translations picker.
+ *
+ * Builds the overview / layer `TemplatePickerEntry[]` (remote rows plus the
+ * bundled-only rows that come off the sync-status badge list) and the per-row
+ * metadata — sync badge, has-local-draft flag, divergence, and the per-locale
+ * status chips (overlay sync state, with the operator's unstaged browser draft
+ * taking precedence). The active list switches on the picker's selected kind.
+ */
+
+import { computed, type ComputedRef, type Ref } from 'vue';
+import { useTemplateSources } from '@/features/admin/_shared/useTemplateSources';
+import { useTemplateSync } from '@/features/admin/_shared/useTemplateSync';
+import { type TemplatePickerEntry } from '@/features/admin/_shared/TemplatePicker.vue';
+import { useLocalTranslationEdits } from '@/controls/localTranslationEdits';
+import { SUPPORTED_LOCALES } from '@/i18n';
+import type { AdminLayerTemplate } from '@/api/client';
+import type { OverviewDashboard } from '@skywalking-horizon-ui/api-client';
+
+export interface UseTranslationPickerReturn {
+ overviewSources: ReturnType<typeof useTemplateSources>;
+ layerSources: ReturnType<typeof useTemplateSources>;
+ layerSync: ReturnType<typeof useTemplateSync>;
+ overviewSync: ReturnType<typeof useTemplateSync>;
+ overviewEntries: ComputedRef<TemplatePickerEntry[]>;
+ layerEntries: ComputedRef<TemplatePickerEntry[]>;
+ activeEntries: ComputedRef<TemplatePickerEntry[]>;
+}
+
+export function useTranslationPicker(selectedKind: Ref<'overview' | 'layer'>): UseTranslationPickerReturn {
+ const overviewSources = useTemplateSources('overview');
+ const layerSources = useTemplateSources('layer');
+ const layerSync = useTemplateSync({ kind: 'layer' });
+ const overviewSync = useTemplateSync({ kind: 'overview' });
+ const localEdits = useLocalTranslationEdits();
+
+ // Bundled-only entries (overview / layer rows the operator may not
+ // have pushed yet) come off the sync-status badge list.
+ const bundledOverviewNames = computed<string[]>(() => {
+ const s = overviewSync.status.value;
+ return s ? s.badges.filter((b) => b.kind === 'overview').map((b) => b.name) : [];
+ });
+ const layerNames = computed<string[]>(() => {
+ const s = layerSync.status.value;
+ return s ? s.badges.filter((b) => b.kind === 'layer').map((b) => b.name) : [];
+ });
+
+ function metaFor(name: string, kind: 'overview' | 'layer'): {
+ syncBadge: ReturnType<typeof layerSync.badgeFor>;
+ hasLocalDraft: boolean;
+ isDiverged: boolean;
+ localeBadges: TemplatePickerEntry['localeBadges'];
+ } {
+ const sync = kind === 'overview' ? overviewSync : layerSync;
+ const sources = kind === 'overview' ? overviewSources : layerSources;
+ const badge = sync.badgeFor(name);
+ // Per-locale status chips: derived from the overlay sibling rows
+ // already present in sync-status, with the operator's unstaged
+ // browser draft taking precedence ('local' wins over any sync state).
+ const localeBadges = SUPPORTED_LOCALES.filter((l) => l !== 'en').map((locale) => {
+ if (localEdits.has(name, locale)) {
+ return { locale, status: 'local' as const };
+ }
+ const s = sources.overlayStatus(name, locale);
+ return { locale, status: s ?? ('empty' as const) };
+ });
+ return {
+ syncBadge: badge,
+ // Picker chip lights up when ANY locale has an unstaged draft for
+ // this template.
+ hasLocalDraft: localEdits.localesFor(name).length > 0,
+ isDiverged: badge === 'diverged',
+ localeBadges,
+ };
+ }
+
+ const overviewEntries = computed<TemplatePickerEntry[]>(() => {
+ const out: TemplatePickerEntry[] = [];
+ const seen = new Set<string>();
+ const push = (name: string, content: OverviewDashboard | null): void => {
+ if (!content || seen.has(name)) return;
+ seen.add(name);
+ out.push({
+ value: name,
+ label: content.title || content.id,
+ key: content.id,
+ ...metaFor(name, 'overview'),
+ });
+ };
+ for (const name of overviewSources.remoteNames()) {
+ push(name, overviewSources.remote<OverviewDashboard>(name));
+ }
+ for (const name of bundledOverviewNames.value) {
+ push(name, overviewSources.bundled<OverviewDashboard>(name));
+ }
+ out.sort((a, b) => a.label.localeCompare(b.label));
+ return out;
+ });
+
+ const layerEntries = computed<TemplatePickerEntry[]>(() => {
+ const out: TemplatePickerEntry[] = [];
+ for (const name of layerNames.value) {
+ const content =
+ layerSources.remote<AdminLayerTemplate>(name) ??
+ layerSources.bundled<AdminLayerTemplate>(name);
+ if (!content) continue;
+ out.push({
+ value: name,
+ label: content.alias || content.key,
+ key: content.key,
+ color: content.color,
+ ...metaFor(name, 'layer'),
+ });
+ }
+ out.sort((a, b) => a.label.localeCompare(b.label));
+ return out;
+ });
+
+ const activeEntries = computed<TemplatePickerEntry[]>(() =>
+ selectedKind.value === 'overview' ? overviewEntries.value : layerEntries.value,
+ );
+
+ return {
+ overviewSources,
+ layerSources,
+ layerSync,
+ overviewSync,
+ overviewEntries,
+ layerEntries,
+ activeEntries,
+ };
+}
diff --git a/apps/ui/src/features/admin/users/UsersAdminView.vue b/apps/ui/src/features/admin/users/UsersAdminView.vue
index 402b41b..1ca045d 100644
--- a/apps/ui/src/features/admin/users/UsersAdminView.vue
+++ b/apps/ui/src/features/admin/users/UsersAdminView.vue
@@ -104,7 +104,6 @@ function rolePill(role: string): string {
<div v-if="loading" class="loading">{{ t('Loading users…') }}</div>
<div v-else-if="error" class="error">{{ t('Failed to load: {msg}', { msg: error }) }}</div>
<template v-else-if="data">
- <!-- LDAP hint banner -->
<div v-if="data.backend === 'ldap'" class="hint hint-info">
<span class="hint-icon">ⓘ</span>
<div class="hint-body">
@@ -133,7 +132,6 @@ function rolePill(role: string): string {
</div>
</div>
- <!-- KPI cards -->
<div class="kpi-grid">
<div class="kpi-card">
<div class="kpi-label">{{ t('Total') }}</div>
@@ -166,7 +164,6 @@ function rolePill(role: string): string {
<template #node><code>{{ data.node }}</code></template>
</i18n-t>
... 40191 lines suppressed ...