Compare commits

...

8 Commits

Author SHA1 Message Date
Ashwin Bhatkal
aad689acd2 test(frontend): cap local jest workers and recycle workers that grow past 1 GB 2026-11-19 08:31:00 +05:30
Ashwin Bhatkal
77ebf4dca9 test(frontend): skip antd popup scroll-container lookups in every test 2026-11-19 08:31:00 +05:30
Ashwin Bhatkal
c4ac1929fa docs(frontend): run checks only at the gate and add a no-checks keyword 2026-11-19 08:31:00 +05:30
Ashwin Bhatkal
df0f26b5fb docs(frontend): test rules that keep jest tests fast and stable 2026-11-19 08:31:00 +05:30
Ashwin Bhatkal
3843ac4eeb test(frontend): skip pointer-events checks and Floating UI layout in every test 2026-11-19 08:31:00 +05:30
Ashwin Bhatkal
0add9cce0d feat(dashboards): let dashboard creators set the default time range (#13446)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
#### Description

- Dashboard settings get a "Default time range" select on the Overview
tab, saved to `spec.duration`. Picking "Default (Last 30 minutes)"
clears it.
- When a viewer opens a dashboard with no time range in the URL and no
saved choice for that dashboard, the URL gets `relativeTime=<duration>`
before the time picker and panels mount. A time in the URL or a saved
choice still wins.
- When the default changes while a viewer is still on the old one, they
move to the new one. A viewer who picked a time keeps it.
- The JSON editor and JSON import reject a `spec.duration` that is not a
whole number of minutes above zero (`1s`, `90s`, `0m`), since the time
picker has no seconds. The editor footer names the line of an invalid
duration or image and shows the full error on hover.
- A value set through the API can still carry seconds. It opens rounded
up to whole minutes: `15s` opens as `1m`, `1h30m` as `90m`. An empty or
zero duration is ignored, and the picker behaves as before: the viewer's
saved choice, else 30 minutes.
- Settings show a stored value that is not one of the options with how
it opens, e.g. "Last 1s (opens as 1m)" or "0m (not applied)".
- The API description of `spec.duration` now says how the UI applies it.
It said "Stored, but not applied by the UI".
- The Prometheus duration parser behind Jira reopen durations moves to
`utils/prometheusDuration.ts`, shared with the dashboard code. Units
must now come largest first and each only once, as the API requires, so
`30m1h` is rejected in the JSON editor, on import, and in the Jira form.
- Carries the frontend part of
[#12861](https://github.com/SigNoz/signoz/pull/12861), moved onto the
`lib/router` facade. Its backend validation is left out: `spec.duration`
is already checked when the spec is decoded.
- The dashboard stories get a "Default time range" control and four new
states: the settings select open, a stored value off the list, the
dashboard opening on its default, and the JSON editor rejecting `1s`.

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/695
Closes https://github.com/SigNoz/signoz/issues/12860

#### Screenshots / Screen Recordings

[Visual diff](https://claude.ai/artifact/5mSCBVGEirWfkiC29ZbnEo) against
the merge-base, dark and light: 38 shots, 8 new, 15 changed, 15
identical. `default-time-range-card` is the new card on the settings
Overview tab (12), `new-stories` the four new states (8), and `noise` a
focus ring left on a clicked tab or button in the before shots (3).
2026-11-18 18:46:46 +00:00
Aditya Singh
4ffa6ac5da fix(hotkeys): ignore keydown events whose target is not an element (#13149)
#### Description
- The hotkeys handler threw `t.closest is not a function` when a script
dispatched `keydown` on `document` itself. The `Document` node has no
`closest`.
- The handler now ignores events whose target is not an `Element`. Real
key presses always target an element, so shortcuts work the same.

#### Issues closed by this PR

Closes https://github.com/SigNoz/events-pod/issues/179
2026-11-18 15:12:43 +00:00
ashu8912
824315b093 fix(alerts): let the empty rules page scroll to the sample alerts (#13619)
#### Description

- With no alert rules, the empty state sat in a `min-height: 0` flex
column with no overflow, so "Or get started with these sample alerts"
and its cards were clipped below the fold with no way to scroll to them.
- The empty state is now its own scroll container; `margin: auto` keeps
it centered when it fits and top-aligned when it doesn't.
- Only the empty state's stylesheet changes; the rule list is
unaffected.

#### Issues closed by this PR

Closes SigNoz/pulse-pod#744

#### Screenshots / Screen Recordings

[Visual diff](https://claude.ai/artifact/Y3cH28AULH1vvj62uNebgP) of
`Pages/Alerts/Rules/No Rules`, merge-base vs branch, dark and light: 2
changed, 0 new.

#### Additional Information

Storybook already covers this state with `Pages/Alerts/Rules/No Rules`;
no story edit needed.
2026-11-18 14:41:05 +00:00
41 changed files with 1246 additions and 122 deletions

View File

@@ -9,12 +9,14 @@ paths:
Examples and the harness API live in [`frontend/src/tests/README.md`](../../frontend/src/tests/README.md).
- **Import from the harness.** `render`, `screen`, `userEvent`, `waitFor` and the rest come from `tests/test-utils`, never from `@testing-library/react`. The harness mounts the router, React Query, Redux, app context and preferences. When it can't do what a test needs, extend `tests/test-utils` instead of importing around it.
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` computes the accessibility tree on every call and is the slowest query.
- **Interact like a user.** `const user = userEvent.setup({ pointerEventsCheck: 0 })`, then an awaited `user.click`, `hover`, `keyboard` or `type`. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` computes the accessibility tree on every call and is the slowest query. Never call a `*ByRole` query inside `waitFor` or a loop: `waitFor` re-runs its callback every 50 ms. Wait with `findByTestId`, then query.
- **Interact like a user.** `const user = userEvent.setup()`, then an awaited `user.click`, `hover`, `keyboard` or `type`. The harness turns off the pointer-events check, which walks `getComputedStyle` up the tree on every action; never turn it back on. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
- **Fake timers per test only**, for debounce or throttle, with `userEvent.setup({ advanceTimers: (ms) => jest.advanceTimersByTime(ms) })`. Never global.
- **Network through MSW.** The global server runs for every test; override per test with `server.use(...)` from `mocks-server/server`. Large fixtures go in `mocks-server/__mockdata__`.
- **Router through the harness.** Pass `initialRoute`/`routePath` to `render` and assert with `getCurrentLocation()` from `lib/router/navigation`. Never mock `react-router`, `react-router-dom` or `lib/history`; when a test can't render at a route, use the `lib/router` spies in `tests/router-mocks`.
- **Mock only business boundaries.** Local `jest.mock` for API modules, custom hooks and domain components. Never re-mock what the harness provides or what `jest.config.ts` maps (`uplot`, `@signozhq/icons`, `useSafeNavigate`, `logEvent`).
- **Mock only business boundaries.** Local `jest.mock` for API modules, custom hooks and domain components. Never re-mock what the harness provides (`@floating-ui/dom`, `@testing-library/user-event` and antd's `collectScroller` in `jest.setup.ts`) or what `jest.config.ts` maps (`uplot`, `@signozhq/icons`, `useSafeNavigate`, `logEvent`).
- **Type mocks and fixtures.** `jest.mocked(fn)` for module mocks, `jest.fn() as jest.MockedFunction<T>` for a standalone mock you configure or assert on. Fixtures carry their real type, from `src/api/generated` where it exists. No `any`, no `as unknown as`. An inline `onX={jest.fn()}` on a typed prop that is never asserted needs no annotation.
- **A test fails without its change.** Revert the change, or break the line under test, and run the test before you finish: it must fail. Assert the specific outcome (exact text, request payload, call arguments), never only that an element exists.
- **One behaviour per test, at the smallest render.** Render the component that owns the behaviour, not the page around it, unless the page wiring is the behaviour. A flow of steps (a wizard, a multi-step form) becomes one test per step that starts at that step through props, store or route. A full click-through belongs in the e2e suite (`tests/e2e`).
- **Each test under 500 ms.** `pnpm jest <file> --verbose` prints each test's time. CI runs about four times slower than a laptop, and the timeout is 5 s. Never raise a timeout (`jest.setTimeout`, a third argument to `it`) to make a slow test pass; slim the test instead.
- **A test fails without its change.** At the gate in [`frontend/AGENTS.md`](../../frontend/AGENTS.md), revert the change, or break the line under test, and run the test: it must fail, and each test must stay under 500 ms. Assert the specific outcome (exact text, request payload, call arguments), never only that an element exists.
- **No limit on tests per file.** Split a file when it mixes unrelated behaviour, not to hit a count.

View File

@@ -4420,7 +4420,8 @@ components:
description: The dashboard title and description.
duration:
description: The default time range, as a Prometheus duration such as 1h
or 7d. Stored, but not applied by the UI.
or 7d. The UI opens the dashboard on it, rounded up to whole minutes,
when neither the URL nor the viewer's last pick sets a time range.
type: string
layouts:
description: The Grid layouts that place panels, at most 500. Each panel

View File

@@ -99,7 +99,7 @@ is still by hand. The generator never adds a SideNav item; do that in
CSS Modules (`docs/css-modules-guide.md`), React Query for server state (prefer
`api/generated` hooks), nuqs for URL state, Zustand for client state, `data-testid` on
every interactive element.
5. **Verify** before reporting done:
5. **Verify** at the gate in `AGENTS.md` (commit, push or PR), not after each edit; skip it while the user says `no checks`:
```bash
pnpm tsgo --noEmit
pnpm oxlint src/pages/<Feature>

View File

@@ -34,14 +34,18 @@ You are operating within a constrained context window and strict system prompts.
- Identity keys (legend groups, color groups, CSV headers, React keys) come from structured values, never from joined display text: `['us, east', 'prod']` and `['us', 'east, prod']` both join to `us, east, prod`.
- A payload saved under another kind or schema copies only the fields that schema accepts, and drops bindings to columns the user removed. The server rejects unknown or stale fields, so the preview works and the save fails.
3. FORCED VERIFICATION: Your internal tools mark file writes as successful even if the code does not compile. Run these checks once all changes of a task are done, never after each edit. You are FORBIDDEN from reporting a task as complete until you have:
3. CHECKS AT THE GATE: Your internal tools mark file writes as successful even if the code does not compile, so the checks below are required, but only at the gate. The gate is when the user says commit, push, raise or update the PR, mark it ready, or "run checks". Never run them after each edit or between the user's iterations.
- Between gates, after an edit, run at most the one test file that covers it.
- `no checks`: when the user says it (or "don't run tests", "just making changes"), run nothing: no tests, type check, lint, format or build. Make the change and stop. This holds until the user names a gate.
At the gate, you are FORBIDDEN from reporting a task as complete until you have:
- Run `pnpm tsgo --noEmit`
- Run `pnpm lint:js --quiet` to find critical errors
- Run `pnpm oxlint <file1> <file2>` and fix all warnings
- Run `pnpm build`
- Find if the file has tests for it, or if there's `__test__` folder or the parent folder has tests, and run. Run them before coding the change or after all changes, never in between.
- For e2e, run only the specs you added or changed: the stack is heavy. Leave the full jest and e2e suites to CI unless the user asks.
- For every test you added or changed, revert the change it covers and confirm the test fails
- For every test you added or changed, revert the change it covers and confirm the test fails, and that each test runs under 500 ms (`pnpm jest <file> --verbose`)
- On a stacked branch (`gh stack`), run `pnpm tsgo --noEmit` on every branch above it before pushing: a renamed prop or moved export breaks them
- Fixed ALL resulting errors

View File

@@ -65,6 +65,8 @@ const config: Config.InitialOptions = {
testPathIgnorePatterns: ['/node_modules/', '/public/'],
moduleDirectories: ['node_modules', 'src'],
testEnvironment: '<rootDir>/jest.environment.cjs',
// Local only: the default (cores - 1) workers exhaust RAM when several runs overlap.
...(process.env.CI ? {} : { maxWorkers: 4, workerIdleMemoryLimit: '1GB' }),
coverageThreshold: {
global: {
statements: 80,

View File

@@ -144,6 +144,39 @@ window.getComputedStyle = function (
}
};
// jsdom has no layout, and Floating UI's getComputedStyle walk over every
// popover ancestor costs up to ~1 s per open.
jest.mock('@floating-ui/dom', () => ({
...jest.requireActual('@floating-ui/dom'),
autoUpdate: (): (() => void) => (): void => {},
computePosition: (
_reference: unknown,
_floating: unknown,
{ placement = 'bottom', strategy = 'absolute' } = {},
): Promise<unknown> =>
Promise.resolve({ x: 0, y: 0, placement, strategy, middlewareData: {} }),
}));
jest.mock('@testing-library/user-event', () =>
jest.requireActual('tests/userEventWithDefaults'),
);
// antd popups walk getComputedStyle up every ancestor to find scroll
// containers on each open. pnpm keeps the package under antd, not at the root.
jest.mock(
require.resolve('@rc-component/trigger/lib/util', {
paths: [require.resolve('antd')],
}),
() => ({
...jest.requireActual(
require.resolve('@rc-component/trigger/lib/util', {
paths: [require.resolve('antd')],
}),
),
collectScroller: (): HTMLElement[] => [],
}),
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());

View File

@@ -8042,7 +8042,7 @@ export interface DashboardtypesDashboardSpecDTO {
display: DashboardtypesDisplayDTO;
/**
* @type string
* @description The default time range, as a Prometheus duration such as 1h or 7d. Stored, but not applied by the UI.
* @description The default time range, as a Prometheus duration such as 1h or 7d. The UI opens the dashboard on it, rounded up to whole minutes, when neither the URL nor the viewer's last pick sets a time range.
*/
duration?: string;
/**

View File

@@ -160,11 +160,14 @@ describe('jira reopen duration', () => {
).toMatchObject({ reopenDuration: sent });
});
it('leaves a duration it cannot parse for the validator to reject', () => {
expect(
toChannelConfig(ChannelKind.jira, { reopenDuration: 'tomorrow' }).spec,
).toMatchObject({ reopenDuration: 'tomorrow' });
});
it.each(['tomorrow', '30m1h'])(
'leaves %s, which it cannot parse, for the validator to reject',
(typed) => {
expect(
toChannelConfig(ChannelKind.jira, { reopenDuration: typed }).spec,
).toMatchObject({ reopenDuration: typed });
},
);
});
describe('jira deployment', () => {

View File

@@ -1,31 +1,18 @@
import {
PROMETHEUS_DURATION_UNIT_MS,
prometheusDurationToMs,
} from 'utils/prometheusDuration';
import { ChannelFormValues, WebhookAuth } from './types';
// mirrors go's prometheus model.Duration units
const JIRA_DURATION_UNIT_MS: Record<string, number> = {
ms: 1,
s: 1_000,
m: 60_000,
h: 3_600_000,
d: 86_400_000,
w: 604_800_000,
y: 31_536_000_000,
};
const JIRA_DURATION_RE = /^(\d+(ms|s|m|h|d|w|y))+$/;
const JIRA_DURATION_TOKEN_RE = /(\d+)(ms|s|m|h|d|w|y)/g;
const JIRA_MIN_REOPEN_MS = 60_000;
export const isValidJiraReopenDuration = (value: string): boolean => {
if (!value || value === '0') {
return true;
}
if (!JIRA_DURATION_RE.test(value)) {
return false;
}
let totalMs = 0;
for (const [, amount, unit] of value.matchAll(JIRA_DURATION_TOKEN_RE)) {
totalMs += Number(amount) * JIRA_DURATION_UNIT_MS[unit];
}
return totalMs >= JIRA_MIN_REOPEN_MS;
const totalMs = prometheusDurationToMs(value);
return totalMs !== null && totalMs >= JIRA_MIN_REOPEN_MS;
};
/**
@@ -33,25 +20,23 @@ export const isValidJiraReopenDuration = (value: string): boolean => {
* back: "72h" becomes "3d", "7d" becomes "1w".
*/
const JIRA_DURATION_FORMAT: { unit: string; ms: number; exact: boolean }[] = [
{ unit: 'y', ms: JIRA_DURATION_UNIT_MS.y, exact: true },
{ unit: 'w', ms: JIRA_DURATION_UNIT_MS.w, exact: true },
{ unit: 'd', ms: JIRA_DURATION_UNIT_MS.d, exact: false },
{ unit: 'h', ms: JIRA_DURATION_UNIT_MS.h, exact: false },
{ unit: 'm', ms: JIRA_DURATION_UNIT_MS.m, exact: false },
{ unit: 's', ms: JIRA_DURATION_UNIT_MS.s, exact: false },
{ unit: 'ms', ms: JIRA_DURATION_UNIT_MS.ms, exact: false },
{ unit: 'y', ms: PROMETHEUS_DURATION_UNIT_MS.y, exact: true },
{ unit: 'w', ms: PROMETHEUS_DURATION_UNIT_MS.w, exact: true },
{ unit: 'd', ms: PROMETHEUS_DURATION_UNIT_MS.d, exact: false },
{ unit: 'h', ms: PROMETHEUS_DURATION_UNIT_MS.h, exact: false },
{ unit: 'm', ms: PROMETHEUS_DURATION_UNIT_MS.m, exact: false },
{ unit: 's', ms: PROMETHEUS_DURATION_UNIT_MS.s, exact: false },
{ unit: 'ms', ms: PROMETHEUS_DURATION_UNIT_MS.ms, exact: false },
];
/** The API rejects a duration it would print differently. */
export const canonicalJiraReopenDuration = (value: string): string => {
if (!value || value === '0' || !JIRA_DURATION_RE.test(value)) {
const totalMs = value && value !== '0' ? prometheusDurationToMs(value) : null;
if (totalMs === null) {
return value;
}
let remaining = 0;
for (const [, amount, unit] of value.matchAll(JIRA_DURATION_TOKEN_RE)) {
remaining += Number(amount) * JIRA_DURATION_UNIT_MS[unit];
}
let remaining = totalMs;
if (remaining === 0) {
return '0s';
}

View File

@@ -30,19 +30,6 @@ jest.mock('@signozhq/ui/sonner', () => ({
},
}));
// jsdom has no layout, and Floating UI's getComputedStyle walk over every
// popover ancestor costs ~1 s per open here, enough to time out under load.
jest.mock('@floating-ui/dom', () => ({
...jest.requireActual('@floating-ui/dom'),
autoUpdate: (): (() => void) => (): void => {},
computePosition: (
_reference: unknown,
_floating: unknown,
{ placement = 'bottom', strategy = 'absolute' } = {},
): Promise<unknown> =>
Promise.resolve({ x: 0, y: 0, placement, strategy, middlewareData: {} }),
}));
type AccountSettingsDrawerProps = ComponentProps<typeof AccountSettingsDrawer>;
const onClose = jest.fn() as jest.MockedFunction<

View File

@@ -1,12 +1,14 @@
.alertListContainer {
margin-top: auto;
margin-bottom: auto;
flex: 1;
min-height: 0;
overflow-y: auto;
display: flex;
justify-content: center;
width: 100%;
}
.alertListViewContent {
margin: auto;
padding: 24px 0;
width: calc(100% - 30px);
max-width: 836px;
}

View File

@@ -18,19 +18,6 @@ import {
import { renderListAlertRules, runSearchQuery } from './_helpers';
// jsdom has no layout, and Floating UI's getComputedStyle walk over every
// popover ancestor costs ~1 s per open here, enough to time out under load.
jest.mock('@floating-ui/dom', () => ({
...jest.requireActual('@floating-ui/dom'),
autoUpdate: (): (() => void) => (): void => {},
computePosition: (
_reference: unknown,
_floating: unknown,
{ placement = 'bottom', strategy = 'absolute' } = {},
): Promise<unknown> =>
Promise.resolve({ x: 0, y: 0, placement, strategy, middlewareData: {} }),
}));
jest.setTimeout(15_000);
const VIEW_1_ORDER_BY = JSON.stringify({ columnName: 'name', order: 'asc' });

View File

@@ -73,4 +73,21 @@ describe('KeyboardHotkeysProvider', () => {
expect(handleShortcut).not.toHaveBeenCalled();
});
it('ignores keydown events dispatched on document itself', () => {
const handleShortcut = jest.fn() as jest.MockedFunction<() => void>;
render(
<KeyboardHotkeysProvider>
<TestComponentWithRegister handleShortcut={handleShortcut} />
</KeyboardHotkeysProvider>,
);
expect(() =>
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'a' })),
).not.toThrow();
document.dispatchEvent(new KeyboardEvent('keyup', { key: 'a' }));
expect(handleShortcut).not.toHaveBeenCalled();
});
});

View File

@@ -79,11 +79,11 @@ export function KeyboardHotkeysProvider({
const wasExtended = useRef(false);
const handleKeyDown = (event: KeyboardEvent): void => {
if (event.repeat) {
const { target } = event;
if (event.repeat || !(target instanceof Element)) {
return;
}
const target = event.target as HTMLElement;
const isCodeMirrorEditor = target.closest('.cm-editor') !== null;
const isMonacoEditor = target.closest('.monaco-editor') !== null;
if (

View File

@@ -107,9 +107,13 @@ function JsonEditorDrawer({
} else if (!readOnly && !validity.valid) {
applyDisabledReason = 'Fix the JSON errors first';
}
const validationText = validity.valid
? `Valid JSON · ${validity.lineCount} lines`
: `Line ${validity.errorLine ?? '?'} · ${validity.message ?? 'Invalid JSON'}`;
const errorText = validity.message ?? 'Invalid JSON';
let validationText = `Valid JSON · ${validity.lineCount} lines`;
if (!validity.valid) {
validationText = validity.errorLine
? `Line ${validity.errorLine} · ${errorText}`
: errorText;
}
const plural = (n: number): string => (n === 1 ? '' : 's');
const danglingWarning =
danglingPanelIds.length > 0
@@ -135,15 +139,17 @@ function JsonEditorDrawer({
footer={
<div className={styles.footer}>
<div className={styles.footerStatus}>
<Typography.Text
className={cx(styles.validation, {
[styles.validationValid]: validity.valid,
[styles.validationInvalid]: !validity.valid,
})}
data-testid="json-editor-validation"
>
{validationText}
</Typography.Text>
<Tooltip title={validity.valid ? undefined : validationText}>
<Typography.Text
className={cx(styles.validation, {
[styles.validationValid]: validity.valid,
[styles.validationInvalid]: !validity.valid,
})}
data-testid="json-editor-validation"
>
{validationText}
</Typography.Text>
</Tooltip>
{danglingWarning && (
<Tooltip title={danglingPanelIds.join(', ')}>
<span

View File

@@ -1,4 +1,4 @@
import { fireEvent, render, screen } from 'tests/test-utils';
import { fireEvent, render, screen, userEvent } from 'tests/test-utils';
import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
import JsonEditorDrawer from '../JsonEditorDrawer';
@@ -170,6 +170,36 @@ describe('JsonEditorDrawer', () => {
);
});
it('shows only the message when the error line is unknown', () => {
mockUseJsonEditor.mockReturnValue(
hookValue({
validity: { valid: false, lineCount: 4, message: 'Bad value' },
}),
);
render(<JsonEditorDrawer dashboard={dashboard} isOpen onClose={jest.fn()} />);
expect(screen.getByTestId('json-editor-validation')).toHaveTextContent(
/^Bad value$/,
);
});
it('shows the whole error on hover', async () => {
const message = 'A long error that the footer cuts off';
mockUseJsonEditor.mockReturnValue(
hookValue({
validity: { valid: false, lineCount: 4, errorLine: 2, message },
}),
);
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<JsonEditorDrawer dashboard={dashboard} isOpen onClose={jest.fn()} />);
await user.hover(screen.getByTestId('json-editor-validation'));
await expect(screen.findByRole('tooltip')).resolves.toHaveTextContent(
`Line 2 · ${message}`,
);
});
it('disables Apply when not dirty, invalid, or saving', () => {
mockUseJsonEditor.mockReturnValue(hookValue({ isDirty: false }));
const { rerender } = render(

View File

@@ -95,6 +95,54 @@ describe('useJsonEditor', () => {
expect(result.current.isDirty).toBe(true);
});
const withDuration = (duration: unknown): string =>
JSON.stringify({ ...redacted, spec: { ...redacted.spec, duration } });
it.each(['1s', '90s', '500ms', '0m', 'abc', '30m1h', '1m1m', 30])(
'rejects a spec.duration of %p the time picker cannot open',
(duration) => {
const { result } = renderHook(() =>
useJsonEditor({ dashboard, isOpen: true, onApplied: jest.fn() }),
);
act(() => result.current.setDraft(withDuration(duration)));
expect(result.current.validity).toStrictEqual({
valid: false,
lineCount: 1,
errorLine: 1,
message:
'"spec.duration" must be a whole number of minutes above zero, like 30m, 6h or 1d. The time picker has no seconds.',
});
},
);
it.each([
['spec.duration', '{\n "spec": {\n "duration": "1s"\n }\n}', 3],
['image', '{\n "spec": {},\n "image": "https://x.io/a.png"\n}', 3],
])('points at the line of an invalid %s', (_field, draft, errorLine) => {
const { result } = renderHook(() =>
useJsonEditor({ dashboard, isOpen: true, onApplied: jest.fn() }),
);
act(() => result.current.setDraft(draft));
expect(result.current.validity.errorLine).toBe(errorLine);
});
it.each(['', '30m', '1h30m', '60s', '1y'])(
'accepts a spec.duration of %p',
(duration) => {
const { result } = renderHook(() =>
useJsonEditor({ dashboard, isOpen: true, onApplied: jest.fn() }),
);
act(() => result.current.setDraft(withDuration(duration)));
expect(result.current.validity.valid).toBe(true);
},
);
it('format() pretty-prints valid JSON and leaves invalid JSON untouched', () => {
const { result } = renderHook(() =>
useJsonEditor({ dashboard, isOpen: true, onApplied: jest.fn() }),

View File

@@ -0,0 +1,15 @@
import { escapeRegExp } from 'lodash-es';
// ponytail: a text match, not a JSON path, so an identical `"key": value` earlier
// in the document wins. Switch to a JSON tree parser (jsonc-parser) if that bites.
export function lineOfJsonEntry(
source: string,
key: string,
value: unknown,
): number | undefined {
const entry = new RegExp(
`"${escapeRegExp(key)}"\\s*:\\s*${escapeRegExp(JSON.stringify(value))}`,
);
const index = source.search(entry);
return index < 0 ? undefined : source.slice(0, index).split('\n').length;
}

View File

@@ -12,8 +12,10 @@ import { toAPIError } from 'utils/errorUtils';
import { dashboardToUpdatable } from './dashboardToUpdatable';
import { findPanelLayoutIssues } from './danglingPanels';
import { lineOfJsonEntry } from './lineOfJsonEntry';
import { compactSpecLayouts } from '../../layoutCompaction';
import { isValidDashboardImage } from '../../dashboardIcons';
import { dashboardDurationError } from '../../utils/dashboardDuration';
import { useDashboardStore } from '../../store/useDashboardStore';
export interface JsonValidity {
@@ -109,7 +111,7 @@ export function useJsonEditor({
const validity = useMemo<JsonValidity>(() => {
const lineCount = draft.split('\n').length;
let parsed: { image?: unknown };
let parsed: { image?: unknown; spec?: { duration?: unknown } };
try {
parsed = JSON.parse(draft);
} catch (error) {
@@ -131,10 +133,21 @@ export function useJsonEditor({
return {
valid: false,
lineCount,
errorLine: lineOfJsonEntry(draft, 'image', image),
message:
'"image" must be an /assets/Icons/<name> or /assets/Logos/<name> path, or a base64 image data URI',
};
}
const duration = parsed.spec?.duration;
const durationError = dashboardDurationError(duration);
if (durationError) {
return {
valid: false,
lineCount,
errorLine: lineOfJsonEntry(draft, 'duration', duration),
message: durationError,
};
}
return { valid: true, lineCount };
}, [draft]);

View File

@@ -0,0 +1,30 @@
.infoItemContainer {
display: flex;
flex-direction: column;
gap: 4px;
}
.infoTitle {
color: var(--l2-foreground);
}
.defaultTimeRangeInput {
[data-radix-popper-content-wrapper] {
z-index: 1100 !important;
}
// Radix sets --radix-select-trigger-width on the content element (the wrapper's
// child), so match it there to make the dropdown take the trigger's width.
[data-radix-popper-content-wrapper] > * {
width: var(--radix-select-trigger-width);
min-width: var(--radix-select-trigger-width);
}
}
.defaultTimeRangeSelect {
width: 100%;
}
.infoHint {
color: var(--l3-foreground);
}

View File

@@ -0,0 +1,41 @@
import { SelectSimple } from '@signozhq/ui/select';
import { Typography } from '@signozhq/ui/typography';
import { buildDefaultTimeRangeItems, DEFAULT_TIME_RANGE_UNSET } from '../utils';
import settingsStyles from '../../DashboardSettings.module.scss';
import styles from './DefaultTimeRange.module.scss';
interface DefaultTimeRangeProps {
value: string;
onChange: (value: string) => void;
}
function DefaultTimeRange({
value,
onChange,
}: DefaultTimeRangeProps): JSX.Element {
return (
<div className={settingsStyles.settingsCard}>
<div className={styles.infoItemContainer}>
<Typography className={styles.infoTitle}>Default time range</Typography>
<section className={styles.defaultTimeRangeInput}>
<SelectSimple
className={styles.defaultTimeRangeSelect}
testId="dashboard-default-time-range"
items={buildDefaultTimeRangeItems(value)}
value={value && value !== '30m' ? value : DEFAULT_TIME_RANGE_UNSET}
withPortal={false}
onChange={(value): void =>
onChange(value === DEFAULT_TIME_RANGE_UNSET ? '' : (value as string))
}
/>
</section>
<Typography className={styles.infoHint}>
Applies by default when a viewer opens the dashboard for the first time.
</Typography>
</div>
</div>
);
}
export default DefaultTimeRange;

View File

@@ -24,9 +24,11 @@ function UnsavedChangesFooter({
<div className={styles.overviewSettingsFooter}>
<div className={styles.unsaved}>
<div className={styles.unsavedDot} />
<Typography.Text className={styles.unsavedChanges}>
{count} unsaved change
{count > 1 && 's'}
<Typography.Text
className={styles.unsavedChanges}
data-testid="unsaved-changes-count"
>
{`${count} unsaved change${count > 1 ? 's' : ''}`}
</Typography.Text>
</div>
<div className={styles.footerActionButtons}>

View File

@@ -0,0 +1,138 @@
import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
import { DashboardtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import type { UseOptimisticPatch } from '../../../hooks/useOptimisticPatch';
import Overview from '../index';
const mockPatchAsync = jest.fn() as jest.MockedFunction<
UseOptimisticPatch['patchAsync']
>;
jest.mock('../../../hooks/useOptimisticPatch', () => ({
useOptimisticPatch: (): UseOptimisticPatch => ({
patchAsync: mockPatchAsync,
isPatching: false,
error: null,
}),
}));
jest.mock('../CrossPanelSync/CrossPanelSync', () => ({
__esModule: true,
default: (): null => null,
}));
function buildDashboard(
duration?: string,
): DashboardtypesGettableDashboardV2DTO {
return {
id: 'dash-1',
name: 'D',
orgId: 'org',
source: DashboardtypesSourceDTO.user,
locked: false,
schemaVersion: 'v6',
tags: [],
updatedAt: '2026-01-01T00:00:00Z',
spec: {
display: { name: 'D' },
panels: {},
layouts: [],
variables: [],
duration,
},
};
}
describe('Dashboard settings - default time range', () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
async function selectOption(label: string): Promise<void> {
await user.click(screen.getByTestId('dashboard-default-time-range'));
await user.click(await screen.findByText(label));
}
async function save(): Promise<void> {
await user.click(await screen.findByTestId('save-dashboard-config'));
}
beforeEach(() => {
mockPatchAsync.mockReset();
mockPatchAsync.mockResolvedValue(undefined);
});
it('shows the stored window and patches a new one', async () => {
render(<Overview dashboard={buildDashboard('30m')} />);
const trigger = await screen.findByTestId('dashboard-default-time-range');
expect(trigger).toHaveTextContent('Default (Last 30 minutes)');
await selectOption('Last 1 hour');
await expect(
screen.findByTestId('unsaved-changes-count'),
).resolves.toHaveTextContent(/^1 unsaved change$/);
await save();
await waitFor(() => {
expect(mockPatchAsync).toHaveBeenCalledWith([
{ op: 'replace', path: '/spec/duration', value: '1h' },
]);
});
});
it('offers the 30-minute default once', async () => {
render(<Overview dashboard={buildDashboard('1h')} />);
await user.click(await screen.findByTestId('dashboard-default-time-range'));
expect(
screen.getByRole('option', { name: 'Default (Last 30 minutes)' }),
).toBeInTheDocument();
expect(
screen.queryByRole('option', { name: 'Last 30 minutes', exact: true }),
).not.toBeInTheDocument();
});
it('patches an empty window when the setting is cleared', async () => {
render(<Overview dashboard={buildDashboard('1h')} />);
await selectOption('Default (Last 30 minutes)');
await save();
await waitFor(() => {
expect(mockPatchAsync).toHaveBeenCalledWith([
{ op: 'replace', path: '/spec/duration', value: '' },
]);
});
});
it.each([
['2h', 'Last 2h'],
['1s', 'Last 1s (opens as 1m)'],
['1h30m', 'Last 1h30m (opens as 90m)'],
['0m', '0m (not applied)'],
])(
'labels a stored %s that is not one of the options as "%s"',
async (duration, label) => {
render(<Overview dashboard={buildDashboard(duration)} />);
const trigger = await screen.findByTestId('dashboard-default-time-range');
expect(trigger).toHaveTextContent(label);
},
);
it('does not patch the window when it is untouched', async () => {
render(<Overview dashboard={buildDashboard('1h')} />);
await user.type(await screen.findByTestId('dashboard-name'), 'X');
await save();
await waitFor(() => {
expect(mockPatchAsync).toHaveBeenCalledWith([
{ op: 'replace', path: '/spec/display/name', value: 'DX' },
]);
});
});
});

View File

@@ -13,6 +13,7 @@ import APIError from 'types/api/error';
import { useOptimisticPatch } from '../../hooks/useOptimisticPatch';
import CrossPanelSync from './CrossPanelSync/CrossPanelSync';
import DefaultTimeRange from './DefaultTimeRange/DefaultTimeRange';
import DashboardInfoForm from './DashboardInfoForm/DashboardInfoForm';
import UnsavedChangesFooter from './UnsavedChangesFooter/UnsavedChangesFooter';
import { stringsToTags, tagsToStrings } from './utils';
@@ -31,6 +32,7 @@ function Overview({ dashboard }: OverviewProps): JSX.Element {
const title = dashboard.spec.display.name;
const description = dashboard.spec.display.description ?? '';
const image = dashboard.image || DEFAULT_DASHBOARD_ICON_PATH;
const defaultTimeRange = dashboard.spec.duration ?? '';
const tagsAsStrings = useMemo(
() => tagsToStrings(dashboard.tags ?? []),
[dashboard.tags],
@@ -41,6 +43,8 @@ function Overview({ dashboard }: OverviewProps): JSX.Element {
const [updatedDescription, setUpdatedDescription] =
useState<string>(description);
const [updatedImage, setUpdatedImage] = useState<string>(image);
const [updatedDefaultTimeRange, setUpdatedDefaultTimeRange] =
useState<string>(defaultTimeRange);
const [isSaving, setIsSaving] = useState<boolean>(false);
const [numberOfUnsavedChanges, setNumberOfUnsavedChanges] =
useState<number>(0);
@@ -53,6 +57,7 @@ function Overview({ dashboard }: OverviewProps): JSX.Element {
setUpdatedDescription(description);
setUpdatedImage(image);
setUpdatedTags(tagsAsStrings);
setUpdatedDefaultTimeRange(defaultTimeRange);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dashboard.updatedAt]);
@@ -102,6 +107,9 @@ function Overview({ dashboard }: OverviewProps): JSX.Element {
if (!isEqual(updatedTags, tagsAsStrings)) {
ops.push(replace('/tags', stringsToTags(updatedTags)));
}
if (updatedDefaultTimeRange !== defaultTimeRange) {
ops.push(replace('/spec/duration', updatedDefaultTimeRange));
}
return ops;
}, [
updatedTitle,
@@ -113,6 +121,8 @@ function Overview({ dashboard }: OverviewProps): JSX.Element {
dashboard.image,
updatedTags,
tagsAsStrings,
updatedDefaultTimeRange,
defaultTimeRange,
]);
const onSaveHandler = useCallback(async (): Promise<void> => {
@@ -135,12 +145,19 @@ function Overview({ dashboard }: OverviewProps): JSX.Element {
useEffect(() => {
let numberOfUnsavedChanges = 0;
const initialValues = [title, description, tagsAsStrings, image];
const initialValues = [
title,
description,
tagsAsStrings,
image,
defaultTimeRange,
];
const updatedValues = [
updatedTitle,
updatedDescription,
updatedTags,
updatedImage,
updatedDefaultTimeRange,
];
initialValues.forEach((val, index) => {
if (!isEqual(val, updatedValues[index])) {
@@ -153,10 +170,12 @@ function Overview({ dashboard }: OverviewProps): JSX.Element {
image,
tagsAsStrings,
title,
defaultTimeRange,
updatedDescription,
updatedImage,
updatedTags,
updatedTitle,
updatedDefaultTimeRange,
]);
const discardHandler = useCallback((): void => {
@@ -164,8 +183,9 @@ function Overview({ dashboard }: OverviewProps): JSX.Element {
setUpdatedImage(image);
setUpdatedTags(tagsAsStrings);
setUpdatedDescription(description);
setUpdatedDefaultTimeRange(defaultTimeRange);
void logEvent(DashboardDetailEvents.OverviewDiscarded, { dashboardId: id });
}, [title, image, tagsAsStrings, description, id]);
}, [title, image, tagsAsStrings, description, defaultTimeRange, id]);
return (
<div className={styles.overviewContent}>
@@ -179,6 +199,10 @@ function Overview({ dashboard }: OverviewProps): JSX.Element {
onImageChange={setUpdatedImage}
onTagsChange={setUpdatedTags}
/>
<DefaultTimeRange
value={updatedDefaultTimeRange}
onChange={setUpdatedDefaultTimeRange}
/>
<CrossPanelSync dashboardId={id} />
{numberOfUnsavedChanges > 0 && (
<UnsavedChangesFooter

View File

@@ -1,4 +1,7 @@
import type { TagtypesPostableTagDTO } from 'api/generated/services/sigNoz.schemas';
import { RelativeDurationOptions } from 'container/TopNav/DateTimeSelectionV2/constants';
import { toPickerRelativeTime } from '../../utils/dashboardDuration';
export { parseKeyValueTag } from 'components/TagKeyValueInput/utils';
@@ -22,3 +25,41 @@ export function stringsToTags(tagStrings: string[]): TagtypesPostableTagDTO[] {
})
.filter((t) => t.key.length > 0);
}
// Radix rejects an empty option value, so "not set" travels through the select
// under a sentinel and is mapped back to '' on the way out.
export const DEFAULT_TIME_RANGE_UNSET = '__unset__';
// The default entry represents 30m; the API rejects `1month`, which is not a
// Prometheus duration.
const SELECTABLE_DURATIONS = RelativeDurationOptions.filter(
(option) => option.value !== '1month' && option.value !== '30m',
);
function storedDurationLabel(value: string): string {
const relativeTime = toPickerRelativeTime(value);
if (!relativeTime) {
return `${value} (not applied)`;
}
return relativeTime === value
? `Last ${value}`
: `Last ${value} (opens as ${relativeTime})`;
}
// A window set through the API or the JSON editor may sit outside the list;
// it's appended so the select shows it instead of rendering blank.
export function buildDefaultTimeRangeItems(
value: string,
): { value: string; label: string }[] {
const items = [
{ value: DEFAULT_TIME_RANGE_UNSET, label: 'Default (Last 30 minutes)' },
...SELECTABLE_DURATIONS.map((option) => ({
value: option.value,
label: option.label,
})),
];
if (value && value !== '30m' && !items.some((item) => item.value === value)) {
items.push({ value, label: storedDurationLabel(value) });
}
return items;
}

View File

@@ -0,0 +1,281 @@
import { StrictMode, type ReactNode } from 'react';
import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
import { DashboardtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { LOCALSTORAGE } from 'constants/localStorage';
import { getCurrentLocation, navigate } from 'lib/router/navigation';
import { UpdateTimeInterval } from 'store/actions';
import { act, render, screen } from 'tests/test-utils';
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
import DashboardContainer from '../index';
jest.mock('store/actions', () => ({
...jest.requireActual('store/actions'),
UpdateTimeInterval: jest.fn(() => (): void => {}),
}));
const mockUpdateTimeInterval = jest.mocked(UpdateTimeInterval);
const mockSelectorMount = jest.fn() as jest.MockedFunction<
(search: string) => void
>;
const mockPanelMount = jest.fn() as jest.MockedFunction<
(search: string) => void
>;
const mockStore = { resetVariableFetch: jest.fn(), setEditContext: jest.fn() };
jest.mock('../store/useDashboardStore', () => ({
useDashboardStore: (selector: (state: typeof mockStore) => unknown): unknown =>
selector(mockStore),
}));
jest.mock('../hooks/useResolvedVariables', () => ({
useResolvedVariables: jest.fn(),
}));
jest.mock('../hooks/useSyncVariablesForSuggestions', () => ({
useSyncVariablesForSuggestions: jest.fn(),
}));
jest.mock('../hooks/useDashboardStaleCheck', () => ({
useDashboardStaleCheck: (): object => ({
showPrompt: false,
reload: jest.fn(),
dismiss: jest.fn(),
}),
}));
jest.mock('../dashboardIcons', () => ({
resolveDashboardImage: (): string => '',
}));
jest.mock('react-full-screen', () => ({
FullScreen: ({ children }: { children: ReactNode }): ReactNode => children,
useFullScreenHandle: (): object => ({ active: false }),
}));
jest.mock('../DashboardPageToolbar', () => ({
__esModule: true,
default: (): JSX.Element => {
mockSelectorMount(getUnstableCurrentSearchParams().toString());
return <div data-testid="time-selector" />;
},
}));
jest.mock('../PanelsAndSectionsLayout', () => ({
__esModule: true,
default: (): JSX.Element => {
mockPanelMount(getUnstableCurrentSearchParams().toString());
return <div data-testid="panels" />;
},
}));
jest.mock('../components/DashboardPageHeader/DashboardPageHeader', () => ({
__esModule: true,
default: (): null => null,
}));
jest.mock('../components/LockedIndicator/LockedIndicator', () => ({
__esModule: true,
default: (): null => null,
}));
jest.mock(
'../components/DashboardChangedDialog/DashboardChangedDialog',
() => ({ __esModule: true, default: (): null => null }),
);
jest.mock('container/TopNav/AutoRefreshV2/AutoRefreshTicker', () => ({
__esModule: true,
default: (): null => null,
}));
const PATH = '/dashboard/abc';
const refetch = jest.fn();
function dashboard(
duration = '1h',
id = 'abc',
): DashboardtypesGettableDashboardV2DTO {
return {
id,
name: id,
orgId: 'org',
source: DashboardtypesSourceDTO.user,
locked: false,
schemaVersion: 'v6',
tags: [],
spec: {
display: { name: id },
duration,
layouts: [],
panels: {},
variables: [],
},
};
}
function view(data: DashboardtypesGettableDashboardV2DTO): JSX.Element {
return (
<StrictMode>
<DashboardContainer dashboard={data} refetch={refetch} />
</StrictMode>
);
}
function mountDashboard(
search = '',
duration = '1h',
): ReturnType<typeof render> & {
update: (data: DashboardtypesGettableDashboardV2DTO) => void;
} {
const result = render(view(dashboard(duration)), undefined, {
initialRoute: `${PATH}${search}`,
});
return {
...result,
update: (data): void => result.rerender(view(data)),
};
}
describe('dashboard default time initialization', () => {
beforeEach(() => {
jest.clearAllMocks();
localStorage.clear();
});
it('writes the default before the selector and panels first mount, replacing history', () => {
const historyLength = window.history.length;
mountDashboard('?variables=selected&tab=overview');
expect(screen.getByTestId('time-selector')).toBeInTheDocument();
expect(screen.getByTestId('panels')).toBeInTheDocument();
for (const mounted of [mockSelectorMount, mockPanelMount]) {
expect(mounted).toHaveBeenCalled();
for (const [search] of mounted.mock.calls) {
expect(new URLSearchParams(search).get('relativeTime')).toBe('1h');
}
}
const params = new URLSearchParams(getCurrentLocation().search);
expect(params.get('variables')).toBe('selected');
expect(params.get('tab')).toBe('overview');
expect(window.history).toHaveLength(historyLength);
});
it.each([
'?relativeTime=15m',
'?startTime=1000&endTime=2000',
'?startTime=1000',
'?endTime=2000',
])('preserves explicit URL time %s', (search) => {
mountDashboard(search);
expect(getCurrentLocation().search).toBe(search);
expect(mockSelectorMount.mock.calls[0][0]).toBe(search.slice(1));
});
it.each(['1d', JSON.stringify({ startTime: 1000, endTime: 2000 })])(
'leaves a saved route preference %s for the shared selector',
(saved) => {
localStorage.setItem(
LOCALSTORAGE.METRICS_TIME_IN_DURATION,
JSON.stringify({ [PATH]: saved }),
);
mountDashboard();
expect(getCurrentLocation().search).toBe('');
expect(
JSON.parse(
localStorage.getItem(LOCALSTORAGE.METRICS_TIME_IN_DURATION) ?? '{}',
)[PATH],
).toBe(saved);
expect(mockSelectorMount.mock.calls[0][0]).toBe('');
},
);
it('does not use preferences from another dashboard', () => {
localStorage.setItem(
LOCALSTORAGE.METRICS_TIME_IN_DURATION,
JSON.stringify({ '/dashboard/other': '1d' }),
);
mountDashboard();
expect(getCurrentLocation().search).toBe('?relativeTime=1h');
});
it.each([
['1h30m', '90m'],
['120m', '2h'],
['14d', '2w'],
['1y', '365d'],
['15s', '1m'],
['90s', '2m'],
['500ms', '1m'],
])('opens a %s default as %s, in whole minutes', (duration, relativeTime) => {
mountDashboard('', duration);
expect(getCurrentLocation().search).toBe(`?relativeTime=${relativeTime}`);
});
it.each(['', '0m', '0s', 'invalid'])(
'keeps the normal selector flow for unusable default %s',
(duration) => {
mountDashboard('', duration);
expect(getCurrentLocation().search).toBe('');
expect(screen.getByTestId('time-selector')).toBeInTheDocument();
},
);
it('does not reset a current selection when settings refetch', () => {
const { update } = mountDashboard();
act(() => navigate(`${PATH}?relativeTime=15m`, { replace: true }));
update(dashboard('1w'));
expect(getCurrentLocation().search).toBe('?relativeTime=15m');
expect(mockUpdateTimeInterval).not.toHaveBeenCalled();
});
it('moves a viewer still on the old default to a changed one', () => {
const { update } = mountDashboard();
update(dashboard('1d'));
expect(getCurrentLocation().search).toBe('?relativeTime=1d');
expect(mockUpdateTimeInterval).toHaveBeenCalledWith('1d');
});
it('moves a viewer to 30 minutes when the default is cleared', () => {
const { update } = mountDashboard();
update(dashboard(''));
expect(getCurrentLocation().search).toBe('?relativeTime=30m');
expect(mockUpdateTimeInterval).toHaveBeenCalledWith('30m');
});
it('moves a viewer off 30 minutes when a default is first set', () => {
const { update } = mountDashboard('', '');
act(() => navigate(`${PATH}?relativeTime=30m`, { replace: true }));
update(dashboard('1d'));
expect(getCurrentLocation().search).toBe('?relativeTime=1d');
expect(mockUpdateTimeInterval).toHaveBeenCalledWith('1d');
});
it('keeps a shared link time that matches the old default', () => {
const { update } = mountDashboard('?relativeTime=1h');
update(dashboard('1d'));
expect(getCurrentLocation().search).toBe('?relativeTime=1h');
expect(mockUpdateTimeInterval).not.toHaveBeenCalled();
});
it('keeps the time a viewer picked when the default changes', () => {
const { update } = mountDashboard();
localStorage.setItem(
LOCALSTORAGE.METRICS_TIME_IN_DURATION,
JSON.stringify({ [PATH]: '1h' }),
);
update(dashboard('1d'));
expect(getCurrentLocation().search).toBe('?relativeTime=1h');
expect(mockUpdateTimeInterval).not.toHaveBeenCalled();
});
it('initializes a different dashboard before mounting its children', () => {
const { update } = mountDashboard();
mockSelectorMount.mockClear();
mockPanelMount.mockClear();
act(() => {
navigate('/dashboard/other');
update(dashboard('1w', 'other'));
});
expect(getCurrentLocation().search).toBe('?relativeTime=1w');
expect(mockSelectorMount).toHaveBeenCalled();
expect(mockPanelMount).toHaveBeenCalled();
expect(
mockSelectorMount.mock.calls.every(
([search]) => new URLSearchParams(search).get('relativeTime') === '1w',
),
).toBe(true);
expect(
mockPanelMount.mock.calls.every(
([search]) => new URLSearchParams(search).get('relativeTime') === '1w',
),
).toBe(true);
});
});

View File

@@ -0,0 +1,85 @@
import { useEffect, useRef, useState } from 'react';
// eslint-disable-next-line no-restricted-imports -- TODO: migrate global time dispatch off redux
import { useDispatch } from 'react-redux';
import { QueryParams } from 'constants/query';
import { getDefaultOption } from 'container/TopNav/DateTimeSelectionV2/constants';
import type { Time } from 'container/TopNav/DateTimeSelectionV2/types';
import { useAppLocation } from 'lib/router/useAppLocation';
import { useAppNavigate } from 'lib/router/useAppNavigate';
import { UpdateTimeInterval } from 'store/actions';
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
import { hasPersistedTimeForRoute } from 'utils/metricsTimeStorageUtils';
import { toPickerRelativeTime } from '../utils/dashboardDuration';
/**
* Prepares the dashboard URL before its time selector and panels mount, and
* moves a viewer still on the previous default to a changed one.
*/
export function useDashboardDefaultTime(
dashboardId: string,
duration: string | undefined,
): boolean {
const { pathname } = useAppLocation();
const navigate = useAppNavigate();
const dispatch = useDispatch();
const previousDuration = useRef(duration);
const [initialized, setInitialized] = useState<{
dashboardId: string;
pathname: string;
followsDefault: boolean;
}>();
const isInitialized =
initialized?.dashboardId === dashboardId && initialized.pathname === pathname;
const followsDefault = isInitialized && initialized.followsDefault;
useEffect(() => {
if (isInitialized) {
return;
}
const params = getUnstableCurrentSearchParams();
const hasUrlTime = [
QueryParams.relativeTime,
QueryParams.startTime,
QueryParams.endTime,
].some((key) => params.has(key));
const relativeTime = toPickerRelativeTime(duration);
const opensOnDefault = !hasUrlTime && !hasPersistedTimeForRoute(pathname);
if (opensOnDefault && relativeTime) {
params.set(QueryParams.relativeTime, relativeTime);
navigate(`${pathname}?${params.toString()}`, { replace: true });
}
// Keep the first run: StrictMode reruns this after it has already written the URL.
setInitialized((current) =>
current?.dashboardId === dashboardId && current.pathname === pathname
? current
: { dashboardId, pathname, followsDefault: opensOnDefault },
);
}, [dashboardId, duration, pathname, isInitialized, navigate]);
useEffect(() => {
const previous = previousDuration.current;
previousDuration.current = duration;
if (!followsDefault || previous === duration) {
return;
}
const params = getUnstableCurrentSearchParams();
const routeDefault = getDefaultOption(pathname);
const isOnPreviousDefault =
params.get(QueryParams.relativeTime) ===
(toPickerRelativeTime(previous) ?? routeDefault) &&
!params.has(QueryParams.startTime) &&
!params.has(QueryParams.endTime) &&
!hasPersistedTimeForRoute(pathname);
if (!isOnPreviousDefault) {
return;
}
const next = toPickerRelativeTime(duration) ?? routeDefault;
params.set(QueryParams.relativeTime, next);
navigate(`${pathname}?${params.toString()}`, { replace: true });
dispatch(UpdateTimeInterval(next as Time));
}, [duration, followsDefault, pathname, navigate, dispatch]);
return isInitialized;
}

View File

@@ -14,6 +14,7 @@ import DashboardPageHeader from './components/DashboardPageHeader/DashboardPageH
import LockedIndicator from './components/LockedIndicator/LockedIndicator';
import DashboardChangedDialog from './components/DashboardChangedDialog/DashboardChangedDialog';
import { useDashboardStaleCheck } from './hooks/useDashboardStaleCheck';
import { useDashboardDefaultTime } from './hooks/useDashboardDefaultTime';
import { resolveDashboardImage } from 'pages/DashboardPage/DashboardContainer/dashboardIcons';
interface DashboardContainerProps {
@@ -33,8 +34,9 @@ function DashboardContainer({
dashboard,
refetch,
canEditDashboardOverride,
}: DashboardContainerProps): JSX.Element {
}: DashboardContainerProps): JSX.Element | null {
const spec = dashboard.spec;
const isTimeInitialized = useDashboardDefaultTime(dashboard.id, spec.duration);
const image = resolveDashboardImage(dashboard.image);
const name = spec.display.name;
@@ -68,6 +70,10 @@ function DashboardContainer({
const staleCheck = useDashboardStaleCheck(dashboard, refetch);
if (!isTimeInitialized) {
return null;
}
// In full screen show only the sections and panels — the header/toolbar chrome
// is hidden for a clean presentation view (exit with Esc).
return (

View File

@@ -0,0 +1,41 @@
import {
PROMETHEUS_DURATION_UNIT_MS,
prometheusDurationToMs,
} from 'utils/prometheusDuration';
const MINUTE_MS = PROMETHEUS_DURATION_UNIT_MS.m;
const PICKER_UNITS: { unit: string; minutes: number }[] = [
{ unit: 'w', minutes: 10_080 },
{ unit: 'd', minutes: 1_440 },
{ unit: 'h', minutes: 60 },
];
/**
* The time picker's relative time for a dashboard duration, or null when the
* duration is empty, zero or not a duration. The picker has no seconds, so the
* window is rounded up to whole minutes: `1h30m` opens as `90m`, `15s` as `1m`.
*/
export function toPickerRelativeTime(
duration: string | undefined,
): string | null {
const totalMs = duration ? prometheusDurationToMs(duration) : null;
if (!totalMs) {
return null;
}
const minutes = Math.ceil(totalMs / MINUTE_MS);
const largest = PICKER_UNITS.find((option) => minutes % option.minutes === 0);
return largest ? `${minutes / largest.minutes}${largest.unit}` : `${minutes}m`;
}
/** Why a hand-written `spec.duration` can't be saved, or null when it can. */
export function dashboardDurationError(duration: unknown): string | null {
if (duration === undefined || duration === null || duration === '') {
return null;
}
const totalMs =
typeof duration === 'string' ? prometheusDurationToMs(duration) : null;
if (!totalMs || totalMs % MINUTE_MS !== 0) {
return '"spec.duration" must be a whole number of minutes above zero, like 30m, 6h or 1d. The time picker has no seconds.';
}
return null;
}

View File

@@ -27,12 +27,14 @@ import { queryRangeV5ScalarResponse } from '@/storybook/msw/__story_mockdata__/q
import {
currentDashboardDocument,
cyclicVariablesDashboardResponse,
DURATION_CHOICES,
patchDashboardDocument,
PANEL_IDS,
seedDashboardDocument,
STORY_DASHBOARD_ID,
VARIABLE_KINDS,
type DashboardArgs,
type DurationChoice,
type VariableKind,
} from './__story_mockdata__/dashboard';
import { publicDashboardMeta } from './__story_mockdata__/publicDashboard';
@@ -149,6 +151,13 @@ export const dashboardMocks = defineStoryMocks({
options: VARIABLE_KINDS,
value: [...VARIABLE_KINDS],
}),
duration: choiceControl<DurationChoice>('Default time range', {
group: LAYOUT,
description:
"The dashboard's `spec.duration`, which the time picker opens on when the URL carries no time. `unset` leaves the 30 minute default, `90m` is a window the settings list does not offer, `1s` opens as 1m and `0m` is not applied. The JSON editor rejects the last two.",
options: DURATION_CHOICES,
value: 'unset',
}),
variableValues: countControl('Variable options', {
group: DATA,
description: 'Values the query-backed `service` variable resolves to.',
@@ -224,6 +233,7 @@ export const dashboardMocks = defineStoryMocks({
sectioned: values.sectioned,
variables: values.variables,
locked: values.locked,
duration: values.duration,
};
return [
@@ -363,6 +373,7 @@ export const dashboardMocks = defineStoryMocks({
sectioned: values.sectioned,
variables: values.variables,
locked: values.locked,
duration: values.duration,
});
// The sync mode persists per dashboard, so one story's pick would open the
// next one on it.
@@ -440,9 +451,9 @@ export const clickAction = async (
const item = await screen.findByText(label);
const menuItem = item.closest('[role="menuitem"]') ?? item;
await waitFor(() => {
expect(menuItem).not.toHaveAttribute('aria-disabled', 'true');
expect(menuItem).not.toHaveAttribute('data-disabled');
await waitFor(async () => {
await expect(menuItem).not.toHaveAttribute('aria-disabled', 'true');
await expect(menuItem).not.toHaveAttribute('data-disabled');
});
await userEvent.click(menuItem);
};
@@ -547,6 +558,18 @@ export const openSettings = async (
return screen.findByRole('tabpanel');
};
export const clickWhenEnabled = async (testId: string): Promise<void> => {
await waitFor(
() =>
expect(screen.getByTestId(testId)).not.toHaveAttribute(
'aria-disabled',
'true',
),
PAGE_LOAD,
);
await userEvent.click(screen.getByTestId(testId));
};
export const variableRow = (name: string): Promise<HTMLElement> =>
screen.findByTestId(`variable-row-${name}`, {}, PAGE_LOAD);

View File

@@ -22,6 +22,7 @@ import {
tooltipRoute,
warnedPanelQueryHandler,
} from './DashboardPage.stories.mocks';
import { hoverJsonValidation } from './__story_mockdata__/dashboard.play';
import { TOOLTIP_PANEL_NAME } from './__story_mockdata__/tooltipDashboard';
import DashboardPage from '../DashboardPage';
@@ -100,6 +101,14 @@ export const PanelQueryError: Story = {
parameters: { allowConsoleErrors: true },
};
/**
* A dashboard whose default time range is `6h`, opened without a time in the
* URL: the time picker starts on the last 6 hours instead of 30 minutes.
*/
export const DefaultTimeRange: Story = {
args: { duration: '6h' },
};
/** The panels mid-fetch, with the header, variable bar and grid already laid out. */
export const Loading: Story = {
args: { dataState: 'loading' },
@@ -504,6 +513,15 @@ export const JsonCopiedToast: Story = {
},
};
/**
* The JSON editor on a dashboard stored with `1s`: the footer rejects
* `spec.duration` on its line, and hovering it shows the full message.
*/
export const JsonDurationRejected: Story = {
args: { duration: '1s' },
play: hoverJsonValidation,
};
/**
* The JSON editor with a whitespace edit, applied: the toast announcing the
* update, raised once the PUT answers.

View File

@@ -0,0 +1,91 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { dashboardDurationError } from '../../DashboardContainer/utils/dashboardDuration';
import {
type dashboardMocks,
openJsonEditor,
openSettings,
PAGE_LOAD,
} from '../DashboardPage.stories.mocks';
interface DashboardPlayContext {
canvasElement: HTMLElement;
args: PageStoryArgs<typeof dashboardMocks>;
}
const findDefaultTimeRange = async ({
canvasElement,
args,
}: DashboardPlayContext): Promise<HTMLElement | null> => {
if (args.locked) {
await waitFor(
() =>
expect(within(canvasElement).getByTestId('show-drawer')).toHaveAttribute(
'aria-disabled',
'true',
),
PAGE_LOAD,
);
return null;
}
const panel = await openSettings(canvasElement);
return within(panel).findByTestId(
'dashboard-default-time-range',
{},
PAGE_LOAD,
);
};
export const showDefaultTimeRange = async (
context: DashboardPlayContext,
): Promise<void> => {
await findDefaultTimeRange(context);
};
const isSliding = (element: HTMLElement): boolean => {
for (let node = element.parentElement; node; node = node.parentElement) {
if (getComputedStyle(node).transform !== 'none') {
return true;
}
}
return false;
};
export const openDefaultTimeRange = async (
context: DashboardPlayContext,
): Promise<void> => {
const select = await findDefaultTimeRange(context);
if (!select) {
return;
}
await waitFor(() => expect(isSliding(select)).toBe(false), PAGE_LOAD);
await userEvent.click(select);
await screen.findByRole('listbox');
};
export const hoverJsonValidation = async ({
canvasElement,
args,
}: DashboardPlayContext): Promise<void> => {
await openJsonEditor(canvasElement);
const validation = await screen.findByTestId('json-editor-validation');
if (args.duration === 'unset' || !dashboardDurationError(args.duration)) {
return;
}
await waitFor(() =>
expect(validation).toHaveTextContent('"spec.duration" must be'),
);
await userEvent.hover(validation);
await screen.findByRole('tooltip', {}, PAGE_LOAD);
};

View File

@@ -356,6 +356,10 @@ const CYCLIC_ENVIRONMENT: DashboardtypesVariableDTO = {
},
};
export const DURATION_CHOICES = ['unset', '6h', '90m', '1s', '0m'] as const;
export type DurationChoice = (typeof DURATION_CHOICES)[number];
export interface PanelQueryShape {
requestType: string;
metricName?: string;
@@ -388,6 +392,7 @@ export interface DashboardArgs {
sectioned: boolean;
variables: readonly VariableKind[];
locked: boolean;
duration?: DurationChoice;
}
export const dashboardResponse = ({
@@ -395,6 +400,7 @@ export const dashboardResponse = ({
sectioned,
variables,
locked,
duration,
}: DashboardArgs): GetDashboardV2200 => {
const kept = PANEL_IDS.slice(0, panels);
@@ -432,6 +438,7 @@ export const dashboardResponse = ({
description:
'Traffic, errors and latency for the checkout path, broken down by service.',
},
duration: duration === 'unset' ? undefined : duration,
layouts,
panels: Object.fromEntries(
kept.map((id) => [id, PANELS[id]]),

View File

@@ -7,7 +7,15 @@ import { screen, userEvent, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { dashboardMocks, openSettings } from '../DashboardPage.stories.mocks';
import {
clickWhenEnabled,
dashboardMocks,
openSettings,
} from '../DashboardPage.stories.mocks';
import {
openDefaultTimeRange,
showDefaultTimeRange,
} from '../__story_mockdata__/dashboard.play';
import DashboardPage from '../../DashboardPage';
@@ -78,6 +86,23 @@ export const OverviewTooltipSync: Story = {
},
};
/**
* The Default time range select open: the 30 minute default first, then the
* time picker's presets.
*/
export const OverviewDefaultTimeRangeOpen: Story = {
play: openDefaultTimeRange,
};
/**
* A dashboard stored with `1s`, which no option matches: the select shows it
* as an extra entry saying the dashboard opens on 1m instead.
*/
export const OverviewDefaultTimeRangeOffList: Story = {
args: { duration: '1s' },
play: showDefaultTimeRange,
};
/**
* The Overview tab's own tooltip: Cross-Panel Sync explains what syncing does
* and links out to the docs.
@@ -136,7 +161,7 @@ export const PublishedToast: Story = {
parameters: { allowConsoleErrors: true },
play: async ({ canvasElement, args }) => {
await openSettings(canvasElement, 'Publish');
await userEvent.click(await screen.findByTestId('public-dashboard-publish'));
await clickWhenEnabled('public-dashboard-publish');
if (args.publicWrite === 'success') {
await screen.findByText('Dashboard published successfully');
}
@@ -147,7 +172,7 @@ export const PublishedToast: Story = {
export const PublicUpdatedToast: Story = {
play: async ({ canvasElement, args }) => {
await openSettings(canvasElement, 'Publish');
await userEvent.click(await screen.findByTestId('public-dashboard-update'));
await clickWhenEnabled('public-dashboard-update');
if (args.publicWrite === 'success') {
await screen.findByText('Public dashboard updated successfully');
}
@@ -158,9 +183,7 @@ export const PublicUpdatedToast: Story = {
export const UnpublishedToast: Story = {
play: async ({ canvasElement, args }) => {
await openSettings(canvasElement, 'Publish');
await userEvent.click(
await screen.findByTestId('public-dashboard-unpublish'),
);
await clickWhenEnabled('public-dashboard-unpublish');
if (args.publicWrite === 'success') {
await screen.findByText('Dashboard unpublished successfully');
}

View File

@@ -17,6 +17,7 @@ import { DashboardListEvents } from 'pages/DashboardsListPage/constants/events';
import APIError from 'types/api/error';
import { isValidDashboardImage } from 'pages/DashboardPage/DashboardContainer/dashboardIcons';
import { dashboardDurationError } from 'pages/DashboardPage/DashboardContainer/utils/dashboardDuration';
import { normalizeToPostable } from './importUtils';
import JsonEditor from './JsonEditor';
@@ -46,10 +47,10 @@ function ImportJsonPanel({ onClose }: Props): JSX.Element {
reader.onload = (event): void => {
try {
const target = event.target?.result;
if (!target) {
if (typeof target !== 'string') {
return;
}
const parsed = JSON.parse(target.toString());
const parsed = JSON.parse(target);
setEditorValue(JSON.stringify(parsed, null, 2));
setIsUploadError(false);
} catch {
@@ -63,7 +64,7 @@ function ImportJsonPanel({ onClose }: Props): JSX.Element {
const handleImport = async (): Promise<void> => {
try {
setIsCreating(true);
logEvent('Dashboard List V2: Import and next clicked', {});
void logEvent('Dashboard List V2: Import and next clicked', {});
const parsed = JSON.parse(editorValue) as Record<string, unknown>;
const payload = normalizeToPostable(parsed);
// Only an icon/logo path or a base64 image is a storable `image`; reject
@@ -78,6 +79,15 @@ function ImportJsonPanel({ onClose }: Props): JSX.Element {
);
return;
}
const durationError = dashboardDurationError(payload.spec?.duration);
if (durationError) {
setIsCreateError(true);
void logEvent(DashboardListEvents.ImportFailed, {
reason: 'invalid-duration',
});
toast.error(durationError);
return;
}
const response = await createDashboardV2(payload);
void logEvent(DashboardListEvents.DashboardCreated, { method: 'import' });
onClose();
@@ -129,7 +139,7 @@ function ImportJsonPanel({ onClose }: Props): JSX.Element {
prefix={<MonitorDot size={14} />}
testId="upload-json-file"
onClick={(): void => {
logEvent('Dashboard List V2: Upload JSON file clicked', {});
void logEvent('Dashboard List V2: Upload JSON file clicked', {});
}}
>
{t('upload_json_file')}

View File

@@ -20,7 +20,7 @@ import MyComponent from '../MyComponent';
describe('MyComponent', () => {
it('renders and interacts', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(
rest.get('*/api/v1/example', (_req, res, ctx) => res(ctx.status(200), ctx.json({ value: 42 })))
@@ -40,6 +40,8 @@ The full list is [`.claude/rules/frontend-tests.md`](../../../.claude/rules/fron
- Import from `tests/test-utils` only.
- Prefer `userEvent` for real interactions; use `fireEvent` only for low-level events (scroll/resize/setting `scrollTop`).
- One behaviour per test, rendering the smallest component that owns it; each test under 500 ms (`pnpm jest <file> --verbose`).
- Never call `*ByRole` inside `waitFor`; never raise a timeout to make a slow test pass.
- Use MSW to mock network calls; large JSON goes in `mocks-server/__mockdata__`.
- Keep tests type-safe (`jest.MockedFunction<T>`, avoid `any`).
- Find elements by test ID (`getByTestId`, `findByTestId`); role or text only for markup the app doesn't own.
@@ -48,6 +50,7 @@ The full list is [`.claude/rules/frontend-tests.md`](../../../.claude/rules/fron
Repo-specific reasons:
- The harness wires Redux, React Query, i18n, timezone, preferences, so importing from RTL directly bypasses critical providers.
- Some infra deps are globally mocked (e.g., `uplot`) to keep tests fast and stable.
- `jest.setup.ts` turns off user-event's pointer-events check, Floating UI positioning and antd's scroll-container lookup for every test. Each walks `getComputedStyle` up the DOM, which jsdom computes slowly.
- For virtualization (react-virtuoso), there is no `userEvent` scroll helper; use `fireEvent.scroll` after setting `element.scrollTop`.
#### Example patterns (from `components/QuickFilters/tests/QuickFilters.test.tsx`)
@@ -73,7 +76,7 @@ jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
Interact via test IDs:
```ts
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
await user.click(screen.getByTestId('save-changes'));
expect(screen.getByText(/ADDED FILTERS/i)).toBeInTheDocument();
```
@@ -113,5 +116,5 @@ const navigateSpy = mockNavigate(); // module-level navigate()
```
#### Notes
- Global mocks configured in Jest: `uplot` → `__mocks__/uplotMock.ts`.
- Global mocks configured in Jest: `uplot` → `__mocks__/uplotMock.ts`; `@floating-ui/dom`, `@testing-library/user-event` and antd's `collectScroller` in `jest.setup.ts`.
- If a test needs custom behavior (e.g., different API response), override with `server.use(...)` locally.

View File

@@ -0,0 +1,34 @@
import { render, screen, userEvent } from 'tests/test-utils';
describe('userEvent from the harness', () => {
const onClick = jest.fn();
const renderBlockedButton = (): void => {
render(
<button
type="button"
data-testid="blocked"
style={{ pointerEvents: 'none' }}
onClick={onClick}
>
Blocked
</button>,
);
};
it('skips the pointer-events check for setup()', async () => {
renderBlockedButton();
await userEvent.setup().click(screen.getByTestId('blocked'));
expect(onClick).toHaveBeenCalledTimes(1);
});
it('skips the pointer-events check for the direct API', async () => {
renderBlockedButton();
await userEvent.click(screen.getByTestId('blocked'));
expect(onClick).toHaveBeenCalledTimes(1);
});
});

View File

@@ -0,0 +1,60 @@
type UserEventModule = typeof import('@testing-library/user-event');
type UserEvent = UserEventModule['default'];
type DirectMethod = Exclude<keyof UserEvent, 'setup'>;
const actual = jest.requireActual<UserEventModule>(
'@testing-library/user-event',
);
const userEvent = actual.default;
// The pointer-events check walks getComputedStyle up the tree on every action.
const DEFAULTS = {
pointerEventsCheck: actual.PointerEventsCheckLevel.Never,
};
// Position of the options argument in each direct API call.
const OPTIONS_INDEX: Record<Exclude<DirectMethod, 'clear'>, number> = {
copy: 0,
cut: 0,
tab: 0,
click: 1,
dblClick: 1,
tripleClick: 1,
hover: 1,
unhover: 1,
keyboard: 1,
pointer: 1,
paste: 1,
deselectOptions: 2,
selectOptions: 2,
type: 2,
upload: 2,
};
const withDefaults =
(name: DirectMethod, optionsIndex: number) =>
(...args: unknown[]): Promise<unknown> => {
const next = [...args];
next[optionsIndex] = {
...DEFAULTS,
...(next[optionsIndex] as object | undefined),
};
return Reflect.apply(userEvent[name], userEvent, next);
};
const directApi = Object.fromEntries(
Object.entries(OPTIONS_INDEX).map(([name, index]) => [
name,
withDefaults(name as DirectMethod, index),
]),
);
const userEventWithDefaults: UserEvent = {
...userEvent,
...directApi,
clear: (element) => userEvent.setup(DEFAULTS).clear(element),
setup: (options) => userEvent.setup({ ...DEFAULTS, ...options }),
};
export const { PointerEventsCheckLevel } = actual;
export default userEventWithDefaults;

View File

@@ -2,6 +2,19 @@ import getLocalStorageKey from 'api/browser/localstorage/get';
import setLocalStorageKey from 'api/browser/localstorage/set';
import { LOCALSTORAGE } from 'constants/localStorage';
function readPersistedTimes(): Record<string, string> {
const stored = getLocalStorageKey(LOCALSTORAGE.METRICS_TIME_IN_DURATION);
try {
return stored ? JSON.parse(stored) : {};
} catch {
return {};
}
}
export function hasPersistedTimeForRoute(pathname: string): boolean {
return Boolean(readPersistedTimes()[pathname]);
}
/**
* Updates the stored time duration for a route in localStorage.
* Used by both DateTimeSelectionV2 (manual time pick) and useZoomOut (zoom out button).
@@ -13,14 +26,7 @@ export function persistTimeDurationForRoute(
pathname: string,
value: string,
): void {
const preRoutes = getLocalStorageKey(LOCALSTORAGE.METRICS_TIME_IN_DURATION);
let preRoutesObject: Record<string, string> = {};
try {
preRoutesObject = preRoutes ? JSON.parse(preRoutes) : {};
} catch {
preRoutesObject = {};
}
const preRoute = { ...preRoutesObject, [pathname]: value };
const preRoute = { ...readPersistedTimes(), [pathname]: value };
setLocalStorageKey(
LOCALSTORAGE.METRICS_TIME_IN_DURATION,
JSON.stringify(preRoute),

View File

@@ -0,0 +1,25 @@
// Units of Prometheus `model.Duration`, the duration grammar the API accepts.
export const PROMETHEUS_DURATION_UNIT_MS: Record<string, number> = {
ms: 1,
s: 1_000,
m: 60_000,
h: 3_600_000,
d: 86_400_000,
w: 604_800_000,
y: 31_536_000_000,
};
// Largest unit first, each at most once: `30m1h` and `1m1m` are rejected by the API.
const DURATION_RE = /^(\d+y)?(\d+w)?(\d+d)?(\d+h)?(\d+m)?(\d+s)?(\d+ms)?$/;
const DURATION_TOKEN_RE = /(\d+)(ms|s|m|h|d|w|y)/g;
/** Milliseconds in a Prometheus duration such as `1h30m`, or null when it is not one. */
export function prometheusDurationToMs(value: string): number | null {
if (!value || !DURATION_RE.test(value)) {
return null;
}
let totalMs = 0;
for (const [, amount, unit] of value.matchAll(DURATION_TOKEN_RE)) {
totalMs += Number(amount) * PROMETHEUS_DURATION_UNIT_MS[unit];
}
return totalMs;
}

View File

@@ -25,7 +25,7 @@ type DashboardSpec struct {
Variables []Variable `json:"variables" required:"true" nullable:"false" description:"The dashboard variables, each a ListVariable or TextVariable envelope, referenced in queries as $name. Names must be unique. Use [] for none."`
Panels map[string]*Panel `json:"panels" required:"true" nullable:"false" description:"The panels keyed by panel id. An id has up to 75 characters from letters, digits, dot, underscore and hyphen. A panel is shown only where a layout item references it as #/spec/panels/<id>. Use {} for none."`
Layouts []Layout `json:"layouts" required:"true" nullable:"false" description:"The Grid layouts that place panels, at most 500. Each panel can be placed at most once. Use [] for none."`
Duration common.DurationString `json:"duration" description:"The default time range, as a Prometheus duration such as 1h or 7d. Stored, but not applied by the UI."`
Duration common.DurationString `json:"duration" description:"The default time range, as a Prometheus duration such as 1h or 7d. The UI opens the dashboard on it, rounded up to whole minutes, when neither the URL nor the viewer's last pick sets a time range."`
RefreshInterval common.DurationString `json:"refreshInterval" description:"The auto refresh interval, as a Prometheus duration such as 30s. Stored, but not applied by the UI."`
Links []Link `json:"links,omitzero" description:"External links stored with the dashboard. Not shown by the UI."`
}