Skip to content
This repository was archived by the owner on Nov 4, 2026. It is now read-only.

Commit 1f5a644

Browse files
refactor(plugin-dashboard): one auto-refresh timer for both dashboard surfaces, pinned by call counts (objectui#8820) (#10995)
Fixes #8820 Clause-②: no ## What changed `DashboardGridLayout` and `DashboardRenderer` each carried their own copy of the dashboard auto-refresh logic: a `refreshing` flag, a `handleRefresh` callback used by both the "Refresh All" button and the timer, and an effect that read `refreshIntervalSeconds` and drove `setInterval`. Both surfaces now call one hook, `useDashboardAutoRefresh` (new file `packages/plugin-dashboard/src/useDashboardAutoRefresh.ts`), which is that logic moved unchanged. The authored period is now read in one place. The hook is internal: the package entry is not touched. A new pin, `packages/plugin-dashboard/src/__tests__/dashboardAutoRefreshTimer.test.tsx`, mounts both components and counts `onRefresh` calls under fake timers. ## Base re-read, measured on `42687baf2` before any edit - The two timers were identical in logic: the same `refreshing` state, the same `handleRefresh` body (`setRefreshing(true)`, `onRefresh()`, a 600ms reset), the same early return (no timer when `refreshIntervalSeconds` is falsy, is zero or less, or `onRefresh` is missing), the same `setInterval(handleRefresh, schema.refreshIntervalSeconds * 1000)`, and the same dependency list `[schema.refreshIntervalSeconds, onRefresh, handleRefresh]`. They differed only in comments and in `React.useX` versus named imports. - Each read only `refreshIntervalSeconds`. The string `refreshInterval` appears in both files only inside comments. - The installed `@objectstack/spec` is 17.4.0, and its `DashboardSchema` refuses `refreshInterval` by name (`safeParse` answers `invalid_type` on that path, with the rename message). So the hook reads one key and has no fallback. ## Why this is behaviour-neutral - The gate, the seconds-to-milliseconds arithmetic and the dependency list are copied as they were. - The effect keeps the interval id in an effect-local constant instead of `intervalRef`. The ref was read only by the cleanup of the effect that wrote it, so the two forms clear the same interval in every sequence. - In `DashboardRenderer` the hook call sits where the old `handleRefresh` and effect sat, so the refresh effect keeps its order relative to the component's other effects. In `DashboardGridLayout` it sits where that component's effect sat. ## Departures from the prior-art branch (`claude/issue-8820-dashboard-refresh-interval-seconds`, `e5d95e1a4`) That branch was not pushed to or rewritten; this is a new branch. - **Dropped the both-spelling read**, as the card asks. - **Dropped the number-only filter** (`resolveRefreshIntervalSeconds`, which refused a string `'30'` and `NaN`). On base, the early return only rejects a falsy or non-positive value, so it starts a 30s timer for a string `'30'`, and refusing it would be a behaviour change beyond de-duplication. - **Did not carry** its edits to the published `inputs` row, the config panel, or the i18n overlay: the card puts them out of scope, and objectui#8783 has already moved them. - **Reworked the pin** for a single spelling. The missing-handler case now counts pending timers instead of only asserting that nothing throws. New cases: a changed period re-arming (the card names it), a negative period, the retired spelling, the phase across an equal-period re-render, a handler swap, and the de-duplication case. ## The pin: 11 cases per surface, 22 in all Each block is `describe.each` over both components, so a failure names the surface. 1. fires every `refreshIntervalSeconds` seconds (30s period, 95s elapsed: exactly 3 calls, none before the first period); 2. does not start when no period is authored; 3. and 4. does not start for a period of `0` or `-30`; 5. does not read the retired `refreshInterval` spelling; 6. arms no interval without an `onRefresh` host handler (pending fake-timer count, with a control leg: the same period plus a handler arms exactly one more timer than no period); 7. stops when the dashboard unmounts; 8. re-arms on a changed period: 30s becomes 60s at t=30s, there is no second call by t=89s, and there is one at t=90s; 9. keeps its phase across a re-render that repeats the same period in a new schema object; 10. calls the current `onRefresh` after the host swaps it, never the old one; 11. takes its timer from the shared `useDashboardAutoRefresh` hook (the de-duplication case: the real hook is wrapped in a `vi.fn` passthrough). ## Evidence All test and type-check runs went through `os-verify-lock`. Each verdict below is the one the tool printed. The base leg and the ablation ran at `b98eb6164`. The last commit, `f990a9997`, changes only comments in the hook and the pin plus one changeset sentence, and everything else below was rerun on it. - **Base leg** (the two components checked out at `42687baf2`, with the new hook and pin present). Predicted before the run: only case 11 goes red, on both surfaces. Observed: `Tests 2 failed | 20 passed (22)`. The two failures are the case-11 pair, each reading `Number of calls: 0`. The firing cases are green on base because base's two copies do fire; firing is proven load-bearing by the ablation below. Restore was `git checkout HEAD --` on absolute paths inside a trap. After it, the two blobs were back to their HEAD hashes (`6b2cf9e46`, `bde5d0e96`), `git diff HEAD` was empty and `git status --porcelain` was empty. - **Reader ablation**, through `ablation-replace.mjs`. The anchor `const seconds = schema.refreshIntervalSeconds;` became `const seconds = undefined as number | undefined;`. On disk: anchor x1 to x0, replacement x0 to x1, blob `dd029bbd0484` to `5e8e6e2ffff3`. Predicted before the run: cases 1 and 6 to 10 go red on both surfaces (12), and cases 2 to 5 and 11 stay green (10). Case 6 goes red through its control leg. Observed: `Tests 12 failed | 10 passed (22)`, exactly that set. Restore: `blob == HEAD (dd029bb) and git diff HEAD is empty`, and the tree was clean afterwards. No `dist/` is involved: the pin imports the components and the hook by relative `src` paths. - **`@object-ui/plugin-dashboard` suite plus the derived suites below, in one run** at `f990a9997`: `Test Files 171 passed (171)`, `Tests 2123 passed | 6 skipped (2129)`. At `b98eb6164` the same two sets, run separately, gave 150 files (1368 passed, 6 skipped) and 21 files (755 passed). - **Type-check**: at `b98eb6164`, `turbo run type-check --filter=@object-ui/plugin-dashboard` built the dependencies first and gave `Tasks: 14 successful, 14 total`. At `f990a9997`, `pnpm --filter @object-ui/plugin-dashboard type-check` (`tsc --noEmit && tsc -p tsconfig.test.json`) exited 0. `tsc --listFilesOnly` shows both `tsconfig.json` and `tsconfig.test.json` include the touched files. - **Suites that read the touched files from disk or scan their corpus.** The set is: the `scripts/__tests__` suites for `vi-mock-specifiers`, `vi-mock-inherit`, `vi-mock-override-shape`, `markdown-test-inputs`, `one-authority-per-exported-name-6273`, `new-cross-file-line-citations`, `handler-key-read-sites`, `control-bytes`, `test-path-roots`, `unreferenced-sources`, `type-check-coverage`, `side-effects-declaration-consistency`, the six changeset suites and `changeset-polarity-census`; plus `packages/sdui-parser/src/__tests__/dashboard-widget-options-census.test.ts` and `examples/schema-catalog/test/plugin-dashboard-gallery-render.test.tsx`, which read or render these two components. - **Pin at `f990a9997`**: all 22 cases pass inside the run above. - **Gates** at `f990a9997`, each exit 0 with an OK verdict: `check-control-bytes`, `check:new-line-citations` (`0 new citation(s)`), `check-vi-mock-specifiers`, `check-vi-mock-inherit`, `check-vi-mock-override-shape`, `check-test-path-roots`, `check-unreferenced-sources`, `check-type-check-coverage`, `check:self-import`, `check-phantom-dependencies`, `check:handler-key-reads`, `check-changeset-presence`, `check-changeset-no-major`, `check-changeset-fixed`, `check-changeset-claims`, `check-changeset-overwrite`, `check-pending-changeset-literals`, and `check-governed-queue-guard --test` (`NOT GOVERNED`). - **eslint, narrowed**, at `f990a9997`, to the four touched TypeScript files with `--no-inline-config`. The population is those four files; `eslint --print-config` resolves a config for each. The count comes from `--format json`: 4 files, 0 errors, 16 warnings. The same two components at `42687baf2` give 8 + 8 warnings with the same rule counts, and the two new files give none. `eslint.config.js` declares no `projectService` or `parserOptions.project`, so linting is not type-aware and this diff cannot move the verdict of any untouched file. The repo-wide `eslint .` run belongs to CI. ## Acceptance notes - ⚠️ The hook's effect still lists `handleRefresh`, a `useCallback` identity, as a dependency. AGENTS.md commandment 10 bans this shape. It is carried over because this card changes no behaviour, and a comment in the hook says so. A fix is now one edit instead of two, and cases 9 and 10 pin the timing that such a fix has to keep. Not filed: it only shows under a forced memo discard, which this tree does not produce on its own. - NOT MEASURED: `check:readme-exports`, because it needs every package's `dist/` on disk (`type entry ... is not on disk -- run pnpm build first`). This diff touches no README and no package export. - NOT MEASURED locally: the full `pnpm test` and repo-wide lint. Both belong to CI. Session: `https://claude.ai/code/session_01DuWo5bdP9SdVebamn99GGk` (dispatched by the `domain:ui` seat 1 PM; the claim is objectui#8820 comment 5871391146). --- _Generated by [Claude Code](https://claude.ai/code/session_01DuWo5bdP9SdVebamn99GGk)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 8aa68b1 commit 1f5a644

5 files changed

Lines changed: 324 additions & 44 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
---
2+
'@object-ui/plugin-dashboard': patch
3+
---
4+
5+
`DashboardGridLayout` and `DashboardRenderer` now share one auto-refresh timer
6+
(objectui#8820).
7+
8+
Each surface used to carry its own copy of the auto-refresh logic: the
9+
refreshing indicator, the handler behind the "Refresh All" button, and the
10+
interval that reads `refreshIntervalSeconds`. The two copies were identical in
11+
logic. They are now one internal hook, `useDashboardAutoRefresh`, that both
12+
surfaces call, so the authored period is read in one place.
13+
14+
Behaviour is unchanged. The timer runs only when the host passes `onRefresh`
15+
and `refreshIntervalSeconds` is greater than zero; it is cleared when the
16+
dashboard unmounts and re-armed when the period changes.
17+
18+
A new test mounts both surfaces and counts `onRefresh` calls under fake timers,
19+
so a timer that stops firing on either surface fails a test.

‎packages/plugin-dashboard/src/DashboardGridLayout.tsx‎

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { classifyWidgetType } from './widgetDispatch';
1212
import { LEGACY_RETIRED_WIDGET_SCHEMA, isLegacyRetiredWidget } from './legacyRetiredWidget';
1313
import { DatasetWidget } from './DatasetWidget';
1414
import { useWidgetSubCaption } from './widgetSubCaption';
15+
import { useDashboardAutoRefresh } from './useDashboardAutoRefresh';
1516

1617
/** Bridges editMode transitions to the ObjectUI DnD system when a DndProvider is present. */
1718
function DndEditModeBridge({ editMode }: { editMode: boolean }) {
@@ -128,7 +129,6 @@ export const DashboardGridLayout: React.FC<DashboardGridLayoutProps> = ({
128129
}) => {
129130
const { width, containerRef, mounted } = useContainerWidth();
130131
const [editMode, setEditMode] = React.useState(false);
131-
const [refreshing, setRefreshing] = React.useState(false);
132132
const hasDndProvider = useHasDndProvider();
133133
// Active UI language, for resolving inline per-locale widget titles below.
134134
// `useObjectTranslation` is provider-safe (react-i18next falls back to its
@@ -171,25 +171,11 @@ export const DashboardGridLayout: React.FC<DashboardGridLayoutProps> = ({
171171
* degradation the sibling's title/description lookups perform.
172172
*/
173173
const tWidgetSubCaption = useWidgetSubCaption(schema.name);
174-
const intervalRef = React.useRef<ReturnType<typeof setInterval> | null>(null);
175-
176-
const handleRefresh = React.useCallback(() => {
177-
if (!onRefresh) return;
178-
setRefreshing(true);
179-
onRefresh();
180-
setTimeout(() => setRefreshing(false), 600);
181-
}, [onRefresh]);
182-
183-
// Auto-refresh interval — seconds → milliseconds, as the key now says
184-
// (objectui#7783; the spec renamed `refreshInterval` to
185-
// `refreshIntervalSeconds`, value unchanged).
186-
React.useEffect(() => {
187-
if (!schema.refreshIntervalSeconds || schema.refreshIntervalSeconds <= 0 || !onRefresh) return;
188-
intervalRef.current = setInterval(handleRefresh, schema.refreshIntervalSeconds * 1000);
189-
return () => {
190-
if (intervalRef.current) clearInterval(intervalRef.current);
191-
};
192-
}, [schema.refreshIntervalSeconds, onRefresh, handleRefresh]);
174+
// The refresh indicator, the manual handler and the auto-refresh timer come
175+
// from the one implementation this component shares with `DashboardRenderer`
176+
// (objectui#8820), which is also the only place `refreshIntervalSeconds` is
177+
// read.
178+
const { refreshing, handleRefresh } = useDashboardAutoRefresh(schema, onRefresh);
193179
const [layouts, setLayouts] = React.useState<{ lg: RGLLayout[] }>(
194180
() => buildDefaultLayouts(schema),
195181
);

‎packages/plugin-dashboard/src/DashboardRenderer.tsx‎

Lines changed: 7 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import {
2121
chartConfigPresentation,
2222
} from '@object-ui/core';
2323
import { cn, Card, CardHeader, CardTitle, CardContent, Button, getLazyIcon } from '@object-ui/components';
24-
import { forwardRef, useState, useEffect, useCallback, useMemo, useRef, Fragment } from 'react';
24+
import { forwardRef, useState, useEffect, useCallback, useMemo, Fragment } from 'react';
2525
import type { HTMLAttributes } from 'react';
2626
import { RefreshCw } from 'lucide-react';
2727
import {
@@ -45,6 +45,7 @@ import { classifyWidgetType, METRIC_LIKE_TYPES } from './widgetDispatch';
4545
import { LEGACY_RETIRED_WIDGET_SCHEMA, isLegacyRetiredWidget } from './legacyRetiredWidget';
4646
import { DatasetWidget } from './DatasetWidget';
4747
import { useWidgetSubCaption } from './widgetSubCaption';
48+
import { useDashboardAutoRefresh } from './useDashboardAutoRefresh';
4849
import { DashboardFilterBar } from './DashboardFilterBar';
4950

5051
/**
@@ -286,9 +287,7 @@ const DashboardRendererInner = forwardRef<HTMLDivElement, DashboardRendererProps
286287
// Defined here (not just above desktopBody) so renderWidget can give
287288
// layout-less widgets a sensible default span in the positioned grid.
288289
const hasExplicitColumns = schema.columns != null || inferredColumns !== 4;
289-
const [refreshing, setRefreshing] = useState(false);
290290
const [isMobile, setIsMobile] = useState(false);
291-
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
292291

293292
// Dashboard-level filters (framework#2501). Filter values live as
294293
// dashboard variables — the outer DashboardRenderer mounts a
@@ -488,27 +487,11 @@ const DashboardRendererInner = forwardRef<HTMLDivElement, DashboardRendererProps
488487
return () => window.removeEventListener('resize', checkMobile);
489488
}, []);
490489

491-
const handleRefresh = useCallback(() => {
492-
if (!onRefresh) return;
493-
setRefreshing(true);
494-
onRefresh();
495-
// Reset refreshing indicator after a short delay
496-
setTimeout(() => setRefreshing(false), 600);
497-
}, [onRefresh]);
498-
499-
// Auto-refresh interval. The `* 1000` is seconds → milliseconds, and the
500-
// key now says so itself: @objectstack/spec 17.4.0 renamed
501-
// `refreshInterval` to `refreshIntervalSeconds` precisely because a reader
502-
// multiplying by 1000 was the tell that the unit lived out of band
503-
// (objectstack#15680, objectui#7783). The arithmetic is unchanged — the
504-
// value is still seconds.
505-
useEffect(() => {
506-
if (!schema.refreshIntervalSeconds || schema.refreshIntervalSeconds <= 0 || !onRefresh) return;
507-
intervalRef.current = setInterval(handleRefresh, schema.refreshIntervalSeconds * 1000);
508-
return () => {
509-
if (intervalRef.current) clearInterval(intervalRef.current);
510-
};
511-
}, [schema.refreshIntervalSeconds, onRefresh, handleRefresh]);
490+
// The refresh indicator, the manual handler and the auto-refresh timer come
491+
// from the one implementation this component shares with
492+
// `DashboardGridLayout` (objectui#8820), which is also the only place
493+
// `refreshIntervalSeconds` is read.
494+
const { refreshing, handleRefresh } = useDashboardAutoRefresh(schema, onRefresh);
512495

513496
const handleWidgetClick = useCallback((e: React.MouseEvent, widgetId: string | undefined) => {
514497
if (!designMode || !onWidgetClick || !widgetId) return;
Lines changed: 210 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* The dashboard auto-refresh timer FIRES, on both mount points (objectui#8820).
11+
*
12+
* ## Why the assertion is a call count
13+
*
14+
* When this file was written, every other test for `refreshIntervalSeconds`
15+
* pinned a DECLARATION: that `inputs` publishes the key, that the config panel
16+
* carries a field for it, that a locale has a label for it. None of those goes
17+
* red if the timer never runs. So the claim here is `onRefresh` being CALLED, a counted number of
18+
* times, after the fake time the fixture's own period asks for, on real
19+
* mounted components. Nothing spies on `setInterval` to prove firing: a test
20+
* that asserted `setInterval` was called with `30000` would stay green if the
21+
* callback it scheduled never reached `onRefresh`.
22+
*
23+
* ## Both mount points, deliberately
24+
*
25+
* `DashboardGridLayout` and `DashboardRenderer` each carried their own copy of
26+
* this timer until objectui#8820 moved both onto `useDashboardAutoRefresh`.
27+
* Each component is mounted and driven on its own, so a surface that stops
28+
* wiring the hook fails under its own name. ⛔ Do not collapse the cases into
29+
* one parameterised case over the hook: the hook working is not the claim; the
30+
* claim is that both components still wire it.
31+
*
32+
* The last case of each block is the de-duplication pin: it goes red for a
33+
* surface that carries its own timer instead of calling the shared hook.
34+
*/
35+
36+
import * as React from 'react';
37+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
38+
import { render, cleanup, act } from '@testing-library/react';
39+
import type { DashboardComponentSchema } from '@object-ui/types';
40+
import { DashboardGridLayout } from '../DashboardGridLayout';
41+
import { DashboardRenderer } from '../DashboardRenderer';
42+
import { useDashboardAutoRefresh } from '../useDashboardAutoRefresh';
43+
44+
// The real hook, wrapped so each surface's call to it can be observed. The
45+
// timer under test is still the real one.
46+
vi.mock('../useDashboardAutoRefresh', async (importOriginal) => {
47+
const actual = await importOriginal<typeof import('../useDashboardAutoRefresh')>();
48+
return { ...actual, useDashboardAutoRefresh: vi.fn(actual.useDashboardAutoRefresh) };
49+
});
50+
51+
const sharedHook = vi.mocked(useDashboardAutoRefresh);
52+
53+
interface SurfaceProps {
54+
schema: DashboardComponentSchema;
55+
onRefresh?: () => void;
56+
}
57+
58+
/** The two components under test, each named, so a failure says which one. */
59+
const SURFACES: ReadonlyArray<readonly [string, React.ComponentType<SurfaceProps>]> = [
60+
['DashboardGridLayout', DashboardGridLayout],
61+
['DashboardRenderer', DashboardRenderer],
62+
];
63+
64+
const dash = (root: Record<string, unknown>): DashboardComponentSchema =>
65+
({ type: 'dashboard', name: 'ops', widgets: [], ...root }) as unknown as DashboardComponentSchema;
66+
67+
const advance = (ms: number) => {
68+
act(() => {
69+
vi.advanceTimersByTime(ms);
70+
});
71+
};
72+
73+
beforeEach(() => {
74+
vi.useFakeTimers();
75+
sharedHook.mockClear();
76+
});
77+
78+
afterEach(() => {
79+
cleanup();
80+
vi.useRealTimers();
81+
});
82+
83+
/** Mount `Surface` with `schema`, run `ms` of fake time, report the call count. */
84+
function refreshesWithin(
85+
Surface: React.ComponentType<SurfaceProps>,
86+
schema: DashboardComponentSchema,
87+
ms: number,
88+
): number {
89+
const onRefresh = vi.fn();
90+
render(<Surface schema={schema} onRefresh={onRefresh} />);
91+
// Nothing may have fired yet: a timer that ran on mount would be a
92+
// different bug, and this is the control for it.
93+
expect(onRefresh, 'refreshed before its first period elapsed').not.toHaveBeenCalled();
94+
advance(ms);
95+
return onRefresh.mock.calls.length;
96+
}
97+
98+
/** Pending fake timers right after mounting `Surface` on a clean clock. */
99+
function timersArmedOnMount(
100+
Surface: React.ComponentType<SurfaceProps>,
101+
schema: DashboardComponentSchema,
102+
onRefresh?: () => void,
103+
): number {
104+
vi.clearAllTimers();
105+
const view = render(<Surface schema={schema} onRefresh={onRefresh} />);
106+
const pending = vi.getTimerCount();
107+
view.unmount();
108+
return pending;
109+
}
110+
111+
// `_name` only feeds the `%s` in the title: the run output has to say WHICH
112+
// surface failed, since the two blocks are otherwise identical.
113+
describe.each(SURFACES)('%s: the auto-refresh timer fires (objectui#8820)', (_name, Surface) => {
114+
it('fires every `refreshIntervalSeconds` seconds', () => {
115+
// 30s period, 95s of time: three firings. The COUNT, not merely "was
116+
// called", is what separates a running interval from a one-shot: a
117+
// `setTimeout` mistaken for a `setInterval` returns 1 here.
118+
expect(refreshesWithin(Surface, dash({ refreshIntervalSeconds: 30 }), 95_000)).toBe(3);
119+
});
120+
121+
it('does not start when no period is authored', () => {
122+
expect(refreshesWithin(Surface, dash({}), 95_000)).toBe(0);
123+
});
124+
125+
it.each([0, -30])('does not start when the period is %d', (seconds) => {
126+
// `0` is an authored value meaning "off"; a negative one is off as well.
127+
expect(refreshesWithin(Surface, dash({ refreshIntervalSeconds: seconds }), 95_000)).toBe(0);
128+
});
129+
130+
it('does not read the retired `refreshInterval` spelling', () => {
131+
// The spec's `DashboardSchema` refuses this key by name, so a renderer
132+
// fallback for it would be a second, unsanctioned contract (AGENTS.md #0.1).
133+
expect(refreshesWithin(Surface, dash({ refreshInterval: 30 }), 95_000)).toBe(0);
134+
});
135+
136+
it('arms no interval without an `onRefresh` host handler', () => {
137+
const baseline = timersArmedOnMount(Surface, dash({}), vi.fn());
138+
const wired = timersArmedOnMount(Surface, dash({ refreshIntervalSeconds: 30 }), vi.fn());
139+
const unwired = timersArmedOnMount(Surface, dash({ refreshIntervalSeconds: 30 }));
140+
// The control: with a handler, the same period arms exactly one timer
141+
// more than no period does, so the count below can see an interval.
142+
expect(wired, 'control: a wired handler arms one interval').toBe(baseline + 1);
143+
expect(unwired, 'an interval was armed with no handler to call').toBe(baseline);
144+
// And the unwired surface survives the time passing.
145+
render(<Surface schema={dash({ refreshIntervalSeconds: 30 })} />);
146+
expect(() => advance(95_000)).not.toThrow();
147+
});
148+
149+
it('stops when the dashboard unmounts', () => {
150+
const onRefresh = vi.fn();
151+
const view = render(
152+
<Surface schema={dash({ refreshIntervalSeconds: 30 })} onRefresh={onRefresh} />,
153+
);
154+
advance(30_000);
155+
expect(onRefresh).toHaveBeenCalledTimes(1);
156+
view.unmount();
157+
advance(300_000);
158+
expect(onRefresh, 'the interval outlived the component').toHaveBeenCalledTimes(1);
159+
});
160+
161+
it('re-arms on a changed period: the old interval is cleared, the new period used', () => {
162+
const onRefresh = vi.fn();
163+
const view = render(
164+
<Surface schema={dash({ refreshIntervalSeconds: 30 })} onRefresh={onRefresh} />,
165+
);
166+
advance(30_000);
167+
expect(onRefresh).toHaveBeenCalledTimes(1);
168+
view.rerender(<Surface schema={dash({ refreshIntervalSeconds: 60 })} onRefresh={onRefresh} />);
169+
// Re-armed at 30s with a 60s period: the next firing is at 90s. A 30s
170+
// interval that survived the change would fire at 60s.
171+
advance(59_000);
172+
expect(onRefresh, 'the old 30s interval survived the change').toHaveBeenCalledTimes(1);
173+
advance(1_000);
174+
expect(onRefresh).toHaveBeenCalledTimes(2);
175+
});
176+
177+
it('keeps its phase across a re-render that repeats the same period', () => {
178+
const onRefresh = vi.fn();
179+
const view = render(
180+
<Surface schema={dash({ refreshIntervalSeconds: 30 })} onRefresh={onRefresh} />,
181+
);
182+
advance(20_000);
183+
// A new schema object with the same period: the timer keys on the value,
184+
// so it is not restarted and still fires at 30s rather than at 50s.
185+
view.rerender(<Surface schema={dash({ refreshIntervalSeconds: 30 })} onRefresh={onRefresh} />);
186+
advance(10_000);
187+
expect(onRefresh).toHaveBeenCalledTimes(1);
188+
});
189+
190+
it('calls the current `onRefresh` after the host swaps it, never the old one', () => {
191+
const first = vi.fn();
192+
const second = vi.fn();
193+
const schema = dash({ refreshIntervalSeconds: 30 });
194+
const view = render(<Surface schema={schema} onRefresh={first} />);
195+
advance(30_000);
196+
view.rerender(<Surface schema={schema} onRefresh={second} />);
197+
advance(60_000);
198+
expect(first, 'a stale handler kept firing').toHaveBeenCalledTimes(1);
199+
expect(second).toHaveBeenCalledTimes(2);
200+
});
201+
202+
it('takes its timer from the shared `useDashboardAutoRefresh` hook', () => {
203+
const onRefresh = vi.fn();
204+
render(<Surface schema={dash({ refreshIntervalSeconds: 30 })} onRefresh={onRefresh} />);
205+
expect(sharedHook).toHaveBeenCalledWith(
206+
expect.objectContaining({ refreshIntervalSeconds: 30 }),
207+
onRefresh,
208+
);
209+
});
210+
});

0 commit comments

Comments
 (0)