From a386198a2b1223f836283c5a4085046fabaeec3b Mon Sep 17 00:00:00 2001 From: YektaY Date: Thu, 15 Oct 2026 22:41:32 -0700 Subject: [PATCH 001/150] Install @slaclab packages from GitHub Packages Map the @slaclab scope to npm.pkg.github.com in a committed .npmrc (no token), and give the Test and Lint workflows read access to GitHub Packages: packages: read, setup-node registry-url and scope, and NODE_AUTH_TOKEN from GITHUB_TOKEN on install. The README documents the read:packages PAT developers need in ~/.npmrc, and the per-package Actions access grant that CI relies on. No @slaclab dependency is added yet; #86, #87 and #88 build on this. --- .github/workflows/lint.yml | 11 +++++++++++ .github/workflows/test.yml | 11 +++++++++++ .npmrc | 1 + README.md | 19 +++++++++++++++++++ 4 files changed, 42 insertions(+) create mode 100644 .npmrc diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index cee921d..eac1fd4 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -6,6 +6,13 @@ on: pull_request: branches: [main] +# packages: read lets GITHUB_TOKEN install @slaclab/canopy-* from GitHub Packages. +# Each of those packages must also grant this repository read access +# (package settings -> Manage Actions access). +permissions: + contents: read + packages: read + jobs: lint: name: ESLint & Prettier @@ -28,7 +35,11 @@ jobs: with: node-version: 23.11.0 cache: pnpm + registry-url: 'https://npm.pkg.github.com' + scope: '@slaclab' - run: pnpm install + env: + NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Run ESLint run: pnpm run lint diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 01ebdc5..273591b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -6,6 +6,13 @@ on: pull_request: branches: [main] +# packages: read lets GITHUB_TOKEN install @slaclab/canopy-* from GitHub Packages. +# Each of those packages must also grant this repository read access +# (package settings -> Manage Actions access). +permissions: + contents: read + packages: read + jobs: test: runs-on: ubuntu-latest @@ -20,9 +27,13 @@ jobs: uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6 with: cache: 'pnpm' + registry-url: 'https://npm.pkg.github.com' + scope: '@slaclab' - name: Install dependencies run: pnpm install + env: + NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Run tests run: pnpm test diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..0011faf --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +@slaclab:registry=https://npm.pkg.github.com diff --git a/README.md b/README.md index a0a6fc2..3039375 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,25 @@ React + Vite frontend for the Canopy / Trace plotting tool. Reads archive data from Canopy's Mole module (`/mole/v1/...`). +## Registry access + +The shared Canopy packages (`@slaclab/canopy-*`) are published to GitHub Packages, not +npm. The committed `.npmrc` points the `@slaclab` scope at `https://npm.pkg.github.com`. +That registry requires authentication even to read, so once the app depends on an +`@slaclab` package, `pnpm install` needs a token: + +1. Create a classic personal access token with the `read:packages` scope. +2. Add it to your user-level `~/.npmrc`, never to the repo's `.npmrc`: + + ``` + //npm.pkg.github.com/:_authToken= + ``` + +CI authenticates with the workflow's `GITHUB_TOKEN` (`packages: read`). That only works +if each `@slaclab/canopy-*` package grants this repository read access under +**Package settings → Manage Actions access**. See the +[canopy-sdk-js install notes](https://github.com/slaclab/canopy-sdk-js#installing-consumers). + ## Local dev ### 1. Run the Canopy backend From 8e78a6249ef4112a3224a7494057994769cbe6df Mon Sep 17 00:00:00 2001 From: YektaY Date: Fri, 16 Oct 2026 07:46:59 -0700 Subject: [PATCH 002/150] Adopt canopy-shell color mode (g10/g100) Replace trace's own color-mode store with the shared one from @slaclab/canopy-shell 0.2: - main.tsx configures it with the existing trace.theme key and the dark default, so users keep their choice, and paints before the first render. It also loads the shell's CSS after Carbon's. - App renders ColorModeTheme: g10 in light mode and g100 (not g90) in dark mode. The detached plot and Data Insight windows use it too, and DetachedWindow copies the Carbon theme class to the popup's . - The hard-coded body background is gone; Carbon's theme class on paints it, and index.html starts dark (g100) to avoid a white first paint. - Workspace import calls the store's setColorMode directly. The SDK store reads localStorage lazily and guarded, so the jsdom tests no longer need --no-experimental-webstorage on Node 26. --- index.html | 4 +- package.json | 1 + pnpm-lock.yaml | 18 ++++++++ src/App.tsx | 13 +++--- src/components/DetachedWindow.tsx | 6 +++ src/components/PlotArea.tsx | 2 +- src/components/Toolbar.tsx | 2 +- src/components/TraceApp.tsx | 20 ++++----- src/index.css | 4 -- src/io/serialize.ts | 2 +- src/main.tsx | 6 +++ src/state/colorMode.test.ts | 68 +++++++++++++++++++++++++++++++ src/state/colorMode.ts | 22 ++++++++++ src/state/paletteStore.ts | 2 +- src/state/themeStore.ts | 51 ----------------------- 15 files changed, 140 insertions(+), 81 deletions(-) create mode 100644 src/state/colorMode.test.ts create mode 100644 src/state/colorMode.ts delete mode 100644 src/state/themeStore.ts diff --git a/index.html b/index.html index fa86a70..46c6f64 100644 --- a/index.html +++ b/index.html @@ -1,5 +1,7 @@ - + + diff --git a/package.json b/package.json index 6ccf2a7..5b1e07d 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "@dnd-kit/core": "^6.3.1", "@dnd-kit/sortable": "^10.0.0", "@dnd-kit/utilities": "^3.2.2", + "@slaclab/canopy-shell": "^0.2.0", "echarts": "^6.1.0", "echarts-for-react": "^3.0.6", "react": "^19.2.6", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5d6e303..9388814 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -26,6 +26,9 @@ importers: '@dnd-kit/utilities': specifier: ^3.2.2 version: 3.2.2(react@19.2.6) + '@slaclab/canopy-shell': + specifier: ^0.2.0 + version: 0.2.0(@carbon/icons-react@11.81.0(react@19.2.6))(@carbon/react@1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.99.0))(react-dom@19.2.6(react@19.2.6))(react@19.2.6) echarts: specifier: ^6.1.0 version: 6.1.0 @@ -653,6 +656,14 @@ packages: '@rolldown/pluginutils@1.0.0-rc.7': resolution: {integrity: sha512-qujRfC8sFVInYSPPMLQByRh7zhwkGFS4+tyMQ83srV1qrxL4g8E2tyxVVyxd0+8QeBM1mIk9KbWxkegRr76XzA==} + '@slaclab/canopy-shell@0.2.0': + resolution: {integrity: sha512-j9u6y1CHEePSLirX07NDNnS/ka9tdylV19ogjTJ601KvwrZcxBndGzsp0H8ziJRDQDK6XQBrFBSkV/c7vYksgw==, tarball: https://npm.pkg.github.com/download/@slaclab/canopy-shell/0.2.0/1e0145073a2e6774fe4d54bd68bbea81bf7d38e0} + peerDependencies: + '@carbon/icons-react': ^11.50.0 + '@carbon/react': ^1.90.0 + react: ^19.0.0 + react-dom: ^19.0.0 + '@standard-schema/spec@1.1.0': resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} @@ -2367,6 +2378,13 @@ snapshots: '@rolldown/pluginutils@1.0.0-rc.7': {} + '@slaclab/canopy-shell@0.2.0(@carbon/icons-react@11.81.0(react@19.2.6))(@carbon/react@1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.99.0))(react-dom@19.2.6(react@19.2.6))(react@19.2.6)': + dependencies: + '@carbon/icons-react': 11.81.0(react@19.2.6) + '@carbon/react': 1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.99.0) + react: 19.2.6 + react-dom: 19.2.6(react@19.2.6) + '@standard-schema/spec@1.1.0': {} '@swc/helpers@0.5.21': diff --git a/src/App.tsx b/src/App.tsx index 45c9c5d..a01e0cd 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,16 +1,13 @@ -import { Theme } from '@carbon/react'; +import { ColorModeTheme } from '@slaclab/canopy-shell'; import { TraceApp } from './components/TraceApp'; -import { useColorMode } from './state/themeStore'; import './App.css'; export default function App() { - const { colorMode } = useColorMode(); - // Body theme follows colorMode (g90 = "darkest readable", g10 = "lightest"). - // The header inside TraceApp is wrapped in its own so - // the brand bar stays dark in light mode — same convention as react-squirrel. + // The SLAC standard page themes, from the canopy-shell color-mode store: g10 + // in light mode, g100 in dark mode. The header follows the page theme. return ( - + - + ); } diff --git a/src/components/DetachedWindow.tsx b/src/components/DetachedWindow.tsx index d140da3..bc7b35a 100644 --- a/src/components/DetachedWindow.tsx +++ b/src/components/DetachedWindow.tsx @@ -67,6 +67,12 @@ export function DetachedWindow({ popup.document.title = title; popup.document.body.style.margin = '0'; popup.document.documentElement.dataset.theme = document.documentElement.dataset.theme ?? 'dark'; + // Also the Carbon theme class (cds--g10/cds--g100) the color-mode store puts + // on , so Carbon content portaled inside the popup gets the right tokens. + const carbonTheme = Array.from(document.documentElement.classList).find((c) => + /^cds--(white|g10|g90|g100)$/.test(c) + ); + if (carbonTheme) popup.document.documentElement.classList.add(carbonTheme); const mount = popup.document.createElement('div'); mount.style.height = '100vh'; diff --git a/src/components/PlotArea.tsx b/src/components/PlotArea.tsx index 3ca27a6..2283188 100644 --- a/src/components/PlotArea.tsx +++ b/src/components/PlotArea.tsx @@ -10,7 +10,7 @@ import type { TimeWindowNs } from '../api/time'; import { msToNs, nsToMs, resolveTimeWindow } from '../api/time'; import { echartsLineType, echartsSymbol } from '../curveStyle'; import { traceLabel } from '../traceLabel'; -import { useColorMode } from '../state/themeStore'; +import { useColorMode } from '@slaclab/canopy-shell/color-mode'; import type { PngSource } from '../io/exportPlotImage'; import { AXIS_OFFSET, diff --git a/src/components/Toolbar.tsx b/src/components/Toolbar.tsx index 68fcf2f..7b5773a 100644 --- a/src/components/Toolbar.tsx +++ b/src/components/Toolbar.tsx @@ -13,7 +13,7 @@ import { SendAlt, } from '@carbon/icons-react'; import { HeaderGlobalAction } from '@carbon/react'; -import type { ColorMode } from '../state/themeStore'; +import type { ColorMode } from '@slaclab/canopy-shell'; import { formatShortcut } from '../hooks/useKeyboardShortcuts'; interface ToolbarProps { diff --git a/src/components/TraceApp.tsx b/src/components/TraceApp.tsx index 566bb3b..8714b45 100644 --- a/src/components/TraceApp.tsx +++ b/src/components/TraceApp.tsx @@ -24,7 +24,7 @@ import { useFormulaSeries, type FormulaSeriesResult } from '../hooks/useFormulaS import type { TimeWindowNs } from '../api/time'; import { resolveTimeWindow } from '../api/time'; import { fetchMetadata } from '../api/mole'; -import { useColorMode } from '../state/themeStore'; +import { ColorModeTheme, useColorMode } from '@slaclab/canopy-shell'; import { usePaletteId } from '../state/paletteStore'; import { getPalette, colorForIndex } from '../palettes'; import { downloadBlob, downloadDataUrl, pickFile } from '../io/download'; @@ -113,7 +113,7 @@ export function TraceApp() { detached: boolean; pv?: string; }>({ open: false, minimized: false, detached: false }); - const { colorMode, toggle: toggleTheme } = useColorMode(); + const { colorMode, setColorMode, toggle: toggleTheme } = useColorMode(); const { paletteId } = usePaletteId(); const elogConfig = useElogConfig(); // E-Log post dialog. `captured` holds the plot PNGs snapshotted at open time @@ -677,11 +677,7 @@ export function TraceApp() { } setPlots(result.plots); if (result.plots.length > 0) setActivePlotId(result.plots[0].id); - if (result.theme) { - // setColorMode lives on the store; the hook surface only exposes toggle, - // so go through the module API. - void import('../state/themeStore').then((m) => m.setColorMode(result.theme!)); - } + if (result.theme) setColorMode(result.theme); if (result.warnings.length > 0) { console.warn('Import warnings:', result.warnings); alert(`Imported with ${result.warnings.length} warning(s):\n\n${result.warnings.join('\n')}`); @@ -1110,8 +1106,7 @@ export function TraceApp() { title={`${plot.title} — Trace`} onClose={() => reattachPlot(id)} > - handleChartInstance(plot.id, inst, active)} /> - + ); })} @@ -1180,8 +1175,7 @@ export function TraceApp() { height={560} onClose={() => setInsight((p) => ({ ...p, detached: false }))} > - setInsight((p) => ({ ...p, open: false, detached: false }))} onReattach={() => setInsight((p) => ({ ...p, detached: false }))} /> - + )} diff --git a/src/index.css b/src/index.css index 44c5b74..b686e49 100644 --- a/src/index.css +++ b/src/index.css @@ -14,7 +14,3 @@ body, padding: 0; overflow: hidden; } - -body { - background-color: #161616; -} diff --git a/src/io/serialize.ts b/src/io/serialize.ts index a60904f..d0b7cc5 100644 --- a/src/io/serialize.ts +++ b/src/io/serialize.ts @@ -1,5 +1,5 @@ import type { Plot, PVTrace, Axis } from '../types'; -import type { ColorMode } from '../state/themeStore'; +import type { ColorMode } from '@slaclab/canopy-shell/color-mode'; import { getPalette, colorForIndex, DEFAULT_PALETTE_ID } from '../palettes'; import { parseSpanMs, toDatetimeLocal } from '../api/time'; diff --git a/src/main.tsx b/src/main.tsx index df655ea..1fe0df6 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -1,8 +1,14 @@ import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import './index.css'; +// After Carbon's CSS (imported first by index.css), before the app's own. +import '@slaclab/canopy-shell/styles.css'; +import { setupColorMode } from './state/colorMode'; import App from './App.tsx'; +// Before the first render: read trace.theme and paint to match. +setupColorMode(); + createRoot(document.getElementById('root')!).render( diff --git a/src/state/colorMode.test.ts b/src/state/colorMode.test.ts new file mode 100644 index 0000000..c21cc16 --- /dev/null +++ b/src/state/colorMode.test.ts @@ -0,0 +1,68 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { getColorMode, setColorMode } from '@slaclab/canopy-shell/color-mode'; +import { TRACE_COLOR_MODE, setupColorMode } from './colorMode'; + +// In-memory localStorage, so the test doesn't depend on whether this Node +// version exposes jsdom's storage (Node 26 shadows it without +// --localstorage-file). +function memoryStorage(): Storage { + const data = new Map(); + return { + get length() { + return data.size; + }, + clear: () => data.clear(), + getItem: (key) => data.get(key) ?? null, + key: (i) => Array.from(data.keys())[i] ?? null, + removeItem: (key) => void data.delete(key), + setItem: (key, value) => void data.set(key, String(value)), + }; +} + +let storage: Storage; + +beforeEach(() => { + storage = memoryStorage(); + vi.stubGlobal('localStorage', storage); + document.documentElement.className = ''; + delete document.documentElement.dataset.theme; +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('setupColorMode', () => { + it('keeps the trace.theme key and the dark default', () => { + expect(TRACE_COLOR_MODE).toEqual({ storageKey: 'trace.theme', defaultMode: 'dark' }); + }); + + it("honors an existing user's stored light choice and paints g10", () => { + storage.setItem('trace.theme', 'light'); + setupColorMode(); + expect(getColorMode()).toBe('light'); + expect(document.documentElement.classList.contains('cds--g10')).toBe(true); + expect(document.documentElement.classList.contains('cds--g100')).toBe(false); + expect(document.documentElement.dataset.theme).toBe('light'); + }); + + it('defaults to dark (g100) when nothing is stored', () => { + setupColorMode(); + expect(getColorMode()).toBe('dark'); + expect(document.documentElement.classList.contains('cds--g100')).toBe(true); + expect(document.documentElement.dataset.theme).toBe('dark'); + }); + + it('ignores an invalid stored value', () => { + storage.setItem('trace.theme', 'sepia'); + setupColorMode(); + expect(getColorMode()).toBe('dark'); + }); + + it('persists a new choice under trace.theme', () => { + setupColorMode(); + setColorMode('light'); + expect(storage.getItem('trace.theme')).toBe('light'); + }); +}); diff --git a/src/state/colorMode.ts b/src/state/colorMode.ts new file mode 100644 index 0000000..86ae454 --- /dev/null +++ b/src/state/colorMode.ts @@ -0,0 +1,22 @@ +import { + configureColorMode, + getColorMode, + syncDocumentColorMode, +} from '@slaclab/canopy-shell/color-mode'; + +/** + * Trace's settings for the shared @slaclab/canopy-shell color-mode store. The + * `trace.theme` key is the one trace's own store used, so existing users keep + * their choice; dark stays the default. + */ +export const TRACE_COLOR_MODE = { storageKey: 'trace.theme', defaultMode: 'dark' } as const; + +/** + * Configure the store and mirror the stored mode onto (`data-theme` and + * the Carbon `cds--g10`/`cds--g100` class). Call once in main.tsx, before the + * first render, so the page background is right before React mounts. + */ +export function setupColorMode(): void { + configureColorMode(TRACE_COLOR_MODE); + syncDocumentColorMode(getColorMode()); +} diff --git a/src/state/paletteStore.ts b/src/state/paletteStore.ts index 1c888cc..7268aab 100644 --- a/src/state/paletteStore.ts +++ b/src/state/paletteStore.ts @@ -3,7 +3,7 @@ import { DEFAULT_PALETTE_ID, getPalette } from '../palettes'; // Global default palette id — the palette new curves are colored from // cyclically. Persisted to localStorage so the choice survives reloads, in the -// same lightweight external-store style as themeStore.ts. +// same lightweight external-store style as the canopy-shell color-mode store. const STORAGE_KEY = 'trace.palette'; diff --git a/src/state/themeStore.ts b/src/state/themeStore.ts deleted file mode 100644 index cb6fc25..0000000 --- a/src/state/themeStore.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { useEffect, useSyncExternalStore } from 'react'; - -export type ColorMode = 'light' | 'dark'; -const STORAGE_KEY = 'trace.theme'; -const DEFAULT_MODE: ColorMode = 'dark'; - -function readInitial(): ColorMode { - if (typeof window === 'undefined') return DEFAULT_MODE; - const stored = window.localStorage.getItem(STORAGE_KEY); - return stored === 'light' || stored === 'dark' ? stored : DEFAULT_MODE; -} - -let current: ColorMode = readInitial(); -const listeners = new Set<() => void>(); - -function publish() { - for (const l of listeners) l(); -} - -export function getColorMode(): ColorMode { - return current; -} - -export function setColorMode(mode: ColorMode): void { - if (mode === current) return; - current = mode; - if (typeof window !== 'undefined') window.localStorage.setItem(STORAGE_KEY, mode); - publish(); -} - -export function toggleColorMode(): void { - setColorMode(current === 'dark' ? 'light' : 'dark'); -} - -function subscribe(listener: () => void): () => void { - listeners.add(listener); - return () => listeners.delete(listener); -} - -export function useColorMode(): { colorMode: ColorMode; toggle: () => void } { - const colorMode = useSyncExternalStore(subscribe, getColorMode, getColorMode); - // Mirror the mode onto a data attribute so plain CSS can react via the - // [data-theme="..."] selector when we later refactor the panel CSS to - // variables. Carbon's handles its own components separately. - useEffect(() => { - if (typeof document !== 'undefined') { - document.documentElement.dataset.theme = colorMode; - } - }, [colorMode]); - return { colorMode, toggle: toggleColorMode }; -} From e339f1a5dafd540b4feb2c2abf0b3faf13fa9ec1 Mon Sep 17 00:00:00 2001 From: YektaY Date: Fri, 16 Oct 2026 07:49:09 -0700 Subject: [PATCH 003/150] Replace the Trace header with canopy-shell AppHeader The header is now the SLAC standard AppHeader, rendered by a small TraceHeader component: - "SLAC Trace" in brand red, following the page theme instead of a forced g100 bar - trace's actions first, then the standard theme toggle (Sun/Moon, with the Alt/Option+T hint), "Report a bug" and "Docs" - the live/archive counts in the middle slot, still right-aligned - in-flow (not fixed), with the skip link pointing at the panel group, which is now #main-content Toolbar keeps only trace's own actions. The local header CSS rules go away, since canopy-shell's styles cover them; the 0.04em letter-spacing is dropped to match react-squirrel and react-badger. Tests cover the header's name, action order, e-log action, theme toggle persistence and the bug/docs links. The jsdom helpers for Carbon and an in-memory localStorage live in src/test/dom.ts. --- src/App.css | 20 ++--- src/components/Toolbar.tsx | 36 +-------- src/components/TraceApp.tsx | 63 +++++---------- src/components/TraceHeader.test.tsx | 119 ++++++++++++++++++++++++++++ src/components/TraceHeader.tsx | 42 ++++++++++ src/state/colorMode.test.ts | 18 +---- src/test/dom.ts | 50 ++++++++++++ 7 files changed, 244 insertions(+), 104 deletions(-) create mode 100644 src/components/TraceHeader.test.tsx create mode 100644 src/components/TraceHeader.tsx create mode 100644 src/test/dom.ts diff --git a/src/App.css b/src/App.css index 8b409ed..5d6300b 100644 --- a/src/App.css +++ b/src/App.css @@ -1,7 +1,7 @@ /* Application-level layout overrides * * Colors come from Carbon theme tokens (--cds-*) so panels follow the - * wrapper in App.tsx automatically. Custom hex is + * (g10 | g100) wrapper in App.tsx automatically. Custom hex is * reserved for things Carbon doesn't ship a token for (semantic indicator * colors with fixed hue regardless of theme, e.g. live-data green). */ @@ -15,17 +15,8 @@ overflow: hidden; } -/* Carbon Header takes position: fixed by default; pin it to the flex column - instead so the panel group fills the rest of the height. */ -.trace-header { - position: relative; - flex-shrink: 0; -} - -.trace-header__name { - letter-spacing: 0.04em; -} - +/* The header itself is canopy-shell's AppHeader (in-flow, see TraceHeader). + The live/archive counts sit in its middle slot, pushed to the right. */ .trace-header__archiver { margin-left: auto; display: flex; @@ -47,6 +38,11 @@ display: flex; } +/* Focused only programmatically, by the header's "Skip to main content" link. */ +.trace-panel-group:focus { + outline: none; +} + .trace-resize-handle { width: 1px; background-color: var(--cds-border-subtle); diff --git a/src/components/Toolbar.tsx b/src/components/Toolbar.tsx index 7b5773a..f182b14 100644 --- a/src/components/Toolbar.tsx +++ b/src/components/Toolbar.tsx @@ -4,48 +4,35 @@ import { Upload, Download, Image, - Asleep, - Light, - Debug, - Help, DataTable, Renew, SendAlt, } from '@carbon/icons-react'; import { HeaderGlobalAction } from '@carbon/react'; -import type { ColorMode } from '@slaclab/canopy-shell'; import { formatShortcut } from '../hooks/useKeyboardShortcuts'; interface ToolbarProps { - colorMode: ColorMode; onSave: () => void; onPrint: () => void; onImport: () => void; onExport: () => void; onExportImage: () => void; - onToggleTheme: () => void; - onReportBug: () => void; - onOpenDocs: () => void; onOpenDataInsight: () => void; onRefreshArchive: () => void; /** When set, shows a "Post to E-Log" action. Hidden when e-log is unconfigured. */ onPostElog?: () => void; } -// Carbon HeaderGlobalAction gives us hover/tooltip/keyboard handling for free -// and styles itself based on the surrounding . The header above stays -// in g100 (dark brand bar) regardless of body theme — same convention as -// react-squirrel. +// Trace's own header actions. AppHeader (see TraceHeader) renders them before +// the standard theme toggle, bug report and help actions. Carbon +// HeaderGlobalAction gives us hover/tooltip/keyboard handling for free and +// follows the header's theme. export function Toolbar({ - colorMode, onSave, onPrint, onImport, onExport, onExportImage, - onToggleTheme, - onReportBug, - onOpenDocs, onOpenDataInsight, onRefreshArchive, onPostElog, @@ -106,21 +93,6 @@ export function Toolbar({ > - - {colorMode === 'dark' ? : } - - - - - - - ); } diff --git a/src/components/TraceApp.tsx b/src/components/TraceApp.tsx index 8714b45..8569b8b 100644 --- a/src/components/TraceApp.tsx +++ b/src/components/TraceApp.tsx @@ -7,7 +7,7 @@ import { usePanelRef, } from 'react-resizable-panels'; import { Close, Login, ChevronUp } from '@carbon/icons-react'; -import { Header, HeaderName, HeaderGlobalBar, Theme, ToastNotification } from '@carbon/react'; +import { ToastNotification } from '@carbon/react'; import type { Plot, PVTrace, Axis } from '../types'; import { LeftPanel } from './LeftPanel'; import { DetachedWindow } from './DetachedWindow'; @@ -16,6 +16,7 @@ import { PlotArea, SinglePlot } from './PlotArea'; import { capturePlotPng } from '../capturePlot'; import { RightPanel } from './RightPanel'; import { Toolbar } from './Toolbar'; +import { TraceHeader } from './TraceHeader'; import { useArchiveSeries, type ArchiveSeriesResult } from '../hooks/useArchiveSeries'; import { useLiveSeries, type LiveSeriesResult } from '../hooks/useLiveSeries'; import { archiveStore } from '../state/archiveStore'; @@ -39,9 +40,6 @@ import { PostToElogModal } from './PostToElogModal'; import { useElogConfig } from '../hooks/useElogConfig'; import { useKeyboardShortcuts } from '../hooks/useKeyboardShortcuts'; -const BUG_REPORT_URL = 'https://forms.office.com/r/qV7BmK2xi9'; -const DOCS_URL = 'https://github.com/slaclab/react-trace#readme'; - function generateMockData( points: number, baseline: number, @@ -774,10 +772,6 @@ export function TraceApp() { }; }, [printShots]); - const handleReportBug = () => { - window.open(BUG_REPORT_URL, '_blank', 'noopener,noreferrer'); - }; - // Capture context-aware plots (active plot in tabs view, all plots in grid) // and open the e-log post dialog. Background matches the current chart theme. const openElogPost = useCallback(() => { @@ -800,10 +794,6 @@ export function TraceApp() { return new File([json], 'trace_config.json', { type: 'application/json' }); }, [colorMode, plots]); - const handleOpenDocs = () => { - window.open(DOCS_URL, '_blank', 'noopener,noreferrer'); - }; - const handleRefreshArchive = () => { archiveStore.refetchAll(); }; @@ -844,38 +834,25 @@ export function TraceApp() { return (
- {/* Header — wrapped in g100 so it stays a dark brand bar in light mode. */} - -
- - TRACE - -
- - {liveCount} Live • {archiveCount} Archive - -
- - void handleImport()} - onExport={handleExport} - onExportImage={handleExportImage} - onToggleTheme={toggleTheme} - onReportBug={handleReportBug} - onOpenDocs={handleOpenDocs} - onOpenDataInsight={() => openInsight()} - onRefreshArchive={handleRefreshArchive} - onPostElog={elogConfig?.enabled ? openElogPost : undefined} - /> - -
-
+ void handleImport()} + onExport={handleExport} + onExportImage={handleExportImage} + onOpenDataInsight={() => openInsight()} + onRefreshArchive={handleRefreshArchive} + onPostElog={elogConfig?.enabled ? openElogPost : undefined} + /> + } + /> - {/* 3-panel layout */} -
+ {/* 3-panel layout. #main-content is the header's skip-link target. */} +
{ + storage = memoryStorage(); + vi.stubGlobal('localStorage', storage); + setupColorMode(); // nothing stored: dark +}); + +// No `test.globals`, so @testing-library/react's auto-cleanup never registers. +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +function renderHeader({ elog = false } = {}) { + const noop = () => {}; + return render( + + + } + /> + + ); +} + +function headerButtonLabels(): string[] { + return within(screen.getByRole('banner')) + .queryAllByRole('button') + .map((b) => b.getAttribute('aria-label') ?? b.textContent ?? ''); +} + +describe('TraceHeader', () => { + it('renders the SLAC-branded name and the live/archive counts', () => { + const { container } = renderHeader(); + expect(screen.getByRole('banner').getAttribute('aria-label')).toBe('Trace'); + expect(container.querySelector('.cds--header__name--prefix')?.textContent).toBe('SLAC'); + expect(container.querySelector('.canopy-header__name')?.textContent).toContain('Trace'); + expect(screen.getByText('2 Live • 1 Archive')).toBeDefined(); + }); + + it('puts trace actions first, then theme toggle, bug report and docs', () => { + renderHeader(); + expect(headerButtonLabels()).toEqual([ + 'Refresh archive data', + `Data Insight (${formatShortcut('alt', 'D')})`, + `Save (${formatShortcut('primary', 'S')})`, + `Print (${formatShortcut('primary', 'P')})`, + `Import (${formatShortcut('primary', 'O')})`, + 'Export CSV', + `Export PNG (${formatShortcut('primary', 'I')})`, + `Switch to light mode (${formatShortcut('alt', 'T')})`, + 'Report a bug', + 'Docs', + ]); + }); + + it('shows the E-Log action only when e-log is configured', () => { + renderHeader({ elog: true }); + expect(headerButtonLabels()).toContain(`Post to E-Log (${formatShortcut('primary', 'E')})`); + }); + + it('toggles the shared color mode and persists it under trace.theme', () => { + renderHeader(); + fireEvent.click( + screen.getByRole('button', { name: `Switch to light mode (${formatShortcut('alt', 'T')})` }) + ); + expect(storage.getItem('trace.theme')).toBe('light'); + expect(document.documentElement.classList.contains('cds--g10')).toBe(true); + expect(document.documentElement.dataset.theme).toBe('light'); + expect( + screen.getByRole('button', { name: `Switch to dark mode (${formatShortcut('alt', 'T')})` }) + ).toBeDefined(); + }); + + it('opens the bug form and the docs in a new tab', () => { + const open = vi.spyOn(window, 'open').mockReturnValue(null); + renderHeader(); + fireEvent.click(screen.getByRole('button', { name: 'Report a bug' })); + fireEvent.click(screen.getByRole('button', { name: 'Docs' })); + expect(open).toHaveBeenNthCalledWith( + 1, + 'https://forms.office.com/r/qV7BmK2xi9', + '_blank', + 'noopener,noreferrer' + ); + expect(open).toHaveBeenNthCalledWith( + 2, + 'https://github.com/slaclab/react-trace#readme', + '_blank', + 'noopener,noreferrer' + ); + }); +}); diff --git a/src/components/TraceHeader.tsx b/src/components/TraceHeader.tsx new file mode 100644 index 0000000..ede0804 --- /dev/null +++ b/src/components/TraceHeader.tsx @@ -0,0 +1,42 @@ +import type { ReactNode } from 'react'; +import { AppHeader } from '@slaclab/canopy-shell'; +import { formatShortcut } from '../hooks/useKeyboardShortcuts'; + +const BUG_REPORT_URL = 'https://forms.office.com/r/qV7BmK2xi9'; +const DOCS_URL = 'https://github.com/slaclab/react-trace#readme'; + +interface TraceHeaderProps { + /** Live / archive trace counts of the active plot, shown in the middle slot. */ + liveCount: number; + archiveCount: number; + /** Trace's own actions (the Toolbar), rendered before the standard ones. */ + actions: ReactNode; +} + +/** + * The SLAC standard header from @slaclab/canopy-shell: "SLAC Trace" in brand + * red, following the page theme, with the trailing actions in the standard + * order (app actions, theme toggle, report a bug, docs). In-flow, not fixed: + * trace is a single-screen app laid out as a flex column. + * + * The theme toggle shows the Alt/Option+T shortcut that useKeyboardShortcuts + * binds; the skip link targets #main-content (the panel group in TraceApp). + */ +export function TraceHeader({ liveCount, archiveCount, actions }: TraceHeaderProps) { + return ( + +
+ + {liveCount} Live • {archiveCount} Archive + +
+
+ ); +} diff --git a/src/state/colorMode.test.ts b/src/state/colorMode.test.ts index c21cc16..eaa2442 100644 --- a/src/state/colorMode.test.ts +++ b/src/state/colorMode.test.ts @@ -1,25 +1,9 @@ // @vitest-environment jsdom import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { getColorMode, setColorMode } from '@slaclab/canopy-shell/color-mode'; +import { memoryStorage } from '../test/dom'; import { TRACE_COLOR_MODE, setupColorMode } from './colorMode'; -// In-memory localStorage, so the test doesn't depend on whether this Node -// version exposes jsdom's storage (Node 26 shadows it without -// --localstorage-file). -function memoryStorage(): Storage { - const data = new Map(); - return { - get length() { - return data.size; - }, - clear: () => data.clear(), - getItem: (key) => data.get(key) ?? null, - key: (i) => Array.from(data.keys())[i] ?? null, - removeItem: (key) => void data.delete(key), - setItem: (key, value) => void data.set(key, String(value)), - }; -} - let storage: Storage; beforeEach(() => { diff --git a/src/test/dom.ts b/src/test/dom.ts new file mode 100644 index 0000000..0dd5c19 --- /dev/null +++ b/src/test/dom.ts @@ -0,0 +1,50 @@ +// Test helpers for jsdom tests that render Carbon / canopy-shell components. +// vite.config.ts doesn't load a setup file, so tests import these directly. + +/** + * jsdom implements neither window.matchMedia nor ResizeObserver; Carbon's + * Theme/Header/Tooltip query the first and its Modal observes with the second + * (same stubs as canopy-shell's own vitest.setup.ts). Call at module level, + * before rendering. + */ +export function stubCarbonDom(): void { + if (typeof window.matchMedia === 'undefined') { + window.matchMedia = (query: string): MediaQueryList => + ({ + matches: false, + media: query, + onchange: null, + addListener: () => {}, + removeListener: () => {}, + addEventListener: () => {}, + removeEventListener: () => {}, + dispatchEvent: () => false, + }) as MediaQueryList; + } + if (typeof globalThis.ResizeObserver === 'undefined') { + globalThis.ResizeObserver = class { + observe() {} + unobserve() {} + disconnect() {} + } as unknown as typeof ResizeObserver; + } +} + +/** + * In-memory Storage, for `vi.stubGlobal('localStorage', memoryStorage())`. + * Keeps tests independent of whether this Node version exposes jsdom's + * storage (Node 26 shadows it unless --localstorage-file is given). + */ +export function memoryStorage(): Storage { + const data = new Map(); + return { + get length() { + return data.size; + }, + clear: () => data.clear(), + getItem: (key) => data.get(key) ?? null, + key: (i) => Array.from(data.keys())[i] ?? null, + removeItem: (key) => void data.delete(key), + setItem: (key, value) => void data.set(key, String(value)), + }; +} From e88786ff331a2f5b410c7104ef96977680c94a44 Mon Sep 17 00:00:00 2001 From: YektaY Date: Fri, 16 Oct 2026 07:50:29 -0700 Subject: [PATCH 004/150] Wrap Trace panels in canopy-shell ErrorBoundary A render error (or an ECharts setOption error) in one panel used to unmount the whole app and leave a blank page. The layers panel, the plot area, the docked Data Insight tool and the properties panel now each sit in an ErrorBoundary. A crash shows the standard fallback, with "Try again" and "Reload", in that panel only. TraceApp's state lives above the boundaries, so "Try again" keeps the workspace. Each boundary also resets when its context changes: the active plot, the view mode, the inspected PV or the selection. --- src/components/TraceApp.tsx | 164 +++++++++++++++++++----------------- 1 file changed, 87 insertions(+), 77 deletions(-) diff --git a/src/components/TraceApp.tsx b/src/components/TraceApp.tsx index 8569b8b..b930810 100644 --- a/src/components/TraceApp.tsx +++ b/src/components/TraceApp.tsx @@ -25,7 +25,7 @@ import { useFormulaSeries, type FormulaSeriesResult } from '../hooks/useFormulaS import type { TimeWindowNs } from '../api/time'; import { resolveTimeWindow } from '../api/time'; import { fetchMetadata } from '../api/mole'; -import { ColorModeTheme, useColorMode } from '@slaclab/canopy-shell'; +import { ColorModeTheme, ErrorBoundary, useColorMode } from '@slaclab/canopy-shell'; import { usePaletteId } from '../state/paletteStore'; import { getPalette, colorForIndex } from '../palettes'; import { downloadBlob, downloadDataUrl, pickFile } from '../io/download'; @@ -866,29 +866,31 @@ export function TraceApp() { if (next !== leftCollapsed) setLeftCollapsed(next); }} > - { - leftPanelRef.current?.collapse(); - setLeftCollapsed(true); - }} - onExpand={() => { - leftPanelRef.current?.expand(); - setLeftCollapsed(false); - }} - /> + + { + leftPanelRef.current?.collapse(); + setLeftCollapsed(true); + }} + onExpand={() => { + leftPanelRef.current?.expand(); + setLeftCollapsed(false); + }} + /> +
@@ -896,27 +898,29 @@ export function TraceApp() {
- + + +
{insight.open && !insight.detached && insight.minimized && (
@@ -939,15 +943,17 @@ export function TraceApp() { )} {insight.open && !insight.detached && !insight.minimized && (
- setInsight((p) => ({ ...p, pv: id }))} - onClose={() => setInsight((p) => ({ ...p, open: false }))} - onMinimize={() => setInsight((p) => ({ ...p, minimized: true }))} - onDetach={() => setInsight((p) => ({ ...p, detached: true }))} - /> + + setInsight((p) => ({ ...p, pv: id }))} + onClose={() => setInsight((p) => ({ ...p, open: false }))} + onMinimize={() => setInsight((p) => ({ ...p, minimized: true }))} + onDetach={() => setInsight((p) => ({ ...p, detached: true }))} + /> +
)}
@@ -967,29 +973,33 @@ export function TraceApp() { if (next !== rightCollapsed) setRightCollapsed(next); }} > - assignTraceToUnitAxis(activePlotId, traceId, pvName)} - onUpdateAxis={updateAxis} - onUpdatePlot={(updates) => updatePlot(activePlotId, updates)} - onApplyPalette={applyPalette} - getAxisRange={getAxisRange} - onInspectTrace={(id) => openInsight(id)} - onCreateFormula={(sourceId) => createFormulaFromTrace(activePlotId, sourceId)} - onCollapse={() => { - rightPanelRef.current?.collapse(); - setRightCollapsed(true); - }} - onExpand={() => { - rightPanelRef.current?.expand(); - setRightCollapsed(false); - }} - /> + + + assignTraceToUnitAxis(activePlotId, traceId, pvName) + } + onUpdateAxis={updateAxis} + onUpdatePlot={(updates) => updatePlot(activePlotId, updates)} + onApplyPalette={applyPalette} + getAxisRange={getAxisRange} + onInspectTrace={(id) => openInsight(id)} + onCreateFormula={(sourceId) => createFormulaFromTrace(activePlotId, sourceId)} + onCollapse={() => { + rightPanelRef.current?.collapse(); + setRightCollapsed(true); + }} + onExpand={() => { + rightPanelRef.current?.expand(); + setRightCollapsed(false); + }} + /> +
From 35cfe9b04651fbc34b356f4b48403ec5784d63ee Mon Sep 17 00:00:00 2001 From: YektaY Date: Fri, 16 Oct 2026 07:51:07 -0700 Subject: [PATCH 005/150] Route REST, Mole and time helpers through @slaclab/canopy-client Add @slaclab/canopy-client and @slaclab/canopy-react 0.2 as dependencies and @slaclab/canopy-vite 0.2 as a dev dependency. src/api/connection.ts now defines the one CanopyConnection (the VITE_CANOPY_BASE_PATH prefix, or '' for per-module paths). client.ts, mole.ts and types.ts become thin shims over the SDK with their old signatures, so every REST call already goes through the SDK's canopyFetch and its error mapping (FastAPI 422 bodies become a readable validation_error instead of "[object Object]") without touching call sites. time.ts re-exports the SDK's nowNs/msToNs/nsToMs and keeps its range parsing. Part of #86. --- package.json | 3 + pnpm-lock.yaml | 35 +++++++++++ src/api/client.ts | 98 ++++++------------------------ src/api/connection.test.ts | 16 +++++ src/api/connection.ts | 18 ++++++ src/api/mole.test.ts | 120 +++++++++++++++++++++++++++++++++++++ src/api/mole.ts | 51 +++++----------- src/api/time.ts | 15 +---- src/api/types.ts | 108 +++++++-------------------------- 9 files changed, 252 insertions(+), 212 deletions(-) create mode 100644 src/api/connection.test.ts create mode 100644 src/api/connection.ts create mode 100644 src/api/mole.test.ts diff --git a/package.json b/package.json index 6ccf2a7..52c1279 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,8 @@ "@dnd-kit/core": "^6.3.1", "@dnd-kit/sortable": "^10.0.0", "@dnd-kit/utilities": "^3.2.2", + "@slaclab/canopy-client": "^0.2.0", + "@slaclab/canopy-react": "^0.2.0", "echarts": "^6.1.0", "echarts-for-react": "^3.0.6", "react": "^19.2.6", @@ -31,6 +33,7 @@ }, "devDependencies": { "@eslint/js": "^10.0.1", + "@slaclab/canopy-vite": "^0.2.0", "@testing-library/dom": "^10.4.1", "@testing-library/jest-dom": "github:testing-library/jest-dom", "@testing-library/react": "^16.3.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5d6e303..83a9f4b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -26,6 +26,12 @@ importers: '@dnd-kit/utilities': specifier: ^3.2.2 version: 3.2.2(react@19.2.6) + '@slaclab/canopy-client': + specifier: ^0.2.0 + version: 0.2.0 + '@slaclab/canopy-react': + specifier: ^0.2.0 + version: 0.2.0(react-dom@19.2.6(react@19.2.6))(react@19.2.6) echarts: specifier: ^6.1.0 version: 6.1.0 @@ -45,6 +51,9 @@ importers: '@eslint/js': specifier: ^10.0.1 version: 10.0.1(eslint@10.3.0) + '@slaclab/canopy-vite': + specifier: ^0.2.0 + version: 0.2.0(vite@8.0.12(@types/node@24.12.4)(sass@1.99.0)(yaml@2.9.0)) '@testing-library/dom': specifier: ^10.4.1 version: 10.4.1 @@ -653,6 +662,20 @@ packages: '@rolldown/pluginutils@1.0.0-rc.7': resolution: {integrity: sha512-qujRfC8sFVInYSPPMLQByRh7zhwkGFS4+tyMQ83srV1qrxL4g8E2tyxVVyxd0+8QeBM1mIk9KbWxkegRr76XzA==} + '@slaclab/canopy-client@0.2.0': + resolution: {integrity: sha512-n5FGh5lkyseQ+KKyO2aSzfxx/XstJxnyXERYJjfhr/24/c/FIQA1uTqnpNDC3snGpQuRRHmmeCKgk2fLlSxyZw==, tarball: https://npm.pkg.github.com/download/@slaclab/canopy-client/0.2.0/c43dbcd7454469c9f46f1e3e0f5a39c07dcb5f37} + + '@slaclab/canopy-react@0.2.0': + resolution: {integrity: sha512-k0gzuQcdWMEp92kCbhUmHtHuuDjd++zjob6OJp405K5C5iAHFhw+CvtLPh06LPV3fl7domvSBE2TxIEDGlj1vw==, tarball: https://npm.pkg.github.com/download/@slaclab/canopy-react/0.2.0/c397d109ce90ca18b1e2511bcd27b6b6ede8132a} + peerDependencies: + react: ^19.0.0 + react-dom: ^19.0.0 + + '@slaclab/canopy-vite@0.2.0': + resolution: {integrity: sha512-HRqpkmqSWltGmKrnpLcJZH2fRgFPftA2Iv054i9y1VSkzBAI3cuFbZPIued1XNfyqfcO2zaD5fubfAcdpC1hSw==, tarball: https://npm.pkg.github.com/download/@slaclab/canopy-vite/0.2.0/0e9ab0815488292559c2de3cd14165aba20ad317} + peerDependencies: + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + '@standard-schema/spec@1.1.0': resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} @@ -2367,6 +2390,18 @@ snapshots: '@rolldown/pluginutils@1.0.0-rc.7': {} + '@slaclab/canopy-client@0.2.0': {} + + '@slaclab/canopy-react@0.2.0(react-dom@19.2.6(react@19.2.6))(react@19.2.6)': + dependencies: + '@slaclab/canopy-client': 0.2.0 + react: 19.2.6 + react-dom: 19.2.6(react@19.2.6) + + '@slaclab/canopy-vite@0.2.0(vite@8.0.12(@types/node@24.12.4)(sass@1.99.0)(yaml@2.9.0))': + dependencies: + vite: 8.0.12(@types/node@24.12.4)(sass@1.99.0)(yaml@2.9.0) + '@standard-schema/spec@1.1.0': {} '@swc/helpers@0.5.21': diff --git a/src/api/client.ts b/src/api/client.ts index 86e81b6..c225c3c 100644 --- a/src/api/client.ts +++ b/src/api/client.ts @@ -1,83 +1,23 @@ -import type { ErrorEnvelope } from './types'; - -// Vite dev server proxies /mole/* (and /fox/*) to the Canopy backend (see -// vite.config.ts) and injects X-API-Key, so the browser bundle never sees the -// key. In deployed builds, VITE_CANOPY_BASE_PATH is served by Trace's reverse -// proxy, for example /trace/api/canopy. -const BASE = (import.meta.env.VITE_CANOPY_BASE_PATH ?? '').replace(/\/$/, ''); +// Transitional shim over @slaclab/canopy-client: keeps trace's original +// signatures while call sites move to the SDK (which takes the connection as +// its first argument). Removed once nothing imports it. +import { + canopyFetch as sdkCanopyFetch, + toWsUrl, + type CanopyFetchOptions, +} from '@slaclab/canopy-client'; +import { canopyConnection } from './connection'; + +export { CanopyError } from '@slaclab/canopy-client'; + +export type FetchOptions = CanopyFetchOptions; + +export function canopyFetch(path: string, options: FetchOptions = {}): Promise { + return sdkCanopyFetch(canopyConnection, path, options); +} +// SSR-safe: returns an empty string when `window` is undefined. export function canopyWebSocketUrl(path: string): string { if (typeof window === 'undefined') return ''; - const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; - return `${proto}//${window.location.host}${BASE}${path}`; -} - -export class CanopyError extends Error { - readonly code: string; - readonly status: number; - readonly detail: string; - - constructor(code: string, status: number, detail: string) { - super(`${code} (${status}): ${detail}`); - this.name = 'CanopyError'; - this.code = code; - this.status = status; - this.detail = detail; - } -} - -export interface FetchOptions { - query?: Record; - signal?: AbortSignal; - // HTTP method; defaults to GET. POST is used for Fox's validate/evaluate. - method?: 'GET' | 'POST'; - // JSON request body (POST only). Serialized with a JSON content-type. - body?: unknown; -} - -function buildQuery(query: FetchOptions['query']): string { - if (!query) return ''; - const params = new URLSearchParams(); - for (const [k, v] of Object.entries(query)) { - if (v === undefined || v === null) continue; - params.set(k, String(v)); - } - const s = params.toString(); - return s ? `?${s}` : ''; -} - -export async function canopyFetch(path: string, options: FetchOptions = {}): Promise { - const url = `${BASE}${path}${buildQuery(options.query)}`; - const headers: Record = { Accept: 'application/json' }; - let body: string | undefined; - if (options.body !== undefined) { - headers['Content-Type'] = 'application/json'; - body = JSON.stringify(options.body); - } - let res: Response; - try { - res = await fetch(url, { - method: options.method ?? 'GET', - headers, - body, - signal: options.signal, - }); - } catch (err) { - if ((err as { name?: string }).name === 'AbortError') throw err; - throw new CanopyError('network_error', 0, (err as Error).message ?? 'network failure'); - } - - if (!res.ok) { - let envelope: ErrorEnvelope | null = null; - try { - envelope = (await res.json()) as ErrorEnvelope; - } catch { - // fall through with no envelope - } - const code = envelope?.code ?? 'unknown_error'; - const detail = envelope?.detail ?? res.statusText; - throw new CanopyError(code, res.status, detail); - } - - return (await res.json()) as T; + return toWsUrl(canopyConnection.baseUrl, path); } diff --git a/src/api/connection.test.ts b/src/api/connection.test.ts new file mode 100644 index 0000000..47d3f95 --- /dev/null +++ b/src/api/connection.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest'; +import { canopyBaseUrl } from './connection'; + +describe('canopyBaseUrl', () => { + it('defaults to same-origin per-module paths', () => { + expect(canopyBaseUrl(undefined)).toBe(''); + expect(canopyBaseUrl('')).toBe(''); + expect(canopyBaseUrl(' ')).toBe(''); + }); + + it('keeps a deployed prefix and drops trailing slashes and padding', () => { + expect(canopyBaseUrl('/trace/api/canopy')).toBe('/trace/api/canopy'); + expect(canopyBaseUrl('/trace/api/canopy/')).toBe('/trace/api/canopy'); + expect(canopyBaseUrl(' /trace/api/canopy// ')).toBe('/trace/api/canopy'); + }); +}); diff --git a/src/api/connection.ts b/src/api/connection.ts new file mode 100644 index 0000000..89c55dd --- /dev/null +++ b/src/api/connection.ts @@ -0,0 +1,18 @@ +import type { CanopyConnection } from '@slaclab/canopy-client'; + +// How the browser reaches Canopy. Always a same-origin path: the Vite dev proxy +// (vite.config.ts) and Trace's reverse proxy in deployed builds forward it to +// Canopy and inject X-API-Key, so the bundle never holds the key. +// +// - '' (the local-dev default): per-module paths, /mole/..., /hare/..., /fox/... +// - VITE_CANOPY_BASE_PATH, e.g. /trace/api/canopy: one prefix in front of them. +export function canopyBaseUrl(raw: string | undefined): string { + return (raw ?? '').trim().replace(/\/+$/, ''); +} + +// The connection every Canopy call goes through. React code reads it from +// (main.tsx) with useCanopyConnection(); the module-level +// stores (archiveStore, liveStore) live outside React and import it directly. +export const canopyConnection: CanopyConnection = { + baseUrl: canopyBaseUrl(import.meta.env.VITE_CANOPY_BASE_PATH as string | undefined), +}; diff --git a/src/api/mole.test.ts b/src/api/mole.test.ts new file mode 100644 index 0000000..a2ec48c --- /dev/null +++ b/src/api/mole.test.ts @@ -0,0 +1,120 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { createFakeFetch, jsonResponse } from '@slaclab/canopy-client/testing'; +import type { FakeRoutes } from '@slaclab/canopy-client/testing'; +import { fetchData, fetchMetadata, listArchivers, searchPVs } from './mole'; +import { CanopyError } from './client'; +import { canopyConnection } from './connection'; + +// The shim calls go through the shared connection, which has no injected fetch, +// so the SDK falls back to the global fetch: stub it with the SDK's route fake. +function stubFetch(routes: FakeRoutes) { + const fetch = createFakeFetch(routes, { baseUrl: canopyConnection.baseUrl }); + vi.stubGlobal('fetch', fetch); + return fetch; +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('mole shim over @slaclab/canopy-client', () => { + it('fetchData encodes the PV and sends the window and fetch mode', async () => { + const fetch = stubFetch({ + 'GET /mole/v1/data/:pv': jsonResponse({ + mode: 'raw', + pv: 'A:B/C', + archiver: 'slac', + from: 1, + to: 2, + decimated: false, + samples: [], + }), + }); + + const dto = await fetchData('A:B/C', { + fromNs: 1_000, + toNs: 2_000, + archiver: 'slac', + binning: 'auto', + maxPoints: 500, + }); + + expect(dto.mode).toBe('raw'); + expect(fetch.calls).toHaveLength(1); + const [call] = fetch.calls; + expect(call.params.pv).toBe('A:B/C'); + expect(call.query).toEqual({ + from: '1000', + to: '2000', + archiver: 'slac', + binning: 'auto', + maxPoints: '500', + }); + }); + + it('routes metadata, search and archiver listing to their endpoints', async () => { + const fetch = stubFetch({ + 'GET /mole/v1/metadata/:pv': jsonResponse({ pv: 'X', units: 'mm' }), + 'GET /mole/v1/search': jsonResponse({ archiver: 'slac', pattern: '.*X.*', pvs: ['X'] }), + 'GET /mole/v1/archivers': jsonResponse({ default: 'slac', archivers: [] }), + }); + + expect((await fetchMetadata('X', 'slac')).units).toBe('mm'); + expect((await searchPVs('.*X.*', { limit: 5 })).pvs).toEqual(['X']); + expect((await listArchivers()).default).toBe('slac'); + + expect(fetch.calls.map((c) => c.path)).toEqual([ + '/mole/v1/metadata/X', + '/mole/v1/search', + '/mole/v1/archivers', + ]); + expect(fetch.calls[0].query).toEqual({ archiver: 'slac' }); + expect(fetch.calls[1].query).toEqual({ pattern: '.*X.*', limit: '5' }); + }); + + it('turns a FastAPI 422 into a readable validation_error', async () => { + stubFetch({ + 'GET /mole/v1/data/:pv': jsonResponse( + { + detail: [ + { loc: ['query', 'from'], msg: 'Field required', type: 'missing' }, + { loc: ['query', 'maxPoints'], msg: 'Input should be > 0', type: 'greater_than' }, + ], + }, + { status: 422 } + ), + }); + + const err = await fetchData('X', { fromNs: 0 }).catch((e: unknown) => e); + expect(err).toBeInstanceOf(CanopyError); + expect(err).toMatchObject({ + code: 'validation_error', + status: 422, + detail: 'query.from: Field required; query.maxPoints: Input should be > 0', + }); + expect((err as CanopyError).issues).toHaveLength(2); + }); + + it('keeps the Canopy error envelope', async () => { + stubFetch({ + 'GET /mole/v1/archivers': jsonResponse( + { code: 'archiver_unavailable', detail: 'slac is down' }, + { status: 503 } + ), + }); + await expect(listArchivers()).rejects.toMatchObject({ + code: 'archiver_unavailable', + status: 503, + detail: 'slac is down', + }); + }); + + it('passes an abort through unchanged', async () => { + stubFetch({ 'GET /mole/v1/archivers': jsonResponse({ default: 'slac', archivers: [] }) }); + const controller = new AbortController(); + controller.abort(); + const err = await listArchivers(controller.signal).catch((e: unknown) => e); + expect(err).not.toBeInstanceOf(CanopyError); + expect((err as { name?: string }).name).toBe('AbortError'); + }); +}); diff --git a/src/api/mole.ts b/src/api/mole.ts index 5d213ad..9ea6ca9 100644 --- a/src/api/mole.ts +++ b/src/api/mole.ts @@ -1,61 +1,42 @@ -import { canopyFetch } from './client'; +// Transitional shim over @slaclab/canopy-client's Mole client, bound to the +// shared connection so trace's original signatures keep working while call +// sites move to the SDK. Removed once nothing imports it. +import * as sdk from '@slaclab/canopy-client'; import type { ArchiverDataDTO, ArchiverListDTO, - BinningMode, + FetchDataParams, PVMetadataDTO, SearchResultsDTO, -} from './types'; +} from '@slaclab/canopy-client'; +import { canopyConnection } from './connection'; -export interface FetchDataParams { - fromNs: number; - toNs?: number; - archiver?: string; - binning?: BinningMode; - maxPoints?: number; - binSizeNs?: number; -} +export type { FetchDataParams } from '@slaclab/canopy-client'; -export async function fetchData( +export function fetchData( pv: string, params: FetchDataParams, signal?: AbortSignal ): Promise { - return canopyFetch(`/mole/v1/data/${encodeURIComponent(pv)}`, { - query: { - from: params.fromNs, - to: params.toNs, - archiver: params.archiver, - binning: params.binning, - maxPoints: params.maxPoints, - binSize: params.binSizeNs, - }, - signal, - }); + return sdk.fetchData(canopyConnection, pv, params, signal); } -export async function fetchMetadata( +export function fetchMetadata( pv: string, archiver?: string, signal?: AbortSignal ): Promise { - return canopyFetch(`/mole/v1/metadata/${encodeURIComponent(pv)}`, { - query: { archiver }, - signal, - }); + return sdk.fetchMetadata(canopyConnection, pv, archiver, signal); } -export async function searchPVs( +export function searchPVs( pattern: string, options: { archiver?: string; limit?: number } = {}, signal?: AbortSignal ): Promise { - return canopyFetch('/mole/v1/search', { - query: { pattern, archiver: options.archiver, limit: options.limit }, - signal, - }); + return sdk.searchPVs(canopyConnection, pattern, options, signal); } -export async function listArchivers(signal?: AbortSignal): Promise { - return canopyFetch('/mole/v1/archivers', { signal }); +export function listArchivers(signal?: AbortSignal): Promise { + return sdk.listArchivers(canopyConnection, signal); } diff --git a/src/api/time.ts b/src/api/time.ts index ae9e548..468c03a 100644 --- a/src/api/time.ts +++ b/src/api/time.ts @@ -2,19 +2,10 @@ // Relative ranges are spans like "-1h"/"-90m"; "custom" resolves the plot's // absolute From/To datetime-local fields. -const NS_PER_MS = 1_000_000n; +import { msToNs, nowNs } from '@slaclab/canopy-client'; -export function nowNs(): number { - return Number(BigInt(Date.now()) * NS_PER_MS); -} - -export function msToNs(ms: number): number { - return Number(BigInt(Math.trunc(ms)) * NS_PER_MS); -} - -export function nsToMs(ns: number): number { - return Math.trunc(ns / 1_000_000); -} +// Epoch-ns helpers come from the SDK; re-exported so callers keep one import. +export { msToNs, nowNs, nsToMs } from '@slaclab/canopy-client'; // Span multipliers in milliseconds. Lowercase `m` is minutes; uppercase `M` is // months (approximated as 30 days), matching the Python IOTimeParser units. diff --git a/src/api/types.ts b/src/api/types.ts index 32a1024..7ba5853 100644 --- a/src/api/types.ts +++ b/src/api/types.ts @@ -1,89 +1,25 @@ -// Wire types mirroring Canopy/Mole DTOs (camelCase, as emitted by canopy.contracts.base.CanopyModel). -// Source of truth: the Canopy repo's src/canopy/mole/schemas + Canopy.wiki Module-Architecture:-Mole.md. - -export type AlarmSeverity = 'NO_ALARM' | 'MINOR' | 'MAJOR' | 'INVALID'; -export type BinningMode = 'auto' | 'time'; - -export interface SampleDTO { - tsNs: number; - value: number | string | boolean | null; - severity: AlarmSeverity; - source: 'archive'; -} - -export interface ArchiverSeriesDTO { - mode: 'raw'; - pv: string; - archiver: string; - from: number; - to: number; - decimated: boolean; - samples: SampleDTO[]; -} - -export interface BinnedPointDTO { - tsNs: number; - binNs: number; - mean: number; - stdDev: number; - min: number; - max: number; - count: number; - severity: AlarmSeverity; -} - -export interface ArchiverBinnedSeriesDTO { - mode: 'binned'; - pv: string; - archiver: string; - from: number; - to: number; - binning: BinningMode; - binSizeNs: number | null; - targetBuckets: number | null; - points: BinnedPointDTO[]; -} - -export type ArchiverDataDTO = ArchiverSeriesDTO | ArchiverBinnedSeriesDTO; - -export interface PVMetadataDTO { - pv: string; - archiver: string; - description: string | null; - units: string | null; - precision: number | null; - displayLow: number | null; - displayHigh: number | null; - alarmLow: number | null; - alarmHigh: number | null; - warningLow: number | null; - warningHigh: number | null; -} - -export interface ArchiverInfoDTO { - name: string; - typeName: string; - url: string; - healthy: boolean; - latencyMs: number | null; - lastError: string | null; -} - -export interface ArchiverListDTO { - default: string; - archivers: ArchiverInfoDTO[]; -} - -export interface SearchResultsDTO { - archiver: string; - pattern: string; - pvs: string[]; -} - -export interface ErrorEnvelope { - code: string; - detail: string; -} +// Transitional: trace's wire-type names, now backed by @slaclab/canopy-client. +// The Mole DTOs and the error envelope are the SDK's own types; the Hare and Fox +// sections below go as their modules move to the SDK. Removed once nothing +// imports it. + +import type { WireAlarmSeverity } from '@slaclab/canopy-client'; + +export type AlarmSeverity = WireAlarmSeverity; + +export type { + ArchiverBinnedSeriesDTO, + ArchiverDataDTO, + ArchiverInfoDTO, + ArchiverListDTO, + ArchiverSeriesDTO, + BinnedPointDTO, + BinningMode, + ErrorEnvelope, + PVMetadataDTO, + SampleDTO, + SearchResultsDTO, +} from '@slaclab/canopy-client'; // ── Hare (live PV) DTOs ────────────────────────────────────────────────────── // Source: canopy.contracts.pv.PVValue + canopy.hare.api.v1.ws frame schema. From 8da4af0e813bff18b562e5a3abd0e8cf665e7068 Mon Sep 17 00:00:00 2001 From: YektaY Date: Fri, 16 Oct 2026 07:52:45 -0700 Subject: [PATCH 006/150] Replace the dev proxy blocks with canopyDevProxy vite.config.ts builds its proxy with @slaclab/canopy-vite instead of the hand-written /mole, /hare, /fox and /elog blocks. It forwards REST and WebSocket traffic and injects X-API-Key (and the e-log token) server-side as before. It also refuses cross-origin browser requests, drops cookies, and matches prefixes only on a path-segment boundary. The layout follows VITE_CANOPY_BASE_PATH, the same setting the bundle uses: unset, the per-module paths are forwarded unchanged; set (the deployed /trace/api/canopy layout), that one prefix is proxied and stripped, like the container's nginx. canopyProxyOptions() holds that mapping and has a test. package.json declares "type": "module": canopy-vite is ESM-only, and a CommonJS-loaded vite.config.ts can't require it. eslint.config.js was already ESM. .env.example and the README describe the per-module key scope and the cross-origin refusal. Part of #86. --- .env.example | 14 ++++++-- README.md | 12 +++++-- package.json | 1 + tsconfig.node.json | 2 +- vite.config.test.ts | 40 +++++++++++++++++++++ vite.config.ts | 88 ++++++++++++--------------------------------- 6 files changed, 86 insertions(+), 71 deletions(-) create mode 100644 vite.config.test.ts diff --git a/.env.example b/.env.example index 962946f..0baf3de 100644 --- a/.env.example +++ b/.env.example @@ -3,12 +3,16 @@ CANOPY_BASE_URL=http://localhost:8000 # Public deployment settings. Leave unset for local dev. In the dev container, # VITE_CANOPY_BASE_PATH is /trace/api/canopy: the container injects the API key -# and proxies it to the in-cluster Canopy service. +# and proxies it to the in-cluster Canopy service. When it is set, the dev proxy +# also serves that one prefix (stripped before forwarding) instead of /mole, +# /hare and /fox. VITE_BASE_PATH=/ VITE_CANOPY_BASE_PATH= -# API key the dev proxy injects as X-API-Key on requests to /mole/*. Must match a -# token registered in the backend's CANOPY_API_KEYS env var (e.g. CANOPY_API_KEYS=dev:read+write). +# API key the dev proxy injects as X-API-Key on every Canopy request it forwards +# (/mole, /hare and /fox, HTTP and WebSocket). Must match a token registered in the +# backend's CANOPY_API_KEYS env var (e.g. CANOPY_API_KEYS=dev:read+write), scoped +# to all modules (@*) or to each of mole, hare and fox. # Server-side env var (no VITE_ prefix), so it never reaches the browser bundle. CANOPY_API_KEY=dev @@ -20,5 +24,9 @@ ELOG_BASE_URL= # Server-side env var (no VITE_ prefix), so it never reaches the browser bundle. ELOG_API_KEY= +# Optional: header the e-log token is sent in, for an elog-plus behind a +# different auth proxy. Defaults to x-vouch-idp-accesstoken. +# ELOG_TOKEN_HEADER= + # Comma-separated logbook names preselected in the post dialog. Non-secret (VITE_). VITE_ELOG_DEFAULT_LOGBOOKS= diff --git a/README.md b/README.md index 3039375..4b43d3f 100644 --- a/README.md +++ b/README.md @@ -49,8 +49,16 @@ cp .env.example .env ``` `CANOPY_API_KEY` is a server-side env var (no `VITE_` prefix). The Vite dev server proxies -`/mole/*` to `CANOPY_BASE_URL` and injects the `X-API-Key` header, so the key never reaches -the browser bundle. +`/mole`, `/hare` and `/fox` (HTTP and WebSocket) to `CANOPY_BASE_URL` and injects the +`X-API-Key` header, so the key never reaches the browser bundle. The same key goes to every +module, so it must be scoped to all of them (`@*`) or to each one. If `VITE_CANOPY_BASE_PATH` +is set (for example `/trace/api/canopy`), the dev server proxies that one prefix instead and +strips it before forwarding, like the container's nginx. + +The proxy is [`canopyDevProxy`](https://github.com/slaclab/canopy-sdk-js/tree/main/packages/vite) +from `@slaclab/canopy-vite`. It refuses cross-origin browser requests, including pages on +another `localhost` port, so other sites open in your browser can't use the injected key. +A trusted page on another origin needs to be listed in `allowedOrigins` in `vite.config.ts`. #### E-Log posting (optional) diff --git a/package.json b/package.json index 52c1279..754ba02 100644 --- a/package.json +++ b/package.json @@ -2,6 +2,7 @@ "name": "trace", "version": "0.1.0", "private": true, + "type": "module", "description": "React implementation of Trace", "scripts": { "dev": "vite", diff --git a/tsconfig.node.json b/tsconfig.node.json index d3c52ea..4efa2b7 100644 --- a/tsconfig.node.json +++ b/tsconfig.node.json @@ -20,5 +20,5 @@ "erasableSyntaxOnly": true, "noFallthroughCasesInSwitch": true }, - "include": ["vite.config.ts"] + "include": ["vite.config.ts", "vite.config.test.ts"] } diff --git a/vite.config.test.ts b/vite.config.test.ts new file mode 100644 index 0000000..efe2204 --- /dev/null +++ b/vite.config.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest'; +import { canopyDevProxy } from '@slaclab/canopy-vite'; +import { canopyProxyOptions } from './vite.config'; + +const base = { CANOPY_BASE_URL: 'http://canopy.test:9000', CANOPY_API_KEY: 'k' }; + +describe('canopyProxyOptions', () => { + it('proxies /mole, /hare and /fox when no Canopy base path is set', () => { + const options = canopyProxyOptions({ ...base, ELOG_BASE_URL: '' }); + expect(options).toMatchObject({ + target: 'http://canopy.test:9000', + apiKey: 'k', + modules: ['/mole', '/hare', '/fox'], + }); + expect(options.basePath).toBeUndefined(); + const proxy = canopyDevProxy({ ...options, elog: { ...options.elog, target: '' } }); + expect(Object.keys(proxy)).toEqual([ + '^/mole(?=[/?#]|$)', + '^/hare(?=[/?#]|$)', + '^/fox(?=[/?#]|$)', + ]); + expect(Object.values(proxy).every((route) => route.ws === true)).toBe(true); + }); + + it('switches to the single deployed prefix when VITE_CANOPY_BASE_PATH is set', () => { + const options = canopyProxyOptions({ ...base, VITE_CANOPY_BASE_PATH: ' /trace/api/canopy ' }); + expect(options.basePath).toBe('/trace/api/canopy'); + expect(options.modules).toBeUndefined(); + const proxy = canopyDevProxy({ ...options, elog: { ...options.elog, target: '' } }); + expect(Object.keys(proxy)).toEqual(['^/trace/api/canopy(?=[/?#]|$)']); + }); + + it('adds the /elog route only when an e-log target is configured', () => { + const withElog = canopyDevProxy( + canopyProxyOptions({ ...base, ELOG_BASE_URL: 'http://elog.test', ELOG_API_KEY: 't' }) + ); + expect(Object.keys(withElog)).toContain('^/elog(?=[/?#]|$)'); + expect(withElog['^/elog(?=[/?#]|$)'].target).toBe('http://elog.test'); + }); +}); diff --git a/vite.config.ts b/vite.config.ts index 9caee8b..e5a23da 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,80 +1,38 @@ import { defineConfig } from 'vitest/config'; import { loadEnv } from 'vite'; import react from '@vitejs/plugin-react'; +import { canopyDevProxy, type CanopyDevProxyOptions } from '@slaclab/canopy-vite'; + +// Dev-server proxy options for Canopy and e-log. The keys stay server-side +// (no VITE_ prefix): the proxy injects X-API-Key on Canopy requests and +// WebSocket upgrades, and the e-log access token on /elog, so the browser bundle +// never holds either. In prod a reverse proxy owns the same paths and headers. +// +// The proxy serves the layout the bundle uses (src/api/connection.ts): +// - VITE_CANOPY_BASE_PATH unset: per-module paths /mole, /hare and /fox, +// forwarded unchanged. +// - VITE_CANOPY_BASE_PATH set (the deployed layout, e.g. /trace/api/canopy): +// that one prefix, stripped before forwarding, like the container's nginx. +export function canopyProxyOptions(env: Record): CanopyDevProxyOptions { + const basePath = env.VITE_CANOPY_BASE_PATH?.trim(); + return { + target: env.CANOPY_BASE_URL, + apiKey: env.CANOPY_API_KEY, + ...(basePath ? { basePath } : { modules: ['/mole', '/hare', '/fox'] }), + // Left out when ELOG_BASE_URL is unset, which hides e-log posting. + elog: { target: env.ELOG_BASE_URL, accessToken: env.ELOG_API_KEY }, + }; +} // https://vite.dev/config/ export default defineConfig(({ mode }) => { const env = loadEnv(mode, process.cwd(), ''); - const target = env.CANOPY_BASE_URL ?? 'http://localhost:8000'; - const apiKey = env.CANOPY_API_KEY ?? ''; - // E-log (elog-plus) is a separate microservice; the dev proxy injects its - // access token so the key never reaches the browser bundle. In prod a reverse - // proxy owns the same /elog -> elog-plus rewrite + header injection. - const elogTarget = env.ELOG_BASE_URL ?? ''; - const elogKey = env.ELOG_API_KEY ?? ''; return { base: env.VITE_BASE_PATH || '/', plugins: [react()], server: { - proxy: { - '/mole': { - target, - changeOrigin: true, - configure: (proxy) => { - proxy.on('proxyReq', (proxyReq) => { - if (apiKey) proxyReq.setHeader('X-API-Key', apiKey); - }); - }, - }, - // Hare lives behind the same backend host. WebSocket upgrades for the - // live-PV stream go through this proxy with `ws: true`. The same - // X-API-Key injection covers both the HTTP and the WS upgrade path so - // the bundle never holds the key. - '/hare': { - target, - changeOrigin: true, - ws: true, - configure: (proxy) => { - proxy.on('proxyReq', (proxyReq) => { - if (apiKey) proxyReq.setHeader('X-API-Key', apiKey); - }); - proxy.on('proxyReqWs', (proxyReq) => { - if (apiKey) proxyReq.setHeader('X-API-Key', apiKey); - }); - }, - }, - // Fox (formula evaluation): REST validate/evaluate plus the live-formula - // WebSocket. `ws: true` upgrades /fox/v1/ws/formulas; X-API-Key is injected - // on both the HTTP and WS paths so the bundle never holds the key. - '/fox': { - target, - changeOrigin: true, - ws: true, - configure: (proxy) => { - proxy.on('proxyReq', (proxyReq) => { - if (apiKey) proxyReq.setHeader('X-API-Key', apiKey); - }); - proxy.on('proxyReqWs', (proxyReq) => { - if (apiKey) proxyReq.setHeader('X-API-Key', apiKey); - }); - }, - }, - ...(elogTarget - ? { - '/elog': { - target: elogTarget, - changeOrigin: true, - rewrite: (path: string) => path.replace(/^\/elog/, ''), - configure: (proxy) => { - proxy.on('proxyReq', (proxyReq) => { - if (elogKey) proxyReq.setHeader('x-vouch-idp-accesstoken', elogKey); - }); - }, - }, - } - : {}), - }, + proxy: canopyDevProxy(canopyProxyOptions(env)), }, test: { passWithNoTests: true, From 3caa1698073d756356707d54776de2a931d1e01d Mon Sep 17 00:00:00 2001 From: YektaY Date: Fri, 16 Oct 2026 07:53:22 -0700 Subject: [PATCH 007/150] Use the SDK's WireAlarmSeverity and map numeric severities to it Trace keeps alarm severity as the wire string. Mole samples, Fox results, the Data Insight table, the right panel's colours and the CSV/MAT exports already use it, and it is the SDK's WireAlarmSeverity. liveStore now uses that type. The SDK's PV services report the numeric AlarmSeverity, which adds DISCONNECTED. toWireSeverity() converts it at the boundary, mapping DISCONNECTED to null because it is a connection state, not an alarm. The live store uses it from the next commit. Part of #86. --- src/api/severity.test.ts | 16 ++++++++++++++++ src/api/severity.ts | 17 +++++++++++++++++ src/state/liveStore.ts | 9 +++++---- 3 files changed, 38 insertions(+), 4 deletions(-) create mode 100644 src/api/severity.test.ts create mode 100644 src/api/severity.ts diff --git a/src/api/severity.test.ts b/src/api/severity.test.ts new file mode 100644 index 0000000..113b982 --- /dev/null +++ b/src/api/severity.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest'; +import { AlarmSeverity } from '@slaclab/canopy-client'; +import { toWireSeverity } from './severity'; + +describe('toWireSeverity', () => { + it('maps each alarm level to its wire name', () => { + expect(toWireSeverity(AlarmSeverity.NO_ALARM)).toBe('NO_ALARM'); + expect(toWireSeverity(AlarmSeverity.MINOR)).toBe('MINOR'); + expect(toWireSeverity(AlarmSeverity.MAJOR)).toBe('MAJOR'); + expect(toWireSeverity(AlarmSeverity.INVALID)).toBe('INVALID'); + }); + + it('treats DISCONNECTED as no alarm severity', () => { + expect(toWireSeverity(AlarmSeverity.DISCONNECTED)).toBeNull(); + }); +}); diff --git a/src/api/severity.ts b/src/api/severity.ts new file mode 100644 index 0000000..fac1b01 --- /dev/null +++ b/src/api/severity.ts @@ -0,0 +1,17 @@ +import { AlarmSeverity, type WireAlarmSeverity } from '@slaclab/canopy-client'; + +// Trace keeps alarm severity as the wire string (`WireAlarmSeverity`): Mole +// samples, Fox results, the Data Insight table and the CSV/MAT exports all carry +// it. The SDK's PV services report the numeric `AlarmSeverity` instead, which +// adds DISCONNECTED; that is a connection state, not an alarm, so it maps to null. +const WIRE_SEVERITY: Record = { + [AlarmSeverity.NO_ALARM]: 'NO_ALARM', + [AlarmSeverity.MINOR]: 'MINOR', + [AlarmSeverity.MAJOR]: 'MAJOR', + [AlarmSeverity.INVALID]: 'INVALID', + [AlarmSeverity.DISCONNECTED]: null, +}; + +export function toWireSeverity(severity: AlarmSeverity): WireAlarmSeverity | null { + return WIRE_SEVERITY[severity] ?? null; +} diff --git a/src/state/liveStore.ts b/src/state/liveStore.ts index 89e7837..3d9b141 100644 --- a/src/state/liveStore.ts +++ b/src/state/liveStore.ts @@ -6,14 +6,15 @@ import { liveWsUrl } from '../api/hare'; import { nsToMs } from '../api/time'; -import type { AlarmSeverity, PVValueDTO, WsFrame } from '../api/types'; +import type { WireAlarmSeverity } from '@slaclab/canopy-client'; +import type { PVValueDTO, WsFrame } from '../api/types'; export interface LivePoint { time: number; value: number; // Alarm severity reported alongside this sample. Retained per-point so the // Data Insight Tool can show live-sample severity, not just the PV's latest. - severity: AlarmSeverity; + severity: WireAlarmSeverity; } export type LiveStatus = 'idle' | 'connecting' | 'connected' | 'disconnected'; @@ -30,7 +31,7 @@ export interface LiveEntry { // PV-level connection (Hare's PVValue.connected). True only after a frame // for this PV has been received reporting connected=true. connected: boolean; - severity: AlarmSeverity | null; + severity: WireAlarmSeverity | null; latest: PVValueDTO | null; // Last surfaced connection/protocol error, if any. Cleared on a clean // (re)connect. Distinct from a stale buffer: the chart can keep rendering @@ -55,7 +56,7 @@ interface PVState { points: LivePoint[]; latest: PVValueDTO | null; connected: boolean; - severity: AlarmSeverity | null; + severity: WireAlarmSeverity | null; // Monotonic revision bumped whenever any published field of this PV changes. // `entryFor()` reuses the cached LiveEntry when the rev is unchanged so // downstream shallow-equality / React.memo checks hold across frames. From 816495e4bce31c4fac4f24dab9b64e21b94d005e Mon Sep 17 00:00:00 2001 From: YektaY Date: Fri, 16 Oct 2026 07:56:35 -0700 Subject: [PATCH 008/150] Theme Trace charts with canopy-charts (g10/g100) Plots now take their colors from @slaclab/canopy-charts instead of the local g90-era chart theme: - useChartTheme() follows the shared canopy-shell color mode and gives the Carbon g10/g100 token values. - The option starts from baseChartOption(): animation off, IBM Plex Sans, and the shared axis, tooltip, axis-pointer and legend styling. - Each axis spreads chartAxisStyle(). Trace keeps its own grid, axis layout, font sizes, gridline style and opacity, tooltip content and legend placement on top. - The light chart background is now g10 #f4f4f4 (was #ffffff). The dark tokens move to g100: axis lines #6f6f6f, axis names and crosshair #a8a8a8, tooltip border #525252. The "follow the theme vs user override" rule for plot backgrounds stays in the app, in plotBackground.ts. It treats #161616, #f4f4f4 and the old #ffffff default as theme defaults. Print, PNG export and e-log captures use the same chart theme backgrounds. --- package.json | 1 + pnpm-lock.yaml | 20 +++ src/capturePlot.ts | 5 +- src/chartTheme.ts | 54 -------- src/components/PlotArea.option.test.tsx | 161 ++++++++++++++++++++++++ src/components/PlotArea.tsx | 56 ++++++--- src/components/TraceApp.tsx | 3 +- src/plotBackground.test.ts | 15 +++ src/plotBackground.ts | 16 +++ 9 files changed, 254 insertions(+), 77 deletions(-) delete mode 100644 src/chartTheme.ts create mode 100644 src/components/PlotArea.option.test.tsx create mode 100644 src/plotBackground.test.ts create mode 100644 src/plotBackground.ts diff --git a/package.json b/package.json index 5b1e07d..7bc3d06 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "@dnd-kit/core": "^6.3.1", "@dnd-kit/sortable": "^10.0.0", "@dnd-kit/utilities": "^3.2.2", + "@slaclab/canopy-charts": "^0.2.0", "@slaclab/canopy-shell": "^0.2.0", "echarts": "^6.1.0", "echarts-for-react": "^3.0.6", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9388814..60ceab9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -26,6 +26,9 @@ importers: '@dnd-kit/utilities': specifier: ^3.2.2 version: 3.2.2(react@19.2.6) + '@slaclab/canopy-charts': + specifier: ^0.2.0 + version: 0.2.0(@slaclab/canopy-shell@0.2.0(@carbon/icons-react@11.81.0(react@19.2.6))(@carbon/react@1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.99.0))(react-dom@19.2.6(react@19.2.6))(react@19.2.6))(echarts-for-react@3.0.6(echarts@6.1.0)(react@19.2.6))(echarts@6.1.0)(react-dom@19.2.6(react@19.2.6))(react@19.2.6) '@slaclab/canopy-shell': specifier: ^0.2.0 version: 0.2.0(@carbon/icons-react@11.81.0(react@19.2.6))(@carbon/react@1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.99.0))(react-dom@19.2.6(react@19.2.6))(react@19.2.6) @@ -656,6 +659,15 @@ packages: '@rolldown/pluginutils@1.0.0-rc.7': resolution: {integrity: sha512-qujRfC8sFVInYSPPMLQByRh7zhwkGFS4+tyMQ83srV1qrxL4g8E2tyxVVyxd0+8QeBM1mIk9KbWxkegRr76XzA==} + '@slaclab/canopy-charts@0.2.0': + resolution: {integrity: sha512-8MGXocmqdcUlyIZVb04llbaVDTqCrN3IByUIUBv4K9+BhB3jGWOkn8fEImUa01R75ZNg8t40AUydhchezwhfzQ==, tarball: https://npm.pkg.github.com/download/@slaclab/canopy-charts/0.2.0/db94243a679e1fc7413c00ce12980e53c956efe9} + peerDependencies: + '@slaclab/canopy-shell': ^0.2.0 + echarts: ^6.0.0 + echarts-for-react: ^3.0.0 + react: ^19.0.0 + react-dom: ^19.0.0 + '@slaclab/canopy-shell@0.2.0': resolution: {integrity: sha512-j9u6y1CHEePSLirX07NDNnS/ka9tdylV19ogjTJ601KvwrZcxBndGzsp0H8ziJRDQDK6XQBrFBSkV/c7vYksgw==, tarball: https://npm.pkg.github.com/download/@slaclab/canopy-shell/0.2.0/1e0145073a2e6774fe4d54bd68bbea81bf7d38e0} peerDependencies: @@ -2378,6 +2390,14 @@ snapshots: '@rolldown/pluginutils@1.0.0-rc.7': {} + '@slaclab/canopy-charts@0.2.0(@slaclab/canopy-shell@0.2.0(@carbon/icons-react@11.81.0(react@19.2.6))(@carbon/react@1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.99.0))(react-dom@19.2.6(react@19.2.6))(react@19.2.6))(echarts-for-react@3.0.6(echarts@6.1.0)(react@19.2.6))(echarts@6.1.0)(react-dom@19.2.6(react@19.2.6))(react@19.2.6)': + dependencies: + '@slaclab/canopy-shell': 0.2.0(@carbon/icons-react@11.81.0(react@19.2.6))(@carbon/react@1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.99.0))(react-dom@19.2.6(react@19.2.6))(react@19.2.6) + echarts: 6.1.0 + echarts-for-react: 3.0.6(echarts@6.1.0)(react@19.2.6) + react: 19.2.6 + react-dom: 19.2.6(react@19.2.6) + '@slaclab/canopy-shell@0.2.0(@carbon/icons-react@11.81.0(react@19.2.6))(@carbon/react@1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.99.0))(react-dom@19.2.6(react@19.2.6))(react@19.2.6)': dependencies: '@carbon/icons-react': 11.81.0(react@19.2.6) diff --git a/src/capturePlot.ts b/src/capturePlot.ts index 5c49d3e..7205037 100644 --- a/src/capturePlot.ts +++ b/src/capturePlot.ts @@ -1,6 +1,7 @@ import { getInstanceByDom } from 'echarts'; +import { chartThemeFor } from '@slaclab/canopy-charts'; import type { Plot } from './types'; -import { DARK_CHART_THEME, LIGHT_CHART_THEME, effectiveBackground } from './chartTheme'; +import { effectiveBackground } from './plotBackground'; /** * Snapshot a mounted plot's chart as a PNG data URL. The effective background @@ -25,7 +26,7 @@ export function capturePlotPng( if (!(host instanceof HTMLElement)) return null; const chart = getInstanceByDom(host); if (!chart) return null; - const theme = colorMode === 'dark' ? DARK_CHART_THEME : LIGHT_CHART_THEME; + const theme = chartThemeFor(colorMode); return chart.getDataURL({ type: 'png', pixelRatio: 2, diff --git a/src/chartTheme.ts b/src/chartTheme.ts deleted file mode 100644 index d12016c..0000000 --- a/src/chartTheme.ts +++ /dev/null @@ -1,54 +0,0 @@ -export interface ChartTheme { - bg: string; - axisLabel: string; - axisLine: string; - splitLine: string; - axisName: string; - tooltipBg: string; - tooltipBorder: string; - tooltipText: string; - tooltipMuted: string; - crosshair: string; - legend: string; -} - -export const DARK_CHART_THEME: ChartTheme = { - bg: '#161616', - axisLabel: '#c6c6c6', - axisLine: '#525252', - splitLine: '#393939', - axisName: '#8d8d8d', - tooltipBg: '#262626', - tooltipBorder: '#393939', - tooltipText: '#f4f4f4', - tooltipMuted: '#8d8d8d', - crosshair: '#8d8d8d', - legend: '#c6c6c6', -}; - -export const LIGHT_CHART_THEME: ChartTheme = { - bg: '#ffffff', - axisLabel: '#393939', - axisLine: '#a8a8a8', - splitLine: '#e0e0e0', - axisName: '#525252', - tooltipBg: '#ffffff', - tooltipBorder: '#c6c6c6', - tooltipText: '#161616', - tooltipMuted: '#525252', - crosshair: '#525252', - legend: '#393939', -}; - -// Defaults from `addPlot` / INITIAL_PLOTS so we know which `plot.backgroundColor` -// values are "the theme default" vs. an explicit user override. When toggling -// themes, only the defaults follow. -export const DARK_DEFAULT_BG = '#161616'; -export const LIGHT_DEFAULT_BG = '#ffffff'; - -export function effectiveBackground(plotBg: string, theme: ChartTheme): string { - // If plotBg matches either theme's default bg, snap to current theme's bg. - // User-customized backgrounds (anything else) stay put. - if (plotBg === DARK_DEFAULT_BG || plotBg === LIGHT_DEFAULT_BG) return theme.bg; - return plotBg; -} diff --git a/src/components/PlotArea.option.test.tsx b/src/components/PlotArea.option.test.tsx new file mode 100644 index 0000000..f9040cd --- /dev/null +++ b/src/components/PlotArea.option.test.tsx @@ -0,0 +1,161 @@ +// @vitest-environment jsdom +// +// Renders SinglePlot with echarts-for-react replaced by a recorder and checks +// the ECharts option it builds: canopy-charts' g10/g100 chart theme, the +// plot-background override, and trace's own sizing on top. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, render } from '@testing-library/react'; +import { CHART_THEMES } from '@slaclab/canopy-charts'; +import { setColorMode } from '@slaclab/canopy-shell/color-mode'; +import { memoryStorage } from '../test/dom'; +import { setupColorMode } from '../state/colorMode'; +import { SinglePlot } from './PlotArea'; +import type { Plot, PVTrace } from '../types'; + +// Loose view of the option object; the tests only read a few fields. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type Option = Record; + +const h = vi.hoisted(() => ({ options: [] as Record[] })); + +vi.mock('echarts-for-react', async () => { + const React = await import('react'); + class MockECharts extends React.Component<{ option: Record }> { + getEchartsInstance() { + return undefined; + } + render() { + h.options.push(this.props.option); + return React.createElement('div'); + } + } + return { default: MockECharts }; +}); + +const lastOption = (): Option => h.options[h.options.length - 1] as Option; + +const NOW = Date.now(); + +function makeTrace(values: number[]): PVTrace { + return { + id: 't1', + pvName: 'TEST:PV', + displayName: 'TEST:PV', + color: '#33b1ff', + visible: true, + axisId: 'ax1', + useLive: false, + updateRate: '1s', + useArchive: false, + lineWidth: 1, + lineType: 'direct', + lineStyle: 'solid', + showSymbol: false, + symbolShape: 'none', + symbolSize: 4, + // Mock samples (no live/archive source), one per second ending now. + data: values.map((value, i) => ({ time: NOW - (values.length - 1 - i) * 1000, value })), + }; +} + +function makePlot(overrides: Partial = {}): Plot { + return { + id: 'p1', + title: 'Plot 1', + traces: [makeTrace([1, 2, 3])], + axes: [ + { + id: 'ax1', + name: 'Y', + orientation: 'left', + autoScale: true, + logScale: false, + visible: true, + }, + ], + backgroundColor: '#161616', + showLegend: true, + showXGridlines: true, + showYGridlines: true, + showCrosshair: true, + gridStyle: 'solid', + gridOpacity: 1, + tickFontSize: 11, + xAxis: { timeRange: '-1h' }, + ...overrides, + }; +} + +function renderPlot(plot: Plot) { + return render( + + ); +} + +beforeEach(() => { + h.options.length = 0; + vi.stubGlobal('localStorage', memoryStorage()); + setupColorMode(); // nothing stored: dark +}); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +describe('SinglePlot chart theme', () => { + it('uses the g100 chart theme in dark mode', () => { + renderPlot(makePlot()); + const opt = lastOption(); + const dark = CHART_THEMES.dark; + expect(opt.animation).toBe(false); + expect(opt.backgroundColor).toBe(dark.bg); + expect(opt.xAxis.axisLabel.color).toBe(dark.axisLabel); + expect(opt.xAxis.axisLine.lineStyle.color).toBe(dark.axisLine); + expect(opt.xAxis.splitLine.lineStyle.color).toBe(dark.splitLine); + expect(opt.yAxis[0].axisLabel.color).toBe(dark.axisLabel); + expect(opt.yAxis[0].axisLine).toMatchObject({ + show: true, + lineStyle: { color: dark.axisLine }, + }); + expect(opt.yAxis[0].nameTextStyle.color).toBe(dark.axisName); + expect(opt.tooltip.backgroundColor).toBe(dark.tooltipBg); + expect(opt.tooltip.borderColor).toBe(dark.tooltipBorder); + expect(opt.tooltip.axisPointer.lineStyle.color).toBe(dark.crosshair); + expect(opt.legend.textStyle.color).toBe(dark.legend); + }); + + it('follows the color mode to the g10 chart theme', () => { + renderPlot(makePlot()); + act(() => setColorMode('light')); + const opt = lastOption(); + const light = CHART_THEMES.light; + expect(opt.backgroundColor).toBe(light.bg); + expect(opt.yAxis[0].axisLabel.color).toBe(light.axisLabel); + expect(opt.xAxis.splitLine.lineStyle.color).toBe(light.splitLine); + expect(opt.tooltip.backgroundColor).toBe(light.tooltipBg); + expect(opt.legend.textStyle.color).toBe(light.legend); + }); + + it('keeps a user-chosen plot background', () => { + renderPlot(makePlot({ backgroundColor: '#123456' })); + expect(lastOption().backgroundColor).toBe('#123456'); + }); + + it("keeps trace's own sizes and gridline style on top of the shared styling", () => { + renderPlot(makePlot({ tickFontSize: 13, gridStyle: 'dashed', gridOpacity: 0.5 })); + const opt = lastOption(); + expect(opt.xAxis.axisLabel.fontSize).toBe(13); + expect(opt.yAxis[0].axisLabel.fontSize).toBe(13); + expect(opt.yAxis[0].nameTextStyle.fontSize).toBe(11); + expect(opt.xAxis.splitLine.lineStyle).toMatchObject({ type: 'dashed', opacity: 0.5 }); + expect(opt.tooltip.textStyle.fontSize).toBe(11); + expect(opt.legend.textStyle.fontSize).toBe(11); + expect(opt.legend.bottom).toBe(8); + }); +}); diff --git a/src/components/PlotArea.tsx b/src/components/PlotArea.tsx index 2283188..a168f45 100644 --- a/src/components/PlotArea.tsx +++ b/src/components/PlotArea.tsx @@ -1,6 +1,8 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import ReactECharts from 'echarts-for-react'; -import { DARK_CHART_THEME, LIGHT_CHART_THEME, effectiveBackground } from '../chartTheme'; +import type { LegendComponentOption, TooltipComponentOption } from 'echarts'; +import { baseChartOption, chartAxisStyle, useChartTheme } from '@slaclab/canopy-charts'; +import { effectiveBackground } from '../plotBackground'; import { Add, Close, ColumnDependency, Grid, Launch, Login, Maximize } from '@carbon/icons-react'; import type { Axis, Plot, PVTrace } from '../types'; import type { ArchiveSeriesResult } from '../hooks/useArchiveSeries'; @@ -10,7 +12,6 @@ import type { TimeWindowNs } from '../api/time'; import { msToNs, nsToMs, resolveTimeWindow } from '../api/time'; import { echartsLineType, echartsSymbol } from '../curveStyle'; import { traceLabel } from '../traceLabel'; -import { useColorMode } from '@slaclab/canopy-shell/color-mode'; import type { PngSource } from '../io/exportPlotImage'; import { AXIS_OFFSET, @@ -210,8 +211,8 @@ export function SinglePlot({ fullscreen, onChartInstance, }: SinglePlotProps) { - const { colorMode } = useColorMode(); - const theme = colorMode === 'dark' ? DARK_CHART_THEME : LIGHT_CHART_THEME; + // Carbon g10/g100 chart colors for the current canopy-shell color mode. + const theme = useChartTheme(); const visibleAxes = plot.axes.filter((a) => a.visible); const visibleTraces = plot.traces.filter((t) => t.visible); const labels = new Map(plot.traces.map((t) => [t.id, traceLabel(t, plot.traces)])); @@ -624,9 +625,17 @@ export function SinglePlot({ onUpdateAxisRef.current = onUpdateAxis; }); + // Shared Canopy chart styling from canopy-charts: animation off, the Plex + // font, and themed axes, tooltip and legend. Trace layers its own layout and + // content on top. + const base = baseChartOption(theme); + const baseTooltip = base.tooltip as TooltipComponentOption; + const baseLegend = base.legend as LegendComponentOption; + const axisStyle = chartAxisStyle(theme); + const option = { + ...base, backgroundColor: effectiveBackground(plot.backgroundColor, theme), - animation: false, grid: { top: GRID_TOP, bottom: GRID_BOTTOM, @@ -637,11 +646,15 @@ export function SinglePlot({ type: 'time', min: xAxisMin, max: xAxisMax, - axisLabel: { color: theme.axisLabel, fontSize: plot.tickFontSize }, - axisLine: { lineStyle: { color: theme.axisLine } }, + ...axisStyle, + axisLabel: { ...axisStyle.axisLabel, fontSize: plot.tickFontSize }, splitLine: { show: plot.showXGridlines, - lineStyle: { color: theme.splitLine, type: plot.gridStyle, opacity: plot.gridOpacity }, + lineStyle: { + ...axisStyle.splitLine.lineStyle, + type: plot.gridStyle, + opacity: plot.gridOpacity, + }, }, }, yAxis: visibleAxes.map((axis, axisIdx) => ({ @@ -651,7 +664,8 @@ export function SinglePlot({ // throws "yAxis 0 not found". Index-based mapping fills slots cleanly. type: axis.logScale ? 'log' : 'value', name: axis.name, - nameTextStyle: { color: theme.axisName, fontSize: 11 }, + ...axisStyle, + nameTextStyle: { ...axisStyle.nameTextStyle, fontSize: 11 }, // Run the title vertically alongside its own axis line so titles never // collide when multiple axes share a side. nameGap clears the labels. nameLocation: 'middle', @@ -662,17 +676,21 @@ export function SinglePlot({ min: axis.autoScale ? undefined : axis.min, max: axis.autoScale ? undefined : axis.max, scale: axis.autoScale, - axisLabel: { color: theme.axisLabel, fontSize: plot.tickFontSize, formatter: formatAxisTick }, + axisLabel: { ...axisStyle.axisLabel, fontSize: plot.tickFontSize, formatter: formatAxisTick }, // ECharts hides axisLine on secondary y-axes by default; force it on so // every stacked axis shows its own vertical line next to its labels. - axisLine: { show: true, lineStyle: { color: theme.axisLine } }, + axisLine: { ...axisStyle.axisLine, show: true }, splitLine: { // Horizontal gridlines are a property of the grid, not each axis: with // multiple Y axes on differing scales their ticks fall at different // heights, so drawing more than one set overlaps into a broken-looking // grid. Draw only the primary (first visible) axis's lines. show: plot.showYGridlines && axisIdx === 0, - lineStyle: { color: theme.splitLine, type: plot.gridStyle, opacity: plot.gridOpacity }, + lineStyle: { + ...axisStyle.splitLine.lineStyle, + type: plot.gridStyle, + opacity: plot.gridOpacity, + }, }, })), series: (() => { @@ -816,23 +834,21 @@ export function SinglePlot({ }, ], tooltip: { + ...baseTooltip, trigger: 'axis', axisPointer: { + ...baseTooltip.axisPointer, type: plot.showCrosshair ? 'cross' : 'none', // 'cross' adds Y-axis readout; 'none' hides crosshair but keeps tooltip snap: false, - lineStyle: { color: theme.crosshair, width: 1, type: 'dashed' }, - crossStyle: { color: theme.crosshair, width: 1, type: 'dashed' }, label: { - backgroundColor: theme.tooltipBorder, + ...baseTooltip.axisPointer?.label, formatter: ( p: { value: number; axisDimension?: string } // X --> timestamp, Y --> raw value ) => p.axisDimension === 'y' ? formatTooltipValue(p.value) : formatCrosshairTime(p.value), }, }, - backgroundColor: theme.tooltipBg, - borderColor: theme.tooltipBorder, - textStyle: { color: theme.tooltipText, fontSize: 11 }, + textStyle: { ...baseTooltip.textStyle, fontSize: 11 }, // Walk every visible trace ourselves rather than trusting `params`. With // snap: false, ECharts only includes series that have a sample exactly // under the cursor — sparse archive data leaves most traces out. The @@ -860,10 +876,10 @@ export function SinglePlot({ }, }, legend: { + ...baseLegend, show: plot.showLegend, bottom: 8, - textStyle: { color: theme.legend, fontSize: 11 }, - inactiveColor: theme.tooltipMuted, + textStyle: { ...baseLegend.textStyle, fontSize: 11 }, data: visibleTraces.map((t) => labels.get(t.id)), selectedMode: false, // legend clicks aren't wired to trace.visible --> disable to + avoid drift }, diff --git a/src/components/TraceApp.tsx b/src/components/TraceApp.tsx index b930810..505881f 100644 --- a/src/components/TraceApp.tsx +++ b/src/components/TraceApp.tsx @@ -26,6 +26,7 @@ import type { TimeWindowNs } from '../api/time'; import { resolveTimeWindow } from '../api/time'; import { fetchMetadata } from '../api/mole'; import { ColorModeTheme, ErrorBoundary, useColorMode } from '@slaclab/canopy-shell'; +import { chartThemeFor } from '@slaclab/canopy-charts'; import { usePaletteId } from '../state/paletteStore'; import { getPalette, colorForIndex } from '../palettes'; import { downloadBlob, downloadDataUrl, pickFile } from '../io/download'; @@ -777,7 +778,7 @@ export function TraceApp() { const openElogPost = useCallback(() => { if (!elogConfig?.enabled) return; const targetPlots = viewMode === 'grid' ? plots : [activePlot]; - const bg = colorMode === 'dark' ? '#161616' : '#ffffff'; + const bg = chartThemeFor(colorMode).bg; const captured = capturePlots( targetPlots.map((p) => ({ id: p.id, diff --git a/src/plotBackground.test.ts b/src/plotBackground.test.ts new file mode 100644 index 0000000..32aed5f --- /dev/null +++ b/src/plotBackground.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from 'vitest'; +import { CHART_THEMES } from '@slaclab/canopy-charts'; +import { effectiveBackground } from './plotBackground'; + +describe('effectiveBackground', () => { + it.each(['#161616', '#f4f4f4', '#ffffff'])('treats %s as the theme default', (bg) => { + expect(effectiveBackground(bg, CHART_THEMES.dark)).toBe('#161616'); + expect(effectiveBackground(bg, CHART_THEMES.light)).toBe('#f4f4f4'); + }); + + it('keeps a user-chosen background in both modes', () => { + expect(effectiveBackground('#123456', CHART_THEMES.dark)).toBe('#123456'); + expect(effectiveBackground('#123456', CHART_THEMES.light)).toBe('#123456'); + }); +}); diff --git a/src/plotBackground.ts b/src/plotBackground.ts new file mode 100644 index 0000000..f26b209 --- /dev/null +++ b/src/plotBackground.ts @@ -0,0 +1,16 @@ +import { CHART_THEMES, type ChartTheme } from '@slaclab/canopy-charts'; + +// Stored plot backgrounds that mean "follow the theme" rather than a user +// override: the dark default every new or imported plot is created with +// (#161616), the g10 chart background (#f4f4f4), and the pre-g10 light +// default (#ffffff). Anything else was picked by the user and stays put. +const THEME_DEFAULT_BACKGROUNDS = new Set([ + CHART_THEMES.dark.bg, + CHART_THEMES.light.bg, + '#ffffff', +]); + +/** The background a plot renders (and exports) with in the given chart theme. */ +export function effectiveBackground(plotBg: string, theme: Readonly): string { + return THEME_DEFAULT_BACKGROUNDS.has(plotBg) ? theme.bg : plotBg; +} From d4fc2f9a426efccbfe713a96febfaefe513e4043 Mon Sep 17 00:00:00 2001 From: YektaY Date: Fri, 16 Oct 2026 07:57:16 -0700 Subject: [PATCH 009/150] Build the live store on HarePVService liveStore no longer runs its own WebSocket. The SDK's HarePVService (on the shared ResilientSocket) now owns the connection: capped-backoff reconnect, resubscribe on reconnect, and a ping every 15 s that drops a socket silent for 10 s. Trace keeps what is its own: per-trace retention, the numeric ring buffers the charts draw, refcounting (one Hare subscription per PV however many traces watch it), and ref-stable snapshots. Behaviour notes: - Only connected numeric updates enter the buffer. The service reports a dropped socket as a DISCONNECTED update carrying the last value, and maps a disconnected PV's null to 0; neither may become a sample. - Severity comes through toWireSeverity(), so points and entries keep the wire strings. - The socket closes when the last live trace is released, and the next watch() opens it again, matching the old "no reconnect while idle". - The service is built on the first watch(). Its URL is toWsUrl(connection.baseUrl, '/hare/v1/ws/pvs'), resolved against the page. - `latest` is the SDK's PVData. Nothing outside useLiveSeries reads it. The tests drive the store through the SDK's createFakeWebSocketFactory instead of a hand-rolled MockWebSocket. New cases cover disconnect updates, ping timeout, idle close, factory failure and URL resolution. src/api/hare.ts and trace's Hare wire types are gone. Part of #86. --- src/api/hare.ts | 8 - src/api/types.ts | 55 +---- src/state/liveStore.test.ts | 385 ++++++++++++++++++-------------- src/state/liveStore.ts | 240 +++++++++----------- src/state/liveStore.url.test.ts | 23 ++ 5 files changed, 356 insertions(+), 355 deletions(-) delete mode 100644 src/api/hare.ts create mode 100644 src/state/liveStore.url.test.ts diff --git a/src/api/hare.ts b/src/api/hare.ts deleted file mode 100644 index 57e16ef..0000000 --- a/src/api/hare.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { canopyWebSocketUrl } from './client'; - -// Same-origin WS URL. The Vite dev proxy (vite.config.ts) and any prod reverse -// proxy handle the /hare upgrade and inject X-API-Key, so the bundle never -// holds the key. SSR-safe: returns an empty string when `window` is undefined. -export function liveWsUrl(): string { - return canopyWebSocketUrl('/hare/v1/ws/pvs'); -} diff --git a/src/api/types.ts b/src/api/types.ts index 7ba5853..121cccb 100644 --- a/src/api/types.ts +++ b/src/api/types.ts @@ -1,7 +1,6 @@ // Transitional: trace's wire-type names, now backed by @slaclab/canopy-client. -// The Mole DTOs and the error envelope are the SDK's own types; the Hare and Fox -// sections below go as their modules move to the SDK. Removed once nothing -// imports it. +// The Mole DTOs and the error envelope are the SDK's own types; the Fox section +// below goes when fox.ts moves to the SDK. Removed once nothing imports it. import type { WireAlarmSeverity } from '@slaclab/canopy-client'; @@ -21,56 +20,6 @@ export type { SearchResultsDTO, } from '@slaclab/canopy-client'; -// ── Hare (live PV) DTOs ────────────────────────────────────────────────────── -// Source: canopy.contracts.pv.PVValue + canopy.hare.api.v1.ws frame schema. -// `tsNs` matches Mole's Sample.tsNs so live and archive share one time domain. - -export type PVScalarValue = number | string | boolean | null; -export type PVValueType = PVScalarValue | PVScalarValue[]; - -export interface PVValueDTO { - pv: string; - value: PVValueType; - severity: AlarmSeverity; - tsNs: number; - connected: boolean; - units: string | null; - precision: number | null; - error: string | null; -} - -export interface WsInitialFrame { - type: 'initial'; - data: Record; - count: number; -} - -export interface WsDiffFrame { - type: 'diff'; - data: Record; - count: number; - timestamp: number; -} - -export interface WsHeartbeatFrame { - type: 'heartbeat'; - timestamp: number; - backend: string | null; -} - -export interface WsPongFrame { - type: 'pong'; - timestamp: number; -} - -export interface WsErrorFrame { - type: 'error'; - code: string; - message: string; -} - -export type WsFrame = WsInitialFrame | WsDiffFrame | WsHeartbeatFrame | WsPongFrame | WsErrorFrame; - // ── Fox (formula) DTOs ─────────────────────────────────────────────────────── // Source: canopy.contracts.formula + canopy.fox.schemas.formula (camelCase wire). // A formula curve evaluates an `expression` over named `bindings` (variable -> diff --git a/src/state/liveStore.test.ts b/src/state/liveStore.test.ts index ece52e2..f175f77 100644 --- a/src/state/liveStore.test.ts +++ b/src/state/liveStore.test.ts @@ -1,160 +1,132 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { createFakeWebSocketFactory } from '@slaclab/canopy-client/testing'; +import type { + HareAlarmSeverity, + PVValueDTO, + WebSocketFactory, + WireAlarmSeverity, +} from '@slaclab/canopy-client'; import { LiveStore } from './liveStore'; -import type { PVValueDTO } from '../api/types'; - -// Minimal hand-rolled WebSocket mock. We avoid pulling in a dep; the live -// store only uses readyState, send, close, and the four event handlers. -class MockWebSocket { - static readonly OPEN = 1; - static readonly CLOSED = 3; - static instances: MockWebSocket[] = []; - - url: string; - readyState = 0; - sent: string[] = []; - onopen: ((this: MockWebSocket) => void) | null = null; - onmessage: ((this: MockWebSocket, ev: { data: string }) => void) | null = null; - onclose: ((this: MockWebSocket) => void) | null = null; - onerror: ((this: MockWebSocket) => void) | null = null; - - constructor(url: string) { - this.url = url; - MockWebSocket.instances.push(this); - } - - send(data: string): void { - this.sent.push(data); - } - - close(): void { - if (this.readyState === MockWebSocket.CLOSED) return; - this.readyState = MockWebSocket.CLOSED; - this.onclose?.call(this); - } - - // Test helpers --------------------------------------------------------- - open(): void { - this.readyState = MockWebSocket.OPEN; - this.onopen?.call(this); - } - - emit(frame: unknown): void { - this.onmessage?.call(this, { data: JSON.stringify(frame) }); - } - - parsedSent(): unknown[] { - return this.sent.map((s) => JSON.parse(s)); - } + +const BASE_URL = 'http://canopy.test'; +const HARE_URL = 'ws://canopy.test/hare/v1/ws/pvs'; +const WS_CLOSED = 3; + +function setup(factory?: WebSocketFactory) { + const fake = createFakeWebSocketFactory(); + const store = new LiveStore({ + connection: { baseUrl: BASE_URL }, + webSocketFactory: factory ?? fake.factory, + }); + return { store, instances: fake.instances, fakeFactory: fake.factory }; } -function pvValue(pv: string, value: number, tsMs: number): PVValueDTO { +function pvValue( + pv: string, + value: PVValueDTO['value'], + tsMs: number, + severity: HareAlarmSeverity = 'NO_ALARM' +): PVValueDTO { return { pv, value, - severity: 'NO_ALARM', + valueKind: typeof value === 'string' ? 'string' : 'scalar', + severity, tsNs: tsMs * 1_000_000, connected: true, - units: null, - precision: null, error: null, }; } -const realWebSocket = (globalThis as { WebSocket?: typeof WebSocket }).WebSocket; +// Hare sends per-PV metadata alongside the first values; trace doesn't use it. +function initial(data: Record) { + return { type: 'initial', data, meta: {}, count: Object.keys(data).length }; +} + +function diff(data: Record, timestamp = Date.now()) { + return { type: 'diff', data, count: Object.keys(data).length, timestamp }; +} + +function point(time: number, value: number, severity: WireAlarmSeverity = 'NO_ALARM') { + return { time, value, severity }; +} beforeEach(() => { - MockWebSocket.instances = []; - (globalThis as unknown as { WebSocket: typeof MockWebSocket }).WebSocket = MockWebSocket; vi.useFakeTimers(); vi.setSystemTime(new Date('2026-06-05T12:00:00Z')); }); afterEach(() => { vi.useRealTimers(); - if (realWebSocket) { - (globalThis as unknown as { WebSocket: typeof WebSocket }).WebSocket = realWebSocket; - } else { - delete (globalThis as { WebSocket?: unknown }).WebSocket; - } }); describe('LiveStore', () => { - it('connects lazily and sends a subscribe frame after the socket opens', () => { - const store = new LiveStore(); + it('connects lazily to Hare and subscribes once the socket opens', () => { + const { store, instances } = setup(); + expect(instances).toHaveLength(0); + store.watch('t1', 'TEST:SINE', 60_000); - expect(MockWebSocket.instances).toHaveLength(1); - const ws = MockWebSocket.instances[0]; - // Pre-open: no subscribes were sent (would have errored on a real socket). + expect(instances).toHaveLength(1); + const ws = instances[0]; + expect(ws.url).toBe(HARE_URL); + // Pre-open: nothing sent (it would fail on a real socket). expect(ws.sent).toEqual([]); + expect(store.getSnapshot().get('t1')!.status).toBe('connecting'); ws.open(); expect(ws.parsedSent()).toEqual([{ type: 'subscribe', pvNames: ['TEST:SINE'] }]); + expect(store.getSnapshot().get('t1')!.status).toBe('connected'); }); it('appends numeric samples and exposes them through the snapshot', () => { - const store = new LiveStore(); + const { store, instances } = setup(); store.watch('t1', 'TEST:SINE', 60_000); - const ws = MockWebSocket.instances[0]; + const ws = instances[0]; ws.open(); const tsMs = Date.now(); - ws.emit({ - type: 'initial', - data: { 'TEST:SINE': pvValue('TEST:SINE', 1.5, tsMs) }, - count: 1, - }); + ws.message(initial({ 'TEST:SINE': pvValue('TEST:SINE', 1.5, tsMs) })); const entry = store.getSnapshot().get('t1'); expect(entry).toBeDefined(); expect(entry!.connected).toBe(true); expect(entry!.severity).toBe('NO_ALARM'); - expect(entry!.points).toEqual([{ time: tsMs, value: 1.5, severity: 'NO_ALARM' }]); + expect(entry!.points).toEqual([point(tsMs, 1.5)]); - ws.emit({ - type: 'diff', - data: { 'TEST:SINE': pvValue('TEST:SINE', 2.25, tsMs + 100) }, - count: 1, - timestamp: tsMs + 100, - }); + ws.message(diff({ 'TEST:SINE': pvValue('TEST:SINE', 2.25, tsMs + 100) }, tsMs + 100)); expect(store.getSnapshot().get('t1')!.points).toEqual([ - { time: tsMs, value: 1.5, severity: 'NO_ALARM' }, - { time: tsMs + 100, value: 2.25, severity: 'NO_ALARM' }, + point(tsMs, 1.5), + point(tsMs + 100, 2.25), ]); }); it('retains per-sample severity on each buffered point', () => { - const store = new LiveStore(); + const { store, instances } = setup(); store.watch('t1', 'SEV', 60_000); - const ws = MockWebSocket.instances[0]; + const ws = instances[0]; ws.open(); const tsMs = Date.now(); - ws.emit({ - type: 'initial', - data: { SEV: { ...pvValue('SEV', 1, tsMs), severity: 'MINOR' } }, - count: 1, - }); - ws.emit({ - type: 'diff', - data: { SEV: { ...pvValue('SEV', 2, tsMs + 100), severity: 'MAJOR' } }, - count: 1, - timestamp: tsMs + 100, - }); + ws.message(initial({ SEV: pvValue('SEV', 1, tsMs, 'MINOR') })); + ws.message(diff({ SEV: pvValue('SEV', 2, tsMs + 100, 'MAJOR') })); + ws.message(diff({ SEV: pvValue('SEV', 3, tsMs + 200, 'INVALID') })); // Each point keeps the severity reported with it, not just the PV's latest. expect(store.getSnapshot().get('t1')!.points).toEqual([ - { time: tsMs, value: 1, severity: 'MINOR' }, - { time: tsMs + 100, value: 2, severity: 'MAJOR' }, + point(tsMs, 1, 'MINOR'), + point(tsMs + 100, 2, 'MAJOR'), + point(tsMs + 200, 3, 'INVALID'), ]); + expect(store.getSnapshot().get('t1')!.severity).toBe('INVALID'); }); it('refcounts subscriptions across traces sharing one PV', () => { - const store = new LiveStore(); + const { store, instances } = setup(); store.watch('t1', 'FOO', 60_000); store.watch('t2', 'FOO', 60_000); - const ws = MockWebSocket.instances[0]; + const ws = instances[0]; ws.open(); // Only one outbound subscribe for FOO, even though two traces watch it. @@ -172,10 +144,25 @@ describe('LiveStore', () => { ]); }); + it('delivers one sample per update to every trace on a shared PV', () => { + const { store, instances } = setup(); + store.watch('t1', 'FOO', 60_000); + store.watch('t2', 'FOO', 60_000); + const ws = instances[0]; + ws.open(); + + const tsMs = Date.now(); + ws.message(initial({ FOO: pvValue('FOO', 1, tsMs) })); + + const snap = store.getSnapshot(); + expect(snap.get('t1')!.points).toEqual([point(tsMs, 1)]); + expect(snap.get('t2')!.points).toBe(snap.get('t1')!.points); + }); + it('evicts samples older than the longest active retention once slack is exceeded', () => { - const store = new LiveStore(); + const { store, instances } = setup(); store.watch('t1', 'BAR', 1_000); // 1s retention - const ws = MockWebSocket.instances[0]; + const ws = instances[0]; ws.open(); const t0 = Date.now(); @@ -184,12 +171,7 @@ describe('LiveStore', () => { // we push well past that margin to force a trim pass. const STALE = 300; for (let i = 0; i < STALE; i++) { - ws.emit({ - type: 'diff', - data: { BAR: pvValue('BAR', i, t0) }, - count: 1, - timestamp: t0, - }); + ws.message(diff({ BAR: pvValue('BAR', i, t0) }, t0)); } expect(store.getSnapshot().get('t1')!.points).toHaveLength(STALE); @@ -198,12 +180,7 @@ describe('LiveStore', () => { vi.setSystemTime(new Date(t0 + 1_500)); const FRESH = 300; for (let i = 0; i < FRESH; i++) { - ws.emit({ - type: 'diff', - data: { BAR: pvValue('BAR', 1000 + i, t0 + 1_500) }, - count: 1, - timestamp: t0 + 1_500, - }); + ws.message(diff({ BAR: pvValue('BAR', 1000 + i, t0 + 1_500) }, t0 + 1_500)); } const points = store.getSnapshot().get('t1')!.points; // The t0 batch is older than 1s and has been evicted; only the fresh @@ -213,125 +190,207 @@ describe('LiveStore', () => { }); it('marks PVs disconnected on socket close and re-subscribes on reopen', () => { - const store = new LiveStore(); + const { store, instances } = setup(); store.watch('t1', 'BAZ', 60_000); - const ws = MockWebSocket.instances[0]; + const ws = instances[0]; ws.open(); - ws.emit({ - type: 'initial', - data: { BAZ: pvValue('BAZ', 7, Date.now()) }, - count: 1, - }); + ws.message(initial({ BAZ: pvValue('BAZ', 7, Date.now(), 'MINOR') })); expect(store.getSnapshot().get('t1')!.connected).toBe(true); - ws.close(); - expect(store.getSnapshot().get('t1')!.connected).toBe(false); - // Buffer is preserved so the chart doesn't blank during reconnect. - expect(store.getSnapshot().get('t1')!.points).toHaveLength(1); + ws.close(1006); + const entry = store.getSnapshot().get('t1')!; + expect(entry.status).toBe('disconnected'); + expect(entry.connected).toBe(false); + // Buffer is preserved so the chart doesn't blank during reconnect, and the + // service's "disconnected" update with the stale value adds no sample. + expect(entry.points).toEqual([point(Date.now(), 7, 'MINOR')]); + expect(entry.severity).toBe('MINOR'); // Backoff: first reconnect attempt fires after 1s. - vi.advanceTimersByTime(1_000); - expect(MockWebSocket.instances).toHaveLength(2); - const ws2 = MockWebSocket.instances[1]; + vi.advanceTimersByTime(999); + expect(instances).toHaveLength(1); + vi.advanceTimersByTime(1); + expect(instances).toHaveLength(2); + const ws2 = instances[1]; ws2.open(); // On reopen the store re-subscribes everything currently watched. expect(ws2.parsedSent()).toEqual([{ type: 'subscribe', pvNames: ['BAZ'] }]); }); + it('adds no sample for a PV that Hare reports disconnected', () => { + const { store, instances } = setup(); + store.watch('t1', 'GONE', 60_000); + const ws = instances[0]; + ws.open(); + + const tsMs = Date.now(); + ws.message(initial({ GONE: pvValue('GONE', 4, tsMs) })); + // The IOC goes away: value null, connected false. The SDK hands that on + // with value 0, which must not reach the chart. + ws.message( + diff({ + GONE: { ...pvValue('GONE', null, tsMs + 100, 'INVALID'), connected: false }, + }) + ); + + const entry = store.getSnapshot().get('t1')!; + expect(entry.connected).toBe(false); + expect(entry.points).toEqual([point(tsMs, 4)]); + expect(entry.status).toBe('connected'); + }); + it('skips non-numeric values for the points buffer but updates `latest`', () => { - const store = new LiveStore(); + const { store, instances } = setup(); store.watch('t1', 'STR', 60_000); - const ws = MockWebSocket.instances[0]; + const ws = instances[0]; ws.open(); - ws.emit({ - type: 'initial', - data: { - STR: { ...pvValue('STR', 0, Date.now()), value: 'OPERATIONAL' }, - }, - count: 1, - }); + ws.message(initial({ STR: pvValue('STR', 'OPERATIONAL', Date.now()) })); const entry = store.getSnapshot().get('t1')!; expect(entry.latest?.value).toBe('OPERATIONAL'); + expect(entry.connected).toBe(true); expect(entry.points).toEqual([]); }); it('surfaces ws error frames on the entry and clears them on a clean reopen', () => { - const store = new LiveStore(); + const { store, instances } = setup(); store.watch('t1', 'ERR', 60_000); - const ws = MockWebSocket.instances[0]; + const ws = instances[0]; ws.open(); expect(store.getSnapshot().get('t1')!.error).toBeNull(); - ws.emit({ type: 'error', code: 'BACKEND_DOWN', message: 'archiver unreachable' }); + ws.message({ type: 'error', code: 'BACKEND_DOWN', message: 'archiver unreachable' }); expect(store.getSnapshot().get('t1')!.error).toEqual({ code: 'BACKEND_DOWN', message: 'archiver unreachable', }); // A clean reconnect clears the error. - ws.close(); + ws.close(1006); vi.advanceTimersByTime(1_000); - const ws2 = MockWebSocket.instances[1]; + const ws2 = instances[1]; ws2.open(); expect(store.getSnapshot().get('t1')!.error).toBeNull(); }); + it('reports a socket that cannot be created and retries with backoff', () => { + const fake = createFakeWebSocketFactory(); + let failNext = true; + const { store } = setup((url) => { + if (failNext) { + failNext = false; + throw new Error('blocked'); + } + return fake.factory(url); + }); + + store.watch('t1', 'X', 60_000); + const entry = store.getSnapshot().get('t1')!; + expect(entry.status).toBe('disconnected'); + expect(entry.error).toEqual({ + code: 'ws_connect_failed', + message: 'Could not open live connection: blocked', + }); + + vi.advanceTimersByTime(1_000); + expect(fake.instances).toHaveLength(1); + fake.instances[0].open(); + expect(store.getSnapshot().get('t1')!.error).toBeNull(); + }); + + it('pings the server and reconnects when nothing comes back', () => { + const { store, instances } = setup(); + store.watch('t1', 'PING', 60_000); + const ws = instances[0]; + ws.open(); + ws.message(initial({ PING: pvValue('PING', 1, Date.now()) })); + + vi.advanceTimersByTime(15_000); + expect(ws.parsedSent()).toContainEqual({ type: 'ping' }); + + // No pong (or any frame) within 10s: the socket is treated as dead. + vi.advanceTimersByTime(10_000); + expect(ws.readyState).toBe(WS_CLOSED); + expect(store.getSnapshot().get('t1')!.status).toBe('disconnected'); + + vi.advanceTimersByTime(1_000); + expect(instances).toHaveLength(2); + }); + + it('closes the socket when the last trace is released and reopens on the next watch', () => { + const { store, instances } = setup(); + store.watch('t1', 'IDLE', 60_000); + const ws = instances[0]; + ws.open(); + + store.release('t1'); + expect(ws.readyState).toBe(WS_CLOSED); + expect(store.getSnapshot().size).toBe(0); + + // Nothing is watched, so nothing reconnects. + vi.advanceTimersByTime(60_000); + expect(instances).toHaveLength(1); + + store.watch('t2', 'IDLE', 60_000); + expect(instances).toHaveLength(2); + instances[1].open(); + expect(instances[1].parsedSent()).toEqual([{ type: 'subscribe', pvNames: ['IDLE'] }]); + }); + + it('keeps the socket open when a trace switches PV', () => { + const { store, instances } = setup(); + store.watch('t1', 'OLD', 60_000); + const ws = instances[0]; + ws.open(); + + store.watch('t1', 'NEW', 60_000); + + expect(instances).toHaveLength(1); + expect(ws.readyState).not.toBe(WS_CLOSED); + expect(ws.parsedSent()).toEqual([ + { type: 'subscribe', pvNames: ['OLD'] }, + { type: 'unsubscribe', pvNames: ['OLD'] }, + { type: 'subscribe', pvNames: ['NEW'] }, + ]); + }); + it('reuses the same entry reference when a PV is unchanged between frames', () => { - const store = new LiveStore(); + const { store, instances } = setup(); store.watch('t1', 'AAA', 60_000); store.watch('t2', 'BBB', 60_000); - const ws = MockWebSocket.instances[0]; + const ws = instances[0]; ws.open(); const t0 = Date.now(); - ws.emit({ - type: 'initial', - data: { AAA: pvValue('AAA', 1, t0), BBB: pvValue('BBB', 1, t0) }, - count: 2, - }); + ws.message(initial({ AAA: pvValue('AAA', 1, t0), BBB: pvValue('BBB', 1, t0) })); const first = store.getSnapshot(); const aBefore = first.get('t1')!; const bBefore = first.get('t2')!; // A frame touching only AAA should leave BBB's entry object identical, so // downstream React.memo / shallow checks for the BBB trace short-circuit. - ws.emit({ - type: 'diff', - data: { AAA: pvValue('AAA', 2, t0 + 100) }, - count: 1, - timestamp: t0 + 100, - }); + ws.message(diff({ AAA: pvValue('AAA', 2, t0 + 100) }, t0 + 100)); const second = store.getSnapshot(); expect(second.get('t1')).not.toBe(aBefore); // AAA changed -> new entry expect(second.get('t2')).toBe(bBefore); // BBB unchanged -> same entry }); it('getEntrySnapshot returns one trace and stays ref-stable when unrelated traces change', () => { - const store = new LiveStore(); + const { store, instances } = setup(); store.watch('t1', 'AAA', 60_000); store.watch('t2', 'BBB', 60_000); - const ws = MockWebSocket.instances[0]; + const ws = instances[0]; ws.open(); const t0 = Date.now(); - ws.emit({ - type: 'initial', - data: { AAA: pvValue('AAA', 1, t0), BBB: pvValue('BBB', 1, t0) }, - count: 2, - }); + ws.message(initial({ AAA: pvValue('AAA', 1, t0), BBB: pvValue('BBB', 1, t0) })); const bBefore = store.getEntrySnapshot('t2'); expect(bBefore?.pv).toBe('BBB'); // A frame touching only AAA leaves t2's entry reference identical, so a // consumer subscribed via getEntrySnapshot('t2') can bail its re-render. - ws.emit({ - type: 'diff', - data: { AAA: pvValue('AAA', 2, t0 + 100) }, - count: 1, - timestamp: t0 + 100, - }); + ws.message(diff({ AAA: pvValue('AAA', 2, t0 + 100) }, t0 + 100)); expect(store.getEntrySnapshot('t2')).toBe(bBefore); // unchanged -> same ref expect(store.getEntrySnapshot('t1')).not.toBe(bBefore); expect(store.getEntrySnapshot('missing')).toBeUndefined(); diff --git a/src/state/liveStore.ts b/src/state/liveStore.ts index 3d9b141..e2bcaf0 100644 --- a/src/state/liveStore.ts +++ b/src/state/liveStore.ts @@ -1,13 +1,22 @@ -// Singleton WebSocket-backed store for live PV samples from Canopy/Hare. +// Singleton store for live PV samples from Canopy/Hare. // // Mirrors `archiveStore`: per-trace external store, `useSyncExternalStore`- -// compatible. One shared WebSocket fans out to many traces; PV monitors are -// refcounted so two traces watching the same PV produce one outbound subscribe. - -import { liveWsUrl } from '../api/hare'; -import { nsToMs } from '../api/time'; -import type { WireAlarmSeverity } from '@slaclab/canopy-client'; -import type { PVValueDTO, WsFrame } from '../api/types'; +// compatible. The connection (reconnect with capped backoff, ping/pong +// liveness, resubscribe on reconnect) is the SDK's `HarePVService`; this store +// keeps what is trace-specific on top of it: per-trace retention, the numeric +// ring buffers the charts draw, and ref-stable snapshots. PV monitors are +// refcounted so two traces watching the same PV share one Hare subscription. + +import { + HarePVService, + toWsUrl, + type CanopyConnection, + type PVData, + type WebSocketFactory, + type WireAlarmSeverity, +} from '@slaclab/canopy-client'; +import { canopyConnection } from '../api/connection'; +import { toWireSeverity } from '../api/severity'; export interface LivePoint { time: number; @@ -28,11 +37,12 @@ export interface LiveEntry { pv: string; // Socket-level connection state (shared across all entries). status: LiveStatus; - // PV-level connection (Hare's PVValue.connected). True only after a frame + // PV-level connection (Hare's PVValue.connected). True only after an update // for this PV has been received reporting connected=true. connected: boolean; + // Last alarm severity reported while the PV was connected. severity: WireAlarmSeverity | null; - latest: PVValueDTO | null; + latest: PVData | null; // Last surfaced connection/protocol error, if any. Cleared on a clean // (re)connect. Distinct from a stale buffer: the chart can keep rendering // `points` while showing the error. @@ -42,21 +52,30 @@ export interface LiveEntry { points: readonly LivePoint[]; } +export interface LiveStoreOptions { + // How to reach Canopy. Default: the app's shared connection. + connection?: CanopyConnection; + // Injectable for tests. Default: the global WebSocket. + webSocketFactory?: WebSocketFactory; +} + +const HARE_WS_PATH = '/hare/v1/ws/pvs'; + const HARD_CAP_POINTS = 100_000; // Eviction slack: defer the O(n) front-trim until the buffer holds noticeably // more than the retention window calls for, then trim in one pass. Bounds the // amortized cost per sample to O(1) instead of O(n)-per-sample. const TRIM_SLACK_POINTS = 256; -// Capped backoff schedule. Reset on every successful open. -const RECONNECT_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 15_000]; interface PVState { // traceId -> retentionMs refs: Map; points: LivePoint[]; - latest: PVValueDTO | null; + latest: PVData | null; connected: boolean; severity: WireAlarmSeverity | null; + // Ends the Hare subscription; called when the last trace releases the PV. + unsubscribe: (() => void) | null; // Monotonic revision bumped whenever any published field of this PV changes. // `entryFor()` reuses the cached LiveEntry when the rev is unchanged so // downstream shallow-equality / React.memo checks hold across frames. @@ -71,11 +90,16 @@ interface TraceRef { type Listener = () => void; export class LiveStore { - private ws: WebSocket | null = null; + private readonly options: LiveStoreOptions; + // Built on the first watch(): resolving the WebSocket URL needs the page + // location, which tests and other non-browser imports don't have. + private service: HarePVService | null = null; + // Whether we asked the service to stay connected. Cleared when the last + // trace is released (the socket is closed then) and after a terminal close, + // so the next watch() reconnects without cutting a pending backoff short. + private connectRequested = false; private wsStatus: LiveStatus = 'idle'; private wsError: LiveError | null = null; - private reconnectAttempt = 0; - private reconnectTimer: ReturnType | null = null; private pvs = new Map(); private byTrace = new Map(); @@ -93,6 +117,10 @@ export class LiveStore { private notifyScheduled = false; private listeners = new Set(); + constructor(options: LiveStoreOptions = {}) { + this.options = options; + } + getSnapshot = (): ReadonlyMap => { if (this.dirty) this.rebuild(); return this.snapshot; @@ -125,7 +153,6 @@ export class LiveStore { this.byTrace.set(traceId, { pv, retentionMs }); let state = this.pvs.get(pv); - const isFirst = !state; if (!state) { state = { refs: new Map(), @@ -133,6 +160,7 @@ export class LiveStore { latest: null, connected: false, severity: null, + unsubscribe: null, rev: 0, }; this.pvs.set(pv, state); @@ -140,8 +168,18 @@ export class LiveStore { state.refs.set(traceId, retentionMs); state.rev++; - this.ensureConnected(); - if (isFirst) this.sendSubscribe([pv]); + const service = this.ensureService(); + if (service) { + // One Hare subscription per PV, however many traces watch it. Sent now + // if the socket is open, otherwise on (re)connect. + if (!state.unsubscribe) { + state.unsubscribe = service.subscribe(pv, (data) => this.applyData(pv, data)); + } + if (!this.connectRequested) { + this.connectRequested = true; + service.connect(); + } + } this.markDirty(); } @@ -154,139 +192,79 @@ export class LiveStore { state.refs.delete(traceId); if (state.refs.size === 0) { this.pvs.delete(prev.pv); - this.sendUnsubscribe([prev.pv]); + state.unsubscribe?.(); } return true; } release(traceId: string): void { - if (this.detach(traceId)) this.markDirty(); - } - - /** Released for tests so we can assert post-disconnect state. */ - forceDisconnect(): void { - this.ws?.close(); + if (!this.detach(traceId)) return; + // Nothing left to watch: close the socket rather than keep reconnecting. + // The next watch() opens a new one. + if (this.byTrace.size === 0 && this.connectRequested) { + this.connectRequested = false; + this.service?.disconnect(); + } + this.markDirty(); } // ── internals ────────────────────────────────────────────────────────── - private ensureConnected(): void { - if (typeof WebSocket === 'undefined') return; - if (this.ws || this.wsStatus === 'connecting') return; - this.connect(); - } - - private connect(): void { - if (typeof WebSocket === 'undefined') return; - this.wsStatus = 'connecting'; - let ws: WebSocket; + private ensureService(): HarePVService | null { + if (this.service) return this.service; + const { webSocketFactory } = this.options; + if (!webSocketFactory && typeof WebSocket === 'undefined') return null; + const conn = this.options.connection ?? canopyConnection; try { - ws = new WebSocket(liveWsUrl()); + this.service = new HarePVService({ + url: toWsUrl(conn.baseUrl, HARE_WS_PATH), + apiKey: conn.apiKey, + fetchFn: conn.fetch, + webSocketFactory, + onStatusChange: (status) => this.handleStatus(status), + onError: (error) => { + // A terminal close stops the service until connect() is called again. + if (error.code === 'ws_terminal_close') this.connectRequested = false; + this.setError(error.code, error.message); + }, + }); } catch (err) { - this.wsStatus = 'disconnected'; const detail = err instanceof Error ? err.message : String(err); - this.setError('ws-connect-failed', `Could not open live connection: ${detail}`); - this.scheduleReconnect(); - return; - } - this.ws = ws; - ws.onopen = () => this.handleOpen(); - ws.onmessage = (ev) => this.handleMessage(ev); - ws.onclose = () => this.handleClose(); - // onerror is followed by onclose; let close handle reconnect. Record it so - // the user sees something more useful than a silent disconnect. - ws.onerror = () => this.setError('ws-error', 'Live connection error.'); - } - - private handleOpen(): void { - this.wsStatus = 'connected'; - this.reconnectAttempt = 0; - // A clean open clears any prior connection error. - this.clearError(); - const pvs = [...this.pvs.keys()]; - if (pvs.length) this.sendSubscribe(pvs); - this.markDirty(); - } - - private handleMessage(ev: MessageEvent): void { - let frame: WsFrame; - try { - frame = JSON.parse(ev.data as string) as WsFrame; - } catch { - return; + this.setError('ws_connect_failed', `Could not open live connection: ${detail}`); + return null; } - this.applyFrame(frame); + return this.service; } - private handleClose(): void { - this.ws = null; - this.wsStatus = 'disconnected'; - // Mark every PV pv-level disconnected; keep buffers visible until reconnect. - for (const state of this.pvs.values()) { - if (state.connected) { - state.connected = false; - state.rev++; - } - } + private handleStatus(status: LiveStatus): void { + this.wsStatus = status; + // A clean (re)connect clears any prior connection error. + if (status === 'connected') this.clearError(); this.markDirty(); - this.scheduleReconnect(); } - private scheduleReconnect(): void { - if (this.byTrace.size === 0) return; - if (this.reconnectTimer) return; - const delay = - RECONNECT_DELAYS_MS[Math.min(this.reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)]; - this.reconnectAttempt++; - this.reconnectTimer = setTimeout(() => { - this.reconnectTimer = null; - this.connect(); - }, delay); - } - - private sendSubscribe(pvNames: string[]): void { - this.sendIfOpen({ type: 'subscribe', pvNames }); - } - - private sendUnsubscribe(pvNames: string[]): void { - this.sendIfOpen({ type: 'unsubscribe', pvNames }); - } - - private sendIfOpen(message: { type: string; pvNames: string[] }): void { - if (!message.pvNames.length) return; - if (this.ws && this.ws.readyState === WebSocket.OPEN) { - this.ws.send(JSON.stringify(message)); - } - // Pre-open subscribes are covered by the re-subscribe in `handleOpen`. - } - - private applyFrame(frame: WsFrame): void { - if (frame.type === 'initial' || frame.type === 'diff') { - for (const pv of Object.keys(frame.data)) { - this.applyValue(pv, frame.data[pv]); - } - this.markDirty(); - return; - } - if (frame.type === 'error') { - console.warn('hare ws error frame:', frame); - this.setError(frame.code || 'ws-error', frame.message || 'Live stream error.'); - } - // heartbeat / pong: ignored for now. - } - - private applyValue(pv: string, v: PVValueDTO): void { + private applyData(pv: string, data: PVData): void { const state = this.pvs.get(pv); - // PV may have been released between subscribe and a stray late frame. + // PV may have been released between subscribe and a stray late update. if (!state) return; - state.latest = v; - state.connected = v.connected; - state.severity = v.severity; - state.rev++; - if (typeof v.value === 'number' && Number.isFinite(v.value)) { - state.points.push({ time: nsToMs(v.tsNs), value: v.value, severity: v.severity }); - this.trim(state); + state.latest = data; + state.connected = data.connected; + // A disconnected PV (or a dropped socket, which the service reports as a + // DISCONNECTED update with the last value) keeps its last alarm severity + // and adds no sample: its value is stale, or 0 standing in for null. + if (data.connected) { + state.severity = toWireSeverity(data.severity); + if (typeof data.value === 'number' && Number.isFinite(data.value)) { + state.points.push({ + time: data.timestamp, + value: data.value, + severity: state.severity ?? 'INVALID', + }); + this.trim(state); + } } + state.rev++; + this.markDirty(); } private trim(state: PVState): void { diff --git a/src/state/liveStore.url.test.ts b/src/state/liveStore.url.test.ts new file mode 100644 index 0000000..0ca4104 --- /dev/null +++ b/src/state/liveStore.url.test.ts @@ -0,0 +1,23 @@ +// @vitest-environment jsdom +import { describe, expect, it } from 'vitest'; +import { createFakeWebSocketFactory } from '@slaclab/canopy-client/testing'; +import { LiveStore } from './liveStore'; + +// The app's connection is a same-origin path; the Hare socket URL is resolved +// against the page, like fetch resolves the REST calls. +describe('LiveStore socket URL', () => { + it('resolves the per-module layout against the page origin', () => { + const { factory, instances } = createFakeWebSocketFactory(); + new LiveStore({ connection: { baseUrl: '' }, webSocketFactory: factory }).watch('t', 'X', 1); + expect(instances[0].url).toBe(`ws://${window.location.host}/hare/v1/ws/pvs`); + }); + + it('keeps a deployed base path in front of the Hare route', () => { + const { factory, instances } = createFakeWebSocketFactory(); + new LiveStore({ + connection: { baseUrl: '/trace/api/canopy' }, + webSocketFactory: factory, + }).watch('t', 'X', 1); + expect(instances[0].url).toBe(`ws://${window.location.host}/trace/api/canopy/hare/v1/ws/pvs`); + }); +}); From 0da5186e00f86eda53d8b21745192f68e67bc162 Mon Sep 17 00:00:00 2001 From: YektaY Date: Fri, 16 Oct 2026 07:57:34 -0700 Subject: [PATCH 010/150] Use canopy-charts number formatters in plot axes and tooltips Swap PlotArea's local formatAxisTick and formatTooltipValue for the shared canopy-charts versions. - Axis ticks are unchanged: exponential below 1e-3 and at or above 1e6, otherwise the default number string. - Tooltip values and the crosshair y readout now use formatValue, which keeps 7 significant digits but trims trailing zeros: 0.5 instead of 0.5000000, and 1.234568e-5 instead of 1.2346e-5 (the exponential form now also shows 7 digits). Tests pin the tick formatter and the tooltip output. --- src/components/PlotArea.option.test.tsx | 42 +++++++++++++++++++++++-- src/components/PlotArea.tsx | 31 ++++++------------ 2 files changed, 49 insertions(+), 24 deletions(-) diff --git a/src/components/PlotArea.option.test.tsx b/src/components/PlotArea.option.test.tsx index f9040cd..00c2a3f 100644 --- a/src/components/PlotArea.option.test.tsx +++ b/src/components/PlotArea.option.test.tsx @@ -2,10 +2,11 @@ // // Renders SinglePlot with echarts-for-react replaced by a recorder and checks // the ECharts option it builds: canopy-charts' g10/g100 chart theme, the -// plot-background override, and trace's own sizing on top. +// plot-background override, trace's own sizing on top, and the canopy-charts +// number formatters in the axis ticks and tooltip. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, cleanup, render } from '@testing-library/react'; -import { CHART_THEMES } from '@slaclab/canopy-charts'; +import { CHART_THEMES, formatAxisTick } from '@slaclab/canopy-charts'; import { setColorMode } from '@slaclab/canopy-shell/color-mode'; import { memoryStorage } from '../test/dom'; import { setupColorMode } from '../state/colorMode'; @@ -159,3 +160,40 @@ describe('SinglePlot chart theme', () => { expect(opt.legend.bottom).toBe(8); }); }); + +describe('SinglePlot number formatting', () => { + // The tooltip line for the trace's sample nearest the cursor (at NOW). + function tooltipFor(value: number): string { + renderPlot(makePlot({ traces: [makeTrace([value])] })); + return lastOption().tooltip.formatter([{ axisValue: NOW }]); + } + + it('formats y-axis ticks with canopy-charts formatAxisTick', () => { + const formatter = lastOptionAfterRender().yAxis[0].axisLabel.formatter; + expect(formatter).toBe(formatAxisTick); + expect(formatter(5e-4)).toBe('5.0e-4'); + expect(formatter(1_500_000)).toBe('1.5e+6'); + expect(formatter(12.5)).toBe('12.5'); + }); + + it('shows tooltip values with trailing zeros trimmed', () => { + const html = tooltipFor(0.5); + expect(html).toMatch(/: 0\.5 { + expect(tooltipFor(1.23456789e-5)).toMatch(/: 1\.234568e-5 { + const label = lastOptionAfterRender().tooltip.axisPointer.label; + expect(label.formatter({ value: 12.3, axisDimension: 'y' })).toBe('12.3'); + }); + + function lastOptionAfterRender(): Option { + renderPlot(makePlot()); + return lastOption(); + } +}); diff --git a/src/components/PlotArea.tsx b/src/components/PlotArea.tsx index a168f45..21d6ede 100644 --- a/src/components/PlotArea.tsx +++ b/src/components/PlotArea.tsx @@ -1,7 +1,13 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import ReactECharts from 'echarts-for-react'; import type { LegendComponentOption, TooltipComponentOption } from 'echarts'; -import { baseChartOption, chartAxisStyle, useChartTheme } from '@slaclab/canopy-charts'; +import { + baseChartOption, + chartAxisStyle, + formatAxisTick, + formatValue, + useChartTheme, +} from '@slaclab/canopy-charts'; import { effectiveBackground } from '../plotBackground'; import { Add, Close, ColumnDependency, Grid, Launch, Login, Maximize } from '@carbon/icons-react'; import type { Axis, Plot, PVTrace } from '../types'; @@ -22,16 +28,6 @@ import { type GridBand, } from './axisHitTest'; -// Numbers like 0.000000018 produce extremely wide tick labels that spill past -// neighboring stacked axes. Switch to exponential at the same magnitudes the -// browser's default Number.toString stops being compact. -function formatAxisTick(value: number): string { - if (value === 0) return '0'; - const abs = Math.abs(value); - if (abs < 1e-3 || abs >= 1e6) return value.toExponential(1); - return String(value); -} - // Signature of the user-chosen range. Bumps when picking a new time range so // dataZoom resets to full extent — otherwise the previous zoom stays clipped // over the new range. @@ -119,14 +115,6 @@ function formatCrosshairTime(ms: number): string { return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; } -function formatTooltipValue(v: unknown): string { - if (typeof v !== 'number' || !Number.isFinite(v)) return String(v); - if (v === 0) return '0'; - const abs = Math.abs(v); - if (abs < 1e-3 || abs >= 1e7) return v.toExponential(4); - return v.toPrecision(7); -} - // Human-readable signed offset between the cursor and the sample we're showing. // "0s" when within ±0.5s; otherwise "−12s", "+3m", "+1.4h" etc. function formatTimeOffset(deltaMs: number): string { @@ -844,8 +832,7 @@ export function SinglePlot({ ...baseTooltip.axisPointer?.label, formatter: ( p: { value: number; axisDimension?: string } // X --> timestamp, Y --> raw value - ) => - p.axisDimension === 'y' ? formatTooltipValue(p.value) : formatCrosshairTime(p.value), + ) => (p.axisDimension === 'y' ? formatValue(p.value) : formatCrosshairTime(p.value)), }, }, textStyle: { ...baseTooltip.textStyle, fontSize: 11 }, @@ -866,7 +853,7 @@ export function SinglePlot({ const data = traceData.get(trace.id); const sample = data ? nearestSample(data, cursorMs) : undefined; const valueCell = sample - ? `${formatTooltipValue(sample.value)} (${formatTimeOffset(sample.time - cursorMs)})` + ? `${formatValue(sample.value)} (${formatTimeOffset(sample.time - cursorMs)})` : `no data`; lines.push( `${labels.get(trace.id)}: ${valueCell}` From 21bef3081a8faa189af10d5e0c8864ba468744f2 Mon Sep 17 00:00:00 2001 From: YektaY Date: Fri, 16 Oct 2026 07:58:30 -0700 Subject: [PATCH 011/150] Provide the Canopy connection with CanopyProvider main.tsx wraps the app in @slaclab/canopy-react's CanopyProvider with the shared connection. usePVSearch, ArchiverPicker and TraceApp's unit-axis lookup read it with useCanopyConnection() and call the SDK's searchPVs, listArchivers and fetchMetadata directly. Before, the module-level BASE decided where those calls went. The module-level stores (archiveStore, liveStore) still import the same connection object, because they live outside React. usePVSearch has a test that renders the hook under a provider whose connection uses the SDK's createFakeFetch. Part of #86. --- src/components/ArchiverPicker.tsx | 10 ++--- src/components/TraceApp.tsx | 11 ++++- src/hooks/usePVSearch.test.tsx | 67 +++++++++++++++++++++++++++++++ src/hooks/usePVSearch.ts | 9 +++-- src/main.tsx | 6 ++- 5 files changed, 91 insertions(+), 12 deletions(-) create mode 100644 src/hooks/usePVSearch.test.tsx diff --git a/src/components/ArchiverPicker.tsx b/src/components/ArchiverPicker.tsx index c6d3fc0..5e4d487 100644 --- a/src/components/ArchiverPicker.tsx +++ b/src/components/ArchiverPicker.tsx @@ -1,8 +1,7 @@ import { useEffect, useState } from 'react'; import { Dropdown } from '@carbon/react'; -import { listArchivers } from '../api/mole'; -import { CanopyError } from '../api/client'; -import type { ArchiverInfoDTO } from '../api/types'; +import { CanopyError, listArchivers, type ArchiverInfoDTO } from '@slaclab/canopy-client'; +import { useCanopyConnection } from '@slaclab/canopy-react'; export const GLOBAL_DEFAULT_OPTION = '__default__'; export const GLOBAL_OPTION = '__global__'; @@ -32,6 +31,7 @@ export function ArchiverPicker({ label = 'Archiver', width = 200, }: ArchiverPickerProps) { + const conn = useCanopyConnection(); const [archivers, setArchivers] = useState([]); const [defaultName, setDefaultName] = useState(''); const [error, setError] = useState(null); @@ -40,7 +40,7 @@ export function ArchiverPicker({ const controller = new AbortController(); void (async () => { try { - const list = await listArchivers(controller.signal); + const list = await listArchivers(conn, controller.signal); if (controller.signal.aborted) return; setArchivers(list.archivers); setDefaultName(list.default); @@ -51,7 +51,7 @@ export function ArchiverPicker({ } })(); return () => controller.abort(); - }, []); + }, [conn]); const items: ArchiverItem[] = []; if (includeGlobalOption) { diff --git a/src/components/TraceApp.tsx b/src/components/TraceApp.tsx index 566bb3b..5b53465 100644 --- a/src/components/TraceApp.tsx +++ b/src/components/TraceApp.tsx @@ -23,7 +23,8 @@ import { useAutoScrollTimers } from '../hooks/useAutoScrollTimers'; import { useFormulaSeries, type FormulaSeriesResult } from '../hooks/useFormulaSeries'; import type { TimeWindowNs } from '../api/time'; import { resolveTimeWindow } from '../api/time'; -import { fetchMetadata } from '../api/mole'; +import { fetchMetadata } from '@slaclab/canopy-client'; +import { useCanopyConnection } from '@slaclab/canopy-react'; import { useColorMode } from '../state/themeStore'; import { usePaletteId } from '../state/paletteStore'; import { getPalette, colorForIndex } from '../palettes'; @@ -91,6 +92,7 @@ export type SelectedItem = { } | null; export function TraceApp() { + const canopy = useCanopyConnection(); const [plots, setPlots] = useState(INITIAL_PLOTS); const [activePlotId, setActivePlotId] = useState('plot-1'); const [selectedItem, setSelectedItem] = useState({ @@ -498,7 +500,12 @@ export function TraceApp() { let unit: string | undefined; try { - const meta = await fetchMetadata(pvName, trace.archiver ?? plot.archiver, controller.signal); + const meta = await fetchMetadata( + canopy, + pvName, + trace.archiver ?? plot.archiver, + controller.signal + ); unit = meta.units?.trim() || undefined; } catch { return; // metadata unavailable / aborted — keep the trace on its current axis diff --git a/src/hooks/usePVSearch.test.tsx b/src/hooks/usePVSearch.test.tsx new file mode 100644 index 0000000..9c6f159 --- /dev/null +++ b/src/hooks/usePVSearch.test.tsx @@ -0,0 +1,67 @@ +// @vitest-environment jsdom +import type { ReactNode } from 'react'; +import { describe, expect, it } from 'vitest'; +import { renderHook, waitFor } from '@testing-library/react'; +import { CanopyProvider } from '@slaclab/canopy-react'; +import { createFakeFetch, jsonResponse } from '@slaclab/canopy-client/testing'; +import type { FakeRoutes } from '@slaclab/canopy-client/testing'; +import { usePVSearch } from './usePVSearch'; + +// The hook reads its connection from , so a test can point it +// at a fake Canopy without touching globals. +function renderSearch(pattern: string, routes: FakeRoutes, archiver?: string) { + const fetch = createFakeFetch(routes); + const connection = { baseUrl: 'http://canopy.test', fetch }; + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ); + const hook = renderHook(() => usePVSearch(pattern, archiver, 0, 25), { wrapper }); + return { ...hook, fetch }; +} + +describe('usePVSearch', () => { + it('searches Mole through the provider connection with a substring wildcard', async () => { + const { result, fetch } = renderSearch( + 'BPM', + { + 'GET /mole/v1/search': jsonResponse({ + archiver: 'slac', + pattern: '.*BPM.*', + pvs: ['A:BPM'], + }), + }, + 'slac' + ); + + await waitFor(() => expect(result.current.status).toBe('ready')); + expect(result.current.pvs).toEqual(['A:BPM']); + expect(fetch.calls).toHaveLength(1); + expect(fetch.calls[0].url.startsWith('http://canopy.test/mole/v1/search?')).toBe(true); + expect(fetch.calls[0].query).toEqual({ pattern: '.*BPM.*', archiver: 'slac', limit: '25' }); + }); + + it('passes an explicit pattern through unchanged', async () => { + const { result, fetch } = renderSearch('A:.*', { + 'GET /mole/v1/search': jsonResponse({ archiver: 'slac', pattern: 'A:.*', pvs: [] }), + }); + await waitFor(() => expect(result.current.status).toBe('ready')); + expect(fetch.calls[0].query.pattern).toBe('A:.*'); + }); + + it('reports the Canopy error code and detail', async () => { + const { result } = renderSearch('X', { + 'GET /mole/v1/search': jsonResponse( + { code: 'archiver_unavailable', detail: 'slac is down' }, + { status: 503 } + ), + }); + await waitFor(() => expect(result.current.status).toBe('error')); + expect(result.current.error).toEqual({ code: 'archiver_unavailable', detail: 'slac is down' }); + }); + + it('stays idle for an empty pattern', () => { + const { result, fetch } = renderSearch(' ', {}); + expect(result.current.status).toBe('idle'); + expect(fetch.calls).toHaveLength(0); + }); +}); diff --git a/src/hooks/usePVSearch.ts b/src/hooks/usePVSearch.ts index 196c8e1..0e270db 100644 --- a/src/hooks/usePVSearch.ts +++ b/src/hooks/usePVSearch.ts @@ -1,6 +1,6 @@ import { useEffect, useState } from 'react'; -import { searchPVs } from '../api/mole'; -import { CanopyError } from '../api/client'; +import { CanopyError, searchPVs } from '@slaclab/canopy-client'; +import { useCanopyConnection } from '@slaclab/canopy-react'; export type PVSearchStatus = 'idle' | 'loading' | 'ready' | 'error'; @@ -18,6 +18,7 @@ export function usePVSearch( debounceMs = 300, limit = 50 ): PVSearchResult { + const conn = useCanopyConnection(); const [result, setResult] = useState(EMPTY); useEffect(() => { @@ -36,7 +37,7 @@ export function usePVSearch( try { const wildcard = trimmed.includes('.') || trimmed.includes('*') ? trimmed : `.*${trimmed}.*`; - const dto = await searchPVs(wildcard, { archiver, limit }, controller.signal); + const dto = await searchPVs(conn, wildcard, { archiver, limit }, controller.signal); if (controller.signal.aborted) return; setResult({ status: 'ready', pvs: dto.pvs }); } catch (err) { @@ -52,7 +53,7 @@ export function usePVSearch( controller.abort(); clearTimeout(handle); }; - }, [pattern, archiver, debounceMs, limit]); + }, [conn, pattern, archiver, debounceMs, limit]); return result; } diff --git a/src/main.tsx b/src/main.tsx index df655ea..72d1d28 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -1,10 +1,14 @@ import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; +import { CanopyProvider } from '@slaclab/canopy-react'; import './index.css'; import App from './App.tsx'; +import { canopyConnection } from './api/connection'; createRoot(document.getElementById('root')!).render( - + + + ); From 2f6f6673e172223e9b89099d6873f9a5b38410e9 Mon Sep 17 00:00:00 2001 From: YektaY Date: Fri, 16 Oct 2026 07:59:32 -0700 Subject: [PATCH 012/150] Capture plot PNGs with canopy-charts Print, Export PNG and the e-log capture now go through canopy-charts' captureChartPng, and data: URLs are decoded with its dataUrlToBlob. - capturePlot.ts keeps trace's DOM lookup, which prefers the fullscreen copy and skips detached plots. The capture itself is captureChartPng with the plot's effective background at pixel ratio 2. It returns null instead of throwing for a disposed chart or an ECharts error. - capturePlots (e-log) uses the same helper and skips any plot that yields no image. The local dataUrlToBlob copy is gone. - downloadDataUrl decodes with dataUrlToBlob instead of fetch()ing the data: URL, still downloading through a blob: URL. Tests cover the fullscreen preference, the theme and custom backgrounds, pixel ratio 2, and skipping empty or throwing captures. --- src/capturePlot.test.ts | 97 ++++++++++++++++++++++++++++++++++ src/capturePlot.ts | 15 +++--- src/io/download.ts | 21 +++++--- src/io/exportPlotImage.test.ts | 53 ++++++++++++++----- src/io/exportPlotImage.ts | 34 +++--------- 5 files changed, 164 insertions(+), 56 deletions(-) create mode 100644 src/capturePlot.test.ts diff --git a/src/capturePlot.test.ts b/src/capturePlot.test.ts new file mode 100644 index 0000000..61bb355 --- /dev/null +++ b/src/capturePlot.test.ts @@ -0,0 +1,97 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { capturePlotPng } from './capturePlot'; +import type { Plot } from './types'; + +// getInstanceByDom is replaced by a lookup into charts registered per host +// element; jsdom has no canvas for real ECharts instances. +const h = vi.hoisted(() => ({ + charts: new Map string }>(), +})); + +vi.mock('echarts', () => ({ + getInstanceByDom: (el: Element) => h.charts.get(el), +})); + +const PNG = 'data:image/png;base64,iVBORw0KGgo='; + +function plot(backgroundColor = '#161616'): Plot { + return { + id: 'p1', + title: 'Plot 1', + traces: [], + axes: [], + backgroundColor, + showLegend: true, + showXGridlines: true, + showYGridlines: true, + showCrosshair: true, + gridStyle: 'solid', + gridOpacity: 1, + tickFontSize: 11, + xAxis: { timeRange: '-1h' }, + }; +} + +// Mount a SinglePlot-shaped wrapper: [data-plot-id] > (chart host div). +function mountChart(opts: { fullscreen?: boolean; dataUrl?: string } = {}) { + const wrap = document.createElement('div'); + wrap.dataset.plotId = 'p1'; + if (opts.fullscreen) wrap.dataset.fullscreen = 'true'; + const host = document.createElement('div'); + wrap.appendChild(host); + document.body.appendChild(wrap); + const getDataURL = vi.fn(() => opts.dataUrl ?? PNG); + h.charts.set(host, { getDataURL }); + return getDataURL; +} + +beforeEach(() => { + h.charts.clear(); +}); + +afterEach(() => { + document.body.innerHTML = ''; +}); + +describe('capturePlotPng', () => { + it('returns null when the plot is not mounted in this document', () => { + expect(capturePlotPng(plot(), 'dark')).toBeNull(); + }); + + it('captures at pixel ratio 2 with the theme background for a default plot', () => { + const getDataURL = mountChart(); + expect(capturePlotPng(plot(), 'dark')).toBe(PNG); + expect(getDataURL).toHaveBeenLastCalledWith({ + type: 'png', + pixelRatio: 2, + backgroundColor: '#161616', + }); + capturePlotPng(plot(), 'light'); + expect(getDataURL).toHaveBeenLastCalledWith( + expect.objectContaining({ backgroundColor: '#f4f4f4' }) + ); + }); + + it('keeps a user-chosen background', () => { + const getDataURL = mountChart(); + capturePlotPng(plot('#123456'), 'light'); + expect(getDataURL).toHaveBeenLastCalledWith( + expect.objectContaining({ backgroundColor: '#123456' }) + ); + }); + + it('prefers the fullscreen copy when asked, the in-window one otherwise', () => { + const inWindow = mountChart({ dataUrl: 'data:image/png;base64,aW4=' }); + const fullscreen = mountChart({ fullscreen: true, dataUrl: 'data:image/png;base64,ZnM=' }); + expect(capturePlotPng(plot(), 'dark', true)).toBe('data:image/png;base64,ZnM='); + expect(fullscreen).toHaveBeenCalledTimes(1); + expect(capturePlotPng(plot(), 'dark')).toBe('data:image/png;base64,aW4='); + expect(inWindow).toHaveBeenCalledTimes(1); + }); + + it('returns null instead of throwing when the chart yields no image', () => { + mountChart({ dataUrl: '' }); + expect(capturePlotPng(plot(), 'dark')).toBeNull(); + }); +}); diff --git a/src/capturePlot.ts b/src/capturePlot.ts index 7205037..df861b3 100644 --- a/src/capturePlot.ts +++ b/src/capturePlot.ts @@ -1,5 +1,5 @@ import { getInstanceByDom } from 'echarts'; -import { chartThemeFor } from '@slaclab/canopy-charts'; +import { captureChartPng, chartThemeFor } from '@slaclab/canopy-charts'; import type { Plot } from './types'; import { effectiveBackground } from './plotBackground'; @@ -7,7 +7,9 @@ import { effectiveBackground } from './plotBackground'; * Snapshot a mounted plot's chart as a PNG data URL. The effective background * (theme default or user override) is baked into the image so the result is * legible on paper in both dark and light mode. Returns null when the plot's - * chart isn't mounted in this document (e.g. detached to its own window). + * chart isn't mounted in this document (e.g. detached to its own window), or + * when canopy-charts' captureChartPng can't get an image (disposed chart, + * ECharts error). * * When `preferFullscreen` is set, the popped-out copy is captured instead of * the in-window one. Both are mounted with the same `data-plot-id`, and the @@ -24,12 +26,7 @@ export function capturePlotPng( document.querySelector(`[data-plot-id="${plot.id}"][data-fullscreen] > div`)) || document.querySelector(`[data-plot-id="${plot.id}"] > div`); if (!(host instanceof HTMLElement)) return null; - const chart = getInstanceByDom(host); - if (!chart) return null; - const theme = chartThemeFor(colorMode); - return chart.getDataURL({ - type: 'png', - pixelRatio: 2, - backgroundColor: effectiveBackground(plot.backgroundColor, theme), + return captureChartPng(getInstanceByDom(host), { + background: effectiveBackground(plot.backgroundColor, chartThemeFor(colorMode)), }); } diff --git a/src/io/download.ts b/src/io/download.ts index cc20fa8..cf69a43 100644 --- a/src/io/download.ts +++ b/src/io/download.ts @@ -1,3 +1,5 @@ +import { dataUrlToBlob } from '@slaclab/canopy-charts'; + // Tiny helper: trigger a browser download for an in-memory string blob. export function downloadBlob(filename: string, mime: string, body: BlobPart): void { const blob = new Blob([body], { type: mime }); @@ -14,15 +16,18 @@ export function downloadBlob(filename: string, mime: string, body: BlobPart): vo } // Trigger a download for a `data:` URL (e.g. a canvas-rendered PNG). We decode -// the data URL to a Blob and hand off to downloadBlob so the download goes -// through a `blob:` URL. Anchoring the `data:` URL directly fails in two ways: -// Safari caps `data:` downloads at ~1MB, and browsers block multiple `data:` -// anchor clicks from one user gesture (so a grid export would drop all but the -// first file). `blob:` URLs sidestep both. +// the data URL to a Blob (canopy-charts' dataUrlToBlob, no fetch round-trip) +// and hand off to downloadBlob so the download goes through a `blob:` URL. +// Anchoring the `data:` URL directly fails in two ways: Safari caps `data:` +// downloads at ~1MB, and browsers block multiple `data:` anchor clicks from one +// user gesture (so a grid export would drop all but the first file). `blob:` +// URLs sidestep both. Rejects if the URL can't be decoded. export function downloadDataUrl(filename: string, dataUrl: string): Promise { - return fetch(dataUrl) - .then((r) => r.blob()) - .then((blob) => downloadBlob(filename, blob.type, blob)); + return new Promise((resolve) => { + const blob = dataUrlToBlob(dataUrl); + downloadBlob(filename, blob.type, blob); + resolve(); + }); } export function pickFile(accept: string): Promise { diff --git a/src/io/exportPlotImage.test.ts b/src/io/exportPlotImage.test.ts index 971f24e..7ff7c37 100644 --- a/src/io/exportPlotImage.test.ts +++ b/src/io/exportPlotImage.test.ts @@ -1,6 +1,6 @@ -import { describe, it, expect } from 'vitest'; +import { describe, it, expect, vi } from 'vitest'; -import { dataUrlToBlob, capturePlots, capturedToFile, type PngSource } from './exportPlotImage'; +import { capturePlots, capturedToFile, type PngSource } from './exportPlotImage'; // 1x1 transparent PNG. const PNG_DATA_URL = @@ -10,17 +10,6 @@ function fakeInstance(dataUrl: string): PngSource { return { getDataURL: () => dataUrl }; } -describe('dataUrlToBlob', () => { - it('decodes a base64 data URL into a Blob with the right mime', async () => { - const blob = dataUrlToBlob(PNG_DATA_URL); - expect(blob.type).toBe('image/png'); - expect(blob.size).toBeGreaterThan(0); - const bytes = new Uint8Array(await blob.arrayBuffer()); - // PNG magic number. - expect(Array.from(bytes.slice(0, 4))).toEqual([0x89, 0x50, 0x4e, 0x47]); - }); -}); - describe('capturePlots', () => { it('captures instances and skips plots without one', () => { const captured = capturePlots( @@ -34,6 +23,37 @@ describe('capturePlots', () => { expect(captured).toHaveLength(1); expect(captured[0]).toMatchObject({ id: 'p1', title: 'Plot 1', dataUrl: PNG_DATA_URL }); }); + + it('bakes in the background at pixel ratio 2', () => { + const getDataURL = vi.fn(() => PNG_DATA_URL); + capturePlots([{ id: 'p1', title: 'Plot 1', instance: { getDataURL } }], '#f4f4f4'); + expect(getDataURL).toHaveBeenCalledWith({ + type: 'png', + pixelRatio: 2, + backgroundColor: '#f4f4f4', + }); + }); + + it('skips instances that yield no image or throw', () => { + const captured = capturePlots( + [ + { id: 'empty', title: 'Empty', instance: fakeInstance('') }, + { id: 'bad', title: 'Bad', instance: fakeInstance('not a data url') }, + { + id: 'throws', + title: 'Throws', + instance: { + getDataURL: () => { + throw new Error('disposed'); + }, + }, + }, + { id: 'ok', title: 'OK', instance: fakeInstance(PNG_DATA_URL) }, + ], + '#161616' + ); + expect(captured.map((c) => c.id)).toEqual(['ok']); + }); }); describe('capturedToFile', () => { @@ -43,6 +63,13 @@ describe('capturedToFile', () => { expect(file.type).toBe('image/png'); }); + it('decodes the PNG bytes into the file', async () => { + const file = capturedToFile({ id: 'p1', title: 'Plot', dataUrl: PNG_DATA_URL }, 0); + const bytes = new Uint8Array(await file.arrayBuffer()); + // PNG magic number. + expect(Array.from(bytes.slice(0, 4))).toEqual([0x89, 0x50, 0x4e, 0x47]); + }); + it('falls back to the id when the title has no usable characters', () => { const file = capturedToFile({ id: 'plot-xyz', title: '!!!', dataUrl: PNG_DATA_URL }, 2); expect(file.name).toBe('trace_plot_3_plot-xyz.png'); diff --git a/src/io/exportPlotImage.ts b/src/io/exportPlotImage.ts index c02b1e2..f94cc60 100644 --- a/src/io/exportPlotImage.ts +++ b/src/io/exportPlotImage.ts @@ -1,3 +1,5 @@ +import { captureChartPng, dataUrlToBlob } from '@slaclab/canopy-charts'; + // Capture ECharts plots as PNG blobs for e-log attachments. We only need the // `getDataURL` slice of the ECharts instance, so we type against that to avoid // pulling the full echarts type surface through every caller. @@ -15,38 +17,18 @@ export interface CapturedPlot { dataUrl: string; } -const PIXEL_RATIO = 2; - -function plotDataUrl(instance: PngSource, backgroundColor: string): string { - return instance.getDataURL({ type: 'png', pixelRatio: PIXEL_RATIO, backgroundColor }); -} - -// data: URL -> Blob without a network round-trip via fetch (keeps it sync-ish -// and avoids CSP surprises). The data URL is always base64 PNG here. -export function dataUrlToBlob(dataUrl: string): Blob { - const comma = dataUrl.indexOf(','); - const header = dataUrl.slice(0, comma); - const body = dataUrl.slice(comma + 1); - const mime = header.slice(header.indexOf(':') + 1, header.indexOf(';')) || 'image/png'; - const binary = atob(body); - const bytes = new Uint8Array(binary.length); - for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); - return new Blob([bytes], { type: mime }); -} - -// Capture each plot as its own PNG data URL. Skips plots that fail to render -// (e.g. detached/unmounted) rather than aborting the whole batch. +// Capture each plot as its own PNG data URL (canopy-charts' captureChartPng: +// pixel ratio 2, the given background baked in). Skips plots that yield no +// image (detached/unmounted, disposed, not yet rendered, or an ECharts error) +// rather than aborting the batch or attaching a broken image. export function capturePlots( plots: { id: string; title: string; instance: PngSource | null | undefined }[], backgroundColor: string ): CapturedPlot[] { const out: CapturedPlot[] = []; for (const p of plots) { - if (!p.instance) continue; - const dataUrl = plotDataUrl(p.instance, backgroundColor); - // A disposed or not-yet-rendered instance yields an empty/invalid data URL; - // skip it rather than attaching a broken (empty payload) image. - if (!dataUrl || !dataUrl.startsWith('data:')) continue; + const dataUrl = captureChartPng(p.instance, { background: backgroundColor }); + if (!dataUrl) continue; out.push({ id: p.id, title: p.title, dataUrl }); } return out; From cf3d9e877bbc6165c70bacb56e81f4f4f595fc4b Mon Sep 17 00:00:00 2001 From: YektaY Date: Fri, 16 Oct 2026 08:00:23 -0700 Subject: [PATCH 013/150] Run Fox validate/evaluate on the SDK core and types The SDK has Fox's live-formula WebSocket (FoxFormulaService) but no helpers for its REST validate and evaluate endpoints, so those stay in src/api/fox.ts. They now call the SDK's canopyFetch with an explicit connection and use its FormulaSpec and FormulaResultDTO types. FormulaValidationDTO, which the SDK lacks, moves into fox.ts. The formula editor's validation (RightPanel) and useFormulaSeries read the connection with useCanopyConnection(). A FastAPI 422 from validate now reads as a readable message in the editor, not "[object Object]". formulaWsUrl() is removed; nothing used it. Live formula curves on FoxFormulaService are left for a follow-up, because trace has no live-formula path to port yet. Part of #86. --- src/api/fox.test.ts | 85 +++++++++++++++++++++++++++++++++++ src/api/fox.ts | 44 ++++++++++-------- src/api/types.ts | 62 +------------------------ src/components/RightPanel.tsx | 7 ++- src/components/TraceApp.tsx | 4 +- src/formula.ts | 4 +- src/hooks/useFormulaSeries.ts | 14 +++--- 7 files changed, 130 insertions(+), 90 deletions(-) create mode 100644 src/api/fox.test.ts diff --git a/src/api/fox.test.ts b/src/api/fox.test.ts new file mode 100644 index 0000000..6fdf1cb --- /dev/null +++ b/src/api/fox.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, it } from 'vitest'; +import { CanopyError, type FormulaSpec } from '@slaclab/canopy-client'; +import { createFakeFetch, jsonResponse } from '@slaclab/canopy-client/testing'; +import type { FakeRoutes } from '@slaclab/canopy-client/testing'; +import { evaluateFormula, validateFormula } from './fox'; + +const SPEC: FormulaSpec = { + kind: 'timeseries', + expression: '{a} - {b}', + bindings: { a: 'PV:A', b: 'PV:B' }, +}; + +function connection(routes: FakeRoutes) { + const fetch = createFakeFetch(routes, { baseUrl: '/trace/api/canopy' }); + return { conn: { baseUrl: '/trace/api/canopy', fetch }, fetch }; +} + +describe('validateFormula', () => { + it('posts the spec to Fox and returns the validation result', async () => { + const { conn, fetch } = connection({ + 'POST /fox/v1/validate': jsonResponse({ valid: true, tokens: ['a', 'b'], errors: [] }), + }); + + await expect(validateFormula(conn, SPEC)).resolves.toEqual({ + valid: true, + tokens: ['a', 'b'], + errors: [], + }); + expect(fetch.calls[0].url).toBe('/trace/api/canopy/fox/v1/validate'); + expect(fetch.calls[0].headers['Content-Type']).toBe('application/json'); + expect(fetch.calls[0].json).toEqual(SPEC); + }); + + it('reads a FastAPI 422 as a validation_error with a readable detail', async () => { + const { conn } = connection({ + 'POST /fox/v1/validate': jsonResponse( + { detail: [{ loc: ['body', 'expression'], msg: 'Field required', type: 'missing' }] }, + { status: 422 } + ), + }); + + const err = await validateFormula(conn, SPEC).catch((e: unknown) => e); + expect(err).toBeInstanceOf(CanopyError); + // Used to surface in the editor as "[object Object]". + expect(err).toMatchObject({ + code: 'validation_error', + detail: 'body.expression: Field required', + }); + }); +}); + +describe('evaluateFormula', () => { + it('posts the spec with its window', async () => { + const result = { + kind: 'timeseries', + scalar: null, + waveform: null, + timeseries: { + tsNs: [1_000_000], + values: [2], + severity: ['NO_ALARM'], + inputs: {}, + decimated: false, + }, + }; + const { conn, fetch } = connection({ 'POST /fox/v1/evaluate': jsonResponse(result) }); + + await expect(evaluateFormula(conn, SPEC, 10, 20)).resolves.toEqual(result); + expect(fetch.calls[0].json).toEqual({ spec: SPEC, t0Ns: 10, t1Ns: 20 }); + }); + + it('keeps the Canopy error envelope', async () => { + const { conn } = connection({ + 'POST /fox/v1/evaluate': jsonResponse( + { code: 'formula_eval_failed', detail: 'division by zero' }, + { status: 400 } + ), + }); + await expect(evaluateFormula(conn, SPEC, 0, 0)).rejects.toMatchObject({ + code: 'formula_eval_failed', + status: 400, + detail: 'division by zero', + }); + }); +}); diff --git a/src/api/fox.ts b/src/api/fox.ts index 4448ef9..13bb570 100644 --- a/src/api/fox.ts +++ b/src/api/fox.ts @@ -1,38 +1,46 @@ -import { canopyFetch, canopyWebSocketUrl } from './client'; -import type { FormulaResultDTO, FormulaSpecDTO, FormulaValidationDTO } from './types'; +import { + canopyFetch, + type AbortSignalLike, + type CanopyConnection, + type FormulaResultDTO, + type FormulaSpec, +} from '@slaclab/canopy-client'; + +// Fox's REST endpoints. The SDK covers Fox's live-formula WebSocket +// (FoxFormulaService) but not these, so they stay here on its REST core. + +// Result of POST /fox/v1/validate (canopy.fox.schemas.formula). +export interface FormulaValidationDTO { + valid: boolean; + tokens: string[]; + errors: string[]; +} // Parse + typecheck a formula without evaluating — drives the editor's live // red-lining as the user types. export async function validateFormula( - spec: FormulaSpecDTO, - signal?: AbortSignal + conn: CanopyConnection, + spec: FormulaSpec, + signal?: AbortSignalLike ): Promise { - return canopyFetch('/fox/v1/validate', { + return canopyFetch(conn, '/fox/v1/validate', { method: 'POST', body: spec, signal, }); } -// One-shot evaluation over a fixed window (`t1Ns: 0` means "now"). Live formula -// curves use the WebSocket (formulaWsUrl) for push updates; this REST path serves -// absolute/static windows. +// One-shot evaluation over a fixed window (`t1Ns: 0` means "now"). export async function evaluateFormula( - spec: FormulaSpecDTO, + conn: CanopyConnection, + spec: FormulaSpec, t0Ns: number, t1Ns: number, - signal?: AbortSignal + signal?: AbortSignalLike ): Promise { - return canopyFetch('/fox/v1/evaluate', { + return canopyFetch(conn, '/fox/v1/evaluate', { method: 'POST', body: { spec, t0Ns, t1Ns }, signal, }); } - -// Same-origin WS URL for live formula subscriptions. The Vite dev proxy (and any -// prod reverse proxy) handle the /fox upgrade and inject X-API-Key, so the bundle -// never holds the key. SSR-safe: returns an empty string when `window` is undefined. -export function formulaWsUrl(): string { - return canopyWebSocketUrl('/fox/v1/ws/formulas'); -} diff --git a/src/api/types.ts b/src/api/types.ts index 121cccb..d5a65cd 100644 --- a/src/api/types.ts +++ b/src/api/types.ts @@ -1,6 +1,5 @@ -// Transitional: trace's wire-type names, now backed by @slaclab/canopy-client. -// The Mole DTOs and the error envelope are the SDK's own types; the Fox section -// below goes when fox.ts moves to the SDK. Removed once nothing imports it. +// Transitional: trace's Mole wire-type names and severity alias, backed by +// @slaclab/canopy-client. Removed once nothing imports it. import type { WireAlarmSeverity } from '@slaclab/canopy-client'; @@ -19,60 +18,3 @@ export type { SampleDTO, SearchResultsDTO, } from '@slaclab/canopy-client'; - -// ── Fox (formula) DTOs ─────────────────────────────────────────────────────── -// Source: canopy.contracts.formula + canopy.fox.schemas.formula (camelCase wire). -// A formula curve evaluates an `expression` over named `bindings` (variable -> -// PV name) for a time window. Results are a discriminated union keyed on `kind`. - -export type FormulaKind = 'scalar' | 'timeseries' | 'waveform'; -export type FormulaDataMode = 'raw' | 'binned'; -export type FormulaAlignMode = 'last' | 'interpolate'; -export type FormulaIndexMode = 'union' | 'intersection' | 'grid' | 'first_input'; - -export interface FormulaSpecDTO { - kind: FormulaKind; - expression: string; - // Variable name -> PV name (a referenced curve is resolved to its PV upstream). - bindings: Record; - // mode/align/index carry server defaults (raw / last / union) when omitted. - mode?: FormulaDataMode; - align?: FormulaAlignMode; - index?: FormulaIndexMode; - gridDtNs?: number | null; - maxPoints?: number | null; -} - -export interface FormulaTimeseriesResultDTO { - tsNs: number[]; - values: (number | null)[]; - severity: AlarmSeverity[]; - inputs: Record; - decimated: boolean; -} - -export interface FormulaScalarResultDTO { - tsNs: number; - value: number | string | boolean; - severity: AlarmSeverity; - inputsUsed: Record; -} - -export interface FormulaWaveformResultDTO { - tsNs: number; - values: number[]; - severity: AlarmSeverity; -} - -export interface FormulaResultDTO { - kind: FormulaKind; - scalar?: FormulaScalarResultDTO | null; - timeseries?: FormulaTimeseriesResultDTO | null; - waveform?: FormulaWaveformResultDTO | null; -} - -export interface FormulaValidationDTO { - valid: boolean; - tokens: string[]; - errors: string[]; -} diff --git a/src/components/RightPanel.tsx b/src/components/RightPanel.tsx index 7a11ff9..048fe58 100644 --- a/src/components/RightPanel.tsx +++ b/src/components/RightPanel.tsx @@ -40,8 +40,9 @@ import { import { ArchiverPicker } from './ArchiverPicker'; import { usePVSearch } from '../hooks/usePVSearch'; import { PanelRail } from './PanelRail'; +import { CanopyError } from '@slaclab/canopy-client'; +import { useCanopyConnection } from '@slaclab/canopy-react'; import { validateFormula } from '../api/fox'; -import { CanopyError } from '../api/client'; import { extractFormulaVars, resolveBindings } from '../formula'; interface RightPanelProps { @@ -252,6 +253,7 @@ function FormulaGeneralTab({ // Debounced live validation via Fox. Sends whatever bindings are resolved so // far, so the server red-lines bad syntax (and missing bindings) as you type. + const canopy = useCanopyConnection(); const [validation, setValidation] = useState<{ valid: boolean; errors: string[] } | null>(null); // Resolve to actual PV names here and key the effect on the result. Keying on // the raw bindings object alone would miss a bound curve's pvName changing @@ -265,6 +267,7 @@ function FormulaGeneralTab({ const ac = new AbortController(); const handle = setTimeout(() => { validateFormula( + canopy, { kind: 'timeseries', expression: expr, bindings: resolvedBindings }, ac.signal ) @@ -282,7 +285,7 @@ function FormulaGeneralTab({ ac.abort(); }; // eslint-disable-next-line react-hooks/exhaustive-deps -- expression + resolved bindings capture the inputs - }, [expression, resolvedKey]); + }, [canopy, expression, resolvedKey]); return (
diff --git a/src/components/TraceApp.tsx b/src/components/TraceApp.tsx index 5b53465..33c2284 100644 --- a/src/components/TraceApp.tsx +++ b/src/components/TraceApp.tsx @@ -34,7 +34,7 @@ import { buildCsvFiles } from '../io/exportCsv'; import { safeFilename, timestamp } from '../io/filename'; import { makeId } from '../id'; import { resolveFormulaSpec } from '../formula'; -import type { FormulaSpecDTO } from '../api/types'; +import type { FormulaSpec } from '@slaclab/canopy-client'; import { capturePlots, type PngSource, type CapturedPlot } from '../io/exportPlotImage'; import { PostToElogModal } from './PostToElogModal'; import { useElogConfig } from '../hooks/useElogConfig'; @@ -158,7 +158,7 @@ export function TraceApp() { const plotArchiverByTrace = new Map(); // Resolved Fox spec per formula trace (bindings mapped to PV names); null when // the formula isn't ready to evaluate (empty expression or an unbound variable). - const formulaSpecByTrace = new Map(); + const formulaSpecByTrace = new Map(); for (const plot of plots) { const win = viewWindowByPlot.get(plot.id) ?? resolveTimeWindow(plot.xAxis).window; for (const trace of plot.traces) { diff --git a/src/formula.ts b/src/formula.ts index c6f7fe9..7c7c017 100644 --- a/src/formula.ts +++ b/src/formula.ts @@ -1,5 +1,5 @@ import type { PVTrace } from './types'; -import type { FormulaSpecDTO } from './api/types'; +import type { FormulaSpec } from '@slaclab/canopy-client'; // Formula variables are brace-delimited, e.g. {x1}, {alarm_pv}. Matches the // Python trace's f:// syntax. @@ -37,7 +37,7 @@ export function resolveBindings(trace: PVTrace, candidates: PVTrace[]): Record(); // when a spec or window actually changes (TraceApp rebuilds the maps every // render). State is only updated from the async result callbacks; the prior // result is left in place while a re-evaluation is in flight, so panning doesn't -// blank the curve. Live push updates are a follow-up (the Fox WebSocket). +// blank the curve. Live push updates are a follow-up (the SDK's +// FoxFormulaService over the Fox WebSocket). export function useFormulaSeries( traces: PVTrace[], // Per-trace resolved Fox spec (bindings already mapped to PV names). `null` // means the formula isn't ready (empty / unbound) and is skipped. - specByTrace: Map, + specByTrace: Map, windowByTrace: Map ): Map { + const conn = useCanopyConnection(); const [results, setResults] = useState>(EMPTY_SERIES); const abortByTrace = useRef(new Map()); @@ -56,7 +58,7 @@ export function useFormulaSeries( const ac = new AbortController(); abortByTrace.current.set(trace.id, ac); - evaluateFormula(spec, win.fromNs, win.toNs, ac.signal) + evaluateFormula(conn, spec, win.fromNs, win.toNs, ac.signal) .then((res) => { if (ac.signal.aborted) return; const ts = res.timeseries; @@ -96,7 +98,7 @@ export function useFormulaSeries( } } // eslint-disable-next-line react-hooks/exhaustive-deps -- signature captures the meaningful inputs - }, [signature]); + }, [conn, signature]); // Project `results` down to the current formula traces. Memoized on the result // map and the set of formula trace ids so the returned reference stays stable From be6b54791e3a6203179247d75563e4575ae3e6b9 Mon Sep 17 00:00:00 2001 From: YektaY Date: Fri, 16 Oct 2026 08:01:56 -0700 Subject: [PATCH 014/150] Remove the transitional api shims archiveStore and useInsightData import fetchData, fetchMetadata, CanopyError and the Mole DTO types from @slaclab/canopy-client. Severity is now WireAlarmSeverity. archiveStore passes the shared connection (it lives outside React); useInsightData reads it with useCanopyConnection(). Only imports and call sites change in those files. src/api/mole.ts, src/api/types.ts and the shim's test are gone. src/api/client.ts keeps only a CanopyError re-export for the e-log client, which moves to its own package under a separate ticket. This commit can be dropped if #93's PR lands first and conflicts. That PR adds tests that import or mock ../api/mole, ../api/client and ../api/types, so the shims have to stay until those move too. Part of #86. --- src/api/client.ts | 25 +------ src/api/mole.test.ts | 120 ------------------------------- src/api/mole.ts | 42 ----------- src/api/types.ts | 20 ------ src/hooks/useInsightData.test.ts | 10 ++- src/hooks/useInsightData.ts | 25 +++++-- src/state/archiveStore.ts | 12 +++- 7 files changed, 37 insertions(+), 217 deletions(-) delete mode 100644 src/api/mole.test.ts delete mode 100644 src/api/mole.ts delete mode 100644 src/api/types.ts diff --git a/src/api/client.ts b/src/api/client.ts index c225c3c..d3cfe40 100644 --- a/src/api/client.ts +++ b/src/api/client.ts @@ -1,23 +1,4 @@ -// Transitional shim over @slaclab/canopy-client: keeps trace's original -// signatures while call sites move to the SDK (which takes the connection as -// its first argument). Removed once nothing imports it. -import { - canopyFetch as sdkCanopyFetch, - toWsUrl, - type CanopyFetchOptions, -} from '@slaclab/canopy-client'; -import { canopyConnection } from './connection'; - +// Kept only for the e-log client (api/elog.ts and its tests), which moves to +// its own @slaclab/canopy-elog package under a separate ticket. Everything +// else imports CanopyError from @slaclab/canopy-client directly. export { CanopyError } from '@slaclab/canopy-client'; - -export type FetchOptions = CanopyFetchOptions; - -export function canopyFetch(path: string, options: FetchOptions = {}): Promise { - return sdkCanopyFetch(canopyConnection, path, options); -} - -// SSR-safe: returns an empty string when `window` is undefined. -export function canopyWebSocketUrl(path: string): string { - if (typeof window === 'undefined') return ''; - return toWsUrl(canopyConnection.baseUrl, path); -} diff --git a/src/api/mole.test.ts b/src/api/mole.test.ts deleted file mode 100644 index a2ec48c..0000000 --- a/src/api/mole.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { createFakeFetch, jsonResponse } from '@slaclab/canopy-client/testing'; -import type { FakeRoutes } from '@slaclab/canopy-client/testing'; -import { fetchData, fetchMetadata, listArchivers, searchPVs } from './mole'; -import { CanopyError } from './client'; -import { canopyConnection } from './connection'; - -// The shim calls go through the shared connection, which has no injected fetch, -// so the SDK falls back to the global fetch: stub it with the SDK's route fake. -function stubFetch(routes: FakeRoutes) { - const fetch = createFakeFetch(routes, { baseUrl: canopyConnection.baseUrl }); - vi.stubGlobal('fetch', fetch); - return fetch; -} - -afterEach(() => { - vi.unstubAllGlobals(); -}); - -describe('mole shim over @slaclab/canopy-client', () => { - it('fetchData encodes the PV and sends the window and fetch mode', async () => { - const fetch = stubFetch({ - 'GET /mole/v1/data/:pv': jsonResponse({ - mode: 'raw', - pv: 'A:B/C', - archiver: 'slac', - from: 1, - to: 2, - decimated: false, - samples: [], - }), - }); - - const dto = await fetchData('A:B/C', { - fromNs: 1_000, - toNs: 2_000, - archiver: 'slac', - binning: 'auto', - maxPoints: 500, - }); - - expect(dto.mode).toBe('raw'); - expect(fetch.calls).toHaveLength(1); - const [call] = fetch.calls; - expect(call.params.pv).toBe('A:B/C'); - expect(call.query).toEqual({ - from: '1000', - to: '2000', - archiver: 'slac', - binning: 'auto', - maxPoints: '500', - }); - }); - - it('routes metadata, search and archiver listing to their endpoints', async () => { - const fetch = stubFetch({ - 'GET /mole/v1/metadata/:pv': jsonResponse({ pv: 'X', units: 'mm' }), - 'GET /mole/v1/search': jsonResponse({ archiver: 'slac', pattern: '.*X.*', pvs: ['X'] }), - 'GET /mole/v1/archivers': jsonResponse({ default: 'slac', archivers: [] }), - }); - - expect((await fetchMetadata('X', 'slac')).units).toBe('mm'); - expect((await searchPVs('.*X.*', { limit: 5 })).pvs).toEqual(['X']); - expect((await listArchivers()).default).toBe('slac'); - - expect(fetch.calls.map((c) => c.path)).toEqual([ - '/mole/v1/metadata/X', - '/mole/v1/search', - '/mole/v1/archivers', - ]); - expect(fetch.calls[0].query).toEqual({ archiver: 'slac' }); - expect(fetch.calls[1].query).toEqual({ pattern: '.*X.*', limit: '5' }); - }); - - it('turns a FastAPI 422 into a readable validation_error', async () => { - stubFetch({ - 'GET /mole/v1/data/:pv': jsonResponse( - { - detail: [ - { loc: ['query', 'from'], msg: 'Field required', type: 'missing' }, - { loc: ['query', 'maxPoints'], msg: 'Input should be > 0', type: 'greater_than' }, - ], - }, - { status: 422 } - ), - }); - - const err = await fetchData('X', { fromNs: 0 }).catch((e: unknown) => e); - expect(err).toBeInstanceOf(CanopyError); - expect(err).toMatchObject({ - code: 'validation_error', - status: 422, - detail: 'query.from: Field required; query.maxPoints: Input should be > 0', - }); - expect((err as CanopyError).issues).toHaveLength(2); - }); - - it('keeps the Canopy error envelope', async () => { - stubFetch({ - 'GET /mole/v1/archivers': jsonResponse( - { code: 'archiver_unavailable', detail: 'slac is down' }, - { status: 503 } - ), - }); - await expect(listArchivers()).rejects.toMatchObject({ - code: 'archiver_unavailable', - status: 503, - detail: 'slac is down', - }); - }); - - it('passes an abort through unchanged', async () => { - stubFetch({ 'GET /mole/v1/archivers': jsonResponse({ default: 'slac', archivers: [] }) }); - const controller = new AbortController(); - controller.abort(); - const err = await listArchivers(controller.signal).catch((e: unknown) => e); - expect(err).not.toBeInstanceOf(CanopyError); - expect((err as { name?: string }).name).toBe('AbortError'); - }); -}); diff --git a/src/api/mole.ts b/src/api/mole.ts deleted file mode 100644 index 9ea6ca9..0000000 --- a/src/api/mole.ts +++ /dev/null @@ -1,42 +0,0 @@ -// Transitional shim over @slaclab/canopy-client's Mole client, bound to the -// shared connection so trace's original signatures keep working while call -// sites move to the SDK. Removed once nothing imports it. -import * as sdk from '@slaclab/canopy-client'; -import type { - ArchiverDataDTO, - ArchiverListDTO, - FetchDataParams, - PVMetadataDTO, - SearchResultsDTO, -} from '@slaclab/canopy-client'; -import { canopyConnection } from './connection'; - -export type { FetchDataParams } from '@slaclab/canopy-client'; - -export function fetchData( - pv: string, - params: FetchDataParams, - signal?: AbortSignal -): Promise { - return sdk.fetchData(canopyConnection, pv, params, signal); -} - -export function fetchMetadata( - pv: string, - archiver?: string, - signal?: AbortSignal -): Promise { - return sdk.fetchMetadata(canopyConnection, pv, archiver, signal); -} - -export function searchPVs( - pattern: string, - options: { archiver?: string; limit?: number } = {}, - signal?: AbortSignal -): Promise { - return sdk.searchPVs(canopyConnection, pattern, options, signal); -} - -export function listArchivers(signal?: AbortSignal): Promise { - return sdk.listArchivers(canopyConnection, signal); -} diff --git a/src/api/types.ts b/src/api/types.ts deleted file mode 100644 index d5a65cd..0000000 --- a/src/api/types.ts +++ /dev/null @@ -1,20 +0,0 @@ -// Transitional: trace's Mole wire-type names and severity alias, backed by -// @slaclab/canopy-client. Removed once nothing imports it. - -import type { WireAlarmSeverity } from '@slaclab/canopy-client'; - -export type AlarmSeverity = WireAlarmSeverity; - -export type { - ArchiverBinnedSeriesDTO, - ArchiverDataDTO, - ArchiverInfoDTO, - ArchiverListDTO, - ArchiverSeriesDTO, - BinnedPointDTO, - BinningMode, - ErrorEnvelope, - PVMetadataDTO, - SampleDTO, - SearchResultsDTO, -} from '@slaclab/canopy-client'; diff --git a/src/hooks/useInsightData.test.ts b/src/hooks/useInsightData.test.ts index 0e2854a..c92e455 100644 --- a/src/hooks/useInsightData.test.ts +++ b/src/hooks/useInsightData.test.ts @@ -1,15 +1,19 @@ import { describe, it, expect } from 'vitest'; import { mergeLive, type InsightRow } from './useInsightData'; import type { LivePoint } from '../state/liveStore'; -import type { AlarmSeverity } from '../api/types'; +import type { WireAlarmSeverity } from '@slaclab/canopy-client'; // Archive rows carry ns timestamps; live points carry ms. A live point at // `t` ms lands at `t * 1e6` ns, so these helpers keep the two domains aligned. -function archive(tsMs: number, value: number, severity: AlarmSeverity = 'NO_ALARM'): InsightRow { +function archive( + tsMs: number, + value: number, + severity: WireAlarmSeverity = 'NO_ALARM' +): InsightRow { return { tsNs: tsMs * 1e6, value, severity, source: 'Archive' }; } -function live(tsMs: number, value: number, severity: AlarmSeverity = 'NO_ALARM'): LivePoint { +function live(tsMs: number, value: number, severity: WireAlarmSeverity = 'NO_ALARM'): LivePoint { return { time: tsMs, value, severity }; } diff --git a/src/hooks/useInsightData.ts b/src/hooks/useInsightData.ts index cb7cfa6..064f5c3 100644 --- a/src/hooks/useInsightData.ts +++ b/src/hooks/useInsightData.ts @@ -1,15 +1,20 @@ import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'; -import { fetchData, fetchMetadata } from '../api/mole'; -import { CanopyError } from '../api/client'; +import { + CanopyError, + fetchData, + fetchMetadata, + type ArchiverDataDTO, + type WireAlarmSeverity, +} from '@slaclab/canopy-client'; +import { useCanopyConnection } from '@slaclab/canopy-react'; import { liveStore, type LivePoint } from '../state/liveStore'; import { msToNs } from '../api/time'; -import type { AlarmSeverity, ArchiverDataDTO } from '../api/types'; import type { TimeWindowNs } from '../api/time'; export interface InsightRow { tsNs: number; value: number | string | boolean | null; - severity: AlarmSeverity | ''; + severity: WireAlarmSeverity | ''; source: 'Archive' | 'Live'; } @@ -96,6 +101,7 @@ export function useInsightData( window: TimeWindowNs | undefined, traceId?: string ): InsightData { + const conn = useCanopyConnection(); const [archiveRows, setArchiveRows] = useState([]); const [meta, setMeta] = useState(null); const [status, setStatus] = useState('idle'); @@ -153,10 +159,15 @@ export function useInsightData( void (async () => { try { const [data, metadata] = await Promise.all([ - fetchData(pv, { fromNs: queryFromNs, toNs: queryToNs, archiver }, controller.signal), + fetchData( + conn, + pv, + { fromNs: queryFromNs, toNs: queryToNs, archiver }, + controller.signal + ), // Metadata is best-effort; a missing/erroring metadata endpoint // shouldn't fail the whole table. - fetchMetadata(pv, archiver, controller.signal).catch(() => null), + fetchMetadata(conn, pv, archiver, controller.signal).catch(() => null), ]); if (controller.signal.aborted) return; setArchiveRows(toRows(data)); @@ -174,7 +185,7 @@ export function useInsightData( })(); return () => controller.abort(); - }, [pv, archiver, fromSec, toSec, refreshKey]); + }, [conn, pv, archiver, fromSec, toSec, refreshKey]); // Read the trace's live buffer. Subscribing here only adds a store listener; // the actual PV watch/subscribe is owned by the app-level useLiveSeries, so a diff --git a/src/state/archiveStore.ts b/src/state/archiveStore.ts index a63b331..8612efb 100644 --- a/src/state/archiveStore.ts +++ b/src/state/archiveStore.ts @@ -1,6 +1,11 @@ -import { fetchData } from '../api/mole'; -import { CanopyError } from '../api/client'; -import type { ArchiverDataDTO, BinnedPointDTO, SampleDTO } from '../api/types'; +import { + CanopyError, + fetchData, + type ArchiverDataDTO, + type BinnedPointDTO, + type SampleDTO, +} from '@slaclab/canopy-client'; +import { canopyConnection } from '../api/connection'; import type { TimeWindowNs } from '../api/time'; import { nsToMs } from '../api/time'; @@ -306,6 +311,7 @@ class ArchiveStore { ): Promise { try { const dto = await fetchData( + canopyConnection, opts.pv, { fromNs: opts.window.fromNs, From b09012a6ec001034ddc95cafa6d22ed39a81de55 Mon Sep 17 00:00:00 2001 From: YektaY Date: Fri, 16 Oct 2026 08:18:45 -0700 Subject: [PATCH 015/150] Give the container image build GitHub Packages auth docker/Dockerfile now copies the tokenless .npmrc next to the lockfile, and mounts BuildKit secret "npmrc" as /root/.npmrc for the pnpm install step only, so the token never lands in an image layer. Secret mounts are optional by default, so a plain docker build without --secret still works while there is no @slaclab dependency. build-image.yml opts into the new swapps-ci-helpers npm-github-packages input, which passes GITHUB_TOKEN npm auth as that secret. The helper is pinned to the head of the draft swapps-ci-helpers#15 for now and needs re-pinning to the release tag after it merges. The job's existing packages: write grant covers the packages: read the image build needs. The README's Registry access section covers the image build and the local docker build --secret command. --- .github/workflows/build-image.yml | 6 +++++- README.md | 9 +++++++++ docker/Dockerfile | 8 ++++++-- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build-image.yml b/.github/workflows/build-image.yml index 5f6618e..95ce62e 100644 --- a/.github/workflows/build-image.yml +++ b/.github/workflows/build-image.yml @@ -17,13 +17,17 @@ concurrency: jobs: build-image: name: Build and publish GHCR image - uses: slaclab/swapps-ci-helpers/.github/workflows/build-ghcr-image.yml@73e6ba924aac5f822b050bd6bed12b0e45c64034 # v1.1.0 + uses: slaclab/swapps-ci-helpers/.github/workflows/build-ghcr-image.yml@f260c6e06e16dfa311511c9e56c34958162c4fa8 # yektay/build-secrets (draft swapps-ci-helpers PR #15); re-pin to the release tag after it merges + # packages: write covers GHCR publish and the packages: read the image build + # needs to install @slaclab/canopy-* from GitHub Packages. permissions: contents: read packages: write with: dockerfile: docker/Dockerfile context: . + # Mount GITHUB_TOKEN npm auth as BuildKit secret "npmrc" (see docker/Dockerfile). + npm-github-packages: true dispatch-dev-deploy: name: Trigger swapps-deployment dev deploy diff --git a/README.md b/README.md index 3039375..8fe8f90 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,15 @@ if each `@slaclab/canopy-*` package grants this repository read access under **Package settings → Manage Actions access**. See the [canopy-sdk-js install notes](https://github.com/slaclab/canopy-sdk-js#installing-consumers). +The container image build gets the same token through swapps-ci-helpers' +`npm-github-packages` input. It is a BuildKit secret named `npmrc` that `docker/Dockerfile` +mounts as `/root/.npmrc` for the `pnpm install` step only, so it never lands in an image +layer. To build the image locally, pass your user-level config: + +```bash +docker build --secret id=npmrc,src=$HOME/.npmrc -f docker/Dockerfile . +``` + ## Local dev ### 1. Run the Canopy backend diff --git a/docker/Dockerfile b/docker/Dockerfile index a0c19c1..0ac545a 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -2,8 +2,12 @@ FROM node:24-alpine AS build WORKDIR /app -COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ -RUN corepack enable && pnpm install --frozen-lockfile +# .npmrc maps @slaclab to GitHub Packages and holds no token. CI supplies auth as +# the BuildKit secret "npmrc" (swapps-ci-helpers npm-github-packages), mounted +# only for this step, so the token never lands in an image layer. +COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./ +RUN --mount=type=secret,id=npmrc,target=/root/.npmrc \ + corepack enable && pnpm install --frozen-lockfile COPY . . From 18e1c739618d5691c897f1f4b829b2e8eb6232df Mon Sep 17 00:00:00 2001 From: YektaY Date: Mon, 26 Oct 2026 22:38:39 -0700 Subject: [PATCH 016/150] Forward ELOG_TOKEN_HEADER to the dev e-log proxy .env.example advertised ELOG_TOKEN_HEADER, but canopyProxyOptions() passed only ELOG_BASE_URL and ELOG_API_KEY to canopyDevProxy. loadEnv() doesn't put .env values in process.env, so the SDK's own process.env.ELOG_TOKEN_HEADER fallback never saw it, and the token went out as x-vouch-idp-accesstoken regardless. It is now passed as elog.accessTokenHeader. The SDK treats an empty value as unset, so ELOG_TOKEN_HEADER= still gets the default header. The README's e-log section mentions the setting. Part of #86. --- README.md | 3 ++- vite.config.test.ts | 30 ++++++++++++++++++++++++++++++ vite.config.ts | 9 +++++++-- 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5989be9..54e14d3 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,8 @@ A trusted page on another origin needs to be listed in `allowedOrigins` in `vite Set `ELOG_BASE_URL` to an [elog-plus](https://github.com/eed-web-application/elog-plus) instance and `ELOG_API_KEY` to an application token. The dev server proxies `/elog/*` to that service (stripping the `/elog` prefix) and injects the `x-vouch-idp-accesstoken` header, -so the token never reaches the browser bundle. Leave `ELOG_BASE_URL` unset to disable the +so the token never reaches the browser bundle. For an elog-plus behind a different auth proxy, +set `ELOG_TOKEN_HEADER` to the header it expects. Leave `ELOG_BASE_URL` unset to disable the feature (the "Post to E-Log" toolbar button hides). `VITE_ELOG_DEFAULT_LOGBOOKS` is an optional comma-separated list of logbook names to preselect in the dialog. diff --git a/vite.config.test.ts b/vite.config.test.ts index efe2204..7faa7b6 100644 --- a/vite.config.test.ts +++ b/vite.config.test.ts @@ -37,4 +37,34 @@ describe('canopyProxyOptions', () => { expect(Object.keys(withElog)).toContain('^/elog(?=[/?#]|$)'); expect(withElog['^/elog(?=[/?#]|$)'].target).toBe('http://elog.test'); }); + + // The headers the /elog route sets on a same-origin request: its configure() + // registers a proxyReq handler, which drops cookies and injects the token. + function elogRequestHeaders(env: Record): Record { + const route = canopyDevProxy(canopyProxyOptions(env))['^/elog(?=[/?#]|$)']; + const handlers: Record void> = {}; + const proxy = { + on: (event: string, handler: (typeof handlers)[string]) => (handlers[event] = handler), + }; + (route.configure as (proxy: unknown, options: unknown) => void)(proxy, route); + const set: Record = {}; + const proxyReq = { + removeHeader: () => {}, + setHeader: (name: string, value: string) => (set[name] = value), + }; + handlers.proxyReq(proxyReq, { headers: {} }); + return set; + } + + it('sends the e-log token in ELOG_TOKEN_HEADER when it is set', () => { + const env = { ...base, ELOG_BASE_URL: 'http://elog.test', ELOG_API_KEY: 't' }; + expect(elogRequestHeaders({ ...env, ELOG_TOKEN_HEADER: 'x-custom-token' })).toEqual({ + 'x-custom-token': 't', + }); + // Unset or empty (`ELOG_TOKEN_HEADER=` in .env) keeps the default header. + expect(elogRequestHeaders(env)).toEqual({ 'x-vouch-idp-accesstoken': 't' }); + expect(elogRequestHeaders({ ...env, ELOG_TOKEN_HEADER: '' })).toEqual({ + 'x-vouch-idp-accesstoken': 't', + }); + }); }); diff --git a/vite.config.ts b/vite.config.ts index e5a23da..eb7d570 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -19,8 +19,13 @@ export function canopyProxyOptions(env: Record): CanopyDevProxyO target: env.CANOPY_BASE_URL, apiKey: env.CANOPY_API_KEY, ...(basePath ? { basePath } : { modules: ['/mole', '/hare', '/fox'] }), - // Left out when ELOG_BASE_URL is unset, which hides e-log posting. - elog: { target: env.ELOG_BASE_URL, accessToken: env.ELOG_API_KEY }, + // Left out when ELOG_BASE_URL is unset, which hides e-log posting. An + // empty ELOG_TOKEN_HEADER keeps the SDK's x-vouch-idp-accesstoken. + elog: { + target: env.ELOG_BASE_URL, + accessToken: env.ELOG_API_KEY, + accessTokenHeader: env.ELOG_TOKEN_HEADER, + }, }; } From ff97285e90127ad706c246db83cbc093fda9a90a Mon Sep 17 00:00:00 2001 From: ThorstenHellert Date: Tue, 3 Nov 2026 15:35:14 -0800 Subject: [PATCH 017/150] build: compile Carbon from Sass, self-host IBM Plex, refuse CDN URLs in dist Trace is served on networks without internet access. The precompiled @carbon/styles CSS loads IBM Plex from IBM's CDN (s81c.com), so Carbon is now compiled from Sass with its @font-face rules off (src/index.scss), and the Plex faces Carbon declares come from @ibm/plex-sans and @ibm/plex-mono, bundled under ./assets. main.tsx loads it before the app's own CSS. `pnpm build` runs check-dist afterwards, which fails on any IBM or Google font host in dist/. A build plugin fails on a second copy of react, react-dom or @carbon/react; resolve.dedupe and an @carbon/react alias keep them single when a dependency (the @slaclab SDK packages) brings its own. --- package.json | 6 ++- pnpm-lock.yaml | 75 ++++++++++++++------------ scripts/check-dist.mjs | 57 ++++++++++++++++++++ scripts/check-dist.test.ts | 39 ++++++++++++++ src/index.css | 2 - src/index.scss | 39 ++++++++++++++ src/main.tsx | 2 + tsconfig.node.json | 2 +- vite.config.ts | 32 ++++++++++- vite.dupGuard.test.ts | 106 +++++++++++++++++++++++++++++++++++++ vite.dupGuard.ts | 38 +++++++++++++ 11 files changed, 359 insertions(+), 39 deletions(-) create mode 100644 scripts/check-dist.mjs create mode 100644 scripts/check-dist.test.ts create mode 100644 src/index.scss create mode 100644 vite.dupGuard.test.ts create mode 100644 vite.dupGuard.ts diff --git a/package.json b/package.json index 6ccf2a7..a9709a9 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,8 @@ "description": "React implementation of Trace", "scripts": { "dev": "vite", - "build": "tsc -b && vite build", + "build": "tsc -b && vite build && pnpm run check-dist", + "check-dist": "node scripts/check-dist.mjs dist", "lint": "eslint .", "lint:fix": "eslint . --ext ts,tsx --fix", "format": "prettier --write \"src/**/*.{ts,tsx,css}\"", @@ -31,6 +32,8 @@ }, "devDependencies": { "@eslint/js": "^10.0.1", + "@ibm/plex-mono": "^1.1.0", + "@ibm/plex-sans": "^1.1.0", "@testing-library/dom": "^10.4.1", "@testing-library/jest-dom": "github:testing-library/jest-dom", "@testing-library/react": "^16.3.2", @@ -47,6 +50,7 @@ "jsdom": "^29.1.1", "lint-staged": "^17.0.4", "prettier": "^3.8.3", + "sass": "^1.107.1", "typescript": "~6.0.2", "typescript-eslint": "^8.59.2", "vite": "^8.0.12", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5d6e303..a1bed20 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -13,10 +13,10 @@ importers: version: 11.81.0(react@19.2.6) '@carbon/react': specifier: ^1.108.0 - version: 1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.99.0) + version: 1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.107.1) '@carbon/styles': specifier: ^1.107.0 - version: 1.107.0(sass@1.99.0) + version: 1.107.0(sass@1.107.1) '@dnd-kit/core': specifier: ^6.3.1 version: 6.3.1(react-dom@19.2.6(react@19.2.6))(react@19.2.6) @@ -45,6 +45,12 @@ importers: '@eslint/js': specifier: ^10.0.1 version: 10.0.1(eslint@10.3.0) + '@ibm/plex-mono': + specifier: ^1.1.0 + version: 1.1.0 + '@ibm/plex-sans': + specifier: ^1.1.0 + version: 1.1.0 '@testing-library/dom': specifier: ^10.4.1 version: 10.4.1 @@ -68,7 +74,7 @@ importers: version: 19.2.3(@types/react@19.2.14) '@vitejs/plugin-react': specifier: ^6.0.1 - version: 6.0.1(vite@8.0.12(@types/node@24.12.4)(sass@1.99.0)(yaml@2.9.0)) + version: 6.0.1(vite@8.0.12(@types/node@24.12.4)(sass@1.107.1)(yaml@2.9.0)) eslint: specifier: ^10.3.0 version: 10.3.0 @@ -93,6 +99,9 @@ importers: prettier: specifier: ^3.8.3 version: 3.8.3 + sass: + specifier: ^1.107.1 + version: 1.107.1 typescript: specifier: ~6.0.2 version: 6.0.3 @@ -101,10 +110,10 @@ importers: version: 8.59.3(eslint@10.3.0)(typescript@6.0.3) vite: specifier: ^8.0.12 - version: 8.0.12(@types/node@24.12.4)(sass@1.99.0)(yaml@2.9.0) + version: 8.0.12(@types/node@24.12.4)(sass@1.107.1)(yaml@2.9.0) vitest: specifier: ^4.1.6 - version: 4.1.6(@types/node@24.12.4)(jsdom@29.1.1)(vite@8.0.12(@types/node@24.12.4)(sass@1.99.0)(yaml@2.9.0)) + version: 4.1.6(@types/node@24.12.4)(jsdom@29.1.1)(vite@8.0.12(@types/node@24.12.4)(sass@1.107.1)(yaml@2.9.0)) packages: @@ -895,9 +904,9 @@ packages: resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==} engines: {node: '>=18'} - chokidar@4.0.3: - resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==} - engines: {node: '>= 14.16.0'} + chokidar@5.0.0: + resolution: {integrity: sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==} + engines: {node: '>= 20.19.0'} classnames@2.5.1: resolution: {integrity: sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==} @@ -1474,9 +1483,9 @@ packages: resolution: {integrity: sha512-sfWGGfavi0xr8Pg0sVsyHMAOziVYKgPLNrS7ig+ivMNb3wbCBw3KxtflsGBAwD3gYQlE/AEZsTLgToRrSCjb0Q==} engines: {node: '>=0.10.0'} - readdirp@4.1.2: - resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==} - engines: {node: '>= 14.18.0'} + readdirp@5.1.1: + resolution: {integrity: sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==} + engines: {node: '>= 20.19.0'} redent@3.0.0: resolution: {integrity: sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==} @@ -1498,9 +1507,9 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} hasBin: true - sass@1.99.0: - resolution: {integrity: sha512-kgW13M54DUB7IsIRM5LvJkNlpH+WhMpooUcaWGFARkF1Tc82v9mIWkCbCYf+MBvpIUBSeSOTilpZjEPr2VYE6Q==} - engines: {node: '>=14.0.0'} + sass@1.107.1: + resolution: {integrity: sha512-aJ1/LvxOOb04YhmiBjzZn3jVwdHKol+OVhoMV6fFl02fF9T3i+5Mg9l/CnzqtM+NX5Jn5o3lAbs/ZJivTCLHfQ==} + engines: {node: '>=20.19.0'} hasBin: true saxes@6.0.0: @@ -1976,13 +1985,13 @@ snapshots: dependencies: '@ibm/telemetry-js': 1.11.0 - '@carbon/react@1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.99.0)': + '@carbon/react@1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.107.1)': dependencies: '@babel/runtime': 7.29.2 '@carbon/feature-flags': 1.3.0 '@carbon/icons-react': 11.81.0(react@19.2.6) '@carbon/layout': 11.53.0 - '@carbon/styles': 1.107.0(sass@1.99.0) + '@carbon/styles': 1.107.0(sass@1.107.1) '@carbon/utilities': 0.20.0 '@floating-ui/react': 0.27.19(react-dom@19.2.6(react@19.2.6))(react@19.2.6) '@ibm/telemetry-js': 1.11.0 @@ -1997,10 +2006,10 @@ snapshots: react-dom: 19.2.6(react@19.2.6) react-fast-compare: 3.2.2 react-is: 18.2.0 - sass: 1.99.0 + sass: 1.107.1 tabbable: 6.4.0 - '@carbon/styles@1.107.0(sass@1.99.0)': + '@carbon/styles@1.107.0(sass@1.107.1)': dependencies: '@carbon/colors': 11.52.0 '@carbon/feature-flags': 1.3.0 @@ -2020,7 +2029,7 @@ snapshots: '@ibm/plex-serif': 1.1.0 '@ibm/telemetry-js': 1.11.0 optionalDependencies: - sass: 1.99.0 + sass: 1.107.1 '@carbon/themes@11.74.0': dependencies: @@ -2530,10 +2539,10 @@ snapshots: '@typescript-eslint/types': 8.59.3 eslint-visitor-keys: 5.0.1 - '@vitejs/plugin-react@6.0.1(vite@8.0.12(@types/node@24.12.4)(sass@1.99.0)(yaml@2.9.0))': + '@vitejs/plugin-react@6.0.1(vite@8.0.12(@types/node@24.12.4)(sass@1.107.1)(yaml@2.9.0))': dependencies: '@rolldown/pluginutils': 1.0.0-rc.7 - vite: 8.0.12(@types/node@24.12.4)(sass@1.99.0)(yaml@2.9.0) + vite: 8.0.12(@types/node@24.12.4)(sass@1.107.1)(yaml@2.9.0) '@vitest/expect@4.1.6': dependencies: @@ -2544,13 +2553,13 @@ snapshots: chai: 6.2.2 tinyrainbow: 3.1.0 - '@vitest/mocker@4.1.6(vite@8.0.12(@types/node@24.12.4)(sass@1.99.0)(yaml@2.9.0))': + '@vitest/mocker@4.1.6(vite@8.0.12(@types/node@24.12.4)(sass@1.107.1)(yaml@2.9.0))': dependencies: '@vitest/spy': 4.1.6 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: - vite: 8.0.12(@types/node@24.12.4)(sass@1.99.0)(yaml@2.9.0) + vite: 8.0.12(@types/node@24.12.4)(sass@1.107.1)(yaml@2.9.0) '@vitest/pretty-format@4.1.6': dependencies: @@ -2633,9 +2642,9 @@ snapshots: chai@6.2.2: {} - chokidar@4.0.3: + chokidar@5.0.0: dependencies: - readdirp: 4.1.2 + readdirp: 5.1.1 classnames@2.5.1: {} @@ -3164,7 +3173,7 @@ snapshots: react@19.2.6: {} - readdirp@4.1.2: {} + readdirp@5.1.1: {} redent@3.0.0: dependencies: @@ -3201,9 +3210,9 @@ snapshots: '@rolldown/binding-win32-arm64-msvc': 1.0.0 '@rolldown/binding-win32-x64-msvc': 1.0.0 - sass@1.99.0: + sass@1.107.1: dependencies: - chokidar: 4.0.3 + chokidar: 5.0.0 immutable: 5.1.5 source-map-js: 1.2.1 optionalDependencies: @@ -3342,7 +3351,7 @@ snapshots: dependencies: punycode: 2.3.1 - vite@8.0.12(@types/node@24.12.4)(sass@1.99.0)(yaml@2.9.0): + vite@8.0.12(@types/node@24.12.4)(sass@1.107.1)(yaml@2.9.0): dependencies: lightningcss: 1.32.0 picomatch: 4.0.4 @@ -3352,13 +3361,13 @@ snapshots: optionalDependencies: '@types/node': 24.12.4 fsevents: 2.3.3 - sass: 1.99.0 + sass: 1.107.1 yaml: 2.9.0 - vitest@4.1.6(@types/node@24.12.4)(jsdom@29.1.1)(vite@8.0.12(@types/node@24.12.4)(sass@1.99.0)(yaml@2.9.0)): + vitest@4.1.6(@types/node@24.12.4)(jsdom@29.1.1)(vite@8.0.12(@types/node@24.12.4)(sass@1.107.1)(yaml@2.9.0)): dependencies: '@vitest/expect': 4.1.6 - '@vitest/mocker': 4.1.6(vite@8.0.12(@types/node@24.12.4)(sass@1.99.0)(yaml@2.9.0)) + '@vitest/mocker': 4.1.6(vite@8.0.12(@types/node@24.12.4)(sass@1.107.1)(yaml@2.9.0)) '@vitest/pretty-format': 4.1.6 '@vitest/runner': 4.1.6 '@vitest/snapshot': 4.1.6 @@ -3375,7 +3384,7 @@ snapshots: tinyexec: 1.1.2 tinyglobby: 0.2.16 tinyrainbow: 3.1.0 - vite: 8.0.12(@types/node@24.12.4)(sass@1.99.0)(yaml@2.9.0) + vite: 8.0.12(@types/node@24.12.4)(sass@1.107.1)(yaml@2.9.0) why-is-node-running: 2.3.0 optionalDependencies: '@types/node': 24.12.4 diff --git a/scripts/check-dist.mjs b/scripts/check-dist.mjs new file mode 100644 index 0000000..5705a9a --- /dev/null +++ b/scripts/check-dist.mjs @@ -0,0 +1,57 @@ +#!/usr/bin/env node +// Build-output guard: Trace must be fully self-hosted. It is served on +// networks without internet access, so no file in dist/ may point at an +// external font CDN (IBM's s81c.com, which the precompiled Carbon CSS uses, +// or Google Fonts). Run after `vite build`; exits non-zero on any hit. +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { dirname, join, relative } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +/** Host fragments that mark a font fetched from the internet. */ +export const FORBIDDEN = ['s81c.com', 'fonts.googleapis', 'fonts.gstatic']; + +/** The FORBIDDEN entries that occur in `text`, in list order. */ +export function findHits(text) { + return FORBIDDEN.filter((needle) => text.includes(needle)); +} + +function* walk(dir) { + for (const name of readdirSync(dir)) { + const path = join(dir, name); + if (statSync(path).isDirectory()) yield* walk(path); + else yield path; + } +} + +function main() { + const distDir = process.argv[2] ?? join(dirname(fileURLToPath(import.meta.url)), '..', 'dist'); + + let files; + try { + files = [...walk(distDir)]; + } catch (err) { + console.error(`check-dist: cannot read ${distDir}: ${err.message}`); + process.exit(2); + } + if (files.length === 0) { + console.error(`check-dist: ${distDir} is empty; run the build first`); + process.exit(2); + } + + const hits = []; + for (const file of files) { + // latin1 keeps binary files (fonts, images) scannable byte-for-byte. + const text = readFileSync(file, 'latin1'); + for (const needle of findHits(text)) hits.push(`${relative(distDir, file)}: ${needle}`); + } + + if (hits.length > 0) { + console.error('check-dist: external font references found in the build output:'); + for (const hit of hits) console.error(` ${hit}`); + process.exit(1); + } + console.log(`check-dist: ${files.length} files clean`); +} + +// Importing this module (the unit test does) must not walk dist or exit. +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main(); diff --git a/scripts/check-dist.test.ts b/scripts/check-dist.test.ts new file mode 100644 index 0000000..08c8e8c --- /dev/null +++ b/scripts/check-dist.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest'; +import { FORBIDDEN, findHits } from './check-dist.mjs'; + +describe('FORBIDDEN', () => { + it('lists the IBM and Google font hosts', () => { + expect(FORBIDDEN).toEqual(['s81c.com', 'fonts.googleapis', 'fonts.gstatic']); + }); +}); + +describe('findHits', () => { + it('flags a Google Fonts stylesheet URL', () => { + const css = '@import url("https://fonts.googleapis.com/css2?family=IBM+Plex+Sans");'; + expect(findHits(css)).toEqual(['fonts.googleapis']); + }); + + it('flags a Google Fonts file URL', () => { + const css = '@font-face{src:url(https://fonts.gstatic.com/s/ibmplexsans/v19/a.woff2)}'; + expect(findHits(css)).toEqual(['fonts.gstatic']); + }); + + it('flags the IBM font CDN', () => { + const css = + '@font-face{font-family:"IBM Plex Sans";src:url(https://1.www.s81c.com/common/carbon/plex/fonts/IBM-Plex-Sans/a.woff2)}'; + expect(findHits(css)).toEqual(['s81c.com']); + }); + + it('reports every host found in one text', () => { + expect(findHits('fonts.gstatic.com s81c.com')).toEqual(['s81c.com', 'fonts.gstatic']); + }); + + it('returns nothing for a self-hosted font rule', () => { + const css = '@font-face{font-family:"IBM Plex Sans";src:url(./assets/ibm-plex-sans.woff2)}'; + expect(findHits(css)).toEqual([]); + }); + + it('returns nothing for an empty string', () => { + expect(findHits('')).toEqual([]); + }); +}); diff --git a/src/index.css b/src/index.css index 44c5b74..77693f6 100644 --- a/src/index.css +++ b/src/index.css @@ -1,5 +1,3 @@ -@import '@carbon/styles/css/styles.css'; - *, *::before, *::after { diff --git a/src/index.scss b/src/index.scss new file mode 100644 index 0000000..ea809bb --- /dev/null +++ b/src/index.scss @@ -0,0 +1,39 @@ +// Carbon, compiled from source with its @font-face rules switched off: the +// precompiled @carbon/styles CSS loads IBM Plex from IBM's CDN (s81c.com), +// which Canopy deployments without internet access cannot reach. The Plex +// faces are self-hosted from the @ibm/plex-* packages instead, so vite bundles +// the font files under ./assets. +@use '@carbon/styles' with ( + $css--font-face: false +); + +// Only the faces Carbon itself declares (light, regular and semibold, upright +// and italic) — the same set the CDN CSS offered, without the unused weights. +$-carbon-weights: ( + bold: false, + boldItalic: false, + extralight: false, + extralightItalic: false, + italic: true, + light: true, + lightItalic: true, + medium: false, + mediumItalic: false, + regular: true, + semibold: true, + semiboldItalic: true, + text: false, + textItalic: false, + thin: false, + thinItalic: false, +); + +@use '@ibm/plex-sans/scss' as plex-sans with ( + $font-weights: $-carbon-weights +); +@use '@ibm/plex-mono/scss' as plex-mono with ( + $font-weights: $-carbon-weights +); + +@include plex-sans.all($font-prefix: '@ibm/plex-sans'); +@include plex-mono.all($font-prefix: '@ibm/plex-mono'); diff --git a/src/main.tsx b/src/main.tsx index df655ea..259bbcc 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -1,5 +1,7 @@ import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; +// Carbon compiled from Sass with self-hosted IBM Plex, then the app's own CSS. +import './index.scss'; import './index.css'; import App from './App.tsx'; diff --git a/tsconfig.node.json b/tsconfig.node.json index d3c52ea..ab12ea1 100644 --- a/tsconfig.node.json +++ b/tsconfig.node.json @@ -20,5 +20,5 @@ "erasableSyntaxOnly": true, "noFallthroughCasesInSwitch": true }, - "include": ["vite.config.ts"] + "include": ["vite.config.ts", "vite.dupGuard.ts", "vite.dupGuard.test.ts"] } diff --git a/vite.config.ts b/vite.config.ts index 9caee8b..d2776eb 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,6 +1,25 @@ +import { realpathSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; import { defineConfig } from 'vitest/config'; -import { loadEnv } from 'vite'; +import { loadEnv, type Plugin } from 'vite'; import react from '@vitejs/plugin-react'; +import { assertSinglePackageDirs } from './vite.dupGuard.ts'; + +// Fail the build when react, react-dom or @carbon/react is bundled from more +// than one directory: the resolve block below is what keeps them single, and a +// second copy breaks hooks and context only at runtime. +function dupGuard(): Plugin { + return { + name: 'trace-dup-guard', + apply: 'build', + generateBundle(_options, bundle) { + const ids = Object.values(bundle).flatMap((file) => + file.type === 'chunk' ? file.moduleIds : [] + ); + assertSinglePackageDirs(ids, realpathSync); + }, + }; +} // https://vite.dev/config/ export default defineConfig(({ mode }) => { @@ -15,7 +34,16 @@ export default defineConfig(({ mode }) => { return { base: env.VITE_BASE_PATH || '/', - plugins: [react()], + plugins: [react(), dupGuard()], + // Force react and @carbon/react to this app's single copy; a dependency + // that brings its own (the @slaclab SDK packages do) would otherwise bundle + // a second React/Carbon. + resolve: { + dedupe: ['react', 'react-dom'], + alias: { + '@carbon/react': fileURLToPath(new URL('./node_modules/@carbon/react', import.meta.url)), + }, + }, server: { proxy: { '/mole': { diff --git a/vite.dupGuard.test.ts b/vite.dupGuard.test.ts new file mode 100644 index 0000000..599d955 --- /dev/null +++ b/vite.dupGuard.test.ts @@ -0,0 +1,106 @@ +import { describe, expect, it } from 'vitest'; +import { assertSinglePackageDirs, packageDirs } from './vite.dupGuard'; + +const same = (p: string) => p; +const trace = '/trace/node_modules/.pnpm'; +const sdk = '/sdk/node_modules/.pnpm'; + +describe('packageDirs', () => { + it('maps guarded module ids to their package directory', () => { + const dirs = packageDirs( + [ + `${trace}/react@19.2.6/node_modules/react/index.js`, + `${trace}/react@19.2.6/node_modules/react/cjs/react.production.js`, + `${trace}/react-dom@19.2.6_react@19.2.6/node_modules/react-dom/client.js`, + `${trace}/@carbon+react@1.108.0_x/node_modules/@carbon/react/es/index.js`, + '/trace/node_modules/react/jsx-runtime.js', + '/trace/src/main.tsx', + `${trace}/react-is@19.0.0/node_modules/react-is/index.js`, + ], + same + ); + expect(dirs).toEqual( + new Map([ + [ + 'react', + new Set([`${trace}/react@19.2.6/node_modules/react`, '/trace/node_modules/react']), + ], + ['react-dom', new Set([`${trace}/react-dom@19.2.6_react@19.2.6/node_modules/react-dom`])], + ['@carbon/react', new Set([`${trace}/@carbon+react@1.108.0_x/node_modules/@carbon/react`])], + ]) + ); + }); + + it('resolves symlinked directories through realpath', () => { + const real = (p: string) => + p === '/trace/node_modules/react' ? `${trace}/react@19.2.6/node_modules/react` : p; + const dirs = packageDirs( + ['/trace/node_modules/react/index.js', `${trace}/react@19.2.6/node_modules/react/index.js`], + real + ); + expect([...dirs.get('react')!]).toEqual([`${trace}/react@19.2.6/node_modules/react`]); + }); + + it('reads the path of a virtual module id and ignores its query', () => { + const dirs = packageDirs( + [ + `\0${trace}/react@19.2.6/node_modules/react/index.js?commonjs-module`, + `${trace}/react@19.2.6/node_modules/react/index.js`, + ], + same + ); + expect([...dirs.get('react')!]).toEqual([`${trace}/react@19.2.6/node_modules/react`]); + }); + + it('keeps the unresolved directory when realpath fails', () => { + const dirs = packageDirs(['/gone/node_modules/react/index.js'], () => { + throw new Error('ENOENT'); + }); + expect([...dirs.get('react')!]).toEqual(['/gone/node_modules/react']); + }); +}); + +describe('assertSinglePackageDirs', () => { + it('passes when every guarded package has one directory', () => { + expect(() => + assertSinglePackageDirs( + [ + `${trace}/react@19.2.6/node_modules/react/index.js`, + `${trace}/react-dom@19.2.6_react@19.2.6/node_modules/react-dom/client.js`, + `${trace}/@carbon+react@1.108.0_x/node_modules/@carbon/react/es/index.js`, + ], + same + ) + ).not.toThrow(); + }); + + it('passes when the bundle has none of the guarded packages', () => { + expect(() => assertSinglePackageDirs(['/trace/src/main.tsx'], same)).not.toThrow(); + }); + + it('throws naming the package and both directories', () => { + expect(() => + assertSinglePackageDirs( + [ + `${trace}/react@19.2.6/node_modules/react/index.js`, + `${sdk}/react@19.2.6/node_modules/react/index.js`, + ], + same + ) + ).toThrow( + `duplicate react: ${sdk}/react@19.2.6/node_modules/react, ${trace}/react@19.2.6/node_modules/react` + ); + }); + + it('throws for a second @carbon/react', () => { + expect(() => + assertSinglePackageDirs( + [ + `${trace}/@carbon+react@1.108.0_x/node_modules/@carbon/react/es/index.js`, + `${sdk}/@carbon+react@1.111.0_x/node_modules/@carbon/react/es/index.js`, + ], + same + ) + ).toThrow(/^duplicate @carbon\/react: /); + }); +}); diff --git a/vite.dupGuard.ts b/vite.dupGuard.ts new file mode 100644 index 0000000..a158c17 --- /dev/null +++ b/vite.dupGuard.ts @@ -0,0 +1,38 @@ +// Duplicate-package guard for the build: React and Carbon keep state in module +// scope, so a second copy in the bundle (a linked SDK package resolving its own) +// breaks hooks and context at runtime without failing the build. + +const GUARDED = /node_modules\/(\.pnpm\/[^/]+\/node_modules\/)?(react|react-dom|@carbon\/react)\//; + +/** Map each guarded package name to the real directories its bundled modules come from. */ +export function packageDirs( + moduleIds: Iterable, + realpath: (path: string) => string +): Map> { + const dirs = new Map>(); + for (const id of moduleIds) { + // Virtual ids wrap a real path: "\0?commonjs-module". + const path = id.replace(/^\0/, '').replace(/[?#].*$/, ''); + const match = GUARDED.exec(path); + if (!match) continue; + let dir = path.slice(0, match.index + match[0].length - 1); + try { + dir = realpath(dir); + } catch { + // Not on disk: compare the directory as written. + } + const name = match[2]; + dirs.set(name, (dirs.get(name) ?? new Set()).add(dir)); + } + return dirs; +} + +/** Throw `duplicate : ` when a guarded package is bundled from more than one directory. */ +export function assertSinglePackageDirs( + moduleIds: Iterable, + realpath: (path: string) => string +): void { + for (const [name, dirs] of packageDirs(moduleIds, realpath)) { + if (dirs.size > 1) throw new Error(`duplicate ${name}: ${[...dirs].sort().join(', ')}`); + } +} From 950d9c0efb592d807dd1c19b2cf9518868248dc6 Mon Sep 17 00:00:00 2001 From: ThorstenHellert Date: Tue, 3 Nov 2026 15:30:31 -0800 Subject: [PATCH 018/150] build: Canopy SDK 0.3.1-als.1 All five @slaclab packages (client, react, shell, charts, vite) move from 0.2 to 0.3.1-als.1, pinned exactly. That build is the first to carry the shell's host-theme API (useHostTheme, HOST_THEME_ID, applyHostSheetFallback, useChartFont) that the embedding topics use; the published 0.3.0 lacks it, so a ^0.3.0 range would resolve a release that fails them. The pin moves to the upstream release that carries the API once one is published. 0.3 renames the SDK's Fox symbols to FormulaEngine* and makes FormulaSpec.expression optional (table formulas carry per-column expressions); the one comment and the one test fake that relied on the old shapes follow. --- package.json | 10 +++--- pnpm-lock.yaml | 56 +++++++++++++++++----------------- src/api/formulaEngine.ts | 2 +- src/state/formulaStore.test.ts | 2 +- src/state/liveStore.test.ts | 16 +++++----- 5 files changed, 44 insertions(+), 42 deletions(-) diff --git a/package.json b/package.json index 8e35a64..fb80e07 100644 --- a/package.json +++ b/package.json @@ -26,10 +26,10 @@ "@dnd-kit/core": "^6.3.1", "@dnd-kit/sortable": "^10.0.0", "@dnd-kit/utilities": "^3.2.2", - "@slaclab/canopy-charts": "^0.2.0", - "@slaclab/canopy-client": "^0.2.0", - "@slaclab/canopy-react": "^0.2.0", - "@slaclab/canopy-shell": "^0.2.0", + "@slaclab/canopy-charts": "0.3.1-als.1", + "@slaclab/canopy-client": "0.3.1-als.1", + "@slaclab/canopy-react": "0.3.1-als.1", + "@slaclab/canopy-shell": "0.3.1-als.1", "echarts": "^6.1.0", "echarts-for-react": "^3.0.6", "react": "^19.2.6", @@ -40,7 +40,7 @@ "@eslint/js": "^10.0.1", "@ibm/plex-mono": "^1.1.0", "@ibm/plex-sans": "^1.1.0", - "@slaclab/canopy-vite": "^0.2.0", + "@slaclab/canopy-vite": "0.3.1-als.1", "@testing-library/dom": "^10.4.1", "@testing-library/jest-dom": "github:testing-library/jest-dom", "@testing-library/react": "^16.3.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b934e91..3af28a4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -27,17 +27,17 @@ importers: specifier: ^3.2.2 version: 3.2.2(react@19.2.6) '@slaclab/canopy-charts': - specifier: ^0.2.0 - version: 0.2.0(@slaclab/canopy-shell@0.2.0(@carbon/icons-react@11.81.0(react@19.2.6))(@carbon/react@1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.107.1))(react-dom@19.2.6(react@19.2.6))(react@19.2.6))(echarts-for-react@3.0.6(echarts@6.1.0)(react@19.2.6))(echarts@6.1.0)(react-dom@19.2.6(react@19.2.6))(react@19.2.6) + specifier: 0.3.1-als.1 + version: 0.3.1-als.1(@slaclab/canopy-shell@0.3.1-als.1(@carbon/icons-react@11.81.0(react@19.2.6))(@carbon/react@1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.107.1))(react-dom@19.2.6(react@19.2.6))(react@19.2.6))(echarts-for-react@3.0.6(echarts@6.1.0)(react@19.2.6))(echarts@6.1.0)(react-dom@19.2.6(react@19.2.6))(react@19.2.6) '@slaclab/canopy-client': - specifier: ^0.2.0 - version: 0.2.0 + specifier: 0.3.1-als.1 + version: 0.3.1-als.1 '@slaclab/canopy-react': - specifier: ^0.2.0 - version: 0.2.0(react-dom@19.2.6(react@19.2.6))(react@19.2.6) + specifier: 0.3.1-als.1 + version: 0.3.1-als.1(react-dom@19.2.6(react@19.2.6))(react@19.2.6) '@slaclab/canopy-shell': - specifier: ^0.2.0 - version: 0.2.0(@carbon/icons-react@11.81.0(react@19.2.6))(@carbon/react@1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.107.1))(react-dom@19.2.6(react@19.2.6))(react@19.2.6) + specifier: 0.3.1-als.1 + version: 0.3.1-als.1(@carbon/icons-react@11.81.0(react@19.2.6))(@carbon/react@1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.107.1))(react-dom@19.2.6(react@19.2.6))(react@19.2.6) echarts: specifier: ^6.1.0 version: 6.1.0 @@ -64,8 +64,8 @@ importers: specifier: ^1.1.0 version: 1.1.0 '@slaclab/canopy-vite': - specifier: ^0.2.0 - version: 0.2.0(vite@8.0.12(@types/node@24.12.4)(sass@1.107.1)(yaml@2.9.0)) + specifier: 0.3.1-als.1 + version: 0.3.1-als.1(vite@8.0.12(@types/node@24.12.4)(sass@1.107.1)(yaml@2.9.0)) '@testing-library/dom': specifier: ^10.4.1 version: 10.4.1 @@ -677,34 +677,34 @@ packages: '@rolldown/pluginutils@1.0.0-rc.7': resolution: {integrity: sha512-qujRfC8sFVInYSPPMLQByRh7zhwkGFS4+tyMQ83srV1qrxL4g8E2tyxVVyxd0+8QeBM1mIk9KbWxkegRr76XzA==} - '@slaclab/canopy-charts@0.2.0': - resolution: {integrity: sha512-8MGXocmqdcUlyIZVb04llbaVDTqCrN3IByUIUBv4K9+BhB3jGWOkn8fEImUa01R75ZNg8t40AUydhchezwhfzQ==, tarball: https://npm.pkg.github.com/download/@slaclab/canopy-charts/0.2.0/db94243a679e1fc7413c00ce12980e53c956efe9} + '@slaclab/canopy-charts@0.3.1-als.1': + resolution: {integrity: sha512-u2kd4rFfw3kca7WYAZfNH49hTAxQV0SRyuuJ1mlpCY9F1PSLV03YvdQh7u1GvnehB2EQfKTAaH+MDvbqlJNqpg==} peerDependencies: - '@slaclab/canopy-shell': ^0.2.0 + '@slaclab/canopy-shell': ^0.3.1-als.1 echarts: ^6.0.0 echarts-for-react: ^3.0.0 react: ^19.0.0 react-dom: ^19.0.0 - '@slaclab/canopy-client@0.2.0': - resolution: {integrity: sha512-n5FGh5lkyseQ+KKyO2aSzfxx/XstJxnyXERYJjfhr/24/c/FIQA1uTqnpNDC3snGpQuRRHmmeCKgk2fLlSxyZw==, tarball: https://npm.pkg.github.com/download/@slaclab/canopy-client/0.2.0/c43dbcd7454469c9f46f1e3e0f5a39c07dcb5f37} + '@slaclab/canopy-client@0.3.1-als.1': + resolution: {integrity: sha512-AaZba/iWliYS/UjUnu6fTTQriDZJnLl0MK8gPC1yChJ8c20/ZG55xVghRiRD5gykY1TgxiRVT7+UM9aMDE1rkw==} - '@slaclab/canopy-react@0.2.0': - resolution: {integrity: sha512-k0gzuQcdWMEp92kCbhUmHtHuuDjd++zjob6OJp405K5C5iAHFhw+CvtLPh06LPV3fl7domvSBE2TxIEDGlj1vw==, tarball: https://npm.pkg.github.com/download/@slaclab/canopy-react/0.2.0/c397d109ce90ca18b1e2511bcd27b6b6ede8132a} + '@slaclab/canopy-react@0.3.1-als.1': + resolution: {integrity: sha512-zZm0wK8kcP8DNt9LOtNy8QpN1SdoL7O7y85bXsry+JDE+0sN2UOZwatVB5BT84mXYwhXv01EoBowxjfyiNpSoQ==} peerDependencies: react: ^19.0.0 react-dom: ^19.0.0 - '@slaclab/canopy-shell@0.2.0': - resolution: {integrity: sha512-j9u6y1CHEePSLirX07NDNnS/ka9tdylV19ogjTJ601KvwrZcxBndGzsp0H8ziJRDQDK6XQBrFBSkV/c7vYksgw==, tarball: https://npm.pkg.github.com/download/@slaclab/canopy-shell/0.2.0/1e0145073a2e6774fe4d54bd68bbea81bf7d38e0} + '@slaclab/canopy-shell@0.3.1-als.1': + resolution: {integrity: sha512-5ASeQu4Ln5DdI6HhihnxeKPRN1Vg8Gb0TyzgVogdx7Y5ohTjq3uj+Zj9yDBjfmEuF+qmbggTbggx+WiQoJLsqg==} peerDependencies: '@carbon/icons-react': ^11.50.0 '@carbon/react': ^1.90.0 react: ^19.0.0 react-dom: ^19.0.0 - '@slaclab/canopy-vite@0.2.0': - resolution: {integrity: sha512-HRqpkmqSWltGmKrnpLcJZH2fRgFPftA2Iv054i9y1VSkzBAI3cuFbZPIued1XNfyqfcO2zaD5fubfAcdpC1hSw==, tarball: https://npm.pkg.github.com/download/@slaclab/canopy-vite/0.2.0/0e9ab0815488292559c2de3cd14165aba20ad317} + '@slaclab/canopy-vite@0.3.1-als.1': + resolution: {integrity: sha512-BvEEMACZxCklpz5mw8RvGfMQLjHA6rfRXJQzMov1ZDicFKuCGJ6C6l8kBLHXpBRPwlCdf3POfPSzQ1e/wksUxg==} peerDependencies: vite: ^6.0.0 || ^7.0.0 || ^8.0.0 @@ -2422,30 +2422,30 @@ snapshots: '@rolldown/pluginutils@1.0.0-rc.7': {} - '@slaclab/canopy-charts@0.2.0(@slaclab/canopy-shell@0.2.0(@carbon/icons-react@11.81.0(react@19.2.6))(@carbon/react@1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.107.1))(react-dom@19.2.6(react@19.2.6))(react@19.2.6))(echarts-for-react@3.0.6(echarts@6.1.0)(react@19.2.6))(echarts@6.1.0)(react-dom@19.2.6(react@19.2.6))(react@19.2.6)': + '@slaclab/canopy-charts@0.3.1-als.1(@slaclab/canopy-shell@0.3.1-als.1(@carbon/icons-react@11.81.0(react@19.2.6))(@carbon/react@1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.107.1))(react-dom@19.2.6(react@19.2.6))(react@19.2.6))(echarts-for-react@3.0.6(echarts@6.1.0)(react@19.2.6))(echarts@6.1.0)(react-dom@19.2.6(react@19.2.6))(react@19.2.6)': dependencies: - '@slaclab/canopy-shell': 0.2.0(@carbon/icons-react@11.81.0(react@19.2.6))(@carbon/react@1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.107.1))(react-dom@19.2.6(react@19.2.6))(react@19.2.6) + '@slaclab/canopy-shell': 0.3.1-als.1(@carbon/icons-react@11.81.0(react@19.2.6))(@carbon/react@1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.107.1))(react-dom@19.2.6(react@19.2.6))(react@19.2.6) echarts: 6.1.0 echarts-for-react: 3.0.6(echarts@6.1.0)(react@19.2.6) react: 19.2.6 react-dom: 19.2.6(react@19.2.6) - '@slaclab/canopy-client@0.2.0': {} + '@slaclab/canopy-client@0.3.1-als.1': {} - '@slaclab/canopy-react@0.2.0(react-dom@19.2.6(react@19.2.6))(react@19.2.6)': + '@slaclab/canopy-react@0.3.1-als.1(react-dom@19.2.6(react@19.2.6))(react@19.2.6)': dependencies: - '@slaclab/canopy-client': 0.2.0 + '@slaclab/canopy-client': 0.3.1-als.1 react: 19.2.6 react-dom: 19.2.6(react@19.2.6) - '@slaclab/canopy-shell@0.2.0(@carbon/icons-react@11.81.0(react@19.2.6))(@carbon/react@1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.107.1))(react-dom@19.2.6(react@19.2.6))(react@19.2.6)': + '@slaclab/canopy-shell@0.3.1-als.1(@carbon/icons-react@11.81.0(react@19.2.6))(@carbon/react@1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.107.1))(react-dom@19.2.6(react@19.2.6))(react@19.2.6)': dependencies: '@carbon/icons-react': 11.81.0(react@19.2.6) '@carbon/react': 1.108.0(react-dom@19.2.6(react@19.2.6))(react-is@18.2.0)(react@19.2.6)(sass@1.107.1) react: 19.2.6 react-dom: 19.2.6(react@19.2.6) - '@slaclab/canopy-vite@0.2.0(vite@8.0.12(@types/node@24.12.4)(sass@1.107.1)(yaml@2.9.0))': + '@slaclab/canopy-vite@0.3.1-als.1(vite@8.0.12(@types/node@24.12.4)(sass@1.107.1)(yaml@2.9.0))': dependencies: vite: 8.0.12(@types/node@24.12.4)(sass@1.107.1)(yaml@2.9.0) diff --git a/src/api/formulaEngine.ts b/src/api/formulaEngine.ts index 1c83ee7..2732eec 100644 --- a/src/api/formulaEngine.ts +++ b/src/api/formulaEngine.ts @@ -7,7 +7,7 @@ import { } from '@slaclab/canopy-client'; // The Formula Engine's REST endpoints. The SDK covers its live-formula -// WebSocket (FoxFormulaService) but not these, so they stay here on its REST +// WebSocket (FormulaEngineService) but not these, so they stay here on its REST // core. // Result of POST /formula-engine/v1/validate (canopy.formula_engine.schemas.formula). diff --git a/src/state/formulaStore.test.ts b/src/state/formulaStore.test.ts index 7f079aa..13efa6b 100644 --- a/src/state/formulaStore.test.ts +++ b/src/state/formulaStore.test.ts @@ -32,7 +32,7 @@ function fakeFox(reply?: (call: Call) => void) { const evaluate: EvaluateFn = (spec, t0Ns, t1Ns, signal) => new Promise((resolve, reject) => { const call: Call = { - expression: spec.expression, + expression: spec.expression ?? '', t0Ns, t1Ns, signal, diff --git a/src/state/liveStore.test.ts b/src/state/liveStore.test.ts index f175f77..6f3a36a 100644 --- a/src/state/liveStore.test.ts +++ b/src/state/liveStore.test.ts @@ -122,7 +122,7 @@ describe('LiveStore', () => { expect(store.getSnapshot().get('t1')!.severity).toBe('INVALID'); }); - it('refcounts subscriptions across traces sharing one PV', () => { + it('refcounts subscriptions across traces sharing one PV', async () => { const { store, instances } = setup(); store.watch('t1', 'FOO', 60_000); store.watch('t2', 'FOO', 60_000); @@ -137,11 +137,11 @@ describe('LiveStore', () => { expect(ws.parsedSent()).toEqual([{ type: 'subscribe', pvNames: ['FOO'] }]); store.release('t2'); - // Last subscriber gone -> unsubscribe. - expect(ws.parsedSent()).toEqual([ - { type: 'subscribe', pvNames: ['FOO'] }, - { type: 'unsubscribe', pvNames: ['FOO'] }, - ]); + // Last subscriber gone -> the socket closes, which drops the subscription + // on Hare; the unsubscribe queued for this tick is never sent. + await Promise.resolve(); + expect(ws.readyState).toBe(WS_CLOSED); + expect(ws.parsedSent()).toEqual([{ type: 'subscribe', pvNames: ['FOO'] }]); }); it('delivers one sample per update to every trace on a shared PV', () => { @@ -337,13 +337,15 @@ describe('LiveStore', () => { expect(instances[1].parsedSent()).toEqual([{ type: 'subscribe', pvNames: ['IDLE'] }]); }); - it('keeps the socket open when a trace switches PV', () => { + it('keeps the socket open when a trace switches PV', async () => { const { store, instances } = setup(); store.watch('t1', 'OLD', 60_000); const ws = instances[0]; ws.open(); store.watch('t1', 'NEW', 60_000); + // Subscribe/unsubscribe frames go out at the end of the tick. + await Promise.resolve(); expect(instances).toHaveLength(1); expect(ws.readyState).not.toBe(WS_CLOSED); From e62e1ac202dbd1de10176fe08b40921576480162 Mon Sep 17 00:00:00 2001 From: ThorstenHellert Date: Tue, 3 Nov 2026 15:41:11 -0800 Subject: [PATCH 019/150] feat(embed): host contract for running Trace inside a workspace, same-origin requests - Sub-path gateway: without VITE_CANOPY_BASE_PATH the Canopy connection's base is the page's parent directory (Trace at /x/y/trace/ reaches /x/y/mole, /x/y/hare, /x/y/formula-engine; at the site root it stays the per-module paths). It is read at each request. - Same origin only: the connection's fetch refuses any URL that resolves outside window.location.origin (an absolute VITE_CANOPY_BASE_PATH, a elsewhere), and leading slashes in the page path collapse. - Message bridge: with ?embedded=true, same-origin visibility and theme messages from the parent, and a trace-ready handshake, installed before the first render by a bootstrap module every page entry imports. The bootstrap also fixes the stylesheet order (Carbon, the shell's styles, its host-contract sheet, the app's own) and applies the host-sheet fallback first. - Host theme on the canopy-shell colour-mode store: embedded, the host's ?theme= id and its later theme messages set the store's mode under a key of their own, which each host message clears, so the host wins and the operator's standalone choice under trace.theme is never read or written. The root Carbon zone (and each detached window's) is the host-theme anchor; detached windows inherit the host marker and the opener's body colour. - The per-plot autoscroll clock holds while the host hides Trace and nothing is detached, so live re-renders neither slide a window nor refetch. - Test workers run without Node's own localStorage (Node >= 25 shadows jsdom's), and a test pins the shell's host-contract wiring against this app's Carbon. E-log needs nothing here: since #150 its availability is Canopy's e-log config, the same standalone and embedded. --- package.json | 1 + pnpm-lock.yaml | 23 ++ scripts/hostContractCoverage.test.ts | 45 ++ src/App.anchor.test.tsx | 89 ++++ src/App.tsx | 16 +- src/api/connection.test.ts | 79 +++- src/api/connection.ts | 42 +- src/bootstrap.test.ts | 51 +++ src/bootstrap.ts | 25 ++ .../DetachedWindow.blocked.test.tsx | 55 +++ src/components/DetachedWindow.test.tsx | 273 ++++++++++--- src/components/DetachedWindow.tsx | 11 + src/components/TraceApp.tsx | 40 +- src/embed/bridge.test.ts | 386 ++++++++++++++++++ src/embed/bridge.ts | 134 ++++++ src/embed/embedded.ts | 7 + src/hooks/useAutoScrollTimers.pause.test.ts | 151 +++++++ src/hooks/useAutoScrollTimers.ts | 26 +- src/main.tsx | 10 +- src/state/colorMode.host.test.ts | 146 +++++++ src/state/colorMode.ts | 71 +++- vite.config.ts | 3 + 22 files changed, 1602 insertions(+), 82 deletions(-) create mode 100644 scripts/hostContractCoverage.test.ts create mode 100644 src/App.anchor.test.tsx create mode 100644 src/bootstrap.test.ts create mode 100644 src/bootstrap.ts create mode 100644 src/components/DetachedWindow.blocked.test.tsx create mode 100644 src/embed/bridge.test.ts create mode 100644 src/embed/bridge.ts create mode 100644 src/embed/embedded.ts create mode 100644 src/hooks/useAutoScrollTimers.pause.test.ts create mode 100644 src/state/colorMode.host.test.ts diff --git a/package.json b/package.json index fb80e07..5dbdcca 100644 --- a/package.json +++ b/package.json @@ -45,6 +45,7 @@ "@testing-library/jest-dom": "github:testing-library/jest-dom", "@testing-library/react": "^16.3.2", "@testing-library/user-event": "github:testing-library/user-event", + "@types/jsdom": "^28.0.3", "@types/node": "^24.12.3", "@types/react": "^19.2.14", "@types/react-dom": "^19.2.3", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3af28a4..f4c9f4a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -78,6 +78,9 @@ importers: '@testing-library/user-event': specifier: github:testing-library/user-event version: https://codeload.github.com/testing-library/user-event/tar.gz/ebab6c6e81e7022af7afa5aacd07d01626895eb8(@testing-library/dom@10.4.1) + '@types/jsdom': + specifier: ^28.0.3 + version: 28.0.3 '@types/node': specifier: ^24.12.3 version: 24.12.4 @@ -763,6 +766,9 @@ packages: '@types/estree@1.0.9': resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + '@types/jsdom@28.0.3': + resolution: {integrity: sha512-/HQ2uFoetFTXuye8vzIcHw2z6Fwi7Hi/qcgC+RoS9NCyewiqxhVGqlG+ViGB6lkax481R6dmhf1I7lIGlzJStQ==} + '@types/json-schema@7.0.15': resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} @@ -777,6 +783,9 @@ packages: '@types/react@19.2.14': resolution: {integrity: sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==} + '@types/tough-cookie@4.0.5': + resolution: {integrity: sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==} + '@typescript-eslint/eslint-plugin@8.59.3': resolution: {integrity: sha512-PwFvSKsXGShKGW6n5bZOhGHEcCZXM8HofLK9fNsEwZXzFRjoY+XT1Vsf1zgyXdwTr0ZYz1/2tkZ0DBTT9jZjhw==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -1703,6 +1712,9 @@ packages: undici-types@7.16.0: resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==} + undici-types@7.30.1: + resolution: {integrity: sha512-4CNTj7RmIepmiez9hX5pJzYLi5bv1ZBA6puqC3qYyqluB8zu5uygFc+4iG5Nmcx3fg+6bPFxuEbCrxTa7Yqy3A==} + undici@7.28.0: resolution: {integrity: sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==} engines: {node: '>=20.18.1'} @@ -2507,6 +2519,13 @@ snapshots: '@types/estree@1.0.9': {} + '@types/jsdom@28.0.3': + dependencies: + '@types/node': 24.12.4 + '@types/tough-cookie': 4.0.5 + parse5: 8.0.1 + undici-types: 7.30.1 + '@types/json-schema@7.0.15': {} '@types/node@24.12.4': @@ -2521,6 +2540,8 @@ snapshots: dependencies: csstype: 3.2.3 + '@types/tough-cookie@4.0.5': {} + '@typescript-eslint/eslint-plugin@8.59.3(@typescript-eslint/parser@8.59.3(eslint@10.3.0)(typescript@6.0.3))(eslint@10.3.0)(typescript@6.0.3)': dependencies: '@eslint-community/regexpp': 4.12.2 @@ -3412,6 +3433,8 @@ snapshots: undici-types@7.16.0: {} + undici-types@7.30.1: {} + undici@7.28.0: {} update-browserslist-db@1.2.3(browserslist@4.28.2): diff --git a/scripts/hostContractCoverage.test.ts b/scripts/hostContractCoverage.test.ts new file mode 100644 index 0000000..c4a8ce0 --- /dev/null +++ b/scripts/hostContractCoverage.test.ts @@ -0,0 +1,45 @@ +// @vitest-environment node +// The host contract re-points Carbon's zone tokens through canopy-shell's wiring.json, which is +// generated from the shell's Carbon. This pins it against Trace's own Carbon, so a Carbon bump +// here that adds or drops a token fails until the contract is regenerated. +import { readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { describe, expect, it } from 'vitest'; + +type Wiring = Record<'zone' | 'type' | 'layout', Record>; + +const require = createRequire(import.meta.url); +// Read from disk: vitest blanks `.css` imports, `?raw` included. +const css = readFileSync(require.resolve('@carbon/styles/css/styles.css'), 'utf8'); +const wiring = JSON.parse( + readFileSync(require.resolve('@slaclab/canopy-shell/wiring.json'), 'utf8') +) as Wiring; + +// The regexes of canopy-shell's scripts/gen-tokens.mjs, which the package does not export. +const ZONES = ['white', 'g10', 'g90', 'g100']; +const MIN_ZONE_DECLARATIONS = 200; +const DECLARATION = /(--cds-[a-z0-9-]+):\s*([^;]+);/g; +const TYPE_READ = /var\(\s*(--cds-[a-z0-9-]+-font-(?:size|family))\b/g; + +/** The names declared by the `.cds-- { … }` theme blocks (small same-named rules skipped). */ +function zoneBlocks(zone: string): Set[] { + const block = new RegExp(`(?:^|\\})\\s*\\.cds--${zone}\\s*\\{([^{}]*)\\}`, 'gm'); + return [...css.matchAll(block)] + .map((match) => new Set([...match[1]!.matchAll(DECLARATION)].map((found) => found[1]!))) + .filter((names) => names.size >= MIN_ZONE_DECLARATIONS); +} + +describe('host contract coverage of Trace’s Carbon', () => { + it('wires exactly the tokens the four zone blocks declare', () => { + const blocks = ZONES.map(zoneBlocks); + expect(blocks.map((found) => found.length)).toEqual([1, 1, 1, 1]); + const declared = new Set(blocks.flatMap(([names]) => [...names!])); + expect([...declared].sort()).toEqual(Object.keys(wiring.zone).sort()); + }); + + it('wires every type token the stylesheet reads', () => { + const reads = [...new Set([...css.matchAll(TYPE_READ)].map((match) => match[1]!))]; + expect(reads.length).toBeGreaterThan(0); + expect(reads.filter((name) => !(name in wiring.type))).toEqual([]); + }); +}); diff --git a/src/App.anchor.test.tsx b/src/App.anchor.test.tsx new file mode 100644 index 0000000..8e29c28 --- /dev/null +++ b/src/App.anchor.test.tsx @@ -0,0 +1,89 @@ +// @vitest-environment jsdom +// +// The page root as a theming anchor: the main app's Carbon element +// carries the host-theme attributes, and a Carbon floating menu opened below it +// is portalled into it, not into , so it stays inside the themed subtree. +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { getColorMode } from '@slaclab/canopy-shell/color-mode'; +import { setHostTheme } from './state/colorMode'; + +// The real TraceApp's only overflow menu sits in a tool that is disabled until +// data loads; a bare menu under the real root tests the anchor itself. +vi.mock('./components/TraceApp', async () => { + const React = await import('react'); + const { OverflowMenu, OverflowMenuItem } = await import('@carbon/react'); + return { + TraceApp: () => + React.createElement(OverflowMenu, { + iconDescription: 'Export', + children: React.createElement(OverflowMenuItem, { itemText: 'Export CSV' }), + }), + }; +}); + +const { default: App } = await import('./App'); + +function anchors(): HTMLElement[] { + return Array.from(document.querySelectorAll('[data-canopy-host-root]')); +} + +/** The one anchor on the page, which must be the Carbon theme zone itself. */ +function anchor(): HTMLElement { + const found = anchors(); + expect(found.length).toBe(1); + return found[0]; +} + +function expectAnchor(el: HTMLElement, id: string): void { + expect(el.tagName).toBe('DIV'); + expect(el.getAttribute('data-canopy-host-root')).toBe(''); + expect(el.getAttribute('data-floating-menu-container')).toBe(''); + expect(el.getAttribute('data-theme')).toBe(id); +} + +function expectZone(el: HTMLElement): void { + const zone = getColorMode() === 'dark' ? 'cds--g100' : 'cds--g10'; + expect(el.classList.contains(zone)).toBe(true); + expect(el.style.height).toBe('100%'); +} + +afterEach(() => { + cleanup(); + act(() => setHostTheme(null, 'dark')); + vi.restoreAllMocks(); + localStorage.clear(); + delete document.documentElement.dataset.theme; + window.history.replaceState(null, '', '/'); +}); + +describe('main app root', () => { + it('standalone, the theme zone is the anchor and names the colour mode', () => { + render(); + const el = anchor(); + expectAnchor(el, getColorMode()); + expectZone(el); + }); + + it('carries the host theme id while the Carbon zone follows the mode', () => { + render(); + act(() => setHostTheme('retro-light', 'light')); + const el = anchor(); + expectAnchor(el, 'retro-light'); + expect(el.classList.contains('cds--g10')).toBe(true); + expect(el.classList.contains('cds--g100')).toBe(false); + + act(() => setHostTheme('retro-dark', 'dark')); + expectAnchor(anchor(), 'retro-dark'); + expect(anchor().classList.contains('cds--g100')).toBe(true); + }); + + it('opens overflow menu options inside the anchor', () => { + render(); + const el = anchor(); + fireEvent.click(screen.getByRole('button', { name: 'Export' })); + const option = screen.getByText('Export CSV'); + expect(el.contains(option)).toBe(true); + expect(option.closest('[data-floating-menu-container]')).toBe(el); + }); +}); diff --git a/src/App.tsx b/src/App.tsx index a01e0cd..6988ef5 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,13 +1,23 @@ -import { ColorModeTheme } from '@slaclab/canopy-shell'; +import { Theme } from '@carbon/react'; +import { useColorMode, useHostTheme } from '@slaclab/canopy-shell'; import { TraceApp } from './components/TraceApp'; +import { useHostThemeId } from './state/colorMode'; import './App.css'; export default function App() { // The SLAC standard page themes, from the canopy-shell color-mode store: g10 // in light mode, g100 in dark mode. The header follows the page theme. + const { colorMode, carbonTheme } = useColorMode(); + // The zone is also the host-theme anchor: it names the host's theme (the + // colour mode when standalone) and hosts Carbon's floating menus, so they + // open inside the themed subtree. + const { anchorRef, anchorProps } = useHostTheme( + useHostThemeId() ?? colorMode, + colorMode + ); return ( - + - + ); } diff --git a/src/api/connection.test.ts b/src/api/connection.test.ts index 47d3f95..8155988 100644 --- a/src/api/connection.test.ts +++ b/src/api/connection.test.ts @@ -1,5 +1,27 @@ -import { describe, expect, it } from 'vitest'; -import { canopyBaseUrl } from './connection'; +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { canopyFetch, listArchivers } from '@slaclab/canopy-client'; +import { canopyBaseUrl, canopyConnection } from './connection'; + +function okResponse(body: unknown): Response { + return new Response(JSON.stringify(body), { status: 200 }); +} + +function setBase(href: string | null) { + document.head.querySelectorAll('base').forEach((b) => b.remove()); + if (href !== null) { + const base = document.createElement('base'); + base.href = href; + document.head.appendChild(base); + } +} + +afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + setBase(null); + window.history.replaceState(null, '', '/'); +}); describe('canopyBaseUrl', () => { it('defaults to same-origin per-module paths', () => { @@ -13,4 +35,57 @@ describe('canopyBaseUrl', () => { expect(canopyBaseUrl('/trace/api/canopy/')).toBe('/trace/api/canopy'); expect(canopyBaseUrl(' /trace/api/canopy// ')).toBe('/trace/api/canopy'); }); + + it('is the parent of the document base when no prefix is configured', () => { + expect(canopyBaseUrl(undefined, 'http://h/x/y/trace/')).toBe('/x/y'); + expect(canopyBaseUrl('', 'http://h/x/y/trace/index.html')).toBe('/x/y'); + expect(canopyBaseUrl(undefined, 'http://h/')).toBe(''); + }); + + it('prefers the configured prefix over the derived one', () => { + expect(canopyBaseUrl('/trace/api/canopy', 'http://h/x/y/trace/')).toBe('/trace/api/canopy'); + }); + + it('stays same-origin for a page path that starts with //', () => { + expect(canopyBaseUrl(undefined, 'http://h//evil.example/x/')).toBe('/evil.example'); + }); +}); + +describe('canopyConnection', () => { + it('routes requests through the page directory, read at request time', async () => { + const fetchMock = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => okResponse({})); + window.history.replaceState(null, '', '/x/y/trace/'); + await canopyFetch(canopyConnection, '/mole/v1/pvs', { query: { q: 'TEST:*' } }); + expect(fetchMock.mock.calls[0][0]).toBe('/x/y/mole/v1/pvs?q=TEST%3A*'); + window.history.replaceState(null, '', '/'); + await listArchivers(canopyConnection); + expect(fetchMock.mock.calls[1][0]).toMatch(/^\/mole\/v1\//); + }); + + it('routes requests through VITE_CANOPY_BASE_PATH when the build sets it', async () => { + vi.stubEnv('VITE_CANOPY_BASE_PATH', '/trace/api/canopy'); + window.history.replaceState(null, '', '/trace/'); + const fetchMock = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => okResponse({})); + await canopyFetch(canopyConnection, '/mole/v1/pvs'); + expect(fetchMock.mock.calls[0][0]).toBe('/trace/api/canopy/mole/v1/pvs'); + }); + + it('refuses a request that would leave the origin', async () => { + vi.stubEnv('VITE_CANOPY_BASE_PATH', 'https://elsewhere.example/canopy'); + const fetchMock = vi.spyOn(globalThis, 'fetch'); + await expect(canopyFetch(canopyConnection, '/mole/v1/pvs')).rejects.toMatchObject({ + code: 'network_error', + detail: expect.stringContaining('Refused a request outside this origin'), + }); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('refuses a request when a names another origin', async () => { + setBase('https://elsewhere.example/x/trace/'); + const fetchMock = vi.spyOn(globalThis, 'fetch'); + await expect(canopyFetch(canopyConnection, '/mole/v1/pvs')).rejects.toMatchObject({ + code: 'network_error', + }); + expect(fetchMock).not.toHaveBeenCalled(); + }); }); diff --git a/src/api/connection.ts b/src/api/connection.ts index 642e871..0ff8428 100644 --- a/src/api/connection.ts +++ b/src/api/connection.ts @@ -1,18 +1,48 @@ -import type { CanopyConnection } from '@slaclab/canopy-client'; +import type { CanopyConnection, FetchLike } from '@slaclab/canopy-client'; // How the browser reaches Canopy. Always a same-origin path: the Vite dev proxy // (vite.config.ts) and Trace's reverse proxy in deployed builds forward it to // Canopy and inject X-API-Key, so the bundle never holds the key. // -// - '' (the local-dev default): per-module paths, /mole/..., /hare/..., /formula-engine/... -// - VITE_CANOPY_BASE_PATH, e.g. /trace/api/canopy: one prefix in front of them. -export function canopyBaseUrl(raw: string | undefined): string { - return (raw ?? '').trim().replace(/\/+$/, ''); +// - VITE_CANOPY_BASE_PATH, e.g. /trace/api/canopy: one prefix in front of the +// per-module paths. +// - Unset: the parent directory of the page. Trace served one directory below a +// gateway root (e.g. /x/y/trace/) reaches the modules as its siblings +// (/x/y/mole, /x/y/hare, /x/y/formula-engine); at the site root the prefix is +// empty, the per-module paths /mole/..., /hare/..., /formula-engine/... the +// dev proxy owns. +export function canopyBaseUrl(raw: string | undefined, documentBase?: string): string { + const configured = (raw ?? '').trim().replace(/\/+$/, ''); + if (configured || documentBase === undefined) return configured; + // Collapse leading slashes: a page at `//evil.example/x/` has that pathname, + // and as a prefix it would make every request protocol-relative, off-origin. + const parent = new URL('../', documentBase).pathname.replace(/^\/+/, '/'); + return parent.replace(/\/+$/, ''); } +// Every request stays on this origin: the proxy behind it injects the key. +// A URL that resolves elsewhere (a VITE_CANOPY_BASE_PATH naming another host, +// or a on another origin) is refused before it is sent. +export const sameOriginFetch: FetchLike = (url, init) => { + if ( + typeof document !== 'undefined' && + new URL(url, document.baseURI).origin !== window.location.origin + ) { + return Promise.reject(new Error(`Refused a request outside this origin: ${url}`)); + } + return globalThis.fetch(url, init as RequestInit); +}; + // The connection every Canopy call goes through. React code reads it from // (main.tsx) with useCanopyConnection(); the module-level // stores (archiveStore, liveStore) live outside React and import it directly. +// The base is read at each request, against the document as it is then. export const canopyConnection: CanopyConnection = { - baseUrl: canopyBaseUrl(import.meta.env.VITE_CANOPY_BASE_PATH as string | undefined), + get baseUrl() { + return canopyBaseUrl( + import.meta.env.VITE_CANOPY_BASE_PATH as string | undefined, + typeof document === 'undefined' ? undefined : document.baseURI + ); + }, + fetch: sameOriginFetch, }; diff --git a/src/bootstrap.test.ts b/src/bootstrap.test.ts new file mode 100644 index 0000000..b0a8054 --- /dev/null +++ b/src/bootstrap.test.ts @@ -0,0 +1,51 @@ +// The page start shared by every entry: stylesheet order, then the host-sheet +// fallback, the colour mode, then the bridge when embedded. + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import bootstrapRaw from './bootstrap.ts?raw'; + +const calls: string[] = []; +const embedded = { value: false }; + +vi.mock('@slaclab/canopy-shell', () => ({ + applyHostSheetFallback: () => calls.push('applyHostSheetFallback'), +})); +vi.mock('./embed/embedded', () => ({ isEmbedded: () => embedded.value })); +vi.mock('./state/colorMode', () => ({ setupColorMode: () => calls.push('setupColorMode') })); +vi.mock('./embed/bridge', () => ({ installBridge: () => calls.push('installBridge') })); + +async function runBootstrap(isEmbedded: boolean): Promise { + calls.length = 0; + embedded.value = isEmbedded; + vi.resetModules(); + await import('./bootstrap'); + return [...calls]; +} + +afterEach(() => { + embedded.value = false; +}); + +describe('bootstrap', () => { + it('imports Carbon, the shell styles, its host-contract sheet, then the app chrome', () => { + const sheets = [...bootstrapRaw.matchAll(/^import\s+'([^']+)';$/gm)].map((m) => m[1]); + expect(sheets).toEqual([ + './index.scss', + '@slaclab/canopy-shell/styles.css', + '@slaclab/canopy-shell/host-contract.css', + './index.css', + ]); + }); + + it('applies the host-sheet fallback and the colour mode, no bridge, when standalone', async () => { + expect(await runBootstrap(false)).toEqual(['applyHostSheetFallback', 'setupColorMode']); + }); + + it('applies the fallback first and installs the bridge last when embedded', async () => { + expect(await runBootstrap(true)).toEqual([ + 'applyHostSheetFallback', + 'setupColorMode', + 'installBridge', + ]); + }); +}); diff --git a/src/bootstrap.ts b/src/bootstrap.ts new file mode 100644 index 0000000..9c54c2e --- /dev/null +++ b/src/bootstrap.ts @@ -0,0 +1,25 @@ +// The shared start of every page entry. Each entry imports this module first, +// so it runs before any app module is evaluated. +// +// Stylesheet order: Carbon (compiled from Sass, self-hosted IBM Plex), the +// shell's styles, the shell's host-contract sheet, then the app's own chrome, +// so chrome rules can still override the contract. +import './index.scss'; +import '@slaclab/canopy-shell/styles.css'; +import '@slaclab/canopy-shell/host-contract.css'; +import './index.css'; +import { applyHostSheetFallback } from '@slaclab/canopy-shell'; +import { installBridge } from './embed/bridge'; +import { isEmbedded } from './embed/embedded'; +import { setupColorMode } from './state/colorMode'; + +// First: a host stylesheet that failed to load must not leave the page gated +// on host values it never delivered. +applyHostSheetFallback(); + +// Before the first render: read the stored (or, embedded, the host's) theme +// and paint to match. +setupColorMode(); + +// Before the first render, so a host message sent on trace-ready is not lost. +if (isEmbedded()) installBridge(); diff --git a/src/components/DetachedWindow.blocked.test.tsx b/src/components/DetachedWindow.blocked.test.tsx new file mode 100644 index 0000000..7b1e8e6 --- /dev/null +++ b/src/components/DetachedWindow.blocked.test.tsx @@ -0,0 +1,55 @@ +// @vitest-environment jsdom +// +// Pins issue 116: when the browser blocks the pop-up, DetachedWindow must tell +// its parent (onBlocked) as well as reattaching (onClose), so the user can be +// told why nothing opened. +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, render, waitFor } from '@testing-library/react'; +import { DetachedWindow } from './DetachedWindow'; + +// A stand-in pop-up: a separate document plus the Window members DetachedWindow uses. +function fakePopup() { + const doc = document.implementation.createHTMLDocument('popup'); + return { + document: doc, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + close: vi.fn(), + } as unknown as Window; +} + +describe('DetachedWindow', () => { + afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + }); + + it('reports a blocked pop-up and reattaches', () => { + vi.spyOn(window, 'open').mockReturnValue(null); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const onBlocked = vi.fn(); + const onClose = vi.fn(); + render( + + plot + + ); + expect(onBlocked).toHaveBeenCalledTimes(1); + expect(onClose).toHaveBeenCalledTimes(1); + }); + + it('does not report a block when the pop-up opens', async () => { + const popup = fakePopup(); + vi.spyOn(window, 'open').mockReturnValue(popup); + const onBlocked = vi.fn(); + const onClose = vi.fn(); + render( + + plot + + ); + await waitFor(() => expect(popup.document.body.textContent).toContain('plot')); + expect(onBlocked).not.toHaveBeenCalled(); + expect(onClose).not.toHaveBeenCalled(); + }); +}); diff --git a/src/components/DetachedWindow.test.tsx b/src/components/DetachedWindow.test.tsx index 7b1e8e6..8d7231a 100644 --- a/src/components/DetachedWindow.test.tsx +++ b/src/components/DetachedWindow.test.tsx @@ -1,55 +1,236 @@ // @vitest-environment jsdom // -// Pins issue 116: when the browser blocks the pop-up, DetachedWindow must tell -// its parent (onBlocked) as well as reattaching (onClose), so the user can be -// told why nothing opened. -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render, waitFor } from '@testing-library/react'; -import { DetachedWindow } from './DetachedWindow'; - -// A stand-in pop-up: a separate document plus the Window members DetachedWindow uses. -function fakePopup() { - const doc = document.implementation.createHTMLDocument('popup'); - return { - document: doc, - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - close: vi.fn(), - } as unknown as Window; -} - -describe('DetachedWindow', () => { - afterEach(() => { - cleanup(); - vi.restoreAllMocks(); +// A plot detached into its own browser window keeps the host theme of its +// opener. The popup is a real second jsdom window handed out by window.open, +// and the plot is detached through the app's own "Detach to window" button, so +// the popup root under test is the one TraceApp renders. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { JSDOM } from 'jsdom'; +import { WithCanopy } from '../test/canopy'; +import { setHostTheme } from '../state/colorMode'; + +vi.mock('echarts-for-react', async () => { + const React = await import('react'); + const fakeInstance = { + getWidth: () => 800, + getHeight: () => 400, + isDisposed: () => false, + getZr: () => ({ setCursorStyle: () => {}, on: () => {}, off: () => {} }), + getModel: () => null, + convertToPixel: () => 0, + convertFromPixel: () => 0, + getDataURL: () => '', + resize: () => {}, + dispatchAction: () => {}, + on: () => {}, + off: () => {}, + }; + class MockECharts extends React.Component { + getEchartsInstance() { + return fakeInstance; + } + render() { + return React.createElement('div'); + } + } + return { default: MockECharts }; +}); + +import { TraceApp } from './TraceApp'; + +class NoopResizeObserver { + observe() {} + unobserve() {} + disconnect() {} +} + +class InertWebSocket { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + static readonly CLOSING = 2; + static readonly CLOSED = 3; + readyState = 0; + onopen: (() => void) | null = null; + onmessage: ((ev: { data: string }) => void) | null = null; + onclose: (() => void) | null = null; + onerror: (() => void) | null = null; + send() {} + close() { + this.readyState = 3; + } + addEventListener() {} + removeEventListener() {} +} + +const OPENER_BACKGROUND = 'rgb(18, 52, 86)'; +const SHEET_HREF = 'http://localhost:3000/host/adapter.css'; + +let popup: Window; +let warn: ReturnType; +const added: Element[] = []; + +beforeEach(() => { + vi.stubGlobal('ResizeObserver', NoopResizeObserver); + vi.stubGlobal( + 'matchMedia', + (query: string) => + ({ + matches: false, + media: query, + onchange: null, + addListener: () => {}, + removeListener: () => {}, + addEventListener: () => {}, + removeEventListener: () => {}, + dispatchEvent: () => false, + }) as MediaQueryList + ); + vi.stubGlobal( + 'fetch', + vi.fn(() => new Promise(() => {})) + ); + vi.stubGlobal('WebSocket', InertWebSocket); + + popup = new JSDOM('', { + url: location.href, + }).window as unknown as Window; + vi.spyOn(window, 'open').mockReturnValue(popup); + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); +}); + +afterEach(() => { + cleanup(); + act(() => setHostTheme(null, 'dark')); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + localStorage.clear(); + for (const el of added.splice(0)) el.remove(); + delete document.documentElement.dataset.theme; + delete document.documentElement.dataset.canopyHost; + document.body.style.background = ''; + window.history.replaceState(null, '', '/'); +}); + +/** Mark the opener as hosted, the way canopy_mcp's entry page does. */ +function hostOpener(): void { + document.documentElement.dataset.canopyHost = ''; +} + +/** A host stylesheet link in the opener's head. */ +function addHostSheet(): void { + const link = document.createElement('link'); + link.rel = 'stylesheet'; + link.href = SHEET_HREF; + link.setAttribute('data-canopy-host-sheet', ''); + document.head.appendChild(link); + added.push(link); +} + +/** Open the app and detach its one plot; cloned stylesheets are still loading. */ +function detach(): void { + window.history.replaceState(null, '', '/trace/'); + render(, { wrapper: WithCanopy }); + fireEvent.click(screen.getByTitle('Detach to window')); +} + +/** Let the stylesheet promise settle so the popup root mounts. */ +async function settle(): Promise { + await act(async () => { + await Promise.resolve(); + await Promise.resolve(); }); +} - it('reports a blocked pop-up and reattaches', () => { - vi.spyOn(window, 'open').mockReturnValue(null); - vi.spyOn(console, 'warn').mockImplementation(() => {}); - const onBlocked = vi.fn(); - const onClose = vi.fn(); - render( - - plot - - ); - expect(onBlocked).toHaveBeenCalledTimes(1); - expect(onClose).toHaveBeenCalledTimes(1); +function popupAnchor(): HTMLElement { + const found = popup.document.querySelectorAll('[data-canopy-host-root]'); + expect(found.length).toBe(1); + return found[0]; +} + +function fallbackWarnings(): unknown[][] { + return warn.mock.calls.filter((c: unknown[]) => + String(c[0]).includes('host stylesheet did not load') + ); +} + +describe('detached plot window', () => { + it('copies the host marker from a hosted opener', async () => { + hostOpener(); + detach(); + expect(popup.document.documentElement.getAttribute('data-canopy-host')).toBe(''); + await settle(); + expect(popup.document.documentElement.getAttribute('data-canopy-host')).toBe(''); + expect(fallbackWarnings()).toEqual([]); + }); + + it('leaves the popup unmarked when the opener carries no host marker', async () => { + detach(); + await settle(); + expect(popup.document.documentElement.hasAttribute('data-canopy-host')).toBe(false); + expect(warn).not.toHaveBeenCalled(); + }); + + it('makes the popup root the host-theme anchor', async () => { + detach(); + await settle(); + const el = popupAnchor(); + expect(el.tagName).toBe('DIV'); + expect(el.getAttribute('data-canopy-host-root')).toBe(''); + expect(el.getAttribute('data-floating-menu-container')).toBe(''); + expect(el.getAttribute('data-theme')).toBe('dark'); + expect(el.classList.contains('cds--g100')).toBe(true); + expect(el.style.height).toBe('100vh'); + + act(() => setHostTheme('retro-light', 'light')); + expect(popupAnchor().getAttribute('data-theme')).toBe('retro-light'); + expect(popupAnchor().classList.contains('cds--g10')).toBe(true); + }); + + it('keeps the popup html[data-theme] on the colour mode across a flip', async () => { + detach(); + await settle(); + expect(popup.document.documentElement.dataset.theme).toBe('dark'); + + act(() => setHostTheme('retro-light', 'light')); + expect(popup.document.documentElement.dataset.theme).toBe('light'); + + act(() => setHostTheme('retro-dark', 'dark')); + expect(popup.document.documentElement.dataset.theme).toBe('dark'); + }); + + it("paints the popup body with the opener's background before styles load", async () => { + document.body.style.background = OPENER_BACKGROUND; + addHostSheet(); + detach(); + // The cloned link has not loaded: the root is not mounted yet. + expect(popup.document.querySelector('[data-canopy-host-root]')).toBeNull(); + expect(popup.document.body.style.backgroundColor).toBe(OPENER_BACKGROUND); + expect(getComputedStyle(document.body).backgroundColor).toBe(OPENER_BACKGROUND); }); - it('does not report a block when the pop-up opens', async () => { - const popup = fakePopup(); - vi.spyOn(window, 'open').mockReturnValue(popup); - const onBlocked = vi.fn(); - const onClose = vi.fn(); - render( - - plot - + it('falls back to the standalone theme when the cloned host sheet is dead', async () => { + hostOpener(); + addHostSheet(); + detach(); + expect(popup.document.documentElement.hasAttribute('data-canopy-host')).toBe(true); + + const clone = popup.document.head.querySelector( + 'link[data-canopy-host-sheet]' ); - await waitFor(() => expect(popup.document.body.textContent).toContain('plot')); - expect(onBlocked).not.toHaveBeenCalled(); - expect(onClose).not.toHaveBeenCalled(); + expect(clone).not.toBeNull(); + Object.defineProperty(clone, 'sheet', { value: { cssRules: [] }, configurable: true }); + clone!.dispatchEvent(new Event('load')); + await settle(); + + expect(popup.document.documentElement.hasAttribute('data-canopy-host')).toBe(false); + // Only the popup falls back; the opener's own sheet state is its own. + expect(document.documentElement.hasAttribute('data-canopy-host')).toBe(true); + expect(fallbackWarnings().length).toBe(1); + expect(String(fallbackWarnings()[0][0])).toContain(SHEET_HREF); + // The marker was cleared before the root mounted, so the root is in place + // and reads no host contract. + expect(popupAnchor().getAttribute('data-theme')).toBe('dark'); + expect(warn.mock.calls.length).toBe(1); }); }); diff --git a/src/components/DetachedWindow.tsx b/src/components/DetachedWindow.tsx index f964056..f241e9e 100644 --- a/src/components/DetachedWindow.tsx +++ b/src/components/DetachedWindow.tsx @@ -1,5 +1,6 @@ import { useEffect, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; +import { applyHostSheetFallback } from '@slaclab/canopy-shell'; interface DetachedWindowProps { /** Stable window name; reused so re-opening targets the same browsing context. */ @@ -77,6 +78,13 @@ export function DetachedWindow({ /^cds--(white|g10|g90|g100)$/.test(c) ); if (carbonTheme) popup.document.documentElement.classList.add(carbonTheme); + // A hosted opener hands its marker on; one that already fell back to the + // standalone theme (its host stylesheet did not load) has none to hand on. + const hostMarker = document.documentElement.dataset.canopyHost; + if (hostMarker !== undefined) popup.document.documentElement.dataset.canopyHost = hostMarker; + // The body lies outside every theme zone, and its colour shows until the + // cloned stylesheets load: start from the opener's. + popup.document.body.style.background = getComputedStyle(document.body).backgroundColor; const mount = popup.document.createElement('div'); mount.style.height = '100vh'; @@ -88,6 +96,9 @@ export function DetachedWindow({ // The user may have closed the popup or reattached before stylesheets // resolved — don't mount into a torn-down window. if (cancelled) return; + // A host stylesheet that did not load in this window drops the marker + // here, before the root mounts and reads the host contract. + applyHostSheetFallback(popup.document); setContainer(mount); }); diff --git a/src/components/TraceApp.tsx b/src/components/TraceApp.tsx index be65200..99ad003 100644 --- a/src/components/TraceApp.tsx +++ b/src/components/TraceApp.tsx @@ -7,7 +7,7 @@ import { usePanelRef, } from 'react-resizable-panels'; import { Close, Login, ChevronUp } from '@carbon/icons-react'; -import { ToastNotification } from '@carbon/react'; +import { Theme, ToastNotification } from '@carbon/react'; import type { Plot, PVTrace, Axis } from '../types'; import { LeftPanel } from './LeftPanel'; import { DetachedWindow } from './DetachedWindow'; @@ -26,7 +26,8 @@ import type { TimeWindowNs } from '../api/time'; import { resolveTimeWindow } from '../api/time'; import { fetchMetadata } from '@slaclab/canopy-client'; import { useCanopyConnection } from '@slaclab/canopy-react'; -import { ColorModeTheme, ErrorBoundary, useColorMode } from '@slaclab/canopy-shell'; +import { ErrorBoundary, useColorMode, useHostTheme } from '@slaclab/canopy-shell'; +import { useHostThemeId } from '../state/colorMode'; import { chartThemeFor } from '@slaclab/canopy-charts'; import { usePaletteId } from '../state/paletteStore'; import { getPalette, colorForIndex } from '../palettes'; @@ -90,6 +91,30 @@ export type SelectedItem = { plotId: string; } | null; +/** + * The root of a detached window: the Carbon theme zone, which is also the + * host-theme anchor of that window's document. Rendered inside the + * DetachedWindow portal, so the anchor lives in the popup. + */ +function DetachedRoot({ + style, + children, +}: { + style: React.CSSProperties; + children: React.ReactNode; +}) { + const { colorMode, carbonTheme } = useColorMode(); + const { anchorRef, anchorProps } = useHostTheme( + useHostThemeId() ?? colorMode, + colorMode + ); + return ( + + {children} + + ); +} + export function TraceApp() { const canopy = useCanopyConnection(); const [plots, setPlots] = useState(INITIAL_PLOTS); @@ -146,7 +171,8 @@ export function TraceApp() { // Per-plot "now". A following plot's anchor advances once per its refresh // interval; any other plot's anchor holds, which freezes its window. - const clock = useAutoScrollTimers(plots, viewWindowByPlot); + const anyDetached = detachedPlotIds.length > 0 || (insight.open && insight.detached); + const clock = useAutoScrollTimers(plots, viewWindowByPlot, anyDetached); const activePlot = plots.find((p) => p.id === activePlotId) ?? plots[0]; @@ -1196,7 +1222,7 @@ export function TraceApp() { onBlocked={() => setBlockedPopup(plot.title || 'This plot')} onClose={() => reattachPlot(id)} > - handleChartInstance(plot.id, inst, active)} />
- + ); })} @@ -1269,7 +1295,7 @@ export function TraceApp() { onBlocked={() => setBlockedPopup('Data Insight')} onClose={() => setInsight((p) => ({ ...p, detached: false }))} > - setInsight((p) => ({ ...p, open: false, detached: false }))} onReattach={() => setInsight((p) => ({ ...p, detached: false }))} /> - + )} diff --git a/src/embed/bridge.test.ts b/src/embed/bridge.test.ts new file mode 100644 index 0000000..cefe204 --- /dev/null +++ b/src/embed/bridge.test.ts @@ -0,0 +1,386 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +// The bridge, the shell's colour-mode store and Trace's host theme keep +// module-level state, so every test sets the URL first, imports fresh copies +// and runs the page's colour-mode setup. +type Bridge = typeof import('./bridge'); +type Shell = typeof import('@slaclab/canopy-shell/color-mode'); +type Host = typeof import('../state/colorMode'); +type Theme = Pick & + Pick & { subscribeTheme: Host['subscribeHostThemeId'] }; + +async function load(search: string): Promise<{ bridge: Bridge; theme: Theme }> { + window.history.replaceState(null, '', `/${search}`); + vi.resetModules(); + const shell = await import('@slaclab/canopy-shell/color-mode'); + const host = await import('../state/colorMode'); + host.setupColorMode(); + const bridge = await import('./bridge'); + const theme: Theme = { + getColorMode: shell.getColorMode, + setColorMode: shell.setColorMode, + toggleColorMode: shell.toggleColorMode, + getHostThemeId: host.getHostThemeId, + subscribeTheme: host.subscribeHostThemeId, + }; + return { bridge, theme }; +} + +function fromParent(data: unknown, origin = location.origin): void { + window.dispatchEvent(new MessageEvent('message', { data, origin, source: window.parent })); +} + +let uninstall: (() => void) | undefined; + +beforeEach(() => { + window.localStorage.clear(); +}); + +afterEach(() => { + uninstall?.(); + uninstall = undefined; + vi.restoreAllMocks(); + vi.useRealTimers(); + window.localStorage.clear(); + window.history.replaceState(null, '', '/'); +}); + +describe('installBridge', () => { + it('posts trace-ready to the parent after the listener is installed', async () => { + const { bridge } = await load('?embedded=true'); + const order: string[] = []; + const original = window.addEventListener.bind(window); + const addSpy = vi + .spyOn(window, 'addEventListener') + .mockImplementation((...args: Parameters) => { + if (args[0] === 'message') order.push('listen'); + original(...args); + }); + const post = vi.spyOn(window.parent, 'postMessage').mockImplementation(() => { + order.push('ready'); + }); + uninstall = bridge.installBridge(); + expect(addSpy).toHaveBeenCalledWith('message', expect.any(Function)); + expect(post).toHaveBeenCalledTimes(1); + expect(post).toHaveBeenCalledWith({ type: 'canopy:trace-ready' }, location.origin); + expect(order).toEqual(['listen', 'ready']); + }); + + it('installs nothing and posts nothing when not embedded', async () => { + const { bridge } = await load(''); + const addSpy = vi.spyOn(window, 'addEventListener'); + const post = vi.spyOn(window.parent, 'postMessage').mockImplementation(() => {}); + uninstall = bridge.installBridge(); + expect(addSpy.mock.calls.filter((c) => c[0] === 'message')).toHaveLength(0); + expect(post).not.toHaveBeenCalled(); + fromParent({ type: 'canopy:trace-visibility', visible: false }); + expect(bridge.getSnapshot().visible).toBe(true); + }); + + it('installs one listener even when called twice', async () => { + const { bridge } = await load('?embedded=true'); + const addSpy = vi.spyOn(window, 'addEventListener'); + vi.spyOn(window.parent, 'postMessage').mockImplementation(() => {}); + uninstall = bridge.installBridge(); + bridge.installBridge(); + expect(addSpy.mock.calls.filter((c) => c[0] === 'message')).toHaveLength(1); + }); +}); + +describe('bridge snapshot', () => { + async function installed(search = '?embedded=true'): Promise<{ bridge: Bridge; theme: Theme }> { + const mods = await load(search); + vi.spyOn(window.parent, 'postMessage').mockImplementation(() => {}); + uninstall = mods.bridge.installBridge(); + return mods; + } + + it('defaults to visible with no hiddenAt and no mode', async () => { + const { bridge } = await installed(); + expect(bridge.getSnapshot()).toEqual({ visible: true }); + }); + + it('ignores a message from a foreign source', async () => { + const { bridge } = await installed(); + const other = { postMessage: () => {} } as unknown as Window; + window.dispatchEvent( + new MessageEvent('message', { + data: { type: 'canopy:trace-visibility', visible: false }, + origin: location.origin, + source: other as MessageEventSource, + }) + ); + expect(bridge.getSnapshot().visible).toBe(true); + }); + + it('ignores a message from a foreign origin', async () => { + const { bridge } = await installed(); + fromParent({ type: 'canopy:trace-visibility', visible: false }, 'http://evil.example'); + expect(bridge.getSnapshot().visible).toBe(true); + }); + + it("ignores a mode other than the two literals (mode:'blue')", async () => { + const { bridge, theme } = await installed(); + const listener = vi.fn(); + bridge.subscribe(listener); + const before = theme.getColorMode(); + fromParent({ type: 'canopy:trace-theme', mode: 'blue' }); + expect(bridge.getSnapshot().mode).toBeUndefined(); + expect(theme.getColorMode()).toBe(before); + expect(listener).not.toHaveBeenCalled(); + }); + + it('ignores malformed payloads', async () => { + const { bridge } = await installed(); + const listener = vi.fn(); + bridge.subscribe(listener); + for (const data of [ + null, + 'x', + 42, + {}, + { type: 'canopy:trace-visibility' }, + { type: 'canopy:trace-visibility', visible: 'false' }, + { type: 'other', visible: false }, + ]) { + fromParent(data); + } + expect(bridge.getSnapshot()).toEqual({ visible: true }); + expect(listener).not.toHaveBeenCalled(); + }); + + it('a message before subscribe reaches a later subscriber', async () => { + const { bridge } = await installed(); + fromParent({ type: 'canopy:trace-visibility', visible: false }); + fromParent({ type: 'canopy:trace-theme', mode: 'light' }); + const listener = vi.fn(); + bridge.subscribe(listener); + const snap = bridge.getSnapshot(); + expect(snap.visible).toBe(false); + expect(snap.mode).toBe('light'); + expect(typeof snap.hiddenAt).toBe('number'); + }); + + it('notifies subscribers and stops after unsubscribe', async () => { + const { bridge } = await installed(); + const listener = vi.fn(); + const unsubscribe = bridge.subscribe(listener); + fromParent({ type: 'canopy:trace-visibility', visible: false }); + expect(listener).toHaveBeenCalledTimes(1); + unsubscribe(); + fromParent({ type: 'canopy:trace-visibility', visible: true }); + expect(listener).toHaveBeenCalledTimes(1); + }); + + it('stamps hiddenAt on visible->hidden and a repeated hidden message keeps it', async () => { + vi.useFakeTimers(); + vi.setSystemTime(1_000_000); + const { bridge } = await installed(); + const listener = vi.fn(); + bridge.subscribe(listener); + fromParent({ type: 'canopy:trace-visibility', visible: false }); + const first = bridge.getSnapshot(); + expect(first).toEqual({ visible: false, hiddenAt: 1_000_000 }); + + vi.setSystemTime(1_060_000); + fromParent({ type: 'canopy:trace-visibility', visible: false }); + expect(bridge.getSnapshot().hiddenAt).toBe(1_000_000); + // Unchanged state keeps the same reference, as useSyncExternalStore needs. + expect(bridge.getSnapshot()).toBe(first); + expect(listener).toHaveBeenCalledTimes(1); + + fromParent({ type: 'canopy:trace-visibility', visible: true }); + expect(bridge.getSnapshot()).toEqual({ visible: true }); + + vi.setSystemTime(2_000_000); + fromParent({ type: 'canopy:trace-visibility', visible: false }); + expect(bridge.getSnapshot().hiddenAt).toBe(2_000_000); + }); + + it('getSnapshot is stable between calls', async () => { + const { bridge } = await installed(); + expect(bridge.getSnapshot()).toBe(bridge.getSnapshot()); + }); +}); + +describe('embedded theme', () => { + it("takes the initial mode from ?theme= and leaves Trace's stored choice alone", async () => { + window.localStorage.setItem('trace.theme', 'dark'); + const getItem = vi.spyOn(Storage.prototype, 'getItem'); + const setItem = vi.spyOn(Storage.prototype, 'setItem'); + const { theme } = await load('?embedded=true&theme=light'); + expect(theme.getColorMode()).toBe('light'); + theme.toggleColorMode(); + theme.setColorMode('light'); + // The hosted store runs under its own key; Trace's key stays untouched. + expect(getItem).not.toHaveBeenCalledWith('trace.theme'); + expect(setItem).not.toHaveBeenCalledWith('trace.theme', expect.anything()); + expect(window.localStorage.getItem('trace.theme')).toBe('dark'); + }); + + it("follows the bridge theme and leaves Trace's stored choice alone", async () => { + const { bridge, theme } = await load('?embedded=true&theme=dark'); + const setItem = vi.spyOn(Storage.prototype, 'setItem'); + const getItem = vi.spyOn(Storage.prototype, 'getItem'); + vi.spyOn(window.parent, 'postMessage').mockImplementation(() => {}); + uninstall = bridge.installBridge(); + expect(theme.getColorMode()).toBe('dark'); + fromParent({ type: 'canopy:trace-theme', mode: 'light' }); + expect(theme.getColorMode()).toBe('light'); + expect(bridge.getSnapshot().mode).toBe('light'); + expect(setItem).not.toHaveBeenCalled(); + expect(getItem).not.toHaveBeenCalledWith('trace.theme'); + expect(window.localStorage.getItem('trace.theme')).toBeNull(); + }); + + it('ignores an invalid ?theme= when embedded and falls back to the default', async () => { + const { theme } = await load('?embedded=true&theme=../x'); + expect(theme.getColorMode()).toBe('dark'); + expect(theme.getHostThemeId()).toBeNull(); + }); + + it('has no host theme id without ?theme=', async () => { + const { theme } = await load('?embedded=true'); + expect(theme.getHostThemeId()).toBeNull(); + }); + + it('takes the host theme id from a theme message', async () => { + const { bridge, theme } = await load('?embedded=true'); + vi.spyOn(window.parent, 'postMessage').mockImplementation(() => {}); + uninstall = bridge.installBridge(); + fromParent({ type: 'canopy:trace-theme', mode: 'dark', theme: 'retro-dark' }); + expect(theme.getHostThemeId()).toBe('retro-dark'); + expect(theme.getColorMode()).toBe('dark'); + expect(bridge.getSnapshot().mode).toBe('dark'); + }); + + it('drops an invalid theme id from a theme message but keeps its mode', async () => { + const { bridge, theme } = await load('?embedded=true&theme=retro-dark'); + vi.spyOn(window.parent, 'postMessage').mockImplementation(() => {}); + uninstall = bridge.installBridge(); + expect(theme.getHostThemeId()).toBe('retro-dark'); + fromParent({ type: 'canopy:trace-theme', mode: 'light', theme: '../x' }); + expect(theme.getHostThemeId()).toBeNull(); + expect(theme.getColorMode()).toBe('light'); + }); + + it('clears the host theme id on a theme message without one, or with a non-string', async () => { + const { bridge, theme } = await load('?embedded=true&theme=retro-dark'); + vi.spyOn(window.parent, 'postMessage').mockImplementation(() => {}); + uninstall = bridge.installBridge(); + fromParent({ type: 'canopy:trace-theme', mode: 'dark' }); + expect(theme.getHostThemeId()).toBeNull(); + fromParent({ type: 'canopy:trace-theme', mode: 'dark', theme: 'desy-dark' }); + expect(theme.getHostThemeId()).toBe('desy-dark'); + // `RegExp.test(null)` is true (it tests the string 'null'): must not leak. + fromParent({ type: 'canopy:trace-theme', mode: 'dark', theme: null }); + expect(theme.getHostThemeId()).toBeNull(); + }); + + it('same-mode id change updates hostThemeId', async () => { + const { bridge, theme } = await load('?embedded=true'); + vi.spyOn(window.parent, 'postMessage').mockImplementation(() => {}); + uninstall = bridge.installBridge(); + fromParent({ type: 'canopy:trace-theme', mode: 'dark', theme: 'desy-dark' }); + expect(theme.getHostThemeId()).toBe('desy-dark'); + const listener = vi.fn(); + theme.subscribeTheme(listener); + fromParent({ type: 'canopy:trace-theme', mode: 'dark', theme: 'retro-dark' }); + expect(theme.getHostThemeId()).toBe('retro-dark'); + expect(theme.getColorMode()).toBe('dark'); + expect(listener).toHaveBeenCalledTimes(1); + }); + + it('keeps using localStorage when not embedded', async () => { + window.localStorage.setItem('trace.theme', 'light'); + const { theme } = await load('?theme=dark'); + expect(theme.getColorMode()).toBe('light'); + theme.setColorMode('dark'); + expect(window.localStorage.getItem('trace.theme')).toBe('dark'); + }); +}); + +describe('everVisible latch', () => { + async function installed(): Promise { + const { bridge } = await load('?embedded=true'); + vi.spyOn(window.parent, 'postMessage').mockImplementation(() => {}); + uninstall = bridge.installBridge(); + return bridge; + } + + it('starts unset although the snapshot starts visible', async () => { + const bridge = await installed(); + expect(bridge.getSnapshot().visible).toBe(true); + expect(bridge.getEverVisible()).toBe(false); + }); + + it('latches only on visible:true, never on visible:false or a theme', async () => { + const bridge = await installed(); + const latch = vi.fn(); + bridge.subscribeEverVisible(latch); + fromParent({ type: 'canopy:trace-visibility', visible: false }); + fromParent({ type: 'canopy:trace-theme', mode: 'light' }); + fromParent({ type: 'canopy:trace-visibility', visible: 'true' }); + expect(bridge.getEverVisible()).toBe(false); + expect(latch).not.toHaveBeenCalled(); + fromParent({ type: 'canopy:trace-visibility', visible: true }); + expect(bridge.getEverVisible()).toBe(true); + expect(latch).toHaveBeenCalledTimes(1); + }); + + it('latches on a visible:true that does not change the snapshot', async () => { + const bridge = await installed(); + const snapshotListener = vi.fn(); + bridge.subscribe(snapshotListener); + const before = bridge.getSnapshot(); + fromParent({ type: 'canopy:trace-visibility', visible: true }); + expect(bridge.getEverVisible()).toBe(true); + // Trace's snapshot behaviour is unchanged: no new snapshot, no notify. + expect(bridge.getSnapshot()).toBe(before); + expect(snapshotListener).not.toHaveBeenCalled(); + }); + + it('visible:true, then hidden, then visible again keeps it set', async () => { + const bridge = await installed(); + const latch = vi.fn(); + bridge.subscribeEverVisible(latch); + fromParent({ type: 'canopy:trace-visibility', visible: true }); + fromParent({ type: 'canopy:trace-visibility', visible: false }); + expect(bridge.getEverVisible()).toBe(true); + expect(bridge.getSnapshot().visible).toBe(false); + fromParent({ type: 'canopy:trace-visibility', visible: true }); + expect(bridge.getEverVisible()).toBe(true); + expect(latch).toHaveBeenCalledTimes(1); + }); + + it('is never part of the snapshot', async () => { + const bridge = await installed(); + fromParent({ type: 'canopy:trace-visibility', visible: true }); + fromParent({ type: 'canopy:trace-visibility', visible: false }); + fromParent({ type: 'canopy:trace-theme', mode: 'dark' }); + fromParent({ type: 'canopy:trace-visibility', visible: true }); + expect(bridge.getSnapshot()).toEqual({ visible: true, mode: 'dark' }); + }); + + it('ignores a visible:true from a foreign origin or when not embedded', async () => { + const bridge = await installed(); + fromParent({ type: 'canopy:trace-visibility', visible: true }, 'http://evil.example'); + expect(bridge.getEverVisible()).toBe(false); + + const { bridge: standalone } = await load(''); + uninstall?.(); + uninstall = standalone.installBridge(); + fromParent({ type: 'canopy:trace-visibility', visible: true }); + expect(standalone.getEverVisible()).toBe(false); + }); + + it('stops notifying after unsubscribe', async () => { + const bridge = await installed(); + const latch = vi.fn(); + bridge.subscribeEverVisible(latch)(); + fromParent({ type: 'canopy:trace-visibility', visible: true }); + expect(latch).not.toHaveBeenCalled(); + expect(bridge.getEverVisible()).toBe(true); + }); +}); diff --git a/src/embed/bridge.ts b/src/embed/bridge.ts new file mode 100644 index 0000000..cc40a3a --- /dev/null +++ b/src/embed/bridge.ts @@ -0,0 +1,134 @@ +// The message bridge between Trace and the page that embeds it (the CANOPY +// workspace). One `message` listener, installed only when `?embedded=true`, +// accepts messages solely from `window.parent` on our own origin: +// +// {type:'canopy:trace-visibility', visible: boolean} +// {type:'canopy:trace-theme', mode: 'light' | 'dark', theme?: string} +// +// Anything else is ignored. Once the listener is in place Trace posts +// `{type:'canopy:trace-ready'}` to the parent so the host knows it can send +// its current state. +// +// The last visibility and theme live in a small external store for +// useSyncExternalStore. `hiddenAt` is stamped only on a visible->hidden +// transition, so a repeated hidden message keeps the original time; consumers +// use it as the frozen "now" while the tab is hidden. A theme message is also +// applied to the colour-mode store (state/colorMode.ts; embedded, it never touches the standalone choice): its +// `mode`, and its `theme` as the host theme id when that is a valid id, else +// no id. +// +// `everVisible` is a separate latch, set the first time the host sends +// `visible:true`. It is not part of the snapshot: the snapshot starts visible +// and `applyVisibility` ignores an unchanged value, so only the message itself +// can tell "the host has shown us" from "nobody has said anything yet". A +// `visible:false` (e.g. the host's reply to trace-ready for a hidden tab) +// never sets it. Consumers that must not act before the host shows them +// (the correlation plot's Formula Engine subscription) read it with its own getter. + +import { HOST_THEME_ID } from '@slaclab/canopy-shell'; + +import { isEmbedded } from './embedded'; +import type { ColorMode } from '@slaclab/canopy-shell/color-mode'; +import { setHostTheme } from '../state/colorMode'; + +export interface BridgeSnapshot { + visible: boolean; + /** Epoch ms of the last visible->hidden transition; set only while hidden. */ + hiddenAt?: number; + /** Last mode the host sent; absent until it sends one. */ + mode?: ColorMode; +} + +const READY = { type: 'canopy:trace-ready' } as const; + +let snapshot: BridgeSnapshot = { visible: true }; +const listeners = new Set<() => void>(); +let everVisible = false; +const everVisibleListeners = new Set<() => void>(); +let uninstallCurrent: (() => void) | null = null; + +function publish(next: BridgeSnapshot): void { + snapshot = next; + for (const l of listeners) l(); +} + +export function subscribe(listener: () => void): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +export function getSnapshot(): BridgeSnapshot { + return snapshot; +} + +/** Whether the host has sent `visible:true` at least once. Never resets. */ +export function getEverVisible(): boolean { + return everVisible; +} + +/** Listen for the `everVisible` latch (called once, when it sets). */ +export function subscribeEverVisible(listener: () => void): () => void { + everVisibleListeners.add(listener); + return () => { + everVisibleListeners.delete(listener); + }; +} + +function latchEverVisible(): void { + if (everVisible) return; + everVisible = true; + for (const l of everVisibleListeners) l(); +} + +function applyVisibility(visible: boolean): void { + if (visible === snapshot.visible) return; + if (visible) { + const { mode } = snapshot; + publish(mode === undefined ? { visible: true } : { visible: true, mode }); + } else { + publish({ ...snapshot, visible: false, hiddenAt: Date.now() }); + } +} + +function applyTheme(mode: ColorMode, theme?: unknown): void { + // The store is updated before the snapshot check: a host theme change that + // keeps the mode (desy-dark -> retro-dark) must still reach it. + const id = typeof theme === 'string' && HOST_THEME_ID.test(theme) ? theme : null; + setHostTheme(id, mode); + if (mode === snapshot.mode) return; + publish({ ...snapshot, mode }); +} + +function onMessage(event: MessageEvent): void { + if (event.source !== window.parent || event.origin !== window.location.origin) return; + const data: unknown = event.data; + if (typeof data !== 'object' || data === null) return; + const msg = data as Record; + if (msg.type === 'canopy:trace-visibility') { + if (typeof msg.visible === 'boolean') { + applyVisibility(msg.visible); + if (msg.visible) latchEverVisible(); + } + } else if (msg.type === 'canopy:trace-theme') { + if (msg.mode === 'light' || msg.mode === 'dark') applyTheme(msg.mode, msg.theme); + } +} + +/** + * Install the listener and announce readiness to the parent. A no-op when not + * embedded; idempotent when embedded. Returns a function that removes it. + */ +export function installBridge(): () => void { + if (!isEmbedded()) return () => {}; + if (uninstallCurrent) return uninstallCurrent; + window.addEventListener('message', onMessage); + const uninstall = () => { + window.removeEventListener('message', onMessage); + if (uninstallCurrent === uninstall) uninstallCurrent = null; + }; + uninstallCurrent = uninstall; + window.parent.postMessage(READY, window.location.origin); + return uninstall; +} diff --git a/src/embed/embedded.ts b/src/embed/embedded.ts new file mode 100644 index 0000000..9ee386a --- /dev/null +++ b/src/embed/embedded.ts @@ -0,0 +1,7 @@ +// `?embedded=true` marks the app as hosted inside another page (a Canopy +// workspace). The host then owns the theme (state/colorMode.ts) and talks to +// Trace through the message bridge (embed/bridge.ts). +export function isEmbedded(): boolean { + if (typeof window === 'undefined') return false; + return new URLSearchParams(window.location.search).get('embedded') === 'true'; +} diff --git a/src/hooks/useAutoScrollTimers.pause.test.ts b/src/hooks/useAutoScrollTimers.pause.test.ts new file mode 100644 index 0000000..bd01a98 --- /dev/null +++ b/src/hooks/useAutoScrollTimers.pause.test.ts @@ -0,0 +1,151 @@ +// @vitest-environment jsdom +// +// useAutoScrollTimers pauses while the embedding host reports Trace hidden: +// no plot's anchor advances, so its windows hold still. A detached plot or +// Data Insight window keeps the clock running, because that window is still +// on screen. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, renderHook } from '@testing-library/react'; +import type { Plot } from '../types'; +import type { TimeWindowNs } from '../api/time'; + +type Hook = typeof import('./useAutoScrollTimers'); +type Bridge = typeof import('../embed/bridge'); + +// The bridge keeps module-level state, so every test imports fresh copies. +async function load(search = '/?embedded=true'): Promise<{ hook: Hook; bridge: Bridge }> { + window.history.replaceState(null, '', search); + vi.resetModules(); + const bridge = await import('../embed/bridge'); + const hook = await import('./useAutoScrollTimers'); + return { hook, bridge }; +} + +function fromParent(data: unknown): void { + act(() => { + window.dispatchEvent( + new MessageEvent('message', { data, origin: location.origin, source: window.parent }) + ); + }); +} + +const hide = () => fromParent({ type: 'canopy:trace-visibility', visible: false }); +const show = () => fromParent({ type: 'canopy:trace-visibility', visible: true }); + +function makePlot(overrides: Partial = {}): Plot { + return { + id: 'p1', + title: 'Plot 1', + traces: [], + axes: [], + backgroundColor: 'default', + showLegend: true, + showXGridlines: false, + showYGridlines: false, + showCrosshair: false, + gridStyle: 'solid', + gridOpacity: 1, + tickFontSize: 11, + xAxis: { timeRange: '-1h' }, + refreshIntervalS: 1, + ...overrides, + }; +} + +const NO_VIEW = new Map(); +const T0 = new Date('2026-06-05T12:00:00Z').getTime(); + +let uninstall: (() => void) | undefined; + +beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(T0); +}); + +afterEach(() => { + cleanup(); + uninstall?.(); + uninstall = undefined; + vi.useRealTimers(); + window.history.replaceState(null, '', '/'); +}); + +function mount(hook: Hook, plots: Plot[], anyDetached = false) { + return renderHook( + ({ detached }: { detached: boolean }) => hook.useAutoScrollTimers(plots, NO_VIEW, detached), + { initialProps: { detached: anyDetached } } + ); +} + +// One act per second, so each tick commits before the next is due. +function advance(ms: number): void { + for (let t = 0; t < ms; t += 1000) { + act(() => { + vi.advanceTimersByTime(1000); + }); + } +} + +describe('useAutoScrollTimers visibility pause', () => { + it('advances the anchor while visible', async () => { + const { hook, bridge } = await load(); + uninstall = bridge.installBridge(); + const h = mount(hook, [makePlot()]); + advance(5000); + expect(h.result.current.nowFor('p1')).toBe(T0 + 5000); + }); + + it('holds the anchor while hidden', async () => { + const { hook, bridge } = await load(); + uninstall = bridge.installBridge(); + const h = mount(hook, [makePlot()]); + advance(2000); + hide(); + advance(60_000); + expect(h.result.current.nowFor('p1')).toBe(T0 + 2000); + }); + + it('re-anchors at once and resumes when visible again', async () => { + const { hook, bridge } = await load(); + uninstall = bridge.installBridge(); + const h = mount(hook, [makePlot()]); + hide(); + advance(60_000); + show(); + act(() => { + vi.advanceTimersByTime(0); + }); + expect(h.result.current.nowFor('p1')).toBe(T0 + 60_000); + advance(3000); + expect(h.result.current.nowFor('p1')).toBe(T0 + 63_000); + }); + + it('keeps advancing while hidden when a plot or the DIT is detached', async () => { + const { hook, bridge } = await load(); + uninstall = bridge.installBridge(); + const h = mount(hook, [makePlot()], true); + hide(); + advance(10_000); + expect(h.result.current.nowFor('p1')).toBe(T0 + 10_000); + }); + + it('holds once the last detached window reattaches while hidden', async () => { + const { hook, bridge } = await load(); + uninstall = bridge.installBridge(); + const h = mount(hook, [makePlot()], true); + hide(); + advance(5000); + h.rerender({ detached: false }); + advance(10_000); + expect(h.result.current.nowFor('p1')).toBe(T0 + 5000); + }); + + it('never pauses when not embedded', async () => { + const { hook, bridge } = await load('/'); + uninstall = bridge.installBridge(); + const h = mount(hook, [makePlot()]); + hide(); + advance(2000); + expect(h.result.current.nowFor('p1')).toBe(T0 + 2000); + }); +}); diff --git a/src/hooks/useAutoScrollTimers.ts b/src/hooks/useAutoScrollTimers.ts index b12ff0b..12d8070 100644 --- a/src/hooks/useAutoScrollTimers.ts +++ b/src/hooks/useAutoScrollTimers.ts @@ -1,7 +1,8 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from 'react'; import type { Plot } from '../types'; import type { TimeWindowNs } from '../api/time'; import { relativeRangeMs } from '../api/time'; +import { getSnapshot, subscribe } from '../embed/bridge'; import type { LiveSeriesResult } from './useLiveSeries'; export const DEFAULT_REFRESH_INTERVAL_S = 5; @@ -110,10 +111,21 @@ export interface PlotClock { // One timeout is scheduled for the earliest due following plot. When it fires, // every due plot is re-anchored to the current time (not anchor + interval), so // a throttled background tab catches up in one step. +// +// Visibility pause: while the embedding host reports Trace hidden (bridge +// snapshot) and nothing is detached into its own, still-visible window +// (`anyDetached`: a plot or the Data Insight Tool), no timeout is scheduled, so +// every anchor holds and live re-renders neither slide a window nor refetch. +// On visible the overdue plots are re-anchored by the first timeout, which +// fires at once. export function useAutoScrollTimers( plots: Plot[], - viewWindowByPlot: Map + viewWindowByPlot: Map, + anyDetached = false ): PlotClock { + const bridge = useSyncExternalStore(subscribe, getSnapshot); + const paused = !anyDetached && !bridge.visible; + const [clock, setClock] = useState(() => { const now = Date.now(); return { byPlot: new Map(plots.map((p) => [p.id, now])), lastWriteMs: now }; @@ -131,9 +143,13 @@ export function useAutoScrollTimers( // Following plots and their cadence in ms, as `[id, ms]` pairs in JSON. The // effect parses it back so it re-subscribes only when the following set or an // interval changes. JSON keeps any plot id intact (imports keep ids as saved). - const signature = JSON.stringify( - plots.filter((p) => isFollowing(p, viewWindowByPlot)).map((p) => [p.id, refreshIntervalMs(p)]) - ); + const signature = paused + ? '[]' + : JSON.stringify( + plots + .filter((p) => isFollowing(p, viewWindowByPlot)) + .map((p) => [p.id, refreshIntervalMs(p)]) + ); useEffect(() => { const cadence = JSON.parse(signature) as [string, number][]; diff --git a/src/main.tsx b/src/main.tsx index 494737a..6679a1a 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -1,18 +1,10 @@ +import './bootstrap'; import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import { CanopyProvider } from '@slaclab/canopy-react'; -// Carbon compiled from Sass with self-hosted IBM Plex (index.scss), then the -// shell's styles, then the app's own. -import './index.scss'; -import '@slaclab/canopy-shell/styles.css'; -import './index.css'; -import { setupColorMode } from './state/colorMode'; import App from './App.tsx'; import { canopyConnection } from './api/connection'; -// Before the first render: read trace.theme and paint to match. -setupColorMode(); - createRoot(document.getElementById('root')!).render( diff --git a/src/state/colorMode.host.test.ts b/src/state/colorMode.host.test.ts new file mode 100644 index 0000000..2a2615c --- /dev/null +++ b/src/state/colorMode.host.test.ts @@ -0,0 +1,146 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +// The shell's colour-mode store and Trace's host theme keep module-level +// state, so every test sets the URL first, imports fresh copies and runs the +// page's setup. The React testing helpers are imported after the same reset so +// that they and the stores share one React instance. +type Shell = typeof import('@slaclab/canopy-shell/color-mode'); +type Host = typeof import('./colorMode'); +type Theme = Pick & + Pick; +type Rtl = typeof import('@testing-library/react'); + +async function load(search: string): Promise { + window.history.replaceState(null, '', `/${search}`); + vi.resetModules(); + const shell = await import('@slaclab/canopy-shell/color-mode'); + const host = await import('./colorMode'); + host.setupColorMode(); + return { + getColorMode: shell.getColorMode, + setColorMode: shell.setColorMode, + getHostThemeId: host.getHostThemeId, + setHostTheme: host.setHostTheme, + useHostThemeId: host.useHostThemeId, + subscribeHostThemeId: host.subscribeHostThemeId, + }; +} + +let rtl: Rtl | undefined; + +beforeEach(() => { + window.localStorage.clear(); +}); + +afterEach(() => { + rtl?.cleanup(); + rtl = undefined; + vi.restoreAllMocks(); + window.localStorage.clear(); + window.history.replaceState(null, '', '/'); +}); + +describe('initial host theme', () => { + it('has no host theme id and the default mode without ?theme=', async () => { + const theme = await load('?embedded=true'); + expect(theme.getHostThemeId()).toBeNull(); + expect(theme.getColorMode()).toBe('dark'); + }); + + it('takes a valid ?theme= as the id', async () => { + const theme = await load('?embedded=true&theme=retro-dark'); + expect(theme.getHostThemeId()).toBe('retro-dark'); + expect(theme.getColorMode()).toBe('dark'); + }); + + it("derives the mode from the id with the shell's rule", async () => { + const theme = await load('?embedded=true&theme=solarized-light'); + expect(theme.getHostThemeId()).toBe('solarized-light'); + expect(theme.getColorMode()).toBe('light'); + }); + + it('keeps the two bare modes working as ids', async () => { + const theme = await load('?embedded=true&theme=light'); + expect(theme.getHostThemeId()).toBe('light'); + expect(theme.getColorMode()).toBe('light'); + }); + + it.each(['../x', 'Retro-Dark', '', 'a'.repeat(41)])( + 'rejects the invalid ?theme=%j', + async (bad) => { + const theme = await load(`?embedded=true&theme=${encodeURIComponent(bad)}`); + expect(theme.getHostThemeId()).toBeNull(); + expect(theme.getColorMode()).toBe('dark'); + } + ); + + it('ignores ?theme= when not embedded', async () => { + window.localStorage.setItem('trace.theme', 'light'); + const theme = await load('?theme=retro-dark'); + expect(theme.getHostThemeId()).toBeNull(); + expect(theme.getColorMode()).toBe('light'); + }); +}); + +describe('setHostTheme', () => { + it('applies the id and the mode together', async () => { + const theme = await load('?embedded=true&theme=retro-dark'); + theme.setHostTheme('solarized-light', 'light'); + expect(theme.getHostThemeId()).toBe('solarized-light'); + expect(theme.getColorMode()).toBe('light'); + }); + + it('tells id listeners about an id change only', async () => { + const theme = await load('?embedded=true&theme=desy-dark'); + const listener = vi.fn(); + const unsubscribe = theme.subscribeHostThemeId(listener); + theme.setHostTheme('retro-dark', 'dark'); + expect(theme.getHostThemeId()).toBe('retro-dark'); + expect(listener).toHaveBeenCalledTimes(1); + theme.setHostTheme('retro-dark', 'light'); + expect(listener).toHaveBeenCalledTimes(1); + theme.setHostTheme(null, 'light'); + expect(theme.getHostThemeId()).toBeNull(); + expect(listener).toHaveBeenCalledTimes(2); + unsubscribe(); + theme.setHostTheme('retro-dark', 'dark'); + expect(listener).toHaveBeenCalledTimes(2); + }); + + it("never reads or writes Trace's stored choice", async () => { + const theme = await load('?embedded=true'); + const getItem = vi.spyOn(Storage.prototype, 'getItem'); + const setItem = vi.spyOn(Storage.prototype, 'setItem'); + theme.setHostTheme('solarized-light', 'light'); + expect(getItem).not.toHaveBeenCalledWith('trace.theme'); + expect(setItem).not.toHaveBeenCalled(); + }); + + it('wins over a toggle made since the last host message', async () => { + const theme = await load('?embedded=true&theme=retro-dark'); + theme.setColorMode('light'); + theme.setHostTheme('retro-dark', 'dark'); + expect(theme.getColorMode()).toBe('dark'); + }); + + it('leaves the id alone when only the mode is set', async () => { + const theme = await load('?embedded=true&theme=retro-dark'); + theme.setColorMode('light'); + expect(theme.getHostThemeId()).toBe('retro-dark'); + expect(theme.getColorMode()).toBe('light'); + }); +}); + +describe('useHostThemeId', () => { + it('returns the id and re-renders on a same-mode id change', async () => { + const theme = await load('?embedded=true&theme=desy-dark'); + rtl = await import('@testing-library/react'); + const { result } = rtl.renderHook(() => theme.useHostThemeId()); + expect(result.current).toBe('desy-dark'); + rtl.act(() => theme.setHostTheme('retro-dark', 'dark')); + expect(result.current).toBe('retro-dark'); + rtl.act(() => theme.setHostTheme(null, 'dark')); + expect(result.current).toBeNull(); + }); +}); diff --git a/src/state/colorMode.ts b/src/state/colorMode.ts index 86ae454..cb34cd2 100644 --- a/src/state/colorMode.ts +++ b/src/state/colorMode.ts @@ -1,8 +1,12 @@ +import { useSyncExternalStore } from 'react'; +import { HOST_THEME_ID, modeFromThemeId } from '@slaclab/canopy-shell'; import { configureColorMode, getColorMode, syncDocumentColorMode, + type ColorMode, } from '@slaclab/canopy-shell/color-mode'; +import { isEmbedded } from '../embed/embedded'; /** * Trace's settings for the shared @slaclab/canopy-shell color-mode store. The @@ -12,11 +16,70 @@ import { export const TRACE_COLOR_MODE = { storageKey: 'trace.theme', defaultMode: 'dark' } as const; /** - * Configure the store and mirror the stored mode onto (`data-theme` and - * the Carbon `cds--g10`/`cds--g100` class). Call once in main.tsx, before the - * first render, so the page background is right before React mounts. + * Embedded (`?embedded=true`), the host owns the theme. The store then runs + * under this key instead, which nothing persists across host messages: every + * host theme clears it and becomes the store's default, so the host's mode + * wins over a toggle made in between. The operator's standalone choice under + * `trace.theme` is neither read nor overwritten. + */ +export const HOSTED_COLOR_MODE_KEY = 'trace.theme.hosted'; + +// The host's full theme id (e.g. `retro-dark`); null when it gave none. +let hostThemeId: string | null = null; +const hostListeners = new Set<() => void>(); + +function applyHostMode(mode: ColorMode): void { + try { + window.localStorage.removeItem(HOSTED_COLOR_MODE_KEY); + } catch { + // storage unavailable: nothing was stored either + } + configureColorMode({ storageKey: HOSTED_COLOR_MODE_KEY, defaultMode: mode }); +} + +/** + * Configure the store and mirror the mode onto (`data-theme` and the + * Carbon `cds--g10`/`cds--g100` class). Call once before the first render, so + * the page background is right before React mounts. Embedded, the initial + * host theme comes from `?theme=` when it is a valid id; its mode follows the + * shell's rule, and without one the mode is the default. */ export function setupColorMode(): void { - configureColorMode(TRACE_COLOR_MODE); + if (isEmbedded()) { + const param = new URLSearchParams(window.location.search).get('theme'); + // `RegExp.test` coerces its argument, so `null` would match as 'null'. + hostThemeId = param !== null && HOST_THEME_ID.test(param) ? param : null; + applyHostMode(hostThemeId ? modeFromThemeId(hostThemeId) : TRACE_COLOR_MODE.defaultMode); + } else { + hostThemeId = null; + configureColorMode(TRACE_COLOR_MODE); + } syncDocumentColorMode(getColorMode()); } + +export function getHostThemeId(): string | null { + return hostThemeId; +} + +/** + * Apply what the embedding host sent: its theme id (already validated, or + * `null` when it sent none) and the mode. Id listeners hear only an id change; + * the color-mode store publishes a mode change itself. + */ +export function setHostTheme(id: string | null, mode: ColorMode): void { + const idChanged = id !== hostThemeId; + hostThemeId = id; + applyHostMode(mode); + if (idChanged) for (const l of hostListeners) l(); +} + +export function subscribeHostThemeId(listener: () => void): () => void { + hostListeners.add(listener); + return () => { + hostListeners.delete(listener); + }; +} + +export function useHostThemeId(): string | null { + return useSyncExternalStore(subscribeHostThemeId, getHostThemeId, getHostThemeId); +} diff --git a/vite.config.ts b/vite.config.ts index 2b7ea74..bee32f6 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -100,6 +100,9 @@ export default defineConfig(({ mode }) => { }, test: { passWithNoTests: true, + // Node >= 25 ships a global localStorage that shadows jsdom's; turn it + // off in the test workers so the tests see jsdom's Storage. + execArgv: ['--no-experimental-webstorage'], }, }; }); From 051f28fac38a3b74add3007bd879271c8eaf68f6 Mon Sep 17 00:00:00 2001 From: ThorstenHellert Date: Sat, 31 Oct 2026 14:13:08 -0700 Subject: [PATCH 020/150] feat(workbench): schema-driven tool layout and one properties pane A tool describes itself as a schema plus a binding (ToolDefinition); the workbench renders the actions bar, the one-pane sidebar (cards above, plot-wide sections below), the field controls with the modified dot and reset, the right-click registry, and shortcuts bound from the actions themselves. A host that draws the tool's tile bar (embedded=true&hostbar=1) gets the actions as canopy:tool-actions and invokes them with canopy:tool-invoke. src/pvSearch merges an optional host channel catalog with Mole search behind one PV field. The old panels keep their own hook until Trace moves over. --- src/components/PvCombo.tsx | 161 +++ src/pvSearch/catalog.test.ts | 87 ++ src/pvSearch/catalog.ts | 116 ++ src/pvSearch/fuzzy.test.ts | 63 ++ src/pvSearch/fuzzy.ts | 138 +++ src/pvSearch/index.ts | 27 + src/pvSearch/mole.test.ts | 10 + src/pvSearch/mole.ts | 42 + src/pvSearch/usePVSearch.test.ts | 80 ++ src/pvSearch/usePVSearch.ts | 66 ++ src/tools/dotHelpers.test.ts | 182 ++++ src/tools/dotHelpers.ts | 101 ++ src/workbench/ActionsBar.test.tsx | 461 ++++++++ src/workbench/ActionsBar.tsx | 70 ++ src/workbench/FieldBlock.test.tsx | 264 +++++ src/workbench/FieldBlock.tsx | 127 +++ src/workbench/Outline.drag.test.tsx | 258 +++++ src/workbench/Outline.lock.test.tsx | 133 +++ src/workbench/Outline.test.tsx | 721 +++++++++++++ src/workbench/Outline.tsx | 989 ++++++++++++++++++ src/workbench/OutlineAddRow.test.tsx | 219 ++++ src/workbench/OutlineAddRow.tsx | 168 +++ src/workbench/PlotSettings.test.tsx | 430 ++++++++ src/workbench/PlotSettings.tsx | 220 ++++ src/workbench/Sidebar.resize.test.tsx | 470 +++++++++ src/workbench/Sidebar.test.tsx | 152 +++ src/workbench/Sidebar.tsx | 347 ++++++ src/workbench/WorkbenchLayout.test.tsx | 900 ++++++++++++++++ src/workbench/WorkbenchLayout.tsx | 615 +++++++++++ src/workbench/__fixtures__/PanelHarness.tsx | 47 + src/workbench/__fixtures__/stubTool.test.ts | 290 +++++ src/workbench/__fixtures__/stubTool.ts | 750 +++++++++++++ src/workbench/actions.css | 51 + src/workbench/arrangementStore.test.ts | 246 +++++ src/workbench/arrangementStore.ts | 195 ++++ src/workbench/blockGroups.ts | 26 + src/workbench/contextMenu.css | 80 ++ .../contextMenu/ContextMenuHost.test.tsx | 153 +++ src/workbench/contextMenu/ContextMenuHost.tsx | 306 ++++++ src/workbench/contextMenu/bridges.test.ts | 29 + src/workbench/contextMenu/bridges.ts | 64 ++ src/workbench/contextMenu/context.ts | 46 + src/workbench/contextMenu/registry.test.ts | 315 ++++++ src/workbench/contextMenu/registry.ts | 479 +++++++++ src/workbench/contextMenu/schemaWriters.ts | 67 ++ src/workbench/embedding.ts | 23 + src/workbench/fields.css | 230 ++++ src/workbench/fields/ColourSwatch.test.tsx | 131 +++ src/workbench/fields/ColourSwatch.tsx | 80 ++ src/workbench/fields/Field.test.tsx | 434 ++++++++ src/workbench/fields/Field.tsx | 89 ++ src/workbench/fields/FieldControl.tsx | 349 ++++++ src/workbench/fields/PvFieldControl.test.tsx | 126 +++ src/workbench/fields/PvFieldControl.tsx | 91 ++ src/workbench/fields/hooks.ts | 41 + src/workbench/fields/index.ts | 18 + src/workbench/fields/logic.ts | 88 ++ src/workbench/index.ts | 16 + src/workbench/openMemory.ts | 41 + src/workbench/outline.css | 433 ++++++++ src/workbench/outlineCompare.ts | 53 + src/workbench/outlineGroups.ts | 24 + src/workbench/panel.css | 270 +++++ src/workbench/plotSettingsKeys.ts | 12 + src/workbench/saveView.test.ts | 233 +++++ src/workbench/selection.test.tsx | 213 ++++ src/workbench/selection.ts | 231 ++++ src/workbench/sidebar.css | 159 +++ src/workbench/standardActions.ts | 146 +++ src/workbench/testids.test.ts | 25 + src/workbench/testids.ts | 21 + src/workbench/toolActionsPublisher.test.ts | 239 +++++ src/workbench/toolActionsPublisher.ts | 115 ++ src/workbench/toolInvoke.test.ts | 206 ++++ src/workbench/toolInvoke.ts | 79 ++ src/workbench/types.test.ts | 331 ++++++ src/workbench/types.ts | 431 ++++++++ src/workbench/useCanvasActions.ts | 314 ++++++ src/workbench/useLatest.ts | 30 + src/workbench/workbench.css | 52 + 80 files changed, 16135 insertions(+) create mode 100644 src/components/PvCombo.tsx create mode 100644 src/pvSearch/catalog.test.ts create mode 100644 src/pvSearch/catalog.ts create mode 100644 src/pvSearch/fuzzy.test.ts create mode 100644 src/pvSearch/fuzzy.ts create mode 100644 src/pvSearch/index.ts create mode 100644 src/pvSearch/mole.test.ts create mode 100644 src/pvSearch/mole.ts create mode 100644 src/pvSearch/usePVSearch.test.ts create mode 100644 src/pvSearch/usePVSearch.ts create mode 100644 src/tools/dotHelpers.test.ts create mode 100644 src/tools/dotHelpers.ts create mode 100644 src/workbench/ActionsBar.test.tsx create mode 100644 src/workbench/ActionsBar.tsx create mode 100644 src/workbench/FieldBlock.test.tsx create mode 100644 src/workbench/FieldBlock.tsx create mode 100644 src/workbench/Outline.drag.test.tsx create mode 100644 src/workbench/Outline.lock.test.tsx create mode 100644 src/workbench/Outline.test.tsx create mode 100644 src/workbench/Outline.tsx create mode 100644 src/workbench/OutlineAddRow.test.tsx create mode 100644 src/workbench/OutlineAddRow.tsx create mode 100644 src/workbench/PlotSettings.test.tsx create mode 100644 src/workbench/PlotSettings.tsx create mode 100644 src/workbench/Sidebar.resize.test.tsx create mode 100644 src/workbench/Sidebar.test.tsx create mode 100644 src/workbench/Sidebar.tsx create mode 100644 src/workbench/WorkbenchLayout.test.tsx create mode 100644 src/workbench/WorkbenchLayout.tsx create mode 100644 src/workbench/__fixtures__/PanelHarness.tsx create mode 100644 src/workbench/__fixtures__/stubTool.test.ts create mode 100644 src/workbench/__fixtures__/stubTool.ts create mode 100644 src/workbench/actions.css create mode 100644 src/workbench/arrangementStore.test.ts create mode 100644 src/workbench/arrangementStore.ts create mode 100644 src/workbench/blockGroups.ts create mode 100644 src/workbench/contextMenu.css create mode 100644 src/workbench/contextMenu/ContextMenuHost.test.tsx create mode 100644 src/workbench/contextMenu/ContextMenuHost.tsx create mode 100644 src/workbench/contextMenu/bridges.test.ts create mode 100644 src/workbench/contextMenu/bridges.ts create mode 100644 src/workbench/contextMenu/context.ts create mode 100644 src/workbench/contextMenu/registry.test.ts create mode 100644 src/workbench/contextMenu/registry.ts create mode 100644 src/workbench/contextMenu/schemaWriters.ts create mode 100644 src/workbench/embedding.ts create mode 100644 src/workbench/fields.css create mode 100644 src/workbench/fields/ColourSwatch.test.tsx create mode 100644 src/workbench/fields/ColourSwatch.tsx create mode 100644 src/workbench/fields/Field.test.tsx create mode 100644 src/workbench/fields/Field.tsx create mode 100644 src/workbench/fields/FieldControl.tsx create mode 100644 src/workbench/fields/PvFieldControl.test.tsx create mode 100644 src/workbench/fields/PvFieldControl.tsx create mode 100644 src/workbench/fields/hooks.ts create mode 100644 src/workbench/fields/index.ts create mode 100644 src/workbench/fields/logic.ts create mode 100644 src/workbench/index.ts create mode 100644 src/workbench/openMemory.ts create mode 100644 src/workbench/outline.css create mode 100644 src/workbench/outlineCompare.ts create mode 100644 src/workbench/outlineGroups.ts create mode 100644 src/workbench/panel.css create mode 100644 src/workbench/plotSettingsKeys.ts create mode 100644 src/workbench/saveView.test.ts create mode 100644 src/workbench/selection.test.tsx create mode 100644 src/workbench/selection.ts create mode 100644 src/workbench/sidebar.css create mode 100644 src/workbench/standardActions.ts create mode 100644 src/workbench/testids.test.ts create mode 100644 src/workbench/testids.ts create mode 100644 src/workbench/toolActionsPublisher.test.ts create mode 100644 src/workbench/toolActionsPublisher.ts create mode 100644 src/workbench/toolInvoke.test.ts create mode 100644 src/workbench/toolInvoke.ts create mode 100644 src/workbench/types.test.ts create mode 100644 src/workbench/types.ts create mode 100644 src/workbench/useCanvasActions.ts create mode 100644 src/workbench/useLatest.ts create mode 100644 src/workbench/workbench.css diff --git a/src/components/PvCombo.tsx b/src/components/PvCombo.tsx new file mode 100644 index 0000000..1aa29f0 --- /dev/null +++ b/src/components/PvCombo.tsx @@ -0,0 +1,161 @@ +// The one PV-name field: the properties panel's PV Name, the Layers panel's +// add-trace row and the correlation plot's sections all take a PV through it. +// +// A Carbon ComboBox over two suggestion sources merged by `pvNameSuggestions`: +// the host's channel catalog, ranked in the browser (150 ms), then Mole's +// index through `search` (300 ms), which still lists archived-only PVs the +// catalog does not know. Keystrokes only drive the suggestions; the PV is +// committed on a pick, on Enter or on leaving the field with text (Carbon's +// custom-value rule), never per keystroke, since a committed PV starts an +// archive fetch and a live subscription. The helper line reports the search +// (searching, N matches, failed). Escape, or leaving the field with nothing +// typed, is a cancel for the callers that open the field on demand. + +import { useMemo, useRef, useState, type FocusEvent, type KeyboardEvent } from 'react'; +import { ComboBox, type ComboBoxProps } from '@carbon/react'; +import { + moleSearch, + pvNameSuggestions, + useChannelMatches, + usePVSearch, + type PvSearch, +} from '../pvSearch'; + +export interface PvComboProps { + id: string; + /** The committed PV; '' while there is none. */ + value: string; + onCommit: (pv: string) => void; + /** Escape in the field, or the field left with nothing typed. */ + onCancel?: () => void; + /** Every keystroke, for a caller with its own submit control. */ + onInputChange?: (text: string) => void; + /** + * Whether leaving the field with text commits it (Carbon's custom-value + * rule), as the properties panel's PV Name does. Off for a row with its own + * Add button, where leaving must not add a half-typed name. + */ + commitOnBlur?: boolean; + /** PV search; Mole's index of `archiver` by default. */ + search?: PvSearch; + archiver?: string; + /** Channel catalog ranked ahead of the search hits; the host's by default. */ + catalog?: readonly string[]; + titleText?: string; + hideLabel?: boolean; + placeholder?: string; + autoFocus?: boolean; + disabled?: boolean; + /** `data-testid` of the input. */ + inputTestId?: string; +} + +const itemToString = (item: string | null | undefined) => item ?? ''; + +// The index re-exports the Dropdown's OnChangeData under the same name, so the +// ComboBox's (with `inputValue`) is read off its props. +type PvComboChange = Parameters['onChange']>[0]; + +export function PvCombo({ + id, + value, + onCommit, + onCancel, + onInputChange, + commitOnBlur = true, + search, + archiver, + catalog, + titleText = 'PV name', + hideLabel = false, + placeholder = 'Type to search PVs', + autoFocus = false, + disabled = false, + inputTestId, +}: PvComboProps) { + const [query, setQuery] = useState(value); + // A new committed value (another trace selected, a reset) replaces the + // typed text; useState only seeds on mount. + const [prevValue, setPrevValue] = useState(value); + if (value !== prevValue) { + setPrevValue(value); + setQuery(value); + } + // Stable across renders: the search hook re-fetches when it changes. + const searchFn = useMemo(() => search ?? moleSearch({ archiver }), [search, archiver]); + // While the text still equals the committed PV nothing is searched: a focus + // on a filled field must not re-fetch matches for the PV already chosen. + const pattern = query === value ? '' : query; + const result = usePVSearch(pattern, searchFn); + const channelHits = useChannelMatches(pattern, undefined, catalog); + const items = pvNameSuggestions(value, channelHits, result.pvs); + const suggestionCount = items.length - (value ? 1 : 0); + const helperText = + result.status === 'loading' + ? 'Searching…' + : result.status === 'error' + ? `Search failed: ${result.error?.code ?? 'unknown'}` + : result.status === 'ready' && pattern + ? `${suggestionCount} match${suggestionCount === 1 ? '' : 'es'}` + : ''; + + // Set from the field's blur until its next focus: Carbon commits a custom + // value on blur through a state change, so its onChange lands after the + // blur event, and the flag tells that commit from a pick or an Enter. + const blurred = useRef(false); + + const onKeyDown = (e: KeyboardEvent) => { + if (e.key === 'Escape' && onCancel) { + e.stopPropagation(); + onCancel(); + } + }; + const onBlur = (e: FocusEvent) => { + // A pick in the open menu moves focus within the field: not a leave. + if (!onCancel || e.currentTarget.contains(e.relatedTarget as Node | null)) return; + if (query.trim() === '') onCancel(); + }; + + return ( +
{ + blurred.current = true; + }} + onFocusCapture={() => { + blurred.current = false; + }} + onBlur={onBlur} + > +
+ ); +} diff --git a/src/pvSearch/catalog.test.ts b/src/pvSearch/catalog.test.ts new file mode 100644 index 0000000..fa15ef6 --- /dev/null +++ b/src/pvSearch/catalog.test.ts @@ -0,0 +1,87 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + channelMatches, + loadChannelCatalog, + mergeSuggestions, + pvNameSuggestions, + resetChannelCatalog, +} from './catalog'; + +describe('channelMatches', () => { + const catalog = ['SIM:BPM1:X', 'SIM:BPM1:Y', 'SIM:BPM2:X', 'SIM:MAG:QF1:CURRENT']; + + it('is empty for a blank query or no catalog', () => { + expect(channelMatches('', catalog)).toEqual([]); + expect(channelMatches('bpm', [])).toEqual([]); + expect(channelMatches('bpm2', catalog)).toEqual(['SIM:BPM2:X']); + }); +}); + +describe('merging', () => { + it('keeps order and the first occurrence of each name', () => { + expect(mergeSuggestions(['SIM:A', 'SIM:B'], ['SIM:B', 'SIM:C', 'SIM:A'])).toEqual([ + 'SIM:A', + 'SIM:B', + 'SIM:C', + ]); + }); + + it('Trace: committed PV, then catalog matches, then Mole hits, once each', () => { + expect( + pvNameSuggestions('SIM:BPM1:X', ['SIM:BPM1:X', 'SIM:BPM2:X'], ['SIM:BPM2:X', 'SIM:OLD:Y']) + ).toEqual(['SIM:BPM1:X', 'SIM:BPM2:X', 'SIM:OLD:Y']); + expect(pvNameSuggestions('', ['SIM:BPM2:X'], ['SIM:OLD:Y'])).toEqual([ + 'SIM:BPM2:X', + 'SIM:OLD:Y', + ]); + }); +}); + +describe('loadChannelCatalog', () => { + beforeEach(() => { + resetChannelCatalog(); + window.history.replaceState(null, '', '/panel/canopy/trace/'); + }); + afterEach(() => { + vi.unstubAllGlobals(); + resetChannelCatalog(); + window.history.replaceState(null, '', '/'); + }); + + it('fetches /channels once', async () => { + const fetchMock = vi.fn( + async () => new Response(JSON.stringify(['SIM:BPM1:X']), { status: 200 }) + ); + vi.stubGlobal('fetch', fetchMock); + await expect(loadChannelCatalog()).resolves.toEqual(['SIM:BPM1:X']); + await expect(loadChannelCatalog()).resolves.toEqual(['SIM:BPM1:X']); + expect(fetchMock).toHaveBeenCalledTimes(1); + const url = new URL(String((fetchMock.mock.calls[0] as unknown[])[0])); + expect(url.pathname).toBe('/panel/canopy/channels'); + }); + + it('a 404 means no catalog', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('not found', { status: 404 })) + ); + await expect(loadChannelCatalog()).resolves.toEqual([]); + }); + + it('a network error or a malformed body means no catalog', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + throw new TypeError('offline'); + }) + ); + await expect(loadChannelCatalog()).resolves.toEqual([]); + resetChannelCatalog(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('{"a":1}', { status: 200 })) + ); + await expect(loadChannelCatalog()).resolves.toEqual([]); + }); +}); diff --git a/src/pvSearch/catalog.ts b/src/pvSearch/catalog.ts new file mode 100644 index 0000000..010d850 --- /dev/null +++ b/src/pvSearch/catalog.ts @@ -0,0 +1,116 @@ +// The deployment's channel catalog: every channel the control system knows, +// served by the host at `GET /channels` as a JSON string[] and ranked +// here in the browser (fuzzy.ts). +// +// The catalog is fetched once per page. The host answers with a strong ETag and +// `Cache-Control: no-cache`, so a reload costs a 304. A 404 (this deployment +// has no catalog), a network error or a malformed body all mean "no catalog": +// suggestions then come from Mole alone, silently. + +import { useEffect, useMemo, useState } from 'react'; +import { canopyConnection } from '../api/connection'; +import { matchChannels } from './fuzzy'; + +let catalogPromise: Promise | null = null; +let catalogValue: string[] | null = null; + +async function fetchCatalog(): Promise { + try { + if (typeof window === 'undefined' || typeof fetch !== 'function') return []; + const response = await fetch(`${window.location.origin}${canopyConnection.baseUrl}/channels`, { + headers: { Accept: 'application/json' }, + }); + if (!response.ok) return []; + const body: unknown = await response.json(); + return Array.isArray(body) ? body.filter((v): v is string => typeof v === 'string') : []; + } catch { + return []; + } +} + +/** The channel catalog, fetched once per page; [] when there is none. */ +export function loadChannelCatalog(): Promise { + catalogPromise ??= fetchCatalog().then((list) => (catalogValue = list)); + return catalogPromise; +} + +/** Forget the fetched catalog (tests). */ +export function resetChannelCatalog(): void { + catalogPromise = null; + catalogValue = null; +} + +/** The channel catalog; [] until loaded and when there is none. */ +export function useChannelCatalog(): string[] { + const [catalog, setCatalog] = useState(() => catalogValue ?? []); + useEffect(() => { + let live = true; + void loadChannelCatalog().then((list) => { + // An empty catalog changes nothing: skip the re-render. + if (live && list.length > 0) setCatalog(list); + }); + return () => { + live = false; + }; + }, []); + return catalog; +} + +/** Catalog names matching `query` (at most RENDER_CAP), best first. */ +export function channelMatches(query: string, catalog: readonly string[]): string[] { + if (query.trim() === '' || catalog.length === 0) return []; + return matchChannels(query, catalog).results.map((m) => m.value); +} + +/** Debounce of the catalog matching while the user types. */ +export const CHANNEL_DEBOUNCE_MS = 150; + +/** + * `channelMatches` of `query` against the catalog, debounced. The host's + * catalog unless one is given (tests inject one). + */ +export function useChannelMatches( + query: string, + debounceMs = CHANNEL_DEBOUNCE_MS, + catalog?: readonly string[] +): string[] { + const hostCatalog = useChannelCatalog(); + catalog ??= hostCatalog; + const [settled, setSettled] = useState(query); + useEffect(() => { + const handle = setTimeout(() => setSettled(query), debounceMs); + return () => clearTimeout(handle); + }, [query, debounceMs]); + const cleared = query.trim() === ''; + return useMemo( + () => (cleared ? [] : channelMatches(settled, catalog)), + [cleared, settled, catalog] + ); +} + +/** The lists concatenated in order, each name kept at its first occurrence. */ +export function mergeSuggestions(...lists: ReadonlyArray): string[] { + const seen = new Set(); + const out: string[] = []; + for (const list of lists) { + for (const pv of list) { + if (pv && !seen.has(pv)) { + seen.add(pv); + out.push(pv); + } + } + } + return out; +} + +/** + * Trace's PV-name items: the committed PV first, then catalog + * matches, then Mole hits, each name once. + */ +export function pvNameSuggestions( + current: string, + catalogHits: readonly string[], + moleHits: readonly string[] +): string[] { + return mergeSuggestions(current ? [current] : [], catalogHits, moleHits); +} diff --git a/src/pvSearch/fuzzy.test.ts b/src/pvSearch/fuzzy.test.ts new file mode 100644 index 0000000..e1fdb50 --- /dev/null +++ b/src/pvSearch/fuzzy.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest'; +import { MIN_POOL, RENDER_CAP, fuzzyMatch, matchChannels } from './fuzzy'; + +const values = (query: string, catalog: string[]) => + matchChannels(query, catalog).results.map((r) => r.value); + +describe('fuzzyMatch', () => { + it('an empty query matches with score 0 and no spans', () => { + expect(fuzzyMatch(' ', 'SIM:BPM1:X')).toEqual({ score: 0, spans: [] }); + }); + + it('every token must subsequence-match, case-insensitively', () => { + expect(fuzzyMatch('bpm x', 'SIM:BPM1:X')).not.toBeNull(); + expect(fuzzyMatch('bpm q', 'SIM:BPM1:X')).toBeNull(); + expect(fuzzyMatch('xb', 'SIM:BPM1:X')).toBeNull(); + }); + + it('scores base, boundary and consecutive bonuses and merges spans', () => { + // "si" at 0,1: 1+10 (boundary) + 1+5 (consecutive) = 17. + expect(fuzzyMatch('si', 'SIM:BPM1:X')).toEqual({ score: 17, spans: [[0, 2]] }); + // After '_' is a boundary; after ':' is not. + expect(fuzzyMatch('b', 'a_b')?.score).toBe(11); + expect(fuzzyMatch('b', 'a:b')?.score).toBe(1); + // camelCase transition is a boundary. + expect(fuzzyMatch('c', 'abCd')?.score).toBe(11); + }); +}); + +describe('matchChannels', () => { + const catalog = ['SIM:BPM1:X', 'SIM:BPM1:Y', 'SIM:BPM2:X', 'SIM:MAG:QF1:CURRENT']; + + it('an empty query returns the catalog head in order with an honest total', () => { + const big = Array.from({ length: RENDER_CAP + 5 }, (_, i) => `SIM:CH${i}`); + const result = matchChannels(' ', big); + expect(result.total).toBe(big.length); + expect(result.results.map((r) => r.value)).toEqual(big.slice(0, RENDER_CAP)); + }); + + it('below MIN_POOL substring hits, the pool widens to fuzzy matches', () => { + // "simq" is no substring of anything but subsequence-matches the magnet. + expect(values('simq', catalog)).toEqual(['SIM:MAG:QF1:CURRENT']); + }); + + it('ranks by score descending, ties by value ascending', () => { + expect(values('bpm1', catalog)).toEqual(['SIM:BPM1:X', 'SIM:BPM1:Y']); + expect(values('x', ['SIM:B:X', 'SIM:A:X'])).toEqual(['SIM:A:X', 'SIM:B:X']); + }); + + it('with MIN_POOL substring hits, only those are ranked', () => { + const hits = Array.from({ length: MIN_POOL }, (_, i) => `SIM:QF${i}:I`); + // A fuzzy-only match ("q...f") that is not a substring hit for "qf". + const result = values('qf', [...hits, 'SIM:Q:F']); + expect(result).toHaveLength(MIN_POOL); + expect(result).not.toContain('SIM:Q:F'); + }); + + it('caps results at RENDER_CAP and reports the full total', () => { + const big = Array.from({ length: 120 }, (_, i) => `SIM:BPM${i}:X`); + const result = matchChannels('bpm', big); + expect(result.results).toHaveLength(50); + expect(result.total).toBe(120); + }); +}); diff --git a/src/pvSearch/fuzzy.ts b/src/pvSearch/fuzzy.ts new file mode 100644 index 0000000..447b8a1 --- /dev/null +++ b/src/pvSearch/fuzzy.ts @@ -0,0 +1,138 @@ +// Ranking of PV names typed into a PV field against the channel catalog. +// +// A query is split on whitespace and every token must match the candidate as a +// case-insensitive subsequence. Each matched character scores BASE, plus +// BOUNDARY_BONUS when it starts the name or follows a word boundary (`.`, `_`, +// `-` or a lowercase-to-uppercase step) and CONSECUTIVE_BONUS when it directly +// follows the previous match, so "bpm1" ranks `SIM:BPM1:X` above a name that +// merely contains those letters spread out. The matched character ranges come +// back as spans for highlighting. + +export interface FuzzyResult { + score: number; + spans: Array<[number, number]>; +} + +const BASE = 1; // every matched character is worth at least this +const BOUNDARY_BONUS = 10; // match at index 0 or right after a word boundary +const CONSECUTIVE_BONUS = 5; // match immediately following the previous match + +/** True at index 0, after `.`/`_`/`-`, or on a lowercase→uppercase step. */ +function isBoundary(candidate: string, idx: number): boolean { + if (idx === 0) return true; + const prev = candidate.charAt(idx - 1); + if (prev === '.' || prev === '_' || prev === '-') return true; + const cur = candidate.charAt(idx); + return /[a-z]/.test(prev) && /[A-Z]/.test(cur); +} + +/** Greedy in-order placement of a lowercased token, or null. */ +function matchToken(token: string, lower: string): number[] | null { + const indices: number[] = []; + let from = 0; + for (const ch of token) { + const found = lower.indexOf(ch, from); + if (found === -1) return null; + indices.push(found); + from = found + 1; + } + return indices; +} + +function scoreIndices(indices: number[], candidate: string): number { + let score = 0; + for (let p = 0; p < indices.length; p++) { + const idx = indices[p]; + score += BASE; + if (isBoundary(candidate, idx)) score += BOUNDARY_BONUS; + if (p > 0 && idx === indices[p - 1] + 1) score += CONSECUTIVE_BONUS; + } + return score; +} + +function mergeRanges(ranges: Array<[number, number]>): Array<[number, number]> { + const sorted = ranges.slice().sort((a, b) => a[0] - b[0]); + const merged: Array<[number, number]> = []; + for (const [start, end] of sorted) { + const last = merged[merged.length - 1]; + if (last && start <= last[1]) { + last[1] = Math.max(last[1], end); + } else { + merged.push([start, end]); + } + } + return merged; +} + +/** + * Whitespace-tokenized, all-tokens-AND subsequence match. Null when any token + * fails; an empty query matches with score 0. + */ +export function fuzzyMatch(query: string, candidate: string): FuzzyResult | null { + const tokens = query.split(/\s+/).filter((t) => t.length > 0); + if (tokens.length === 0) return { score: 0, spans: [] }; + + const lower = candidate.toLowerCase(); + const ranges: Array<[number, number]> = []; + let score = 0; + for (const token of tokens) { + const indices = matchToken(token.toLowerCase(), lower); + if (indices === null) return null; + score += scoreIndices(indices, candidate); + for (const idx of indices) ranges.push([idx, idx + 1]); + } + return { score, spans: mergeRanges(ranges) }; +} + +/** Substring hits needed before they alone form the pool. */ +export const MIN_POOL = 8; +/** Most entries returned in `results`; `total` is never capped. */ +export const RENDER_CAP = 50; + +export interface ChannelMatch { + value: string; + spans: Array<[number, number]>; +} + +export interface ChannelMatchResult { + results: ChannelMatch[]; + total: number; +} + +/** + * Rank `catalog` against `query`. Case-insensitive substring hits are the pool + * when there are at least MIN_POOL of them, else every fuzzy match in the + * catalog is; both rank by fuzzy score, then by value. An empty query returns + * the first RENDER_CAP entries in catalog order. + */ +export function matchChannels(query: string, catalog: readonly string[]): ChannelMatchResult { + const trimmed = query.trim(); + if (trimmed === '') { + return { + results: catalog.slice(0, RENDER_CAP).map((value) => ({ value, spans: [] })), + total: catalog.length, + }; + } + + const lowerQuery = trimmed.toLowerCase(); + const substringHits: string[] = []; + for (const value of catalog) { + if (value.toLowerCase().includes(lowerQuery)) substringHits.push(value); + } + + const candidates = substringHits.length >= MIN_POOL ? substringHits : catalog; + const pool: Array<{ value: string; score: number; spans: Array<[number, number]> }> = []; + for (const value of candidates) { + const hit = fuzzyMatch(query, value); + if (hit !== null) pool.push({ value, score: hit.score, spans: hit.spans }); + } + + pool.sort((a, b) => { + if (b.score !== a.score) return b.score - a.score; + return a.value < b.value ? -1 : a.value > b.value ? 1 : 0; + }); + return { + results: pool.slice(0, RENDER_CAP).map(({ value, spans }) => ({ value, spans })), + total: pool.length, + }; +} diff --git a/src/pvSearch/index.ts b/src/pvSearch/index.ts new file mode 100644 index 0000000..ed7197f --- /dev/null +++ b/src/pvSearch/index.ts @@ -0,0 +1,27 @@ +// PV-name suggestions for every PV field: Trace's PV Name, the +// add-trace row and the Correlation and Waveform sections. Two sources, +// merged: the host's channel catalog ranked in the browser (catalog.ts, +// fuzzy.ts), then Mole's archiver index (mole.ts), debounced per field by +// usePVSearch. + +export { + CHANNEL_DEBOUNCE_MS, + channelMatches, + loadChannelCatalog, + mergeSuggestions, + pvNameSuggestions, + resetChannelCatalog, + useChannelCatalog, + useChannelMatches, +} from './catalog'; +export { + MIN_POOL, + RENDER_CAP, + fuzzyMatch, + matchChannels, + type ChannelMatch, + type ChannelMatchResult, + type FuzzyResult, +} from './fuzzy'; +export { MOLE_SEARCH_LIMIT, moleSearch, moleSearchPattern, type PvSearch } from './mole'; +export { usePVSearch, type PVSearchResult, type PVSearchStatus } from './usePVSearch'; diff --git a/src/pvSearch/mole.test.ts b/src/pvSearch/mole.test.ts new file mode 100644 index 0000000..e14d8ec --- /dev/null +++ b/src/pvSearch/mole.test.ts @@ -0,0 +1,10 @@ +import { describe, expect, it } from 'vitest'; +import { moleSearchPattern } from './mole'; + +describe('moleSearchPattern', () => { + it('wraps a plain fragment and keeps a user pattern', () => { + expect(moleSearchPattern(' SIM ')).toBe('.*SIM.*'); + expect(moleSearchPattern('SIM:BPM.*')).toBe('SIM:BPM.*'); + expect(moleSearchPattern('SIM*')).toBe('SIM*'); + }); +}); diff --git a/src/pvSearch/mole.ts b/src/pvSearch/mole.ts new file mode 100644 index 0000000..15147bf --- /dev/null +++ b/src/pvSearch/mole.ts @@ -0,0 +1,42 @@ +// The archiver half of PV search: Mole's index through the SDK client, +// `GET /mole/v1/search` under the page's base (api/connection.ts), +// so it works behind a prefixed gateway path and with a per-trace archiver. +// Mole still contributes archived-only PVs that the channel catalog does not +// list. + +import { searchPVs } from '@slaclab/canopy-client'; +import { canopyConnection } from '../api/connection'; + +/** + * The PV-name search behind every PV field (components/PvCombo.tsx): PV names + * matching the user's text, best first; rejects on a failed search. One + * signature, so a page can inject its own (tests do). + */ +export type PvSearch = (pattern: string, signal?: AbortSignal) => Promise; + +/** Mole's cap on one search; the catalog adds its own matches ahead of these. */ +export const MOLE_SEARCH_LIMIT = 50; + +/** + * Mole's search is an anchored regex (the pattern must match the whole name), + * so a plain fragment is wrapped as `.*x.*`; one that already has `.` or `*` + * is the user's own pattern and passes as is. + */ +export function moleSearchPattern(text: string): string { + const trimmed = text.trim(); + return trimmed.includes('.') || trimmed.includes('*') ? trimmed : `.*${trimmed}.*`; +} + +/** A search of `archiver`'s index (the default archiver when unset). */ +export function moleSearch(options: { archiver?: string; limit?: number } = {}): PvSearch { + const { archiver, limit = MOLE_SEARCH_LIMIT } = options; + return async (pattern, signal) => { + const result = await searchPVs( + canopyConnection, + moleSearchPattern(pattern), + { archiver, limit }, + signal + ); + return result.pvs; + }; +} diff --git a/src/pvSearch/usePVSearch.test.ts b/src/pvSearch/usePVSearch.test.ts new file mode 100644 index 0000000..7e7bb31 --- /dev/null +++ b/src/pvSearch/usePVSearch.test.ts @@ -0,0 +1,80 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, renderHook } from '@testing-library/react'; +import { usePVSearch } from './usePVSearch'; + +async function settle(ms: number) { + await act(async () => { + vi.advanceTimersByTime(ms); + await Promise.resolve(); + await Promise.resolve(); + }); +} + +beforeEach(() => { + vi.useFakeTimers(); +}); + +afterEach(() => { + cleanup(); + vi.useRealTimers(); +}); + +describe('usePVSearch', () => { + it('is idle for a blank pattern and never calls the search', async () => { + const search = vi.fn(async () => ['A']); + const { result } = renderHook(() => usePVSearch(' ', search)); + await settle(500); + expect(result.current).toEqual({ status: 'idle', pvs: [] }); + expect(search).not.toHaveBeenCalled(); + }); + + it('searches the trimmed pattern once after the debounce', async () => { + const search = vi.fn(async () => ['SIM:A', 'SIM:B']); + const { result } = renderHook(() => usePVSearch(' SIM: ', search, 300)); + await settle(299); + expect(search).not.toHaveBeenCalled(); + await settle(1); + expect(search).toHaveBeenCalledWith('SIM:', expect.any(AbortSignal)); + expect(result.current).toEqual({ status: 'ready', pvs: ['SIM:A', 'SIM:B'] }); + }); + + it('aborts the request of a pattern that changed in flight and keeps the latest', async () => { + const seen: AbortSignal[] = []; + const search = vi.fn(async (pattern: string, signal?: AbortSignal) => { + seen.push(signal as AbortSignal); + await new Promise((r) => setTimeout(r, 50)); + return [`${pattern}:HIT`]; + }); + const { result, rerender } = renderHook(({ p }) => usePVSearch(p, search), { + initialProps: { p: 'one' }, + }); + await settle(300); + expect(result.current.status).toBe('loading'); + rerender({ p: 'two' }); + expect(seen[0].aborted).toBe(true); + await settle(300); + await settle(50); + expect(result.current).toEqual({ status: 'ready', pvs: ['two:HIT'] }); + }); + + it('reports the backend code of a failed search, unknown_error without one', async () => { + const coded = vi.fn(async () => { + throw Object.assign(new Error('nope'), { code: 'archiver_unavailable', detail: 'down' }); + }); + const { result } = renderHook(() => usePVSearch('x', coded)); + await settle(300); + expect(result.current).toEqual({ + status: 'error', + pvs: [], + error: { code: 'archiver_unavailable', detail: 'down' }, + }); + + const plain = vi.fn(async () => { + throw new Error('boom'); + }); + const other = renderHook(() => usePVSearch('x', plain)); + await settle(300); + expect(other.result.current.error).toEqual({ code: 'unknown_error', detail: 'boom' }); + }); +}); diff --git a/src/pvSearch/usePVSearch.ts b/src/pvSearch/usePVSearch.ts new file mode 100644 index 0000000..802431e --- /dev/null +++ b/src/pvSearch/usePVSearch.ts @@ -0,0 +1,66 @@ +import { useEffect, useState } from 'react'; +import type { PvSearch } from './mole'; + +export type PVSearchStatus = 'idle' | 'loading' | 'ready' | 'error'; + +export interface PVSearchResult { + status: PVSearchStatus; + pvs: string[]; + error?: { code: string; detail: string }; +} + +const EMPTY: PVSearchResult = { status: 'idle', pvs: [] }; + +/** + * `search` of `pattern`, debounced; idle while the pattern is blank. A pattern + * that changes mid-flight aborts the request in flight. The error carries the + * backend's code (the SDK's and the local client's `CanopyError` both have + * one) or `unknown_error`. + */ +export function usePVSearch(pattern: string, search: PvSearch, debounceMs = 300): PVSearchResult { + const [result, setResult] = useState(EMPTY); + + useEffect(() => { + const trimmed = pattern.trim(); + if (trimmed.length < 1) { + // Reset to empty when there's no query. + // eslint-disable-next-line react-hooks/set-state-in-effect + setResult(EMPTY); + return; + } + + const controller = new AbortController(); + const handle = setTimeout(() => { + setResult({ status: 'loading', pvs: [] }); + void (async () => { + try { + const pvs = await search(trimmed, controller.signal); + if (controller.signal.aborted) return; + setResult({ status: 'ready', pvs }); + } catch (err) { + if (controller.signal.aborted || (err as { name?: string }).name === 'AbortError') return; + const { code, detail, message } = err as { + code?: unknown; + detail?: unknown; + message?: unknown; + }; + setResult({ + status: 'error', + pvs: [], + error: { + code: typeof code === 'string' ? code : 'unknown_error', + detail: typeof detail === 'string' ? detail : String(message ?? err), + }, + }); + } + })(); + }, debounceMs); + + return () => { + controller.abort(); + clearTimeout(handle); + }; + }, [pattern, search, debounceMs]); + + return result; +} diff --git a/src/tools/dotHelpers.test.ts b/src/tools/dotHelpers.test.ts new file mode 100644 index 0000000..b685396 --- /dev/null +++ b/src/tools/dotHelpers.test.ts @@ -0,0 +1,182 @@ +import { describe, expect, it } from 'vitest'; +import type { DotProps, Target, ToolContext } from '../workbench/types'; +import { optionalPath, recordKey, stampedValue } from './dotHelpers'; + +interface Trace { + id: string; + pv: string; + width?: number; + colour: string; + slot: number; +} +interface State { + traces: Trace[]; + ranges?: Record; +} +type Model = { palette: string[] }; + +const PALETTE = ['#111111', '#222222', '#333333']; + +function harness(initial: State, target: Target) { + let state = initial; + let updates = 0; + const ctx = (): ToolContext => ({ + state, + model: { palette: PALETTE }, + update(fn) { + updates += 1; + state = fn(state); + }, + selection: null, + target, + capabilities: { elog: false }, + ui: {}, + }); + return { ctx, state: () => state, updates: () => updates }; +} + +const item = (id: string): Target => ({ level: 'item', kind: 'trace', id }); +const traceOf = (state: State, id: string) => state.traces.find((t) => t.id === id)!; +const patch = (state: State, id: string, p: Partial): State => ({ + ...state, + traces: state.traces.map((t) => (t.id === id ? { ...t, ...p } : t)), +}); + +const base = (): State => ({ + traces: [ + { id: 'a', pv: 'PV:A', colour: PALETTE[0], slot: 0 }, + { id: 'b', pv: 'PV:B', width: 3, colour: PALETTE[1], slot: 1 }, + ], +}); + +describe('optionalPath', () => { + const dot = optionalPath({ + get: (ctx) => traceOf(ctx.state, ctx.target.id).width, + set: (state, target, value) => patch(state, target.id, { width: value }), + }); + + it('is pinned iff a value is present', () => { + expect(dot.modified(harness(base(), item('a')).ctx())).toBe(false); + expect(dot.modified(harness(base(), item('b')).ctx())).toBe(true); + }); + + it('treats a falsy present value as pinned', () => { + const h = harness(patch(base(), 'a', { width: 0 }), item('a')); + expect(dot.modified(h.ctx())).toBe(true); + }); + + it('reset writes undefined at the target and clears the dot', () => { + const h = harness(base(), item('b')); + dot.reset(h.ctx()); + expect(h.updates()).toBe(1); + expect(traceOf(h.state(), 'b').width).toBeUndefined(); + expect('width' in traceOf(h.state(), 'b')).toBe(true); + expect(traceOf(h.state(), 'a')).toEqual(base().traces[0]); + expect(dot.modified(h.ctx())).toBe(false); + }); + + it('satisfies DotProps', () => { + const props: DotProps = dot; + expect(typeof props.modified).toBe('function'); + }); +}); + +describe('recordKey', () => { + const dot = recordKey>({ + record: (state) => state.ranges, + key: (ctx) => ctx.state.traces.find((t) => t.id === ctx.target.id)?.pv, + write: (state, ranges) => ({ ...state, ranges }), + }); + const withRanges = (): State => ({ + ...base(), + ranges: { 'PV:B': { min: 0, max: 1 }, 'PV:C': { min: 2, max: 3 } }, + }); + + it('is pinned iff a per-PV record exists', () => { + expect(dot.modified(harness(withRanges(), item('a')).ctx())).toBe(false); + expect(dot.modified(harness(withRanges(), item('b')).ctx())).toBe(true); + }); + + it('is not pinned with no record at all or no key', () => { + expect(dot.modified(harness(base(), item('b')).ctx())).toBe(false); + expect(dot.modified(harness(withRanges(), item('missing')).ctx())).toBe(false); + }); + + it('does not count an inherited key as a record', () => { + const h = harness({ ...base(), ranges: {} }, item('a')); + const ctx = h.ctx(); + expect( + recordKey({ + record: (s) => s.ranges, + key: () => 'toString', + write: (s) => s, + }).modified(ctx) + ).toBe(false); + }); + + it('reset deletes only this key and does not mutate the old state', () => { + const before = withRanges(); + const h = harness(before, item('b')); + dot.reset(h.ctx()); + expect(h.state().ranges).toEqual({ 'PV:C': { min: 2, max: 3 } }); + expect(Object.hasOwn(h.state().ranges!, 'PV:B')).toBe(false); + expect(before.ranges).toHaveProperty('PV:B'); + expect(dot.modified(h.ctx())).toBe(false); + }); + + it('reset with no entry leaves the state untouched', () => { + const before = withRanges(); + const h = harness(before, item('a')); + dot.reset(h.ctx()); + expect(h.state()).toBe(before); + }); +}); + +describe('stampedValue', () => { + const autoColour = (ctx: ToolContext) => + ctx.model.palette[traceOf(ctx.state, ctx.target.id).slot % ctx.model.palette.length]; + const dot = stampedValue({ + get: (ctx) => traceOf(ctx.state, ctx.target.id).colour, + isAutomatic: (value, ctx) => value === autoColour(ctx), + automatic: autoColour, + set: (state, target, colour) => patch(state, target.id, { colour }), + }); + + it('is not pinned when the value is the slot automatic value', () => { + expect(dot.modified(harness(base(), item('a')).ctx())).toBe(false); + expect(dot.modified(harness(base(), item('b')).ctx())).toBe(false); + }); + + it('is pinned for a value no rule produces', () => { + const h = harness(patch(base(), 'a', { colour: '#abcdef' }), item('a')); + expect(dot.modified(h.ctx())).toBe(true); + }); + + it("is pinned when the value equals a different slot's automatic value", () => { + // b sits in slot 1 but carries slot 0's colour: still a user choice. + const h = harness(patch(base(), 'b', { colour: PALETTE[0] }), item('b')); + expect(dot.modified(h.ctx())).toBe(true); + dot.reset(h.ctx()); + expect(traceOf(h.state(), 'b').colour).toBe(PALETTE[1]); + expect(traceOf(h.state(), 'a').colour).toBe(PALETTE[0]); + expect(dot.modified(h.ctx())).toBe(false); + }); + + it('defers to the tool predicate when it accepts several values', () => { + const lenient = stampedValue({ + get: (ctx) => traceOf(ctx.state, ctx.target.id).colour, + isAutomatic: (value, ctx) => ctx.model.palette.includes(value), + automatic: autoColour, + set: (state, target, colour) => patch(state, target.id, { colour }), + }); + const h = harness(patch(base(), 'b', { colour: PALETTE[0] }), item('b')); + expect(lenient.modified(h.ctx())).toBe(false); + }); + + it('reset writes the automatic value at the target captured at reset time', () => { + const h = harness(patch(base(), 'a', { colour: '#abcdef', slot: 2 }), item('a')); + dot.reset(h.ctx()); + expect(h.updates()).toBe(1); + expect(traceOf(h.state(), 'a').colour).toBe(PALETTE[2]); + }); +}); diff --git a/src/tools/dotHelpers.ts b/src/tools/dotHelpers.ts new file mode 100644 index 0000000..b338091 --- /dev/null +++ b/src/tools/dotHelpers.ts @@ -0,0 +1,101 @@ +// The tool-side builders for a field's modified dot and its reset. +// +// A dot-bearing field spreads one of these into its schema entry, so no tool +// hand-writes the dot rule and the workbench never sees a default: it only +// calls `modified(ctx)` and `reset(ctx)`. Three shapes cover every dot: +// +// - `optionalPath`: the field is an optional value. Pinned iff a value is +// present; reset writes `undefined`. +// - `recordKey`: the field lives in a per-PV record. Pinned iff the record has +// an entry for this key; reset deletes the entry. +// - `stampedValue`: the tool stamps an automatic value (a palette colour, an +// axis slot) into the object. Pinned iff the stored value is not one the +// tool's automatic rule produces for this object; reset writes the automatic +// value for the object's slot. The tool supplies both the predicate and the +// slot value, so a value equal to a *different* slot's automatic value is +// judged by the tool's rule, not by a global list here. +// +// A field with no automatic rule (axis Side) uses no helper and has no dot. +// +// Readers take the whole ctx and read `ctx.target`, never `ctx.selection`; +// writers are pure state transforms handed to `ctx.update`, given the target +// captured when reset was invoked. + +import type { Target, ToolContext, ToolUi } from '../workbench/types'; + +/** The dot half of `DotProps`: both functions, ready to spread into a field. */ +export interface Dot { + modified(ctx: ToolContext): boolean; + reset(ctx: ToolContext): void; +} + +/** Pinned iff `get` yields a value; reset writes `undefined` through `set`. */ +export function optionalPath(spec: { + get(ctx: ToolContext): unknown; + set(state: State, target: Target, value: undefined): State; +}): Dot { + return { + modified: (ctx) => spec.get(ctx) !== undefined, + reset: (ctx) => { + const target = ctx.target; + ctx.update((state) => spec.set(state, target, undefined)); + }, + }; +} + +type PvRecord = Readonly>; + +/** + * Pinned iff the per-PV record holds an entry for `key(ctx)`; reset hands + * `write` a copy of the record without that entry. A missing record or an + * undefined key is never pinned, and its reset changes nothing. + */ +export function recordKey< + State, + Model, + Ui extends ToolUi = ToolUi, + R extends PvRecord = PvRecord, +>(spec: { + record(state: State): R | undefined; + key(ctx: ToolContext): string | undefined; + write(state: State, record: R): State; +}): Dot { + return { + modified: (ctx) => { + const key = spec.key(ctx); + const record = spec.record(ctx.state); + return key !== undefined && record !== undefined && Object.hasOwn(record, key); + }, + reset: (ctx) => { + const key = spec.key(ctx); + if (key === undefined) return; + ctx.update((state) => { + const record = spec.record(state); + if (record === undefined || !Object.hasOwn(record, key)) return state; + const rest: Record = { ...record }; + delete rest[key]; + return spec.write(state, rest as R); + }); + }, + }; +} + +/** + * Pinned iff `isAutomatic` rejects the stored value; reset writes + * `automatic(ctx)` (the object's own slot value) through `set`. + */ +export function stampedValue(spec: { + get(ctx: ToolContext): Value; + isAutomatic(value: Value, ctx: ToolContext): boolean; + automatic(ctx: ToolContext): Value; + set(state: State, target: Target, value: Value): State; +}): Dot { + return { + modified: (ctx) => !spec.isAutomatic(spec.get(ctx), ctx), + reset: (ctx) => { + const target = ctx.target; + const value = spec.automatic(ctx); + ctx.update((state) => spec.set(state, target, value)); + }, + }; +} diff --git a/src/workbench/ActionsBar.test.tsx b/src/workbench/ActionsBar.test.tsx new file mode 100644 index 0000000..074677c --- /dev/null +++ b/src/workbench/ActionsBar.test.tsx @@ -0,0 +1,461 @@ +// @vitest-environment jsdom +// +// The actions bar: actions are registered at runtime +// from inside the canvas, rendered under `actions-bar`, and every shortcut is +// bound from that one list. +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { StrictMode, useState, type ReactNode } from 'react'; +import { Add, Pause } from '@carbon/icons-react'; + +import type { Action } from './types'; +import { TESTIDS } from './testids'; +import { ActionsBar } from './ActionsBar'; +import { + CanvasActionsProvider, + createActionRegistry, + formatShortcut, + parseShortcut, + resolveActionShortcut, + useActionShortcuts, + useCanvasActions, + type ActionRegistry, +} from './useCanvasActions'; +import { standardActions } from './standardActions'; + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +function action(over: Partial & Pick): Action { + return { icon: Add, kind: 'button', onClick: () => {}, ...over }; +} + +/** A canvas that registers whatever it is given. */ +function Canvas({ actions }: { actions: Action[] }) { + useCanvasActions(actions); + return
canvas
; +} + +/** The workbench side: one registry, its shortcut listener, the canvas slot and the bar. */ +function Harness({ registry, children }: { registry: ActionRegistry; children: ReactNode }) { + useActionShortcuts(registry, { hostBar: false }); + return ( + + + {children} + + ); +} + +function bar(): HTMLElement { + return screen.getByTestId(TESTIDS.actionsBar); +} + +function barButtons(): HTMLElement[] { + return Array.from(bar().querySelectorAll('button')); +} + +function primaryKey(key: string, init: KeyboardEventInit = {}) { + // jsdom's navigator.platform is not a Mac, so primary is Ctrl. + return { key: key.toLowerCase(), code: `Key${key.toUpperCase()}`, ctrlKey: true, ...init }; +} + +describe('registration', () => { + it('renders the actions a child registers, in order, under actions-bar', () => { + const registry = createActionRegistry(); + render( + + + + ); + expect(barButtons()).toHaveLength(2); + expect(screen.getByRole('button', { name: 'Export' })).toBeTruthy(); + expect(screen.getByRole('button', { name: 'Clear' })).toBeTruthy(); + expect(bar().textContent).toMatch(/Export[\s\S]*Clear/); + }); + + it('unregisters on unmount', () => { + const registry = createActionRegistry(); + function Toggle() { + const [on, setOn] = useState(true); + return ( + + + {on && } + + ); + } + render(); + expect(screen.getByRole('button', { name: 'Export' })).toBeTruthy(); + fireEvent.click(screen.getByRole('button', { name: 'unmount' })); + expect(screen.queryByRole('button', { name: 'Export' })).toBeNull(); + expect(registry.getSnapshot()).toHaveLength(0); + }); + + it('keeps two registrants apart and survives StrictMode double effects', () => { + const registry = createActionRegistry(); + render( + + + + + + + ); + expect(barButtons()).toHaveLength(2); + }); + + it('calls the latest onClick without re-publishing an unchanged list', () => { + const registry = createActionRegistry(); + const first = vi.fn(); + const second = vi.fn(); + const { rerender } = render( + + + + ); + const before = registry.getSnapshot(); + rerender( + + + + ); + expect(registry.getSnapshot()).toBe(before); + fireEvent.click(screen.getByRole('button', { name: 'Export' })); + expect(first).not.toHaveBeenCalled(); + expect(second).toHaveBeenCalledTimes(1); + }); + + it('is a no-op outside a provider', () => { + expect(() => render()).not.toThrow(); + }); +}); + +describe('rendering', () => { + it('gives a toggle aria-pressed that follows `pressed`', () => { + const registry = createActionRegistry(); + function PauseCanvas() { + const [paused, setPaused] = useState(false); + useCanvasActions([ + action({ + id: 'pause', + label: 'Pause', + icon: Pause, + kind: 'toggle', + pressed: paused, + onClick: () => setPaused((p) => !p), + }), + ]); + return null; + } + render( + + + + ); + const button = screen.getByRole('button', { name: 'Pause' }); + expect(button.getAttribute('aria-pressed')).toBe('false'); + fireEvent.click(button); + expect(screen.getByRole('button', { name: 'Pause' }).getAttribute('aria-pressed')).toBe('true'); + }); + + it('gives a plain button no aria-pressed', () => { + const registry = createActionRegistry(); + render( + + + + ); + expect(screen.getByRole('button', { name: 'Export' }).hasAttribute('aria-pressed')).toBe(false); + }); + + it('puts the disabled reason in the tooltip and does not fire', () => { + const registry = createActionRegistry(); + const onClick = vi.fn(); + render( + + + + ); + const button = screen.getByRole('button', { name: /Export/ }); + expect( + button.getAttribute('aria-disabled') === 'true' || (button as HTMLButtonElement).disabled + ).toBe(true); + expect(screen.getByRole('button', { name: /No frame yet/ })).toBe(button); + expect(screen.getAllByText(/No frame yet/).length).toBeGreaterThan(0); + fireEvent.click(button); + expect(onClick).not.toHaveBeenCalled(); + }); + + it('shows the shortcut in the tooltip', () => { + const registry = createActionRegistry(); + render( + + + + ); + expect( + screen.getByRole('button', { name: `Save (${formatShortcut('primary+S')})` }) + ).toBeTruthy(); + }); +}); + +describe('shortcuts', () => { + it('fires a registered shortcut exactly once', () => { + const registry = createActionRegistry(); + const onSave = vi.fn(); + render( + + + + + + ); + const event = new KeyboardEvent('keydown', { + ...primaryKey('s'), + bubbles: true, + cancelable: true, + }); + act(() => { + window.dispatchEvent(event); + }); + expect(onSave).toHaveBeenCalledTimes(1); + expect(event.defaultPrevented).toBe(true); + }); + + it('ignores keys typed in inputs', () => { + const registry = createActionRegistry(); + const onSave = vi.fn(); + render( + + + + + ); + fireEvent.keyDown(screen.getByRole('textbox', { name: 'field' }), primaryKey('s')); + expect(onSave).not.toHaveBeenCalled(); + }); + + it('claims primary+P in an input, so Print never leaks to the browser', () => { + const registry = createActionRegistry(); + const onPrint = vi.fn(); + const onSave = vi.fn(); + render( + + +