Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

refactor(frontend): unify contextual focus state

rcourtman6a27c5d66f51
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 9eb00cd43f..8230aa9b85 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -147,6 +147,7 @@ work extends shared components instead of creating new local variants.
7. Keep top-of-page summary interaction on shared primitives. Infrastructure, workloads, and storage summary cards must route sticky-shell behavior through `frontend-modern/src/components/shared/StickySummarySection.tsx` and route row-hover or focused-series rendering through shared chart primitives such as `frontend-modern/src/components/shared/InteractiveSparkline.tsx` and `frontend-modern/src/components/shared/DensityMap.tsx`, rather than page-local sticky wrappers or metric-card-specific hover logic.
8. Keep summary chart interaction identity on one shared helper. Summary surfaces that expose hover- or focus-driven chart emphasis must derive the active series ID through `frontend-modern/src/components/shared/summaryCardInteraction.ts` and pass the same resolved ID into card-state, sparkline, and density-map primitives, rather than letting cards read `hovered || focused` while charts listen to a different page-local ID source.
9. Keep page summaries page-scoped when table rows enter contextual focus. Route-backed row selection may add a focused label and shared series emphasis, but infrastructure, workloads, and storage summary cards must continue to render the page-level series set instead of collapsing the summary down to the selected row or replacing the global trend view with row-local empty states.
+10. Keep contextual row focus on the shared summary primitive. Summary surfaces and same-route table drill-ins must reuse `frontend-modern/src/components/shared/contextualFocus.ts` for interactive-series filtering, focused-name lookup, active-series derivation, and local scroll preservation instead of rebuilding page-local `Set` filters, focused-label scans, or ad hoc scroll restoration in each surface.
## Forbidden Paths
@@ -226,6 +227,7 @@ work extends shared components instead of creating new local variants.
infrastructure-fallback truth must stay in
`frontend-modern/src/routing/resourceLinks.ts` instead of freezing raw
route strings or provider-local link builders inside feature panels.
+15. Keep shared contextual focus canonical after adoption. Once a summary or table surface enters route-backed contextual focus, future additions must extend `frontend-modern/src/components/shared/contextualFocus.ts` and its guardrail tests rather than forking another helper for workload IDs, resource IDs, or scroll-preserving same-route selection.
14. Keep shared infrastructure/resource selectors on the canonical agent-facet
truth. Shared primitives and settings-facing selector helpers must treat
top-level TrueNAS appliances as agent-facet infrastructure via shared
@@ -238,6 +240,14 @@ work extends shared components instead of creating new local variants.
fallback objects collapse API-backed TrueNAS systems back into generic
agent-host presentation.
16. Keep the authenticated app root aligned with that same first-session path.
+That same shared-primitive ownership now includes contextual row focus.
+`frontend-modern/src/components/shared/contextualFocus.ts` is the canonical
+owner for interactive-series filtering, focused-label lookup, active-series
+resolution, and nearest-scrollable-ancestor preservation across page-scoped
+summary surfaces. Dashboard row focus, infrastructure summary emphasis,
+storage summary emphasis, and workloads summary emphasis must all route through
+that helper instead of maintaining page-local copies of the same hover/focus
+rules.
`frontend-modern/src/App.tsx` must land `/` on the dashboard shell and let
the governed dashboard empty state route first-time operators into
Infrastructure Install, instead of preserving a separate root-only jump to
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 6b2858dd64..24b6f6a927 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -213,6 +213,12 @@ workloads summary surfaces must keep the summary page-scoped while that focus
reuses the shared highlight contract; density maps may retain page-level
context, but line-card isolation must still flow through the shared sparkline
runtime instead of a page-local focus overlay.
+That same hot-path rule now has one shared runtime boundary. Interactive-series
+filtering, active-series derivation, focused-label lookup, and local
+scroll-preserving row focus must extend
+`frontend-modern/src/components/shared/contextualFocus.ts` instead of
+rebuilding page-local `Set` scans or scroll repair logic in dashboard,
+infrastructure, or workloads hot paths.
That same hot-path rule now applies to infrastructure summary resource
filtering: `frontend-modern/src/components/Infrastructure/useInfrastructureSummaryState.ts`
must include API-backed systems such as top-level TrueNAS appliances through
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index c5fd1b4bbb..d897ae0064 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -222,6 +222,12 @@ the shared summary contract so pool usage, used capacity, and available space
cards can isolate the active row through the shared sparkline primitive while
non-matching cards such as disk temperature demote to inactive context instead
of rebuilding a row-local summary surface.
+That same storage summary contract now uses the shared contextual-focus owner.
+`frontend-modern/src/components/Storage/StorageSummary.tsx` must route
+interactive-series filtering, focused-label lookup, and active-series
+resolution through `frontend-modern/src/components/shared/contextualFocus.ts`
+so storage keeps the same page-scoped focus semantics as infrastructure and
+workloads instead of preserving a storage-local hover/focus branch.
The recovery backend is a real product boundary, not just a helper package:
`internal/recovery/` owns per-tenant SQLite persistence, rollup derivation,
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index c0d6dba5ac..2fc499d936 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -232,6 +232,13 @@ may vary card presentation, but the active sparkline or density-map series must
still resolve through the shared resource ID already emitted by unified
resources so table hover, focused detail state, and summary highlight all point
to the same resource identity.
+That same unified-resource boundary now also applies to infrastructure
+contextual focus plumbing. `frontend-modern/src/components/Infrastructure/useInfrastructureSummaryState.ts`
+must reuse `frontend-modern/src/components/shared/contextualFocus.ts` for
+interactive-series filtering, focused-resource naming, and active-series
+resolution so the infrastructure summary stays page-scoped while still
+highlighting the same canonical resource IDs used by the unified-resource
+table and route state.
That same unified-resource boundary now also owns stored metrics-target
continuity for provider-backed resources. When registry rebuild cannot derive a
fresh metrics target from raw source facets, `internal/unifiedresources/registry.go`
diff --git a/frontend-modern/src/components/Dashboard/__tests__/useDashboardSelectionState.test.ts b/frontend-modern/src/components/Dashboard/__tests__/useDashboardSelectionState.test.ts
index 44e625b0aa..da1084b8cf 100644
--- a/frontend-modern/src/components/Dashboard/__tests__/useDashboardSelectionState.test.ts
+++ b/frontend-modern/src/components/Dashboard/__tests__/useDashboardSelectionState.test.ts
@@ -35,6 +35,7 @@ describe('useDashboardSelectionState', () => {
afterEach(() => {
vi.runOnlyPendingTimers();
vi.useRealTimers();
+ document.body.innerHTML = '';
vi.unstubAllGlobals();
});
@@ -117,4 +118,44 @@ describe('useDashboardSelectionState', () => {
ROUTE_STATE_REPLACE_OPTIONS,
);
});
+
+ it('preserves the nearest scrollable ancestor when row focus changes locally', () => {
+ locationSearch = '?type=app-container&platform=truenas&agent=truenas-main';
+ const [filteredGuests] = createSignal<WorkloadGuest[]>([]);
+
+ const { result } = renderHook(() =>
+ useDashboardSelectionState({
+ filteredGuests,
+ setSelectedNode: vi.fn(),
+ }),
+ );
+
+ const scroller = document.createElement('div');
+ scroller.style.overflowY = 'auto';
+ Object.defineProperty(scroller, 'scrollHeight', {
+ configurable: true,
+ value: 400,
+ });
+ Object.defineProperty(scroller, 'clientHeight', {
+ configurable: true,
+ value: 200,
+ });
+ scroller.scrollTop = 140;
+
+ const tableWrapper = document.createElement('div');
+ scroller.appendChild(tableWrapper);
+ document.body.appendChild(scroller);
+
+ result.setTableWrapperRef(tableWrapper as HTMLDivElement);
+ result.setSelectedGuestId('app-container:truenas-main:nextcloud');
+
+ expect(scroller.scrollTop).toBe(140);
+
+ vi.runAllTimers();
+
+ expect(navigateSpy).toHaveBeenCalledWith(
+ '/workloads?type=app-container&platform=truenas&agent=truenas-main&resource=app-container%3Atruenas-main%3Anextcloud',
+ ROUTE_STATE_REPLACE_OPTIONS,
+ );
+ });
});
diff --git a/frontend-modern/src/components/Dashboard/useDashboardSelectionState.ts b/frontend-modern/src/components/Dashboard/useDashboardSelectionState.ts
index 011ee2ded9..da734d3e35 100644
--- a/frontend-modern/src/components/Dashboard/useDashboardSelectionState.ts
+++ b/frontend-modern/src/components/Dashboard/useDashboardSelectionState.ts
@@ -1,6 +1,7 @@
import { useLocation, useNavigate } from '@solidjs/router';
import { createEffect, createSignal, onCleanup, untrack, type Accessor } from 'solid-js';
+import { preserveScrollableAncestorVerticalOffset } from '@/components/shared/contextualFocus';
import type { WorkloadGuest } from '@/types/workloads';
import { createRouteStateNavigateScheduler } from '@/utils/routeStateNavigation';
import {
@@ -34,24 +35,8 @@ export function useDashboardSelectionState(options: UseDashboardSelectionStateOp
};
const setSelectedGuestIdState = (id: string | null) => {
- let scroller: HTMLElement | null = tableRef ?? null;
- while (scroller) {
- const { overflowY } = getComputedStyle(scroller);
- if (
- (overflowY === 'auto' || overflowY === 'scroll') &&
- scroller.scrollHeight > scroller.clientHeight
- ) {
- break;
- }
- scroller = scroller.parentElement;
- }
-
- const scrollTop = scroller?.scrollTop ?? 0;
- setSelectedGuestIdRaw(id);
-
- if (scroller) scroller.scrollTop = scrollTop;
- requestAnimationFrame(() => {
- if (scroller) scroller.scrollTop = scrollTop;
+ preserveScrollableAncestorVerticalOffset(tableRef, () => {
+ setSelectedGuestIdRaw(id);
});
};
diff --git a/frontend-modern/src/components/Infrastructure/InfrastructureSummary.tsx b/frontend-modern/src/components/Infrastructure/InfrastructureSummary.tsx
index de6023cc35..325a22442b 100644
--- a/frontend-modern/src/components/Infrastructure/InfrastructureSummary.tsx
+++ b/frontend-modern/src/components/Infrastructure/InfrastructureSummary.tsx
@@ -5,18 +5,12 @@ import { InteractiveSparkline } from '@/components/shared/InteractiveSparkline';
import { DensityMap } from '@/components/shared/DensityMap';
import { SummaryPanel } from '@/components/shared/SummaryPanel';
import { SummaryMetricCard } from '@/components/shared/SummaryMetricCard';
-import {
- resolveSummaryActiveSeriesId,
- resolveSummaryCardInteractionState,
-} from '@/components/shared/summaryCardInteraction';
import { formatThroughputRate } from '@/utils/throughputPresentation';
import type { InfrastructureSummaryProps } from './infrastructureSummaryModel';
import { useInfrastructureSummaryState } from './useInfrastructureSummaryState';
export const InfrastructureSummary: Component<InfrastructureSummaryProps> = (props) => {
const state = useInfrastructureSummaryState(props);
- const effectiveHoveredResourceId = () =>
- state.hasInteractiveResourceId(props.hoveredResourceId) ? props.hoveredResourceId : null;
const rangeLabel = () => props.timeRange || '1h';
@@ -25,17 +19,6 @@ export const InfrastructureSummary: Component<InfrastructureSummaryProps> = (pro
if (!name) return undefined;
return <span class="text-xs text-muted ml-1.5 truncate">&mdash; {name}</span>;
};
- const activeSeriesId = () =>
- resolveSummaryActiveSeriesId({
- hoveredSeriesId: effectiveHoveredResourceId(),
- focusedSeriesId: state.effectiveFocusedResourceId(),
- });
- const interactionStateFor = (series: Array<{ id: string }>) =>
- resolveSummaryCardInteractionState({
- series,
- hoveredSeriesId: effectiveHoveredResourceId(),
- focusedSeriesId: state.effectiveFocusedResourceId(),
- });
return (
<Show when={props.resources.length > 0}>
@@ -67,7 +50,7 @@ export const InfrastructureSummary: Component<InfrastructureSummaryProps> = (pro
loaded={state.isCurrentRangeLoaded()}
hasData={state.hasData('cpu')}
emptyMessage={state.emptyMessage()}
- interactionState={interactionStateFor(state.seriesFor('cpu'))}
+ interactionState={state.interactionStateFor(state.seriesFor('cpu'))}
>
<InteractiveSparkline
series={state.seriesFor('cpu')}
@@ -76,8 +59,8 @@ export const InfrastructureSummary: Component<InfrastructureSummaryProps> = (pro
activeSeriesDisplay="isolate"
yMode="percent"
highlightNearestSeriesOnHover
- highlightSeriesId={activeSeriesId()}
- interactionState={interactionStateFor(state.seriesFor('cpu'))}
+ highlightSeriesId={state.activeSeriesId()}
+ interactionState={state.interactionStateFor(state.seriesFor('cpu'))}
/>
</SummaryMetricCard>
@@ -87,7 +70,7 @@ export const InfrastructureSummary: Component<InfrastructureSummaryProps> = (pro
loaded={state.isCurrentRangeLoaded()}
hasData={state.hasData('memory')}
emptyMessage={state.emptyMessage()}
- interactionState={interactionStateFor(state.seriesFor('memory'))}
+ interactionState={state.interactionStateFor(state.seriesFor('memory'))}
>
<InteractiveSparkline
series={state.seriesFor('memory')}
@@ -96,8 +79,8 @@ export const InfrastructureSummary: Component<InfrastructureSummaryProps> = (pro
activeSeriesDisplay="isolate"
yMode="percent"
highlightNearestSeriesOnHover
- highlightSeriesId={activeSeriesId()}
- interactionState={interactionStateFor(state.seriesFor('memory'))}
+ highlightSeriesId={state.activeSeriesId()}
+ interactionState={state.interactionStateFor(state.seriesFor('memory'))}
/>
</SummaryMetricCard>
@@ -116,15 +99,15 @@ export const InfrastructureSummary: Component<InfrastructureSummaryProps> = (pro
loaded={state.isCurrentRangeLoaded()}
hasData={state.hasDiskIOData()}
emptyMessage={state.emptyMessage()}
- interactionState={interactionStateFor(state.diskioSeries())}
+ interactionState={state.interactionStateFor(state.diskioSeries())}
>
<DensityMap
series={state.diskioSeries()}
rangeLabel={rangeLabel()}
timeRange={props.timeRange}
formatValue={formatThroughputRate}
- highlightSeriesId={activeSeriesId()}
- interactionState={interactionStateFor(state.diskioSeries())}
+ highlightSeriesId={state.activeSeriesId()}
+ interactionState={state.interactionStateFor(state.diskioSeries())}
/>
</SummaryMetricCard>
@@ -188,15 +171,15 @@ export const InfrastructureSummary: Component<InfrastructureSummaryProps> = (pro
loaded={state.isCurrentRangeLoaded()}
hasData={state.hasNetData()}
emptyMessage={state.emptyHistoryLabel()}
- interactionState={interactionStateFor(state.networkSeries())}
+ interactionState={state.interactionStateFor(state.networkSeries())}
>
<DensityMap
series={state.networkSeries()}
rangeLabel={rangeLabel()}
timeRange={props.timeRange}
formatValue={formatThroughputRate}
- highlightSeriesId={activeSeriesId()}
- interactionState={interactionStateFor(state.networkSeries())}
+ highlightSeriesId={state.activeSeriesId()}
+ interactionState={state.interactionStateFor(state.networkSeries())}
/>
</SummaryMetricCard>
</Show>
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/infrastructureSummaryModel.test.ts b/frontend-modern/src/components/Infrastructure/__tests__/infrastructureSummaryModel.test.ts
index 6aa4dd68a1..c479aad7d9 100644
--- a/frontend-modern/src/components/Infrastructure/__tests__/infrastructureSummaryModel.test.ts
+++ b/frontend-modern/src/components/Infrastructure/__tests__/infrastructureSummaryModel.test.ts
@@ -63,6 +63,30 @@ describe('infrastructureSummaryModel', () => {
expect(getFocusedInfrastructureResourceName(allSeries, 'host-2')).toBe('Host 2');
});
+ it('keeps page-scoped metric series on canonical resource ids while focused highlight resolves separately', () => {
+ const allSeries = [
+ makeSeries('host-1', {
+ name: 'Host 1',
+ cpu: [{ timestamp: 1, value: 20 }],
+ }),
+ makeSeries('host-2', {
+ name: 'Host 2',
+ cpu: [{ timestamp: 2, value: 40 }],
+ }),
+ ];
+
+ expect(buildInfrastructureMetricSeries(buildInfrastructureDisplaySeries(allSeries, null), 'cpu')).toEqual([
+ { id: 'host-1', data: [{ timestamp: 1, value: 20 }], color: '#00aaff', name: 'Host 1' },
+ { id: 'host-2', data: [{ timestamp: 2, value: 40 }], color: '#00aaff', name: 'Host 2' },
+ ]);
+ expect(
+ resolveSummaryActiveSeriesId({
+ hoveredSeriesId: null,
+ focusedSeriesId: 'host-2',
+ }),
+ ).toBe('host-2');
+ });
+
it('keeps first-sample waiting logic on canonical summary inputs', () => {
const onlineResource = makeResource({ lastSeen: 5_000 });
diff --git a/frontend-modern/src/components/Infrastructure/useInfrastructureSummaryState.ts b/frontend-modern/src/components/Infrastructure/useInfrastructureSummaryState.ts
index 30b819dff0..1f6f110a52 100644
--- a/frontend-modern/src/components/Infrastructure/useInfrastructureSummaryState.ts
+++ b/frontend-modern/src/components/Infrastructure/useInfrastructureSummaryState.ts
@@ -1,6 +1,7 @@
import { createEffect, createMemo, createSignal, onCleanup } from 'solid-js';
import type { ChartData, TimeRange } from '@/api/charts';
import { useResources } from '@/hooks/useResources';
+import { useSummaryContextualFocusState } from '@/components/shared/contextualFocus';
import {
fetchInfrastructureSummaryAndCache,
readInfrastructureSummaryCache,
@@ -19,7 +20,6 @@ import {
buildInfrastructureResourceCounts,
buildInfrastructureSummarySeries,
buildInfrastructureWorkloadStats,
- getFocusedInfrastructureResourceName,
getAverageDiskCapacity,
getSingleDisplayedOnlineInfrastructureResource,
hasInfrastructureSeriesData,
@@ -228,37 +228,23 @@ export function useInfrastructureSummaryState(props: InfrastructureSummaryProps)
? buildInfrastructureSummarySeries(props.resources, chartMap(), agentResources())
: buildInfrastructureSummarySeries(props.resources, new Map(), agentResources()),
);
+ const summaryFocus = useSummaryContextualFocusState({
+ interactiveSeries: resourceSeries,
+ hoveredSeriesId: () => props.hoveredResourceId,
+ focusedSeriesId: () => props.focusedResourceId,
+ isSeriesInteractive: (series) =>
+ series.cpu.length >= 1 ||
+ series.memory.length >= 1 ||
+ series.diskio.length >= 1 ||
+ series.network.length >= 1,
+ });
const displaySeries = createMemo(() => {
return buildInfrastructureDisplaySeries(resourceSeries(), null);
});
- const interactiveResourceIds = createMemo(() => {
- const ids = new Set<string>();
- for (const series of resourceSeries()) {
- if (
- series.cpu.length >= 1 ||
- series.memory.length >= 1 ||
- series.diskio.length >= 1 ||
- series.network.length >= 1
- ) {
- ids.add(series.id);
- }
- }
- return ids;
- });
-
- const hasInteractiveResourceId = (value: string | null | undefined): value is string => {
- const normalized = value?.trim() || '';
- return normalized !== '' && interactiveResourceIds().has(normalized);
- };
-
- const effectiveFocusedResourceId = createMemo<string | null>(() => {
- return hasInteractiveResourceId(props.focusedResourceId) ? props.focusedResourceId : null;
- });
-
const focusedResourceName = createMemo(() => {
- return getFocusedInfrastructureResourceName(resourceSeries(), effectiveFocusedResourceId());
+ return summaryFocus.getFocusedSeriesName(resourceSeries());
});
const singleDisplayedOnlineResource = createMemo(() => {
@@ -308,9 +294,11 @@ export function useInfrastructureSummaryState(props: InfrastructureSummaryProps)
isCurrentRangeLoaded,
emptyHistoryLabel,
emptyMessage,
- effectiveFocusedResourceId,
+ activeSeriesId: summaryFocus.activeSeriesId,
+ effectiveFocusedResourceId: summaryFocus.effectiveFocusedSeriesId,
focusedResourceName,
- hasInteractiveResourceId,
+ hasInteractiveResourceId: summaryFocus.hasInteractiveSeriesId,
+ interactionStateFor: summaryFocus.interactionStateFor,
resourceCounts,
workloadStats,
avgDiskCapacity,
diff --git a/frontend-modern/src/components/Storage/StorageSummary.tsx b/frontend-modern/src/components/Storage/StorageSummary.tsx
index c89062272f..4a4420a462 100644
--- a/frontend-modern/src/components/Storage/StorageSummary.tsx
+++ b/frontend-modern/src/components/Storage/StorageSummary.tsx
@@ -1,12 +1,9 @@
import { Component, Show, createEffect, createMemo, createSignal, onCleanup } from 'solid-js';
import { InteractiveSparkline } from '@/components/shared/InteractiveSparkline';
import type { InteractiveSparklineSeries } from '@/components/shared/InteractiveSparkline';
+import { useSummaryContextualFocusState } from '@/components/shared/contextualFocus';
import { SummaryPanel } from '@/components/shared/SummaryPanel';
import { SummaryMetricCard } from '@/components/shared/SummaryMetricCard';
-import {
- resolveSummaryActiveSeriesId,
- resolveSummaryCardInteractionState,
-} from '@/components/shared/summaryCardInteraction';
import {
ChartsAPI,
type MetricPoint,
@@ -171,12 +168,6 @@ const StorageSummary: Component<StorageSummaryProps> = (props) => {
// Series builders
// ---------------------------------------------------------------------------
- const getFocusedSeriesName = (series: InteractiveSparklineSeries[]): string | null => {
- const focusedId = effectiveFocusedResourceId();
- if (!focusedId) return null;
- return series.find((entry) => entry.id === focusedId)?.name ?? null;
- };
-
const poolUsageSeries = createMemo((): InteractiveSparklineSeries[] => {
const d = data();
if (!d?.pools) return [];
@@ -232,32 +223,18 @@ const StorageSummary: Component<StorageSummaryProps> = (props) => {
data: disk.temperature as MetricPoint[],
}));
});
- const interactiveResourceIds = createMemo(() => {
- const ids = new Set<string>();
- for (const series of [
+ const interactiveSummarySeries = createMemo<InteractiveSparklineSeries[]>(() => [
...poolUsageSeries(),
...poolUsedSeries(),
...poolAvailSeries(),
...diskTempSeries(),
- ]) {
- ids.add(series.id);
- }
- return ids;
+ ]);
+ const summaryFocus = useSummaryContextualFocusState({
+ interactiveSeries: interactiveSummarySeries,
+ hoveredSeriesId: () => props.hoveredResourceId,
+ focusedSeriesId: () => props.focusedResourceId,
});
- const isInteractiveResourceId = (value: string | null | undefined): value is string => {
- const normalized = value?.trim() || '';
- return normalized !== '' && interactiveResourceIds().has(normalized);
- };
-
- const effectiveHoveredResourceId = createMemo<string | null>(() =>
- isInteractiveResourceId(props.hoveredResourceId) ? props.hoveredResourceId : null,
- );
-
- const effectiveFocusedResourceId = createMemo<string | null>(() =>
- isInteractiveResourceId(props.focusedResourceId) ? props.focusedResourceId : null,
- );
-
const hasPoolUsage = () => poolUsageSeries().length > 0;
const hasDiskTemp = () => diskTempSeries().length > 0;
const hasPoolUsed = () => poolUsedSeries().length > 0;
@@ -270,22 +247,13 @@ const StorageSummary: Component<StorageSummaryProps> = (props) => {
const formatTemp = (value: number) => `${value.toFixed(0)}°C`;
const showComponent = () => props.poolCount > 0 || props.diskCount > 0;
+ const getFocusedSeriesName = (series: InteractiveSparklineSeries[]): string | null =>
+ summaryFocus.getFocusedSeriesName(series);
const focusedLabel = (series: InteractiveSparklineSeries[]) => {
const name = getFocusedSeriesName(series);
if (!name) return undefined;
return <span class="text-xs text-muted ml-1.5 truncate">&mdash; {name}</span>;
};
- const activeSeriesId = () =>
- resolveSummaryActiveSeriesId({
- hoveredSeriesId: effectiveHoveredResourceId(),
- focusedSeriesId: effectiveFocusedResourceId(),
- });
- const interactionStateFor = (series: InteractiveSparklineSeries[]) =>
- resolveSummaryCardInteractionState({
- series,
- hoveredSeriesId: effectiveHoveredResourceId(),
- focusedSeriesId: effectiveFocusedResourceId(),
- });
return (
<Show when={showComponent()}>
@@ -313,7 +281,7 @@ const StorageSummary: Component<StorageSummaryProps> = (props) => {
loaded={loaded()}
hasData={hasPoolUsage()}
emptyMessage={emptyLabel()}
- interactionState={interactionStateFor(poolUsageSeries())}
+ interactionState={summaryFocus.interactionStateFor(poolUsageSeries())}
>
<InteractiveSparkline
series={poolUsageSeries()}
@@ -322,8 +290,8 @@ const StorageSummary: Component<StorageSummaryProps> = (props) => {
activeSeriesDisplay="isolate"
yMode="percent"
highlightNearestSeriesOnHover
- highlightSeriesId={activeSeriesId()}
- interactionState={interactionStateFor(poolUsageSeries())}
+ highlightSeriesId={summaryFocus.activeSeriesId()}
+ interactionState={summaryFocus.interactionStateFor(poolUsageSeries())}
/>
</SummaryMetricCard>
@@ -333,7 +301,7 @@ const StorageSummary: Component<StorageSummaryProps> = (props) => {
loaded={loaded()}
hasData={hasDiskTemp()}
emptyMessage={emptyLabel()}
- interactionState={interactionStateFor(diskTempSeries())}
+ interactionState={summaryFocus.interactionStateFor(diskTempSeries())}
>
<InteractiveSparkline
series={diskTempSeries()}
@@ -344,8 +312,8 @@ const StorageSummary: Component<StorageSummaryProps> = (props) => {
formatValue={formatTemp}
formatTopLabel={(max) => `${max.toFixed(0)}°C`}
highlightNearestSeriesOnHover
- highlightSeriesId={activeSeriesId()}
- interactionState={interactionStateFor(diskTempSeries())}
+ highlightSeriesId={summaryFocus.activeSeriesId()}
+ interactionState={summaryFocus.interactionStateFor(diskTempSeries())}
/>
</SummaryMetricCard>
@@ -355,7 +323,7 @@ const StorageSummary: Component<StorageSummaryProps> = (props) => {
loaded={loaded()}
hasData={hasPoolUsed()}
emptyMessage={emptyLabel()}
- interactionState={interactionStateFor(poolUsedSeries())}
+ interactionState={summaryFocus.interactionStateFor(poolUsedSeries())}
>
<InteractiveSparkline
series={poolUsedSeries()}
@@ -366,8 +334,8 @@ const StorageSummary: Component<StorageSummaryProps> = (props) => {
formatValue={(v) => formatBytes(v)}
formatTopLabel={(max) => formatBytes(max)}
highlightNearestSeriesOnHover
- highlightSeriesId={activeSeriesId()}
- interactionState={interactionStateFor(poolUsedSeries())}
+ highlightSeriesId={summaryFocus.activeSeriesId()}
+ interactionState={summaryFocus.interactionStateFor(poolUsedSeries())}
/>
</SummaryMetricCard>
@@ -377,7 +345,7 @@ const StorageSummary: Component<StorageSummaryProps> = (props) => {
loaded={loaded()}
hasData={hasPoolAvail()}
emptyMessage={emptyLabel()}
- interactionState={interactionStateFor(poolAvailSeries())}
+ interactionState={summaryFocus.interactionStateFor(poolAvailSeries())}
>
<InteractiveSparkline
series={poolAvailSeries()}
@@ -388,8 +356,8 @@ const StorageSummary: Component<StorageSummaryProps> = (props) => {
formatValue={(v) => formatBytes(v)}
formatTopLabel={(max) => formatBytes(max)}
highlightNearestSeriesOnHover
- highlightSeriesId={activeSeriesId()}
- interactionState={interactionStateFor(poolAvailSeries())}
+ highlightSeriesId={summaryFocus.activeSeriesId()}
+ interactionState={summaryFocus.interactionStateFor(poolAvailSeries())}
/>
</SummaryMetricCard>
</SummaryPanel>
diff --git a/frontend-modern/src/components/Storage/__tests__/Storage.test.tsx b/frontend-modern/src/components/Storage/__tests__/Storage.test.tsx
index bba63e7888..f093be05a5 100644
--- a/frontend-modern/src/components/Storage/__tests__/Storage.test.tsx
+++ b/frontend-modern/src/components/Storage/__tests__/Storage.test.tsx
@@ -915,6 +915,7 @@ describe('Storage', () => {
'[data-highlight-series-active="true"][data-highlight-series-id="pool:alpha"]',
).length,
).toBe(1);
+ expect(summary.querySelectorAll('[data-summary-card-state="inactive"]').length).toBe(3);
expect(
screen
.getByText('Used Capacity')
@@ -927,6 +928,12 @@ describe('Storage', () => {
.closest('[data-summary-card-state]')
?.textContent?.includes('No history yet'),
).toBe(false);
+ expect(
+ screen
+ .getByText('Pool Usage')
+ .closest('[data-summary-card-state]')
+ ?.getAttribute('data-summary-card-state'),
+ ).toBe('active');
});
storageSummarySpy.mockRestore();
diff --git a/frontend-modern/src/components/Workloads/WorkloadsSummary.test.tsx b/frontend-modern/src/components/Workloads/WorkloadsSummary.test.tsx
index e276cb61c0..7f5b008041 100644
--- a/frontend-modern/src/components/Workloads/WorkloadsSummary.test.tsx
+++ b/frontend-modern/src/components/Workloads/WorkloadsSummary.test.tsx
@@ -67,6 +67,7 @@ vi.mock('@/components/shared/DensityMap', () => ({
}));
const now = Date.now();
+const singlePointSeries = [{ timestamp: now, value: 12 }];
const twoPointSeries = [
{ timestamp: now - 60_000, value: 12 },
{ timestamp: now, value: 18 },
@@ -313,6 +314,57 @@ describe('WorkloadsSummary performance behavior', () => {
});
});
+ it('ignores focused workload ids that do not have interactive history', async () => {
+ const interactiveWorkloadId = 'cluster-a:pve1:101';
+ const nonInteractiveWorkloadId = 'cluster-a:pve1:102';
+ mockGetWorkloadCharts.mockResolvedValueOnce({
+ data: {
+ [interactiveWorkloadId]: {
+ cpu: twoPointSeries,
+ memory: twoPointSeries,
+ disk: twoPointSeries,
+ diskread: twoPointSeries,
+ diskwrite: twoPointSeries,
+ netin: twoPointSeries,
+ netout: twoPointSeries,
+ },
+ [nonInteractiveWorkloadId]: {
+ cpu: singlePointSeries,
+ memory: singlePointSeries,
+ disk: singlePointSeries,
+ diskread: singlePointSeries,
+ diskwrite: singlePointSeries,
+ netin: singlePointSeries,
+ netout: singlePointSeries,
+ },
+ },
+ dockerData: {},
+ guestTypes: {},
+ timestamp: now,
+ stats: {
+ oldestDataTimestamp: now - 60_000,
+ },
+ });
+
+ render(() => (
+ <WorkloadsSummary
+ timeRange="1h"
+ fallbackGuestCounts={{ total: 2, running: 2, stopped: 0 }}
+ fallbackSnapshots={makeSnapshots([interactiveWorkloadId, nonInteractiveWorkloadId])}
+ focusedWorkloadId={nonInteractiveWorkloadId}
+ />
+ ));
+
+ await waitFor(() => {
+ const sparklines = screen.getAllByTestId('sparkline');
+ expect(sparklines).toHaveLength(4);
+ for (const sparkline of sparklines) {
+ expect(sparkline.getAttribute('data-highlight-series-id')).toBe('');
+ expect(sparkline.getAttribute('data-interaction-state')).toBe('default');
+ }
+ });
+ });
+
it('keeps the page summary series page-scoped when a focused workload is selected', async () => {
const workloadIds = ['cluster-a:pve1:101', 'cluster-a:pve1:102'];
mockGetWorkloadCharts.mockResolvedValueOnce(makeChartsResponse(workloadIds));
diff --git a/frontend-modern/src/components/Workloads/WorkloadsSummary.tsx b/frontend-modern/src/components/Workloads/WorkloadsSummary.tsx
index 23d5e30d5f..d78404ec61 100644
--- a/frontend-modern/src/components/Workloads/WorkloadsSummary.tsx
+++ b/frontend-modern/src/components/Workloads/WorkloadsSummary.tsx
@@ -3,13 +3,10 @@ import {
InteractiveSparkline,
type InteractiveSparklineSeries,
} from '@/components/shared/InteractiveSparkline';
+import { useSummaryContextualFocusState } from '@/components/shared/contextualFocus';
import { DensityMap } from '@/components/shared/DensityMap';
import { SummaryPanel } from '@/components/shared/SummaryPanel';
import { SummaryMetricCard } from '@/components/shared/SummaryMetricCard';
-import {
- resolveSummaryActiveSeriesId,
- resolveSummaryCardInteractionState,
-} from '@/components/shared/summaryCardInteraction';
import {
ChartsAPI,
type ChartData,
@@ -650,41 +647,18 @@ export const WorkloadsSummary: Component<WorkloadsSummaryProps> = (props) => {
});
const displaySeries = createMemo(() => workloadSeries());
-
- const interactiveWorkloadIds = createMemo(() => {
- const ids = new Set<string>();
- for (const series of workloadSeries()) {
- if (
- series.cpu.length >= 2 ||
- series.memory.length >= 2 ||
- series.diskio.length >= 2 ||
- series.network.length >= 2
- ) {
- ids.add(series.id);
- }
- }
- return ids;
+ const summaryFocus = useSummaryContextualFocusState({
+ interactiveSeries: workloadSeries,
+ hoveredSeriesId: () => props.hoveredWorkloadId,
+ focusedSeriesId: () => props.focusedWorkloadId,
+ isSeriesInteractive: (series) =>
+ series.cpu.length >= 2 ||
+ series.memory.length >= 2 ||
+ series.diskio.length >= 2 ||
+ series.network.length >= 2,
});
- const isInteractiveWorkloadId = (value: string | null | undefined): value is string => {
- const normalized = value?.trim() || '';
- return normalized !== '' && interactiveWorkloadIds().has(normalized);
- };
-
- const effectiveHoveredWorkloadId = createMemo<string | null>(() =>
- isInteractiveWorkloadId(props.hoveredWorkloadId) ? props.hoveredWorkloadId : null,
- );
-
- const effectiveFocusedWorkloadId = createMemo<string | null>(() =>
- isInteractiveWorkloadId(props.focusedWorkloadId) ? props.focusedWorkloadId : null,
- );
-
- const focusedWorkloadName = createMemo(() => {
- const focused = effectiveFocusedWorkloadId();
- if (!focused) return null;
- const match = workloadSeries().find((s) => s.id === focused);
- return match?.name || null;
- });
+ const focusedWorkloadName = createMemo(() => summaryFocus.getFocusedSeriesName(workloadSeries()));
const cpuSeries = createMemo<InteractiveSparklineSeries[]>(() =>
displaySeries().map((series) => ({
@@ -740,17 +714,6 @@ export const WorkloadsSummary: Component<WorkloadsSummaryProps> = (props) => {
if (!name) return undefined;
return <span class="text-xs text-muted ml-1.5 truncate">&mdash; {name}</span>;
};
- const activeSeriesId = () =>
- resolveSummaryActiveSeriesId({
- hoveredSeriesId: effectiveHoveredWorkloadId(),
- focusedSeriesId: effectiveFocusedWorkloadId(),
- });
- const interactionStateFor = (series: InteractiveSparklineSeries[]) =>
- resolveSummaryCardInteractionState({
- series,
- hoveredSeriesId: effectiveHoveredWorkloadId(),
- focusedSeriesId: effectiveFocusedWorkloadId(),
- });
return (
<SummaryPanel
@@ -778,7 +741,7 @@ export const WorkloadsSummary: Component<WorkloadsSummaryProps> = (props) => {
loaded={!isLoading()}
hasData={hasCpuData()}
emptyMessage={fallbackTrendMessage() ?? undefined}
- interactionState={interactionStateFor(cpuSeries())}
+ interactionState={summaryFocus.interactionStateFor(cpuSeries())}
>
<InteractiveSparkline
series={cpuSeries()}
@@ -789,8 +752,8 @@ export const WorkloadsSummary: Component<WorkloadsSummaryProps> = (props) => {
sortTooltipByValue
maxTooltipRows={8}
highlightNearestSeriesOnHover
- highlightSeriesId={activeSeriesId()}
- interactionState={interactionStateFor(cpuSeries())}
+ highlightSeriesId={summaryFocus.activeSeriesId()}
+ interactionState={summaryFocus.interactionStateFor(cpuSeries())}
/>
</SummaryMetricCard>
@@ -800,7 +763,7 @@ export const WorkloadsSummary: Component<WorkloadsSummaryProps> = (props) => {
loaded={!isLoading()}
hasData={hasMemoryData()}
emptyMessage={fallbackTrendMessage() ?? undefined}
- interactionState={interactionStateFor(memorySeries())}
+ interactionState={summaryFocus.interactionStateFor(memorySeries())}
>
<InteractiveSparkline
series={memorySeries()}
@@ -811,8 +774,8 @@ export const WorkloadsSummary: Component<WorkloadsSummaryProps> = (props) => {
sortTooltipByValue
maxTooltipRows={8}
highlightNearestSeriesOnHover
- highlightSeriesId={activeSeriesId()}
- interactionState={interactionStateFor(memorySeries())}
+ highlightSeriesId={summaryFocus.activeSeriesId()}
+ interactionState={summaryFocus.interactionStateFor(memorySeries())}
/>
</SummaryMetricCard>
@@ -822,15 +785,15 @@ export const WorkloadsSummary: Component<WorkloadsSummaryProps> = (props) => {
loaded={!isLoading()}
hasData={hasDiskIOData()}
emptyMessage={fallbackTrendMessage() ?? undefined}
- interactionState={interactionStateFor(diskioSeries())}
+ interactionState={summaryFocus.interactionStateFor(diskioSeries())}
>
<DensityMap
series={diskioSeries()}
rangeLabel={selectedRange()}
timeRange={selectedRange()}
formatValue={formatThroughputRate}
- highlightSeriesId={activeSeriesId()}
- interactionState={interactionStateFor(diskioSeries())}
+ highlightSeriesId={summaryFocus.activeSeriesId()}
+ interactionState={summaryFocus.interactionStateFor(diskioSeries())}
/>
</SummaryMetricCard>
@@ -840,15 +803,15 @@ export const WorkloadsSummary: Component<WorkloadsSummaryProps> = (props) => {
loaded={!isLoading()}
hasData={hasNetworkData()}
emptyMessage={fallbackTrendMessage() ?? undefined}
- interactionState={interactionStateFor(networkSeries())}
+ interactionState={summaryFocus.interactionStateFor(networkSeries())}
>
<DensityMap
series={networkSeries()}
rangeLabel={selectedRange()}
timeRange={selectedRange()}
formatValue={formatThroughputRate}
- highlightSeriesId={activeSeriesId()}
- interactionState={interactionStateFor(networkSeries())}
+ highlightSeriesId={summaryFocus.activeSeriesId()}
+ interactionState={summaryFocus.interactionStateFor(networkSeries())}
/>
</SummaryMetricCard>
</SummaryPanel>
diff --git a/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts b/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts
index 95f929b2a7..ee50a81501 100644
--- a/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts
+++ b/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts
@@ -55,6 +55,7 @@ import trialBannerSource from '@/components/shared/TrialBanner.tsx?raw';
import trialBannerModelSource from '@/components/shared/trialBannerModel.ts?raw';
import interactiveSparklineSource from '@/components/shared/InteractiveSparkline.tsx?raw';
import interactiveSparklineModelSource from '@/components/shared/interactiveSparklineModel.ts?raw';
+import contextualFocusSource from '@/components/shared/contextualFocus.ts?raw';
import infrastructureSummaryTableSource from '@/components/shared/InfrastructureSummaryTable.tsx?raw';
import infrastructureSummaryTableRowSource from '@/components/shared/InfrastructureSummaryTableRow.tsx?raw';
import infrastructureSelectorModelSource from '@/components/shared/infrastructureSelectorModel.ts?raw';
@@ -99,6 +100,10 @@ import webInterfaceUrlFieldSource from '@/components/shared/WebInterfaceUrlField
import webInterfaceUrlFieldModelSource from '@/components/shared/webInterfaceUrlFieldModel.ts?raw';
import webInterfaceUrlFieldStateSource from '@/components/shared/useWebInterfaceUrlFieldState.ts?raw';
import guestRowSource from '@/components/Dashboard/GuestRow.tsx?raw';
+import dashboardSelectionStateSource from '@/components/Dashboard/useDashboardSelectionState.ts?raw';
+import infrastructureSummaryStateSource from '@/components/Infrastructure/useInfrastructureSummaryState.ts?raw';
+import storageSummarySource from '@/components/Storage/StorageSummary.tsx?raw';
+import workloadsSummarySource from '@/components/Workloads/WorkloadsSummary.tsx?raw';
import resourceDetailDrawerOverviewSource from '@/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx?raw';
import aiSettingsDialogsSource from '@/components/Settings/AISettingsDialogs.tsx?raw';
import generalSettingsPanelSource from '@/components/Settings/GeneralSettingsPanel.tsx?raw';
@@ -236,6 +241,23 @@ describe('shared primitive guardrails', () => {
expect(subtabsSource).toContain('subtabButtonClass');
});
+ it('keeps contextual row focus on one shared helper across summary consumers', () => {
+ expect(contextualFocusSource).toContain('export const preserveScrollableAncestorVerticalOffset');
+ expect(contextualFocusSource).toContain('export function useSummaryContextualFocusState');
+
+ expect(dashboardSelectionStateSource).toContain('preserveScrollableAncestorVerticalOffset');
+ expect(dashboardSelectionStateSource).not.toContain('const scrollTop = scroller?.scrollTop');
+
+ expect(infrastructureSummaryStateSource).toContain('useSummaryContextualFocusState');
+ expect(infrastructureSummaryStateSource).not.toContain('const interactiveResourceIds = createMemo');
+
+ expect(storageSummarySource).toContain('useSummaryContextualFocusState');
+ expect(storageSummarySource).not.toContain('resolveSummaryActiveSeriesId');
+
+ expect(workloadsSummarySource).toContain('useSummaryContextualFocusState');
+ expect(workloadsSummarySource).not.toContain('const interactiveWorkloadIds = createMemo');
+ });
+
it('keeps trial banner on shell, runtime, and model owners', () => {
expect(trialBannerSource).toContain('useTrialBannerState');
expect(trialBannerSource).toContain('TRIAL_BANNER_TITLE');
diff --git a/frontend-modern/src/components/shared/__tests__/summaryCardInteraction.test.ts b/frontend-modern/src/components/shared/__tests__/summaryCardInteraction.test.ts
index ccd817833d..941fd466fe 100644
--- a/frontend-modern/src/components/shared/__tests__/summaryCardInteraction.test.ts
+++ b/frontend-modern/src/components/shared/__tests__/summaryCardInteraction.test.ts
@@ -1,10 +1,29 @@
-import { describe, expect, it } from 'vitest';
+import { cleanup, renderHook } from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ preserveScrollableAncestorVerticalOffset,
+ useSummaryContextualFocusState,
+} from '@/components/shared/contextualFocus';
import {
resolveSummaryActiveSeriesId,
resolveSummaryCardInteractionState,
} from '@/components/shared/summaryCardInteraction';
describe('summaryCardInteraction', () => {
+ beforeEach(() => {
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
+ callback(0);
+ return 1;
+ });
+ });
+
+ afterEach(() => {
+ cleanup();
+ document.body.innerHTML = '';
+ vi.unstubAllGlobals();
+ });
+
it('prefers hovered series ids and falls back to focused ids', () => {
expect(
resolveSummaryActiveSeriesId({
@@ -48,4 +67,58 @@ describe('summaryCardInteraction', () => {
}),
).toBe('inactive');
});
+
+ it('filters contextual focus down to interactive series ids through one shared hook', () => {
+ const [hoveredSeriesId] = createSignal<string | null>('gamma');
+ const [focusedSeriesId] = createSignal<string | null>('alpha');
+
+ const { result } = renderHook(() =>
+ useSummaryContextualFocusState({
+ interactiveSeries: () => [
+ { id: 'alpha', name: 'Alpha', interactive: true },
+ { id: 'beta', name: 'Beta', interactive: false },
+ ],
+ hoveredSeriesId,
+ focusedSeriesId,
+ isSeriesInteractive: (series) => series.interactive,
+ }),
+ );
+
+ expect(result.hasInteractiveSeriesId('alpha')).toBe(true);
+ expect(result.hasInteractiveSeriesId('beta')).toBe(false);
+ expect(result.effectiveHoveredSeriesId()).toBeNull();
+ expect(result.effectiveFocusedSeriesId()).toBe('alpha');
+ expect(result.activeSeriesId()).toBe('alpha');
+ expect(
+ result.getFocusedSeriesName([
+ { id: 'alpha', name: 'Alpha', interactive: true },
+ { id: 'beta', name: 'Beta', interactive: false },
+ ]),
+ ).toBe('Alpha');
+ expect(result.interactionStateFor([{ id: 'alpha' }])).toBe('active');
+ expect(result.interactionStateFor([{ id: 'beta' }])).toBe('inactive');
+ });
+
+ it('preserves the nearest scrollable ancestor when contextual focus changes locally', () => {
+ const scroller = document.createElement('div');
+ scroller.style.overflowY = 'auto';
+ Object.defineProperty(scroller, 'scrollHeight', {
+ configurable: true,
+ value: 400,
+ });
+ Object.defineProperty(scroller, 'clientHeight', {
+ configurable: true,
+ value: 200,
+ });
+ scroller.scrollTop = 120;
+ const child = document.createElement('div');
+ scroller.appendChild(child);
+ document.body.appendChild(scroller);
+
+ preserveScrollableAncestorVerticalOffset(child, () => {
+ scroller.scrollTop = 0;
+ });
+
+ expect(scroller.scrollTop).toBe(120);
+ });
});
diff --git a/frontend-modern/src/components/shared/contextualFocus.ts b/frontend-modern/src/components/shared/contextualFocus.ts
new file mode 100644
index 0000000000..fc71748769
--- /dev/null
+++ b/frontend-modern/src/components/shared/contextualFocus.ts
@@ -0,0 +1,133 @@
+import { createMemo, type Accessor } from 'solid-js';
+import {
+ resolveSummaryActiveSeriesId,
+ resolveSummaryCardInteractionState,
+ type SummaryCardInteractionState,
+} from './summaryCardInteraction';
+
+type ContextualFocusSeries = {
+ id?: string | null;
+ name?: string | null;
+};
+
+export interface UseSummaryContextualFocusStateOptions<T extends ContextualFocusSeries> {
+ focusedSeriesId?: Accessor<string | null | undefined>;
+ getSeriesName?: (series: T) => string | null | undefined;
+ hoveredSeriesId?: Accessor<string | null | undefined>;
+ interactiveSeries: Accessor<readonly T[]>;
+ isSeriesInteractive?: (series: T) => boolean;
+}
+
+const normalizeSeriesId = (value: string | null | undefined): string => value?.trim() || '';
+
+const resolveScrollableAncestor = (element: Element | null | undefined): HTMLElement | null => {
+ let scroller = element instanceof HTMLElement ? element : null;
+ while (scroller) {
+ const { overflowY } = getComputedStyle(scroller);
+ if (
+ (overflowY === 'auto' || overflowY === 'scroll') &&
+ scroller.scrollHeight > scroller.clientHeight
+ ) {
+ return scroller;
+ }
+ scroller = scroller.parentElement;
+ }
+ return null;
+};
+
+export const preserveScrollableAncestorVerticalOffset = (
+ anchor: Element | null | undefined,
+ apply: () => void,
+): void => {
+ const scroller = resolveScrollableAncestor(anchor);
+ const scrollTop = scroller?.scrollTop ?? null;
+
+ apply();
+
+ if (!scroller || scrollTop === null) {
+ return;
+ }
+
+ scroller.scrollTop = scrollTop;
+ if (typeof window === 'undefined' || typeof window.requestAnimationFrame !== 'function') {
+ return;
+ }
+ window.requestAnimationFrame(() => {
+ if (scroller.isConnected) {
+ scroller.scrollTop = scrollTop;
+ }
+ });
+};
+
+export function useSummaryContextualFocusState<T extends ContextualFocusSeries>(
+ options: UseSummaryContextualFocusStateOptions<T>,
+) {
+ const hoveredSeriesId = options.hoveredSeriesId ?? (() => null);
+ const focusedSeriesId = options.focusedSeriesId ?? (() => null);
+ const getSeriesName =
+ options.getSeriesName ??
+ ((series: T) => (typeof series.name === 'string' ? series.name : null));
+ const isSeriesInteractive =
+ options.isSeriesInteractive ?? ((series: T) => normalizeSeriesId(series.id) !== '');
+
+ const interactiveSeriesIds = createMemo(() => {
+ const ids = new Set<string>();
+ for (const series of options.interactiveSeries()) {
+ if (!isSeriesInteractive(series)) {
+ continue;
+ }
+ const id = normalizeSeriesId(series.id);
+ if (id) {
+ ids.add(id);
+ }
+ }
+ return ids;
+ });
+
+ const hasInteractiveSeriesId = (value: string | null | undefined): value is string => {
+ const normalized = normalizeSeriesId(value);
+ return normalized !== '' && interactiveSeriesIds().has(normalized);
+ };
+
+ const effectiveHoveredSeriesId = createMemo<string | null>(() => {
+ return hasInteractiveSeriesId(hoveredSeriesId()) ? normalizeSeriesId(hoveredSeriesId()) : null;
+ });
+
+ const effectiveFocusedSeriesId = createMemo<string | null>(() => {
+ return hasInteractiveSeriesId(focusedSeriesId()) ? normalizeSeriesId(focusedSeriesId()) : null;
+ });
+
+ const activeSeriesId = createMemo<string | null>(() =>
+ resolveSummaryActiveSeriesId({
+ hoveredSeriesId: effectiveHoveredSeriesId(),
+ focusedSeriesId: effectiveFocusedSeriesId(),
+ }),
+ );
+
+ const getFocusedSeriesName = (series: readonly T[]): string | null => {
+ const focusedId = effectiveFocusedSeriesId();
+ if (!focusedId) {
+ return null;
+ }
+ const match = series.find((entry) => normalizeSeriesId(entry.id) === focusedId);
+ return match ? getSeriesName(match) || null : null;
+ };
+
+ const interactionStateFor = (
+ series: ReadonlyArray<{ id?: string | null }>,
+ ): SummaryCardInteractionState =>
+ resolveSummaryCardInteractionState({
+ series,
+ hoveredSeriesId: effectiveHoveredSeriesId(),
+ focusedSeriesId: effectiveFocusedSeriesId(),
+ });
+
+ return {
+ activeSeriesId,
+ effectiveFocusedSeriesId,
+ effectiveHoveredSeriesId,
+ getFocusedSeriesName,
+ hasInteractiveSeriesId,
+ interactionStateFor,
+ } as const;
+}