mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-19 23:01:18 +00:00
Compare commits
9 Commits
issue_nerv
...
test/jest-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aad689acd2 | ||
|
|
77ebf4dca9 | ||
|
|
c4ac1929fa | ||
|
|
df0f26b5fb | ||
|
|
3843ac4eeb | ||
|
|
0add9cce0d | ||
|
|
4ffa6ac5da | ||
|
|
824315b093 | ||
|
|
1ee097b60a |
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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;
|
||||
/**
|
||||
|
||||
@@ -56,6 +56,8 @@
|
||||
.title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
gap: 7px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
@@ -63,6 +65,7 @@
|
||||
}
|
||||
|
||||
.shortcut {
|
||||
flex-shrink: 0;
|
||||
font-size: 10px;
|
||||
font-family: var(--font-mono, monospace);
|
||||
font-weight: 500;
|
||||
@@ -81,6 +84,7 @@
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { TextEllipsis } from '@signozhq/ui/text-ellipsis';
|
||||
import { navigate } from 'lib/router/navigation';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
@@ -17,6 +18,7 @@ import {
|
||||
normalizePage,
|
||||
useAIAssistantAnalyticsContext,
|
||||
} from '../hooks/useAIAssistantAnalyticsContext';
|
||||
import { useActiveChatTitle } from '../hooks/useActiveChatTitle';
|
||||
import { useAIAssistantStore } from '../store/useAIAssistantStore';
|
||||
import { VariantContext } from '../VariantContext';
|
||||
|
||||
@@ -39,6 +41,7 @@ export default function AIAssistantModal(): JSX.Element | null {
|
||||
const activeConversationId = useAIAssistantStore(
|
||||
(s) => s.activeConversationId,
|
||||
);
|
||||
const chatTitle = useActiveChatTitle();
|
||||
const openModal = useAIAssistantStore((s) => s.openModal);
|
||||
const closeModal = useAIAssistantStore((s) => s.closeModal);
|
||||
const minimizeModal = useAIAssistantStore((s) => s.minimizeModal);
|
||||
@@ -151,7 +154,7 @@ export default function AIAssistantModal(): JSX.Element | null {
|
||||
<div className={styles.header}>
|
||||
<div className={`${styles.title} noz-wave`}>
|
||||
<Noz size={16} />
|
||||
<span>Noz</span>
|
||||
{chatTitle && <TextEllipsis position="end">{chatTitle}</TextEllipsis>}
|
||||
<kbd className={styles.shortcut}>
|
||||
<span>⌘</span>
|
||||
<span>J</span>
|
||||
|
||||
@@ -1,39 +1,3 @@
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-shrink: 0;
|
||||
height: 100%;
|
||||
border-left: 1px solid var(--l1-border);
|
||||
background: var(--l1-background);
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.resizeHandle {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 4px;
|
||||
height: 100%;
|
||||
cursor: col-resize;
|
||||
z-index: 10;
|
||||
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 1px;
|
||||
width: 2px;
|
||||
height: 100%;
|
||||
background: transparent;
|
||||
transition: background 0.15s ease;
|
||||
}
|
||||
|
||||
&:hover::after {
|
||||
background: var(--accent-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -47,6 +11,8 @@
|
||||
.title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
@@ -55,6 +21,7 @@
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useState } from 'react';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { TextEllipsis } from '@signozhq/ui/text-ellipsis';
|
||||
import { matchRoute } from 'lib/router/matchRoute';
|
||||
import { navigate } from 'lib/router/navigation';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
@@ -7,6 +8,9 @@ import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { History, Maximize2, Plus, X } from '@signozhq/icons';
|
||||
import Noz from 'components/Noz/Noz';
|
||||
import { BOTTOM_STRIP_HEIGHT } from 'container/BottomStrip';
|
||||
import { supportChatObstacle } from 'container/BottomStrip/SupportButton/supportChatObstacle';
|
||||
import { FloatingPanel } from 'periscope/components/FloatingPanel';
|
||||
|
||||
import logEvent from 'api/common/logEvent';
|
||||
|
||||
@@ -14,13 +18,28 @@ import ConversationsList from '../components/ConversationsList';
|
||||
import ConversationView from '../ConversationView';
|
||||
import { AIAssistantEvents } from '../events';
|
||||
import { useAIAssistantAnalyticsContext } from '../hooks/useAIAssistantAnalyticsContext';
|
||||
import { useActiveChatTitle } from '../hooks/useActiveChatTitle';
|
||||
import { useAIAssistantStore } from '../store/useAIAssistantStore';
|
||||
import { VariantContext } from '../VariantContext';
|
||||
|
||||
import styles from './AIAssistantPanel.module.scss';
|
||||
|
||||
const AI_ASSISTANT_PANEL_OPEN_CLASS = 'ai-assistant-panel-open';
|
||||
const AI_ASSISTANT_PANEL_WIDTH_VAR = '--ai-assistant-panel-width';
|
||||
const PANEL_WIDTH = 420;
|
||||
const PANEL_HEIGHT = 601;
|
||||
const PANEL_MIN_WIDTH = 380;
|
||||
const PANEL_MIN_HEIGHT = 500;
|
||||
const PANEL_MARGIN = 8;
|
||||
const PANEL_RESIZE_EDGES = {
|
||||
top: true,
|
||||
right: true,
|
||||
bottom: true,
|
||||
left: true,
|
||||
topRight: false,
|
||||
bottomRight: false,
|
||||
bottomLeft: false,
|
||||
topLeft: false,
|
||||
};
|
||||
const PANEL_AVOID = [supportChatObstacle];
|
||||
|
||||
export default function AIAssistantPanel(): JSX.Element | null {
|
||||
const { pathname } = useAppLocation();
|
||||
@@ -38,6 +57,7 @@ export default function AIAssistantPanel(): JSX.Element | null {
|
||||
(s) => s.startNewConversation,
|
||||
);
|
||||
const analyticsCtx = useAIAssistantAnalyticsContext();
|
||||
const chatTitle = useActiveChatTitle();
|
||||
|
||||
const handleExpand = useCallback(() => {
|
||||
if (!activeConversationId) {
|
||||
@@ -72,75 +92,36 @@ export default function AIAssistantPanel(): JSX.Element | null {
|
||||
setShowHistory(false);
|
||||
}, []);
|
||||
|
||||
// ── Resize logic ──────────────────────────────────────────────────────────
|
||||
const [panelWidth, setPanelWidth] = useState(380);
|
||||
const dragStartX = useRef(0);
|
||||
const dragStartWidth = useRef(0);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const shouldOffsetChatSupport = isOpen && !isFullScreenPage;
|
||||
|
||||
document.body.classList.toggle(
|
||||
AI_ASSISTANT_PANEL_OPEN_CLASS,
|
||||
shouldOffsetChatSupport,
|
||||
);
|
||||
|
||||
if (shouldOffsetChatSupport) {
|
||||
document.body.style.setProperty(
|
||||
AI_ASSISTANT_PANEL_WIDTH_VAR,
|
||||
`${panelWidth}px`,
|
||||
);
|
||||
} else {
|
||||
document.body.style.removeProperty(AI_ASSISTANT_PANEL_WIDTH_VAR);
|
||||
}
|
||||
|
||||
return (): void => {
|
||||
document.body.classList.remove(AI_ASSISTANT_PANEL_OPEN_CLASS);
|
||||
document.body.style.removeProperty(AI_ASSISTANT_PANEL_WIDTH_VAR);
|
||||
};
|
||||
}, [isFullScreenPage, isOpen, panelWidth]);
|
||||
|
||||
const handleResizeMouseDown = useCallback(
|
||||
(e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
dragStartX.current = e.clientX;
|
||||
dragStartWidth.current = panelWidth;
|
||||
|
||||
const onMouseMove = (ev: MouseEvent): void => {
|
||||
// Panel is on the right; dragging left (lower clientX) increases width
|
||||
const delta = dragStartX.current - ev.clientX;
|
||||
const next = Math.min(Math.max(dragStartWidth.current + delta, 380), 800);
|
||||
setPanelWidth(next);
|
||||
};
|
||||
|
||||
const onMouseUp = (): void => {
|
||||
document.removeEventListener('mousemove', onMouseMove);
|
||||
document.removeEventListener('mouseup', onMouseUp);
|
||||
document.body.style.cursor = '';
|
||||
document.body.style.userSelect = '';
|
||||
};
|
||||
|
||||
document.body.style.cursor = 'col-resize';
|
||||
document.body.style.userSelect = 'none';
|
||||
document.addEventListener('mousemove', onMouseMove);
|
||||
document.addEventListener('mouseup', onMouseUp);
|
||||
},
|
||||
[panelWidth],
|
||||
);
|
||||
|
||||
if (!isOpen || isFullScreenPage) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const availableHeight = Math.max(
|
||||
0,
|
||||
window.innerHeight - BOTTOM_STRIP_HEIGHT - 2 * PANEL_MARGIN,
|
||||
);
|
||||
const panelHeight = Math.min(PANEL_HEIGHT, availableHeight);
|
||||
|
||||
return (
|
||||
<VariantContext.Provider value="panel">
|
||||
<div className={styles.panel} style={{ width: panelWidth }}>
|
||||
{/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
|
||||
<div className={styles.resizeHandle} onMouseDown={handleResizeMouseDown} />
|
||||
<div className={styles.header}>
|
||||
<FloatingPanel
|
||||
isOpen
|
||||
width={PANEL_WIDTH}
|
||||
height={panelHeight}
|
||||
minWidth={PANEL_MIN_WIDTH}
|
||||
minHeight={Math.min(PANEL_MIN_HEIGHT, availableHeight)}
|
||||
enableResizing={PANEL_RESIZE_EDGES}
|
||||
keepInViewport
|
||||
avoid={PANEL_AVOID}
|
||||
defaultPosition={{
|
||||
x: window.innerWidth - PANEL_WIDTH - PANEL_MARGIN,
|
||||
y: PANEL_MARGIN + availableHeight - panelHeight,
|
||||
}}
|
||||
>
|
||||
<div className={`${styles.header} floating-panel__drag-handle`}>
|
||||
<div className={`${styles.title} noz-wave`}>
|
||||
<Noz size={18} />
|
||||
<span>Noz</span>
|
||||
{chatTitle && <TextEllipsis position="end">{chatTitle}</TextEllipsis>}
|
||||
</div>
|
||||
|
||||
<div className={styles.actions}>
|
||||
@@ -191,6 +172,7 @@ export default function AIAssistantPanel(): JSX.Element | null {
|
||||
size="sm"
|
||||
icon
|
||||
color="secondary"
|
||||
testId="ai-assistant-panel-close"
|
||||
onClick={closeDrawer}
|
||||
aria-label="Close panel"
|
||||
>
|
||||
@@ -207,7 +189,7 @@ export default function AIAssistantPanel(): JSX.Element | null {
|
||||
<ConversationView conversationId={activeConversationId} />
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</FloatingPanel>
|
||||
</VariantContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -17,13 +17,17 @@
|
||||
|
||||
.empty {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
// `safe` falls back to the top once the content overflows, so it stays scrollable.
|
||||
justify-content: safe center;
|
||||
padding: 32px 24px;
|
||||
gap: 8px;
|
||||
text-align: center;
|
||||
@include scrollbar;
|
||||
}
|
||||
|
||||
.emptyIcon {
|
||||
@@ -54,6 +58,7 @@
|
||||
}
|
||||
|
||||
.suggestion {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
padding: 10px 14px;
|
||||
border: 1px solid var(--l2-border);
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { renderHook } from 'tests/test-utils';
|
||||
|
||||
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
|
||||
import type { Conversation } from '../../types';
|
||||
import { NEW_CHAT_TITLE, useActiveChatTitle } from '../useActiveChatTitle';
|
||||
|
||||
const initialState = useAIAssistantStore.getState();
|
||||
|
||||
const open = (conversation: Conversation): void => {
|
||||
useAIAssistantStore.setState({
|
||||
conversations: { [conversation.id]: conversation },
|
||||
activeConversationId: conversation.id,
|
||||
});
|
||||
};
|
||||
|
||||
describe('useActiveChatTitle', () => {
|
||||
afterEach(() => {
|
||||
useAIAssistantStore.setState(initialState, true);
|
||||
});
|
||||
|
||||
it('is the open chat’s title', () => {
|
||||
open({ id: 'a', title: 'Checkout p99', messages: [], createdAt: 0 });
|
||||
|
||||
const { result } = renderHook(() => useActiveChatTitle());
|
||||
|
||||
expect(result.current).toBe('Checkout p99');
|
||||
});
|
||||
|
||||
it('is "New chat" until the chat has a title', () => {
|
||||
open({ id: 'a', messages: [], createdAt: 0 });
|
||||
|
||||
const { result } = renderHook(() => useActiveChatTitle());
|
||||
|
||||
expect(result.current).toBe(NEW_CHAT_TITLE);
|
||||
});
|
||||
|
||||
it('is empty while a restored chat loads, rather than flashing "New chat"', () => {
|
||||
open({ id: 'a', messages: [], createdAt: 0, isHydrating: true });
|
||||
|
||||
const { result } = renderHook(() => useActiveChatTitle());
|
||||
|
||||
expect(result.current).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { useAIAssistantStore } from '../store/useAIAssistantStore';
|
||||
|
||||
export const NEW_CHAT_TITLE = 'New chat';
|
||||
|
||||
/** The open chat's title for a header: "New chat" until it has one, null while a restored chat loads. */
|
||||
export function useActiveChatTitle(): string | null {
|
||||
return useAIAssistantStore((s) => {
|
||||
const conversation = s.activeConversationId
|
||||
? s.conversations[s.activeConversationId]
|
||||
: undefined;
|
||||
if (conversation?.title) {
|
||||
return conversation.title;
|
||||
}
|
||||
return conversation?.isHydrating ? null : NEW_CHAT_TITLE;
|
||||
});
|
||||
}
|
||||
@@ -23,7 +23,8 @@ import styles from './AskNoz.module.scss';
|
||||
|
||||
/**
|
||||
* Opens the Noz drawer, matching the header entry it replaces. Cmd+K opens the
|
||||
* modal instead; this is deliberately the drawer.
|
||||
* modal instead; this is deliberately the drawer. It stays while the drawer is
|
||||
* open, where it closes the drawer and keeps the chat for the next open.
|
||||
*
|
||||
* Carries the header's pending badge: when Noz is blocked on the user
|
||||
* (`awaiting_approval` / `awaiting_clarification`) a dot pulses. Without it,
|
||||
@@ -38,21 +39,28 @@ function AskNoz(): JSX.Element | null {
|
||||
selectPendingUserInputStreamCount,
|
||||
);
|
||||
|
||||
// Noz is already on screen in the modal, so the "needs you" dot would be noise.
|
||||
const showPendingBadge = pendingUserInputCount > 0 && !isModalOpen;
|
||||
const closeDrawer = useAIAssistantStore((state) => state.closeDrawer);
|
||||
|
||||
// Noz is already on screen in the drawer or modal, so the "needs you" dot would be noise.
|
||||
const showPendingBadge =
|
||||
pendingUserInputCount > 0 && !isDrawerOpen && !isModalOpen;
|
||||
|
||||
// The drawer does not render on the Noz full page, so the button would be inert.
|
||||
const isAIAssistantPage = pathname.startsWith(ROUTES.AI_ASSISTANT_BASE);
|
||||
|
||||
const handleOpen = useCallback((): void => {
|
||||
const handleClick = useCallback((): void => {
|
||||
if (isDrawerOpen) {
|
||||
closeDrawer();
|
||||
return;
|
||||
}
|
||||
void logEvent(AIAssistantEvents.Opened, {
|
||||
source: AIAssistantOpenSource.BottomStrip,
|
||||
currentPage: normalizePage(pathname),
|
||||
});
|
||||
openAIAssistant();
|
||||
}, [pathname]);
|
||||
}, [closeDrawer, isDrawerOpen, pathname]);
|
||||
|
||||
if (!isAIAssistantEnabled || isDrawerOpen || isAIAssistantPage) {
|
||||
if (!isAIAssistantEnabled || isAIAssistantPage) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -72,7 +80,9 @@ function AskNoz(): JSX.Element | null {
|
||||
color="secondary"
|
||||
size="sm"
|
||||
prefix={<Noz size={16} />}
|
||||
onClick={handleOpen}
|
||||
testId="bottom-strip-ask-noz-button"
|
||||
onClick={handleClick}
|
||||
aria-pressed={isDrawerOpen}
|
||||
aria-label={
|
||||
showPendingBadge
|
||||
? `Ask Noz, ${pendingUserInputCount} ${
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { fireEvent } from '@testing-library/react';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import {
|
||||
AIAssistantEvents,
|
||||
@@ -6,15 +5,11 @@ import {
|
||||
} from 'container/AIAssistant/events';
|
||||
import { openAIAssistant } from 'container/AIAssistant/store/useAIAssistantStore';
|
||||
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
|
||||
import { render } from 'tests/test-utils';
|
||||
import { render, userEvent } from 'tests/test-utils';
|
||||
|
||||
import AskNoz from '../AskNoz';
|
||||
|
||||
jest.mock('hooks/useIsAIAssistantEnabled');
|
||||
jest.mock('api/common/logEvent', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn(),
|
||||
}));
|
||||
jest.mock('container/AIAssistant/store/useAIAssistantStore', () => ({
|
||||
openAIAssistant: jest.fn(),
|
||||
useAIAssistantStore: jest.fn(),
|
||||
@@ -24,6 +19,7 @@ const mockEnabled = useIsAIAssistantEnabled as jest.MockedFunction<
|
||||
typeof useIsAIAssistantEnabled
|
||||
>;
|
||||
const mockOpen = openAIAssistant as jest.MockedFunction<typeof openAIAssistant>;
|
||||
const mockClose = jest.fn() as jest.MockedFunction<() => void>;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const { useAIAssistantStore } = jest.requireMock(
|
||||
@@ -40,7 +36,12 @@ function mockStore({
|
||||
isModalOpen?: boolean;
|
||||
pendingCount?: number;
|
||||
} = {}): void {
|
||||
const state = { isDrawerOpen, isModalOpen, streams: {} };
|
||||
const state = {
|
||||
isDrawerOpen,
|
||||
isModalOpen,
|
||||
streams: {},
|
||||
closeDrawer: mockClose,
|
||||
};
|
||||
useAIAssistantStore.mockImplementation((selector: (s: unknown) => unknown) => {
|
||||
const picked = selector(state);
|
||||
// `selectPendingUserInputStreamCount` walks `streams`, which is empty here,
|
||||
@@ -49,9 +50,8 @@ function mockStore({
|
||||
});
|
||||
}
|
||||
|
||||
// `TooltipSimple` replaces its trigger's props, so the testId lives on the
|
||||
// wrapper and the button itself is reached by role — there is only ever one.
|
||||
const SLOT = 'bottom-strip-ask-noz';
|
||||
const BUTTON = 'bottom-strip-ask-noz-button';
|
||||
|
||||
describe('AskNoz', () => {
|
||||
beforeEach(() => {
|
||||
@@ -62,9 +62,9 @@ describe('AskNoz', () => {
|
||||
|
||||
describe('visibility', () => {
|
||||
it('renders when the assistant is enabled', () => {
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(getByRole('button')).toBeInTheDocument();
|
||||
expect(getByTestId(BUTTON)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders nothing when the assistant is disabled', () => {
|
||||
@@ -75,12 +75,12 @@ describe('AskNoz', () => {
|
||||
expect(queryByTestId(SLOT)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders nothing while the drawer is open', () => {
|
||||
it('stays pressed while the drawer is open', () => {
|
||||
mockStore({ isDrawerOpen: true });
|
||||
|
||||
const { queryByTestId } = render(<AskNoz />);
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(queryByTestId(SLOT)).not.toBeInTheDocument();
|
||||
expect(getByTestId(BUTTON)).toHaveAttribute('aria-pressed', 'true');
|
||||
});
|
||||
|
||||
it('renders nothing on the Noz full page, where the drawer does not mount', () => {
|
||||
@@ -93,18 +93,32 @@ describe('AskNoz', () => {
|
||||
});
|
||||
|
||||
describe('what it does', () => {
|
||||
it('opens the drawer on click', () => {
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
it('opens the drawer on click', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
fireEvent.click(getByRole('button'));
|
||||
await user.click(getByTestId(BUTTON));
|
||||
|
||||
expect(mockOpen).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('reports the open as coming from the strip', () => {
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
it('closes the open drawer on the same chat instead of starting a new one', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
mockStore({ isDrawerOpen: true });
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
fireEvent.click(getByRole('button'));
|
||||
await user.click(getByTestId(BUTTON));
|
||||
|
||||
expect(mockClose).toHaveBeenCalledTimes(1);
|
||||
expect(mockOpen).not.toHaveBeenCalled();
|
||||
expect(logEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports the open as coming from the strip', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
await user.click(getByTestId(BUTTON));
|
||||
|
||||
expect(logEvent).toHaveBeenCalledWith(
|
||||
AIAssistantEvents.Opened,
|
||||
@@ -117,9 +131,9 @@ describe('AskNoz', () => {
|
||||
it('announces the count when Noz is waiting on the user', () => {
|
||||
mockStore({ pendingCount: 2 });
|
||||
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(getByRole('button')).toHaveAttribute(
|
||||
expect(getByTestId(BUTTON)).toHaveAttribute(
|
||||
'aria-label',
|
||||
'Ask Noz, 2 actions need your response',
|
||||
);
|
||||
@@ -128,26 +142,34 @@ describe('AskNoz', () => {
|
||||
it('uses the singular for one pending action', () => {
|
||||
mockStore({ pendingCount: 1 });
|
||||
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(getByRole('button')).toHaveAttribute(
|
||||
expect(getByTestId(BUTTON)).toHaveAttribute(
|
||||
'aria-label',
|
||||
'Ask Noz, 1 action needs your response',
|
||||
);
|
||||
});
|
||||
|
||||
it('stays quiet when nothing is pending', () => {
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(getByRole('button')).toHaveAttribute('aria-label', 'Ask Noz');
|
||||
expect(getByTestId(BUTTON)).toHaveAttribute('aria-label', 'Ask Noz');
|
||||
});
|
||||
|
||||
it('stays quiet while the drawer is open, Noz is already on screen', () => {
|
||||
mockStore({ isDrawerOpen: true, pendingCount: 3 });
|
||||
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(getByTestId(BUTTON)).toHaveAttribute('aria-label', 'Ask Noz');
|
||||
});
|
||||
|
||||
it('stays quiet while the modal is open, Noz is already on screen', () => {
|
||||
mockStore({ isModalOpen: true, pendingCount: 3 });
|
||||
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(getByRole('button')).toHaveAttribute('aria-label', 'Ask Noz');
|
||||
expect(getByTestId(BUTTON)).toHaveAttribute('aria-label', 'Ask Noz');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import type { FloatingRect } from 'periscope/components/FloatingPanel/types';
|
||||
|
||||
import { supportChatObstacle } from '../supportChatObstacle';
|
||||
|
||||
type Pylon = Window['Pylon'];
|
||||
|
||||
const SUPPORT_CHAT: FloatingRect = { x: 882, y: 286, width: 384, height: 478 };
|
||||
const CLOSED_CLASS = 'PylonChat-chatWindowFrameContainer--closed';
|
||||
|
||||
const originalPylon = window.Pylon;
|
||||
const pylonCallbacks = new Map<string, unknown>();
|
||||
const unsubscribes: (() => void)[] = [];
|
||||
|
||||
function subscribe(onChange: () => void): () => void {
|
||||
const unsubscribe = supportChatObstacle.subscribe(onChange);
|
||||
unsubscribes.push(unsubscribe);
|
||||
return unsubscribe;
|
||||
}
|
||||
|
||||
function installPylon(): jest.MockedFunction<Pylon> {
|
||||
const pylon = jest.fn<ReturnType<Pylon>, Parameters<Pylon>>(
|
||||
(command, callback) => {
|
||||
pylonCallbacks.set(command, callback);
|
||||
},
|
||||
);
|
||||
window.Pylon = pylon;
|
||||
return pylon;
|
||||
}
|
||||
|
||||
function firePylon(event: 'onShow' | 'onHide'): void {
|
||||
const callback = pylonCallbacks.get(event);
|
||||
if (typeof callback === 'function') {
|
||||
callback();
|
||||
}
|
||||
}
|
||||
|
||||
function renderSupportChat(): HTMLElement {
|
||||
const element = document.createElement('div');
|
||||
element.className = 'PylonChat-chatWindowFrameContainer';
|
||||
Object.defineProperties(element, {
|
||||
offsetLeft: { value: SUPPORT_CHAT.x },
|
||||
offsetTop: { value: SUPPORT_CHAT.y },
|
||||
offsetWidth: { value: SUPPORT_CHAT.width },
|
||||
offsetHeight: { value: SUPPORT_CHAT.height },
|
||||
});
|
||||
document.body.appendChild(element);
|
||||
return element;
|
||||
}
|
||||
|
||||
describe('supportChatObstacle', () => {
|
||||
beforeEach(() => pylonCallbacks.clear());
|
||||
|
||||
afterEach(() => {
|
||||
unsubscribes.splice(0).forEach((unsubscribe) => unsubscribe());
|
||||
window.Pylon = originalPylon;
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('reports the chat window box only while it is open', () => {
|
||||
const chat = renderSupportChat();
|
||||
|
||||
expect(supportChatObstacle.getRect()).toStrictEqual(SUPPORT_CHAT);
|
||||
|
||||
chat.classList.add(CLOSED_CLASS);
|
||||
|
||||
expect(supportChatObstacle.getRect()).toBeNull();
|
||||
});
|
||||
|
||||
it('treats the chat as closed once Pylon reports it hidden', () => {
|
||||
installPylon();
|
||||
renderSupportChat();
|
||||
subscribe(jest.fn());
|
||||
|
||||
firePylon('onHide');
|
||||
|
||||
expect(supportChatObstacle.getRect()).toBeNull();
|
||||
});
|
||||
|
||||
it('notifies every subscriber through one Pylon registration', () => {
|
||||
const pylon = installPylon();
|
||||
const first = jest.fn() as jest.MockedFunction<() => void>;
|
||||
const second = jest.fn() as jest.MockedFunction<() => void>;
|
||||
subscribe(first);
|
||||
subscribe(second);
|
||||
|
||||
firePylon('onShow');
|
||||
|
||||
expect(pylon.mock.calls.map(([command]) => command)).toStrictEqual([
|
||||
'onShow',
|
||||
'onHide',
|
||||
]);
|
||||
expect(first).toHaveBeenCalledTimes(1);
|
||||
expect(second).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('unregisters through the loaded widget, not the stub it registered with', () => {
|
||||
const stub = installPylon();
|
||||
const unsubscribe = subscribe(jest.fn());
|
||||
// Pylon's script swaps out the queueing stub, which then can no longer be called.
|
||||
const widget = installPylon();
|
||||
|
||||
unsubscribe();
|
||||
|
||||
expect(stub.mock.calls.map(([command]) => command)).toStrictEqual([
|
||||
'onShow',
|
||||
'onHide',
|
||||
]);
|
||||
expect(widget.mock.calls).toStrictEqual([
|
||||
['onShow', null],
|
||||
['onHide', null],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import type {
|
||||
FloatingObstacle,
|
||||
FloatingRect,
|
||||
} from 'periscope/components/FloatingPanel/types';
|
||||
|
||||
// Pylon's own class names, which styles.scss also targets.
|
||||
const SUPPORT_CHAT_SELECTOR = '.PylonChat-chatWindowFrameContainer';
|
||||
const SUPPORT_CHAT_CLOSED_CLASS = 'PylonChat-chatWindowFrameContainer--closed';
|
||||
|
||||
const listeners = new Set<() => void>();
|
||||
// Pylon's last show/hide while subscribed; undefined until one arrives.
|
||||
let isOpen: boolean | undefined;
|
||||
|
||||
function setOpen(open: boolean): void {
|
||||
isOpen = open;
|
||||
listeners.forEach((listener) => listener());
|
||||
}
|
||||
|
||||
const onShow = (): void => setOpen(true);
|
||||
const onHide = (): void => setOpen(false);
|
||||
|
||||
// Offsets ignore the scale animation Pylon opens with, so this is the settled box.
|
||||
function getSupportChatRect(): FloatingRect | null {
|
||||
const element = document.querySelector<HTMLElement>(SUPPORT_CHAT_SELECTOR);
|
||||
if (!element) {
|
||||
return null;
|
||||
}
|
||||
// Pylon's event decides; the class covers a chat opened before anyone subscribed.
|
||||
if (!(isOpen ?? !element.classList.contains(SUPPORT_CHAT_CLOSED_CLASS))) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
x: element.offsetLeft,
|
||||
y: element.offsetTop,
|
||||
width: element.offsetWidth,
|
||||
height: element.offsetHeight,
|
||||
};
|
||||
}
|
||||
|
||||
function subscribeToSupportChat(onChange: () => void): () => void {
|
||||
if (!window.Pylon) {
|
||||
return (): void => undefined;
|
||||
}
|
||||
listeners.add(onChange);
|
||||
// Pylon keeps a single callback per event, so all listeners share one registration.
|
||||
if (listeners.size === 1) {
|
||||
window.Pylon('onShow', onShow);
|
||||
window.Pylon('onHide', onHide);
|
||||
}
|
||||
return (): void => {
|
||||
listeners.delete(onChange);
|
||||
if (listeners.size === 0) {
|
||||
isOpen = undefined;
|
||||
// Read `window.Pylon` again: once loaded, the widget replaces the stub, which then throws.
|
||||
window.Pylon?.('onShow', null);
|
||||
window.Pylon?.('onHide', null);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export const supportChatObstacle: FloatingObstacle = {
|
||||
getRect: getSupportChatRect,
|
||||
subscribe: subscribeToSupportChat,
|
||||
};
|
||||
@@ -8,7 +8,8 @@
|
||||
background-color: var(--l1-background);
|
||||
border-top: 1px solid var(--l1-border);
|
||||
padding: 12px;
|
||||
z-index: 1000;
|
||||
// Below FloatingPanel (999), so the Noz panel stacks over the footer.
|
||||
z-index: 998;
|
||||
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
@@ -31,7 +32,3 @@
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
body.ai-assistant-panel-open .create-alert-v2-footer {
|
||||
right: var(--ai-assistant-panel-width, 380px);
|
||||
}
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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';
|
||||
}
|
||||
|
||||
@@ -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<
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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' });
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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() }),
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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]);
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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}>
|
||||
|
||||
@@ -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' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 (
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
91
frontend/src/pages/DashboardPage/stories/__story_mockdata__/dashboard.play.ts
generated
Normal file
91
frontend/src/pages/DashboardPage/stories/__story_mockdata__/dashboard.play.ts
generated
Normal 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);
|
||||
};
|
||||
@@ -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]]),
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
|
||||
@@ -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')}
|
||||
|
||||
@@ -6,6 +6,11 @@
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
|
||||
overflow: hidden;
|
||||
|
||||
// Set only while sliding clear of an obstacle, so drags stay instant.
|
||||
&--sliding {
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
|
||||
// Inner div fills the Rnd-controlled size
|
||||
&__inner {
|
||||
width: 100%;
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { ComponentProps } from 'react';
|
||||
import { ComponentProps, useRef } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Rnd } from 'react-rnd';
|
||||
|
||||
import './FloatingPanel.styles.scss';
|
||||
import type { FloatingObstacle } from './types';
|
||||
import { useAvoidObstacles } from './useAvoidObstacles';
|
||||
import { useKeepInViewport } from './useKeepInViewport';
|
||||
|
||||
type EnableResizing = ComponentProps<typeof Rnd>['enableResizing'];
|
||||
|
||||
@@ -16,6 +19,10 @@ export interface FloatingPanelProps {
|
||||
minHeight?: number;
|
||||
enableResizing?: EnableResizing;
|
||||
className?: string;
|
||||
/** Moves and shrinks the panel back into view when the window resizes. */
|
||||
keepInViewport?: boolean;
|
||||
/** Slides the panel clear of these while they show; keep the array stable across renders. */
|
||||
avoid?: FloatingObstacle[];
|
||||
}
|
||||
|
||||
function FloatingPanel({
|
||||
@@ -28,7 +35,13 @@ function FloatingPanel({
|
||||
minHeight = 300,
|
||||
enableResizing,
|
||||
className,
|
||||
keepInViewport = false,
|
||||
avoid,
|
||||
}: FloatingPanelProps): JSX.Element | null {
|
||||
const rndRef = useRef<Rnd>(null);
|
||||
const viewport = useKeepInViewport(rndRef, isOpen && keepInViewport);
|
||||
useAvoidObstacles(rndRef, avoid, isOpen);
|
||||
|
||||
if (!isOpen) {
|
||||
return null;
|
||||
}
|
||||
@@ -40,6 +53,7 @@ function FloatingPanel({
|
||||
|
||||
return createPortal(
|
||||
<Rnd
|
||||
ref={rndRef}
|
||||
default={{
|
||||
x: initialPosition.x,
|
||||
y: initialPosition.y,
|
||||
@@ -47,27 +61,9 @@ function FloatingPanel({
|
||||
height,
|
||||
}}
|
||||
dragHandleClassName="floating-panel__drag-handle"
|
||||
minWidth={minWidth}
|
||||
minHeight={minHeight}
|
||||
onDrag={(_e, d): void | false => {
|
||||
const HEADER_HEIGHT = 40;
|
||||
// Top: don't allow header to go above viewport
|
||||
if (d.y < 0) {
|
||||
return false;
|
||||
}
|
||||
// Left: don't allow panel to go off-screen left
|
||||
if (d.x < 0) {
|
||||
return false;
|
||||
}
|
||||
// Bottom: only header needs to be visible
|
||||
if (d.y > window.innerHeight - HEADER_HEIGHT) {
|
||||
return false;
|
||||
}
|
||||
// Right: at least the close button (~40px) stays visible
|
||||
if (d.x > window.innerWidth - 40) {
|
||||
return false;
|
||||
}
|
||||
}}
|
||||
bounds="window"
|
||||
minWidth={keepInViewport ? Math.min(minWidth, viewport.width) : minWidth}
|
||||
minHeight={keepInViewport ? Math.min(minHeight, viewport.height) : minHeight}
|
||||
className={`floating-panel ${className || ''}`}
|
||||
enableResizing={enableResizing}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
import { act, render, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import FloatingPanel from '../FloatingPanel';
|
||||
import type { FloatingObstacle, FloatingRect } from '../types';
|
||||
|
||||
const PANEL_WIDTH = 420;
|
||||
const PANEL_HEIGHT = 601;
|
||||
|
||||
function setViewport(width: number, height: number): void {
|
||||
Object.defineProperty(window, 'innerWidth', {
|
||||
configurable: true,
|
||||
value: width,
|
||||
});
|
||||
Object.defineProperty(window, 'innerHeight', {
|
||||
configurable: true,
|
||||
value: height,
|
||||
});
|
||||
}
|
||||
|
||||
// jsdom has no layout, so the box is read back from the styles react-rnd writes.
|
||||
function getPanelBox(): {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
} {
|
||||
const panel = document.querySelector<HTMLElement>('.floating-panel');
|
||||
const [, x, y] =
|
||||
/translate\((-?[\d.]+)px,\s*(-?[\d.]+)px\)/.exec(
|
||||
panel?.style.transform ?? '',
|
||||
) ?? [];
|
||||
return {
|
||||
x: Number(x),
|
||||
y: Number(y),
|
||||
width: parseFloat(panel?.style.width ?? ''),
|
||||
height: parseFloat(panel?.style.height ?? ''),
|
||||
};
|
||||
}
|
||||
|
||||
describe('FloatingPanel', () => {
|
||||
const originalWidth = window.innerWidth;
|
||||
const originalHeight = window.innerHeight;
|
||||
|
||||
beforeEach(() => {
|
||||
jest
|
||||
.spyOn(HTMLElement.prototype, 'offsetWidth', 'get')
|
||||
.mockImplementation(function offsetWidth(this: HTMLElement) {
|
||||
return parseFloat(this.style.width) || 0;
|
||||
});
|
||||
jest
|
||||
.spyOn(HTMLElement.prototype, 'offsetHeight', 'get')
|
||||
.mockImplementation(function offsetHeight(this: HTMLElement) {
|
||||
return parseFloat(this.style.height) || 0;
|
||||
});
|
||||
// react-rnd offsets its position by this box on mount; jsdom's all-zero box doubles it.
|
||||
jest
|
||||
.spyOn(HTMLElement.prototype, 'getBoundingClientRect')
|
||||
.mockImplementation(function getBoundingClientRect(this: HTMLElement) {
|
||||
const [, x = '0', y = '0'] =
|
||||
/translate\((-?[\d.]+)px,\s*(-?[\d.]+)px\)/.exec(this.style.transform) ??
|
||||
[];
|
||||
return new DOMRect(
|
||||
Number(x),
|
||||
Number(y),
|
||||
this.offsetWidth,
|
||||
this.offsetHeight,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
setViewport(originalWidth, originalHeight);
|
||||
});
|
||||
|
||||
it('keeps its header and input on screen when the window shrinks', () => {
|
||||
setViewport(1920, 1080);
|
||||
render(
|
||||
<FloatingPanel
|
||||
isOpen
|
||||
keepInViewport
|
||||
width={PANEL_WIDTH}
|
||||
height={PANEL_HEIGHT}
|
||||
minWidth={380}
|
||||
minHeight={500}
|
||||
defaultPosition={{ x: 1492, y: 447 }}
|
||||
>
|
||||
<div className="floating-panel__drag-handle">
|
||||
<button type="button" data-testid="panel-close">
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
<textarea data-testid="panel-composer" />
|
||||
</FloatingPanel>,
|
||||
);
|
||||
|
||||
setViewport(1280, 450);
|
||||
act(() => {
|
||||
window.dispatchEvent(new Event('resize'));
|
||||
});
|
||||
|
||||
expect(getPanelBox()).toStrictEqual({
|
||||
x: 860,
|
||||
y: 0,
|
||||
width: 420,
|
||||
height: 450,
|
||||
});
|
||||
expect(screen.getByTestId('panel-close')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('panel-composer')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps the grabbed point under the pointer after pushing past an edge', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
setViewport(1280, 800);
|
||||
render(
|
||||
<FloatingPanel
|
||||
isOpen
|
||||
width={PANEL_WIDTH}
|
||||
height={PANEL_HEIGHT}
|
||||
defaultPosition={{ x: 400, y: 100 }}
|
||||
>
|
||||
<div className="floating-panel__drag-handle" data-testid="panel-handle" />
|
||||
</FloatingPanel>,
|
||||
);
|
||||
|
||||
// user-event only sees a move when `x`/`y` change, so they're set alongside `clientX`/`clientY`.
|
||||
await user.pointer([
|
||||
{
|
||||
keys: '[MouseLeft>]',
|
||||
target: screen.getByTestId('panel-handle'),
|
||||
coords: { x: 450, y: 110, clientX: 450, clientY: 110 },
|
||||
},
|
||||
// 60px past the top edge, then back below where the grab started.
|
||||
{ coords: { x: 450, y: -50, clientX: 450, clientY: -50 } },
|
||||
{ coords: { x: 450, y: 160, clientX: 450, clientY: 160 } },
|
||||
{ keys: '[/MouseLeft]' },
|
||||
]);
|
||||
|
||||
expect(getPanelBox()).toStrictEqual({
|
||||
x: 400,
|
||||
y: 150,
|
||||
width: PANEL_WIDTH,
|
||||
height: PANEL_HEIGHT,
|
||||
});
|
||||
});
|
||||
|
||||
describe('avoid', () => {
|
||||
const HOME = { x: 852, y: 167 };
|
||||
const SUPPORT_CHAT: FloatingRect = {
|
||||
x: 882,
|
||||
y: 286,
|
||||
width: 384,
|
||||
height: 478,
|
||||
};
|
||||
// 8px gap left of the support chat: 882 - 8 - 420.
|
||||
const CLEAR_OF_SUPPORT_CHAT = { x: 454, y: 167 };
|
||||
|
||||
function createObstacle(rect: FloatingRect): {
|
||||
obstacle: FloatingObstacle;
|
||||
show: () => void;
|
||||
hide: () => void;
|
||||
} {
|
||||
let isShown = false;
|
||||
const listeners = new Set<() => void>();
|
||||
const setShown = (shown: boolean): void => {
|
||||
isShown = shown;
|
||||
act(() => listeners.forEach((listener) => listener()));
|
||||
};
|
||||
return {
|
||||
obstacle: {
|
||||
getRect: (): FloatingRect | null => (isShown ? rect : null),
|
||||
subscribe: (onChange): (() => void) => {
|
||||
listeners.add(onChange);
|
||||
return (): void => {
|
||||
listeners.delete(onChange);
|
||||
};
|
||||
},
|
||||
},
|
||||
show: (): void => setShown(true),
|
||||
hide: (): void => setShown(false),
|
||||
};
|
||||
}
|
||||
|
||||
function renderPanel(avoid: FloatingObstacle[]): void {
|
||||
render(
|
||||
<FloatingPanel
|
||||
isOpen
|
||||
width={PANEL_WIDTH}
|
||||
height={PANEL_HEIGHT}
|
||||
defaultPosition={HOME}
|
||||
avoid={avoid}
|
||||
>
|
||||
<div className="floating-panel__drag-handle" data-testid="panel-handle" />
|
||||
</FloatingPanel>,
|
||||
);
|
||||
}
|
||||
|
||||
function getPanelPosition(): { x: number; y: number } {
|
||||
const { x, y } = getPanelBox();
|
||||
return { x, y };
|
||||
}
|
||||
|
||||
beforeEach(() => setViewport(1280, 800));
|
||||
|
||||
it('slides left of an obstacle while it shows, and back once it hides', () => {
|
||||
const supportChat = createObstacle(SUPPORT_CHAT);
|
||||
renderPanel([supportChat.obstacle]);
|
||||
|
||||
supportChat.show();
|
||||
|
||||
expect(getPanelPosition()).toStrictEqual(CLEAR_OF_SUPPORT_CHAT);
|
||||
|
||||
supportChat.hide();
|
||||
|
||||
expect(getPanelPosition()).toStrictEqual(HOME);
|
||||
});
|
||||
|
||||
it('stays where the user dragged it while the obstacle showed', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const supportChat = createObstacle(SUPPORT_CHAT);
|
||||
renderPanel([supportChat.obstacle]);
|
||||
supportChat.show();
|
||||
|
||||
// user-event only sees a move when `x`/`y` change, so they're set alongside `clientX`/`clientY`.
|
||||
await user.pointer([
|
||||
{
|
||||
keys: '[MouseLeft>]',
|
||||
target: screen.getByTestId('panel-handle'),
|
||||
coords: { x: 500, y: 200, clientX: 500, clientY: 200 },
|
||||
},
|
||||
{ coords: { x: 346, y: 153, clientX: 346, clientY: 153 } },
|
||||
{ keys: '[/MouseLeft]' },
|
||||
]);
|
||||
supportChat.hide();
|
||||
|
||||
expect(getPanelPosition()).toStrictEqual({ x: 300, y: 120 });
|
||||
});
|
||||
|
||||
it('slides past every obstacle in the way', () => {
|
||||
const supportChat = createObstacle(SUPPORT_CHAT);
|
||||
const widget = createObstacle({ x: 500, y: 200, width: 300, height: 200 });
|
||||
renderPanel([supportChat.obstacle, widget.obstacle]);
|
||||
widget.show();
|
||||
|
||||
supportChat.show();
|
||||
|
||||
// 882 - 8 - 420 = 454 still hits the widget, so 500 - 8 - 420.
|
||||
expect(getPanelPosition()).toStrictEqual({ x: 72, y: 167 });
|
||||
});
|
||||
|
||||
it('slides clear of an obstacle already showing when it opens', () => {
|
||||
const supportChat = createObstacle(SUPPORT_CHAT);
|
||||
supportChat.show();
|
||||
|
||||
renderPanel([supportChat.obstacle]);
|
||||
|
||||
expect(getPanelPosition()).toStrictEqual(CLEAR_OF_SUPPORT_CHAT);
|
||||
});
|
||||
});
|
||||
});
|
||||
17
frontend/src/periscope/components/FloatingPanel/types.ts
Normal file
17
frontend/src/periscope/components/FloatingPanel/types.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
export interface Position {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
export interface FloatingRect extends Position {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** Something on screen the panel slides out of the way of. */
|
||||
export interface FloatingObstacle {
|
||||
/** Viewport box while on screen, null otherwise. */
|
||||
getRect: () => FloatingRect | null;
|
||||
/** Calls `onChange` whenever the box shows, hides or moves; returns the unsubscribe. */
|
||||
subscribe: (onChange: () => void) => () => void;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { RefObject, useEffect } from 'react';
|
||||
import type { Rnd } from 'react-rnd';
|
||||
|
||||
import type { FloatingObstacle, FloatingRect, Position } from './types';
|
||||
import { getPositionClearOf, isAt } from './utils';
|
||||
|
||||
const SLIDING_CLASS = 'floating-panel--sliding';
|
||||
const SLIDE_DURATION_MS = 200;
|
||||
|
||||
/**
|
||||
* Slides the panel clear of `obstacles` while they show, and back once they
|
||||
* hide unless the user has moved it since.
|
||||
*/
|
||||
export function useAvoidObstacles(
|
||||
rndRef: RefObject<Rnd>,
|
||||
obstacles: FloatingObstacle[] | undefined,
|
||||
enabled: boolean,
|
||||
): void {
|
||||
useEffect(() => {
|
||||
if (!enabled || !obstacles?.length) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Where the user left the panel, and where it was slid to from there.
|
||||
let home: Position | null = null;
|
||||
let placed: Position | null = null;
|
||||
let slideTimer: number | undefined;
|
||||
|
||||
const update = (): void => {
|
||||
const rnd = rndRef.current;
|
||||
const element = rnd?.getSelfElement();
|
||||
if (!rnd || !element) {
|
||||
return;
|
||||
}
|
||||
const position = rnd.getDraggablePosition();
|
||||
if (placed && !isAt(position, placed)) {
|
||||
home = null;
|
||||
}
|
||||
const base = home ?? position;
|
||||
const target = getPositionClearOf(
|
||||
{ ...base, width: element.offsetWidth, height: element.offsetHeight },
|
||||
obstacles
|
||||
.map((obstacle) => obstacle.getRect())
|
||||
.filter((rect): rect is FloatingRect => rect !== null),
|
||||
);
|
||||
if (!isAt(position, target)) {
|
||||
element.classList.add(SLIDING_CLASS);
|
||||
rnd.updatePosition(target);
|
||||
window.clearTimeout(slideTimer);
|
||||
slideTimer = window.setTimeout(
|
||||
() => element.classList.remove(SLIDING_CLASS),
|
||||
SLIDE_DURATION_MS,
|
||||
);
|
||||
}
|
||||
const slid = !isAt(base, target);
|
||||
home = slid ? base : null;
|
||||
placed = slid ? target : null;
|
||||
};
|
||||
|
||||
const unsubscribes = obstacles.map((obstacle) => obstacle.subscribe(update));
|
||||
update();
|
||||
|
||||
return (): void => unsubscribes.forEach((unsubscribe) => unsubscribe());
|
||||
}, [enabled, obstacles, rndRef]);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { RefObject, useEffect, useState } from 'react';
|
||||
import type { Rnd } from 'react-rnd';
|
||||
|
||||
interface ViewportSize {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
function readViewport(): ViewportSize {
|
||||
return { width: window.innerWidth, height: window.innerHeight };
|
||||
}
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.min(Math.max(value, min), max);
|
||||
}
|
||||
|
||||
/** Moves and shrinks the panel back into view whenever the window resizes; a panel that still fits stays put. */
|
||||
export function useKeepInViewport(
|
||||
rndRef: RefObject<Rnd>,
|
||||
enabled: boolean,
|
||||
): ViewportSize {
|
||||
const [viewport, setViewport] = useState(readViewport);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
return undefined;
|
||||
}
|
||||
const onResize = (): void => setViewport(readViewport());
|
||||
window.addEventListener('resize', onResize);
|
||||
return (): void => window.removeEventListener('resize', onResize);
|
||||
}, [enabled]);
|
||||
|
||||
useEffect(() => {
|
||||
const rnd = rndRef.current;
|
||||
const element = rnd?.getSelfElement();
|
||||
if (!enabled || !rnd || !element) {
|
||||
return;
|
||||
}
|
||||
const width = Math.min(element.offsetWidth, viewport.width);
|
||||
const height = Math.min(element.offsetHeight, viewport.height);
|
||||
if (width !== element.offsetWidth || height !== element.offsetHeight) {
|
||||
rnd.updateSize({ width, height });
|
||||
}
|
||||
const { x, y } = rnd.getDraggablePosition();
|
||||
const fitted = {
|
||||
x: clamp(x, 0, viewport.width - width),
|
||||
y: clamp(y, 0, viewport.height - height),
|
||||
};
|
||||
if (fitted.x !== x || fitted.y !== y) {
|
||||
rnd.updatePosition(fitted);
|
||||
}
|
||||
}, [enabled, rndRef, viewport]);
|
||||
|
||||
return viewport;
|
||||
}
|
||||
36
frontend/src/periscope/components/FloatingPanel/utils.ts
Normal file
36
frontend/src/periscope/components/FloatingPanel/utils.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import type { FloatingRect, Position } from './types';
|
||||
|
||||
const GAP = 8;
|
||||
|
||||
function overlaps(a: FloatingRect, b: FloatingRect): boolean {
|
||||
return (
|
||||
a.x < b.x + b.width &&
|
||||
b.x < a.x + a.width &&
|
||||
a.y < b.y + b.height &&
|
||||
b.y < a.y + a.height
|
||||
);
|
||||
}
|
||||
|
||||
export function isAt(a: Position, b: Position): boolean {
|
||||
return Math.abs(a.x - b.x) < 1 && Math.abs(a.y - b.y) < 1;
|
||||
}
|
||||
|
||||
/** Slides the panel left past every obstacle it overlaps, `GAP` clear of each. */
|
||||
export function getPositionClearOf(
|
||||
panel: FloatingRect,
|
||||
obstacles: FloatingRect[],
|
||||
): Position {
|
||||
let { x } = panel;
|
||||
// Moving only left, each obstacle is passed at most once.
|
||||
for (let i = 0; i < obstacles.length; i += 1) {
|
||||
const hit = obstacles.find((obstacle) => overlaps({ ...panel, x }, obstacle));
|
||||
if (!hit) {
|
||||
break;
|
||||
}
|
||||
x = hit.x - GAP - panel.width;
|
||||
}
|
||||
if (x === panel.x) {
|
||||
return { x, y: panel.y };
|
||||
}
|
||||
return { x: Math.max(GAP, x), y: panel.y };
|
||||
}
|
||||
@@ -72,6 +72,25 @@ export const NozAwaitingYou: Story = {
|
||||
args: { noz: true, nozAwaiting: 2, support: 'pylon' },
|
||||
};
|
||||
|
||||
/** The Noz chat opened from Ask Noz, floating above the strip; its header drags it. */
|
||||
export const NozPanel: Story = {
|
||||
args: { noz: true, support: 'pylon' },
|
||||
play: async ({ args }): Promise<void> => {
|
||||
// Ask Noz is not rendered with Noz off, so there is no panel to open.
|
||||
if (!args.noz) {
|
||||
return;
|
||||
}
|
||||
await userEvent.click(
|
||||
await screen.findByTestId(
|
||||
'bottom-strip-ask-noz-button',
|
||||
undefined,
|
||||
untilLoaded,
|
||||
),
|
||||
);
|
||||
await screen.findByTestId('ai-assistant-panel-close');
|
||||
},
|
||||
};
|
||||
|
||||
/** Every tooltip the strip carries, held open. */
|
||||
export const Tooltips: Story = {
|
||||
args: { noz: true, support: 'pylon', tooltipsOpen: true },
|
||||
|
||||
@@ -3,6 +3,7 @@ import { AI_API_PATH } from 'api/AIAPIInstance';
|
||||
import type { ThreadListResponse } from 'api/ai-assistant/chat';
|
||||
import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';
|
||||
import type { ConversationStreamState } from 'container/AIAssistant/types';
|
||||
import { chipsResponse } from 'pages/AIAssistantPage/stories/__story_mockdata__/aiAssistant';
|
||||
|
||||
import { countControl, toggleControl } from '../controls/controls';
|
||||
import { defineStoryMocks } from '../controls/defineStoryMocks';
|
||||
@@ -57,6 +58,10 @@ export const nozMocks = defineStoryMocks({
|
||||
`${nozGlobalConfigResponse.data.ai_assistant_url}${AI_API_PATH}/threads`,
|
||||
(_req, res, ctx) => res(ctx.status(200), ctx.json(noThreads)),
|
||||
),
|
||||
rest.get(
|
||||
`${nozGlobalConfigResponse.data.ai_assistant_url}${AI_API_PATH}/empty-state/chips`,
|
||||
(_req, res, ctx) => res(ctx.status(200), ctx.json(chipsResponse())),
|
||||
),
|
||||
]
|
||||
: [],
|
||||
effect: ({ nozAwaiting }) => {
|
||||
@@ -72,6 +77,9 @@ export const nozMocks = defineStoryMocks({
|
||||
for (let index = 0; index < nozAwaiting; index += 1) {
|
||||
state.streams[`${AWAITING_PREFIX}${index}`] = awaitingStream();
|
||||
}
|
||||
|
||||
// Persisted, so a panel one story opened would still be open in the next.
|
||||
state.isDrawerOpen = false;
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
@@ -811,14 +811,6 @@ notifications - 2050
|
||||
right: 45px !important;
|
||||
}
|
||||
|
||||
body.ai-assistant-panel-open {
|
||||
.PylonChat-bubbleFrameContainer,
|
||||
.PylonChat-chatWindowFrameContainer {
|
||||
right: calc(var(--ai-assistant-panel-width, 380px) + 8px) !important;
|
||||
left: auto !important;
|
||||
}
|
||||
}
|
||||
|
||||
body.bottom-strip-on {
|
||||
// Pylon re-shows its own launcher when the chat window opens, so
|
||||
// `hideChatBubble` cannot hold it down.
|
||||
|
||||
@@ -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.
|
||||
|
||||
34
frontend/src/tests/userEventWithDefaults.test.tsx
Normal file
34
frontend/src/tests/userEventWithDefaults.test.tsx
Normal 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);
|
||||
});
|
||||
});
|
||||
60
frontend/src/tests/userEventWithDefaults.ts
Normal file
60
frontend/src/tests/userEventWithDefaults.ts
Normal 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;
|
||||
@@ -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),
|
||||
|
||||
25
frontend/src/utils/prometheusDuration.ts
Normal file
25
frontend/src/utils/prometheusDuration.ts
Normal 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;
|
||||
}
|
||||
@@ -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."`
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user