Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

test(dashboards): panel stories with play assertions for every kind (#13244)

Abhi kumar450ceed5fd1a
diff --git a/frontend/.storybook/preview.tsx b/frontend/.storybook/preview.tsx
index 6196207cfc..2db0e6deca 100644
--- a/frontend/.storybook/preview.tsx
+++ b/frontend/.storybook/preview.tsx
@@ -127,6 +127,7 @@ const preview: Preview = {
'Detail',
[
'Overview',
+ 'Panels',
'Settings',
'Variables',
'New Variable',
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/ConfigPane/__tests__/ConfigPane.test.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/ConfigPane/__tests__/ConfigPane.test.tsx
index d4a7484958..499296ff2f 100644
--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/ConfigPane/__tests__/ConfigPane.test.tsx
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/ConfigPane/__tests__/ConfigPane.test.tsx
@@ -47,6 +47,75 @@ function spec(unit?: string): DashboardtypesPanelSpecDTO {
} as unknown as DashboardtypesPanelSpecDTO;
}
+function kindSpec(kind: string): DashboardtypesPanelSpecDTO {
+ return {
+ display: { name: 'Panel' },
+ plugin: { kind, spec: {} },
+ queries: [],
+ } as unknown as DashboardtypesPanelSpecDTO;
+}
+
+// In render order. Text's header toggle sits inline with the title, not in a section.
+const SECTIONS_BY_KIND: [string, string[]][] = [
+ [
+ 'signoz/TimeSeriesPanel',
+ [
+ 'visualization',
+ 'formatting-&-units',
+ 'axes',
+ 'legend',
+ 'chart-appearance',
+ 'thresholds',
+ 'context-links',
+ ],
+ ],
+ [
+ 'signoz/BarChartPanel',
+ [
+ 'visualization',
+ 'formatting-&-units',
+ 'axes',
+ 'legend',
+ 'thresholds',
+ 'context-links',
+ ],
+ ],
+ [
+ 'signoz/AreaChartPanel',
+ [
+ 'visualization',
+ 'formatting-&-units',
+ 'axes',
+ 'legend',
+ 'chart-appearance',
+ 'thresholds',
+ 'context-links',
+ ],
+ ],
+ [
+ 'signoz/NumberPanel',
+ ['visualization', 'formatting-&-units', 'thresholds', 'context-links'],
+ ],
+ [
+ 'signoz/PieChartPanel',
+ ['visualization', 'formatting-&-units', 'legend', 'context-links'],
+ ],
+ [
+ 'signoz/TablePanel',
+ ['visualization', 'formatting-&-units', 'thresholds', 'context-links'],
+ ],
+ [
+ 'signoz/HistogramPanel',
+ ['visualization', 'legend', 'buckets', 'context-links'],
+ ],
+ [
+ 'signoz/HeatmapPanel',
+ ['visualization', 'chart-appearance', 'formatting-&-units', 'axes', 'legend'],
+ ],
+ ['signoz/ListPanel', ['visualization']],
+ ['signoz/TextPanel', ['visualization', 'panel-appearance']],
+];
+
function renderConfigPane(
overrides: Partial<React.ComponentProps<typeof ConfigPane>> = {},
): React.ComponentProps<typeof ConfigPane> {
@@ -156,4 +225,17 @@ describe('ConfigPane', () => {
screen.queryByTestId('panel-editor-v2-create-alert'),
).not.toBeInTheDocument();
});
+
+ it.each(SECTIONS_BY_KIND)(
+ 'renders the config sections of %s',
+ (kind, expected) => {
+ renderConfigPane({ spec: kindSpec(kind), savedSpec: kindSpec(kind) });
+
+ expect(
+ screen
+ .queryAllByTestId(/^config-section-/)
+ .map((section) => section.getAttribute('data-testid')),
+ ).toStrictEqual(expected.map((title) => `config-section-${title}`));
+ },
+ );
});
diff --git a/frontend/src/pages/DashboardPage/stories/DashboardPage.stories.mocks.tsx b/frontend/src/pages/DashboardPage/stories/DashboardPage.stories.mocks.tsx
index 256a42f7b0..38c4a6942f 100644
--- a/frontend/src/pages/DashboardPage/stories/DashboardPage.stories.mocks.tsx
+++ b/frontend/src/pages/DashboardPage/stories/DashboardPage.stories.mocks.tsx
@@ -35,6 +35,7 @@ import {
type DashboardArgs,
type VariableKind,
} from './__story_mockdata__/dashboard';
+import { publicDashboardMeta } from './__story_mockdata__/publicDashboard';
import {
API_RESULTS,
settle,
@@ -45,6 +46,7 @@ import {
emptyPanelResponse,
VARIABLE_ATTRIBUTES,
panelResponse,
+ partialDataWarning,
serviceVariableValues,
} from './__story_mockdata__/panelData';
import {
@@ -87,14 +89,8 @@ const VARIABLE_QUERY_ERROR = {
"Code: 62. DB::Exception: Syntax error: failed at position 58 ('$environment'). (SYNTAX_ERROR)",
};
-const publicMeta = (): GetPublicDashboard200 => ({
- status: 'success',
- data: {
- timeRangeEnabled: true,
- defaultTimeRange: '30m',
- publicPath: `/public/dashboard/${STORY_DASHBOARD_ID}`,
- },
-});
+const publicMeta = (): GetPublicDashboard200 =>
+ publicDashboardMeta(STORY_DASHBOARD_ID);
const NOT_PUBLIC = {
status: 'error',
@@ -395,17 +391,7 @@ export const warnedPanelQueryHandler = rest.post(
ctx.status(200),
ctx.json(
queryRangeV5ScalarResponse(0.94, 'A', {
- warning: {
- code: 'partial_data',
- message: `Some series for ${TOOLTIP_WARNED_METRIC} were dropped: the metric changed temporality partway through the selected window.`,
- url: 'https://signoz.io/docs/metrics-management/types-and-aggregation/',
- warnings: [
- {
- message:
- 'Narrow the window to a period with one temporality, or re-record the metric as a delta.',
- },
- ],
- },
+ warning: partialDataWarning(TOOLTIP_WARNED_METRIC),
}),
),
);
diff --git a/frontend/src/pages/DashboardPage/stories/__story_mockdata__/dashboard.ts b/frontend/src/pages/DashboardPage/stories/__story_mockdata__/dashboard.ts
index 643366b21e..e44d37248e 100644
--- a/frontend/src/pages/DashboardPage/stories/__story_mockdata__/dashboard.ts
+++ b/frontend/src/pages/DashboardPage/stories/__story_mockdata__/dashboard.ts
@@ -29,8 +29,6 @@ import {
type DashboardtypesDashboardSpecDTOPanels,
type DashboardtypesLayoutDTO,
type DashboardtypesPanelDTO,
- type DashboardtypesGettableDashboardV2DTO,
- type DashboardtypesJSONPatchOperationDTO,
type DashboardtypesQueryDTO,
type DashboardtypesVariableDTO,
type GetDashboardV2200,
@@ -38,7 +36,7 @@ import {
type Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTO as MetricBuilderQuery,
} from 'api/generated/services/sigNoz.schemas';
-import { applyJsonPatch } from '../../DashboardContainer/optimistic/applyJsonPatch';
+import { documentStore } from './documentStore';
export const STORY_DASHBOARD_ID = 'storybook-dashboard-1';
@@ -444,35 +442,13 @@ export const dashboardResponse = ({
};
};
-/**
- * The document the page is editing. Every spec edit (a panel moved, a section
- * renamed, a variable added) travels as a JSON Patch whose response replaces
- * the cache, so the story keeps the document where the handler can apply the ops
- * to it. Reseeded whenever a control changes, which is also when the story
- * remounts.
- */
-let document: DashboardtypesGettableDashboardV2DTO | undefined;
-
-export const seedDashboardDocument = (args: DashboardArgs): void => {
- document = dashboardResponse(args).data;
-};
-
-const envelope = (
- data: DashboardtypesGettableDashboardV2DTO,
-): GetDashboardV2200 => ({ status: 'success', data });
+const store = documentStore(dashboardResponse);
-export const currentDashboardDocument = (
- args: DashboardArgs,
-): GetDashboardV2200 => envelope(document ?? dashboardResponse(args).data);
+export const seedDashboardDocument = store.seed;
-export const patchDashboardDocument = (
- args: DashboardArgs,
- ops: DashboardtypesJSONPatchOperationDTO[],
-): GetDashboardV2200 => {
- document = applyJsonPatch(document ?? dashboardResponse(args).data, ops);
+export const currentDashboardDocument = store.current;
- return envelope(document);
-};
+export const patchDashboardDocument = store.patch;
export const cyclicVariablesDashboardResponse = (): GetDashboardV2200 => {
const response = dashboardResponse({
diff --git a/frontend/src/pages/DashboardPage/stories/__story_mockdata__/documentStore.ts b/frontend/src/pages/DashboardPage/stories/__story_mockdata__/documentStore.ts
new file mode 100644
index 0000000000..0156bc90f3
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/stories/__story_mockdata__/documentStore.ts
@@ -0,0 +1,49 @@
+/**
+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.
+ * Do not hand-edit: regenerate instead.
+ */
+
+import type {
+ DashboardtypesGettableDashboardV2DTO,
+ DashboardtypesJSONPatchOperationDTO,
+ GetDashboardV2200,
+} from 'api/generated/services/sigNoz.schemas';
+
+import { applyJsonPatch } from '../../DashboardContainer/optimistic/applyJsonPatch';
+
+export interface DocumentStore<TArgs> {
+ seed: (args: TArgs) => void;
+ current: (args: TArgs) => GetDashboardV2200;
+ patch: (
+ args: TArgs,
+ ops: DashboardtypesJSONPatchOperationDTO[],
+ ) => GetDashboardV2200;
+}
+
+const envelope = (
+ data: DashboardtypesGettableDashboardV2DTO,
+): GetDashboardV2200 => ({ status: 'success', data });
+
+/**
+ * The document a story is editing. Every spec edit travels as a JSON Patch whose
+ * response replaces the cache, so the document is kept where the handler can
+ * apply the ops to it. Reseeded whenever a control changes, which is also when
+ * the story remounts.
+ */
+export const documentStore = <TArgs>(
+ build: (args: TArgs) => GetDashboardV2200,
+): DocumentStore<TArgs> => {
+ let document: DashboardtypesGettableDashboardV2DTO | undefined;
+
+ return {
+ seed: (args): void => {
+ document = build(args).data;
+ },
+ current: (args): GetDashboardV2200 => envelope(document ?? build(args).data),
+ patch: (args, ops): GetDashboardV2200 => {
+ document = applyJsonPatch(document ?? build(args).data, ops);
+
+ return envelope(document);
+ },
+ };
+};
diff --git a/frontend/src/pages/DashboardPage/stories/__story_mockdata__/panelData.ts b/frontend/src/pages/DashboardPage/stories/__story_mockdata__/panelData.ts
index 71bb19a4fb..09a003976b 100644
--- a/frontend/src/pages/DashboardPage/stories/__story_mockdata__/panelData.ts
+++ b/frontend/src/pages/DashboardPage/stories/__story_mockdata__/panelData.ts
@@ -3,6 +3,7 @@
* Do not hand-edit: regenerate instead.
*/
+import type { Warning } from 'types/api';
import type { MetricRangePayloadV5, RawRow } from 'types/api/v5/queryRange';
import {
@@ -36,6 +37,19 @@ const LOG_LEVELS = ['INFO', 'WARN', 'ERROR'] as const;
const pick = <T>(values: readonly T[], index: number): T =>
values[index % values.length];
+/** A query answered with data, but some series dropped along the way. */
+export const partialDataWarning = (metric?: string): Warning => ({
+ code: 'partial_data',
+ message: `Some series${metric ? ' for '.concat(metric) : ''} were dropped: the metric changed temporality partway through the selected window.`,
+ url: 'https://signoz.io/docs/metrics-management/types-and-aggregation/',
+ warnings: [
+ {
+ message:
+ 'Narrow the window to a period with one temporality, or re-record the metric as a delta.',
+ },
+ ],
+});
+
export interface PanelWindow {
start: number;
end: number;
diff --git a/frontend/src/pages/DashboardPage/stories/__story_mockdata__/publicDashboard.ts b/frontend/src/pages/DashboardPage/stories/__story_mockdata__/publicDashboard.ts
new file mode 100644
index 0000000000..e76cf5c2c5
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/stories/__story_mockdata__/publicDashboard.ts
@@ -0,0 +1,18 @@
+/**
+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.
+ * Do not hand-edit: regenerate instead.
+ */
+
+import type { GetPublicDashboard200 } from 'api/generated/services/sigNoz.schemas';
+
+/** The public link the dashboard header reads on every load. */
+export const publicDashboardMeta = (
+ dashboardId: string,
+): GetPublicDashboard200 => ({
+ status: 'success',
+ data: {
+ timeRangeEnabled: true,
+ defaultTimeRange: '30m',
+ publicPath: `/public/dashboard/${dashboardId}`,
+ },
+});
diff --git a/frontend/src/pages/DashboardPage/stories/panels/Panels.stories.mocks.tsx b/frontend/src/pages/DashboardPage/stories/panels/Panels.stories.mocks.tsx
new file mode 100644
index 0000000000..28312b8f40
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/stories/panels/Panels.stories.mocks.tsx
@@ -0,0 +1,276 @@
+/**
+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.
+ * Do not hand-edit: regenerate instead.
+ */
+
+import { rest } from 'msw';
+import { generatePath } from 'react-router-dom';
+import ROUTES from 'constants/routes';
+import {
+ DashboardtypesHeatmapPaletteDTO as HeatmapPalette,
+ DashboardtypesHeatmapYScaleDTO as HeatmapYScale,
+ DashboardtypesLegendPositionDTO as LegendPosition,
+ DashboardtypesLineStyleDTO as LineStyle,
+ DashboardtypesStackModeDTO as StackMode,
+ DashboardtypesTextAlignDTO as TextAlign,
+} from 'api/generated/services/sigNoz.schemas';
+import { useDashboardPreferencesStore } from 'hooks/dashboard/useDashboardPreference';
+
+import {
+ choiceControl,
+ countControl,
+ toggleControl,
+} from '@/storybook/controls/controls';
+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
+
+import { publicDashboardMeta } from '../__story_mockdata__/publicDashboard';
+
+import {
+ BUCKET_WIDTHS,
+ GAPS,
+ HEATMAP_COUNT_RANGES,
+ HEATMAP_FIXED_COUNTS,
+ HEATMAP_PALETTES,
+ HEATMAP_Y_SCALES,
+ LEGEND_POSITIONS,
+ LINE_STYLES,
+ MAX_SERIES,
+ PANEL_KINDS,
+ PANEL_RESULTS,
+ PANELS_DASHBOARD_ID,
+ SPAN_GAPS,
+ STACK_MODES,
+ TEXT_ALIGNS,
+ TEXT_SAMPLES,
+ UNITS,
+ Y_SCALES,
+} from './__story_mockdata__/constants';
+import {
+ currentPanelsDocument,
+ patchPanelsDocument,
+ seedPanelsDocument,
+} from './__story_mockdata__/panelDocuments';
+import {
+ panelQueryResponse,
+ recordPanelRequest,
+ resetPanelRequests,
+} from './__story_mockdata__/panelResponses';
+import type {
+ BucketWidth,
+ Gaps,
+ HeatmapCountRange,
+ PanelArgs,
+ PanelKind,
+ PanelResult,
+ PanelUnit,
+ SpanGaps,
+ TextSample,
+ YScale,
+} from './__story_mockdata__/types';
+
+const PANEL = 'Panels · panel';
+const DATA = 'Panels · data';
+
+interface QueryRangeBody {
+ start: number;
+ end: number;
+ compositeQuery?: {
+ queries?: { spec?: { offset?: number; limit?: number } }[];
+ };
+}
+
+export const panelsMocks = defineStoryMocks({
+ controls: {
+ kind: choiceControl<PanelKind>('Panel kind', {
+ group: PANEL,
+ description: 'The one panel the dashboard holds.',
+ options: PANEL_KINDS,
+ value: 'TimeSeries',
+ }),
+ legend: choiceControl<LegendPosition>('Legend', {
+ group: PANEL,
+ description: 'Legend position on the charts and the pie.',
+ options: LEGEND_POSITIONS,
+ value: LegendPosition.bottom,
+ }),
+ thresholds: toggleControl('Thresholds', {
+ group: PANEL,
+ description:
+ 'A dashed labelled line on Time Series, Bar and Area; a background colour on Number when the value is above it; a filled `A` cell on Table rows above it, never a `B` cell. Other kinds have none.',
+ value: false,
+ }),
+ unit: choiceControl<PanelUnit>('Unit', {
+ group: PANEL,
+ description:
+ 'Formatting unit: the y axis and tooltip of the charts, the Number value, the pie total, the Table value column.',
+ options: UNITS,
+ value: 'ms',
+ }),
+ stack: choiceControl<StackMode>('Stack', {
+ group: PANEL,
+ description:
+ 'Area stacks `normal` or to `percent`; Bar stacks on anything but `none`. No effect on other kinds.',
+ options: STACK_MODES,
+ value: StackMode.none,
+ }),
+ palette: choiceControl<HeatmapPalette>('Heatmap palette', {
+ group: PANEL,
+ options: HEATMAP_PALETTES,
+ value: HeatmapPalette.lava,
+ }),
+ heatmapScale: choiceControl<HeatmapYScale>('Heatmap y scale', {
+ group: PANEL,
+ description:
+ 'Row layout of the bucket axis. The buckets are linear, so `auto` lays them out linearly.',
+ options: HEATMAP_Y_SCALES,
+ value: HeatmapYScale.auto,
+ }),
+ heatmapCounts: choiceControl<HeatmapCountRange>('Heatmap count range', {
+ group: PANEL,
+ description: `The colour bar's bounds: from 0 to the busiest cell, or fixed at ${HEATMAP_FIXED_COUNTS.min}–${HEATMAP_FIXED_COUNTS.max}.`,
+ options: HEATMAP_COUNT_RANGES,
+ value: 'auto',
+ }),
+ bucketWidth: choiceControl<BucketWidth>('Histogram bucket width', {
+ group: PANEL,
+ description:
+ 'Width of each Histogram bin, in the series unit; `auto` picks one from the value range.',
+ options: BUCKET_WIDTHS,
+ value: 'auto',
+ }),
+ textSample: choiceControl<TextSample>('Text body', {
+ group: PANEL,
+ description:
+ 'The Text panel’s Markdown: a runbook with a heading, list, link and code block, a one-line note, or nothing written yet.',
+ options: TEXT_SAMPLES,
+ value: 'runbook',
+ }),
+ textAlign: choiceControl<TextAlign>('Text alignment', {
+ group: PANEL,
+ options: TEXT_ALIGNS,
+ value: TextAlign.left,
+ }),
+ hideHeader: toggleControl('Hide text header', {
+ group: PANEL,
+ description:
+ 'The Text panel without its title strip; drag and actions move to hover.',
+ value: false,
+ }),
+ yScale: choiceControl<YScale>('Y scale', {
+ group: PANEL,
+ description: 'The y axis of Time Series, Bar and Area.',
+ options: Y_SCALES,
+ value: 'linear',
+ }),
+ lineStyle: choiceControl<LineStyle>('Line style', {
+ group: PANEL,
+ description: 'Time Series and Area lines.',
+ options: LINE_STYLES,
+ value: LineStyle.solid,
+ }),
+ showPoints: toggleControl('Show points', {
+ group: PANEL,
+ description: 'A marker on every Time Series and Area sample.',
+ value: false,
+ }),
+ spanGaps: choiceControl<SpanGaps>('Span gaps', {
+ group: PANEL,
+ description:
+ 'Time Series and Area: bridge every gap, or break the line across gaps of 10m or more. Visible with Gaps on `hole`.',
+ options: SPAN_GAPS,
+ value: 'bridge',
+ }),
+ columnUnits: toggleControl('Table column unit', {
+ group: PANEL,
+ description: 'Formats the Table value column in the Unit above.',
+ value: false,
+ }),
+ result: choiceControl<PanelResult>('Query result', {
+ group: DATA,
+ description:
+ 'What `query_range` answers with: data, a successful empty result, or data with a warning in the panel header. Loading and failed come from the Data control.',
+ options: PANEL_RESULTS,
+ value: 'data',
+ }),
+ series: countControl('Series', {
+ group: DATA,
+ description:
+ 'Series on the charts, groups on the heatmap, slices on the pie, rows on the table.',
+ value: 4,
+ max: MAX_SERIES,
+ }),
+ gaps: choiceControl<Gaps>('Gaps', {
+ group: DATA,
+ description:
+ '`hole` drops 12 of the 30 samples from the middle of every time series, a 13m gap.',
+ options: GAPS,
+ value: 'none',
+ }),
+ listRows: countControl('List rows', {
+ group: DATA,
+ description:
+ 'Log rows the List panel can page through, 25 a page; more than 25 enables Next.',
+ value: 20,
+ max: 80,
+ }),
+ },
+ handlers: (values, response) => {
+ const args: PanelArgs = values;
+
+ return [
+ // The document lays the panel out before it queries, so it answers on its
+ // own: the Data control holds the panel, not the dashboard, in loading
+ // and failed.
+ rest.get('http://localhost/api/v2/dashboards/:id', (_req, res, ctx) =>
+ res(ctx.status(200), ctx.json(currentPanelsDocument(args))),
+ ),
+
+ rest.patch('http://localhost/api/v2/dashboards/:id', async (req, res, ctx) =>
+ res(
+ ctx.status(200),
+ ctx.json(
+ patchPanelsDocument(
+ args,
+ (await req.json()) as Parameters<typeof patchPanelsDocument>[1],
+ ),
+ ),
+ ),
+ ),
+
+ rest.get('http://localhost/api/v1/dashboards/:id/public', (_req, res, ctx) =>
+ res(ctx.status(200), ctx.json(publicDashboardMeta(PANELS_DASHBOARD_ID))),
+ ),
+
+ rest.post(
+ 'http://localhost/api/v5/query_range',
+ response.json(async (req) => {
+ const body = (await req.json()) as QueryRangeBody;
+ const spec = body.compositeQuery?.queries?.[0]?.spec;
+ const request = {
+ window: { start: body.start, end: body.end },
+ offset: spec?.offset ?? 0,
+ limit: spec?.limit ?? values.listRows,
+ };
+ recordPanelRequest(request);
+
+ return panelQueryResponse({
+ ...request,
+ kind: values.kind,
+ result: values.result,
+ series: values.series,
+ listRows: values.listRows,
+ gaps: values.gaps,
+ });
+ }),
+ ),
+ ];
+ },
+ config: () => ({
+ route: generatePath(ROUTES.DASHBOARD, { dashboardId: PANELS_DASHBOARD_ID }),
+ }),
+ effect: (values) => {
+ seedPanelsDocument(values);
+ resetPanelRequests();
+ useDashboardPreferencesStore.setState({ preferences: {} });
+ },
+});
diff --git a/frontend/src/pages/DashboardPage/stories/panels/Panels.stories.tsx b/frontend/src/pages/DashboardPage/stories/panels/Panels.stories.tsx
new file mode 100644
index 0000000000..dc61a76584
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/stories/panels/Panels.stories.tsx
@@ -0,0 +1,238 @@
+import type { ComponentType } from 'react';
+import type { Meta, StoryObj } from '@storybook/react-vite';
+import { Route } from 'react-router-dom';
+import {
+ DashboardtypesHeatmapYScaleDTO as HeatmapYScale,
+ DashboardtypesLegendPositionDTO as LegendPosition,
+ DashboardtypesLineStyleDTO as LineStyleDTO,
+ DashboardtypesStackModeDTO as StackMode,
+} from 'api/generated/services/sigNoz.schemas';
+import ROUTES from 'constants/routes';
+
+import { storyMocks } from '@/storybook/controls/defineStoryMocks';
+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
+
+import DashboardPage from '../../DashboardPage';
+
+import { panelsMocks } from './Panels.stories.mocks';
+import { expectPanel } from './panelPlay/expectPanel';
+import { filterLegend, searchTable } from './panelPlay/interactions';
+import { walkListPages } from './panelPlay/list';
+
+type PanelsArgs = PageStoryArgs<typeof panelsMocks>;
+
+const pageStory = storyMocks(panelsMocks, { layout: 'app' });
+
+/**
+ * A dashboard holding one panel, of whichever kind the Panel kind control
+ * picks, drawn from `query_range` (Text renders its own Markdown and queries
+ * nothing). Each story asserts what the kind draws: the chart's series, bands and
+ * threshold line, the pie's slices, the number's colour, the table's and list's
+ * rows.
+ *
+ * Route: `/dashboard/:dashboardId`.
+ */
+const meta = {
+ title: 'Pages/Dashboards/Detail/Panels',
+ tags: ['play'],
+ // The page is wrapped in `withAuthZPage`, which types its props as an index
+ // signature; the story's args are what the controls resolve to.
+ component: DashboardPage as ComponentType<PanelsArgs>,
+ // The page reads the dashboard id out of the pathname.
+ render: (): JSX.Element => (
+ <Route path={ROUTES.DASHBOARD} component={DashboardPage} />
+ ),
+ ...pageStory,
+ parameters: { ...pageStory.parameters },
+} satisfies Meta<PanelsArgs>;
+
+export default meta;
+
+type Story = StoryObj<PanelsArgs>;
+
+const play: Story['play'] = async ({ canvasElement, args }) => {
+ await expectPanel(canvasElement, args);
+};
+
+/** A time series panel: p99 latency, one line per service, with a bottom legend. */
+export const Default: Story = { play };
+
+/** One bar series per service over time, side by side. */
+export const Bar: Story = {
+ args: { kind: 'Bar' },
+ play,
+};
+
+/** The services' bars stacked on one another at every moment. */
+export const BarStacked: Story = {
+ args: { kind: 'Bar', stack: StackMode.normal },
+ play,
+};
+
+/** The services as filled areas, drawn independently. */
+export const Area: Story = {
+ args: { kind: 'Area' },
+ play,
+};
+
+/** The services' areas stacked on one another, each band filling to the one below. */
+export const AreaStacked: Story = {
+ args: { kind: 'Area', stack: StackMode.normal },
+ play,
+};
+
+/** The stacked areas rescaled so every moment sums to 100%, each band its service's share. */
+export const AreaPercent: Story = {
+ args: { kind: 'Area', stack: StackMode.percent },
+ play,
+};
+
+/** How the latency values distribute across buckets, one bar set per service. */
+export const Histogram: Story = {
+ args: { kind: 'Histogram' },
+ play,
+};
+
+/** The histogram binned 50 apart, every bin starting on a multiple of 50. */
+export const HistogramBucketWidth: Story = {
+ args: { kind: 'Histogram', bucketWidth: '50' },
+ play,
+};
+
+/**
+ * Bucket counts over time on a linear bucket axis, with the count colour bar
+ * under the grid.
+ */
+export const Heatmap: Story = {
+ args: { kind: 'Heatmap' },
+ play,
+};
+
+/** The heatmap's bucket rows laid out on a log scale. */
+export const HeatmapLog: Story = {
+ args: { kind: 'Heatmap', heatmapScale: HeatmapYScale.log },
+ play,
+};
+
+/** The heatmap's colour bar pinned to a fixed 5–250 count range. */
+export const HeatmapCountRange: Story = {
+ args: { kind: 'Heatmap', heatmapCounts: 'fixed' },
+ play,
+};
+
+/** Each service's share of traffic as a donut, with the total in the middle. */
+export const Pie: Story = {
+ args: { kind: 'Pie' },
+ play,
+};
+
+/**
+ * A single p99 latency value with its unit, filled with the threshold colour
+ * because it is above the threshold.
+ */
+export const Number: Story = {
+ args: { kind: 'Number', thresholds: true },
+ play,
+};
+
+/** The value's query matched nothing, which the Number panel draws as its own no-data state. */
+export const NumberNoData: Story = {
+ args: { kind: 'Number', result: 'empty' },
+ play,
+};
+
+/**
+ * One row per service with its calls (`A`) and errors (`B`); only the `A` cells
+ * above the threshold are filled with its colour, though `B` crosses it too.
+ */
+export const Table: Story = {
+ args: { kind: 'Table', thresholds: true, columnUnits: true },
+ play,
+};
+
+/**
+ * The table's header search, opened and narrowed to one service, then cleared
+ * back to every row.
+ */
+export const TableSearch: Story = {
+ args: { kind: 'Table' },
+ play: async ({ canvasElement, args }): Promise<void> => {
+ await expectPanel(canvasElement, args);
+ await searchTable(canvasElement, args);
+ },
+};
+
+/** The latest log lines, newest first, on a single page. */
+export const List: Story = {
+ args: { kind: 'List' },
+ play,
+};
+
+/**
+ * Logs spanning three pages, 25 a request: Next walks to the second and then
+ * the last, shorter page, where Next turns off.
+ */
+export const ListPaginated: Story = {
+ args: { kind: 'List', listRows: 60 },
+ play: async ({ canvasElement, args }): Promise<void> => {
+ await expectPanel(canvasElement, args);
+ await walkListPages(canvasElement, args);
+ },
+};
+
+/** A Markdown runbook: heading, list, link and code block. */
+export const Text: Story = {
+ args: { kind: 'Text' },
+ play,
+};
+
+/** The time series on a logarithmic y axis. */
+export const LogScale: Story = {
+ args: { yScale: 'log' },
+ play,
+};
+
+/** Dashed lines with a marker on every sample. */
+export const LineStyle: Story = {
+ args: { lineStyle: LineStyleDTO.dashed, showPoints: true },
+ play,
+};
+
+/**
+ * A 13m hole in every series, broken rather than bridged because it is wider
+ * than the 10m the panel spans.
+ */
+export const SpanGaps: Story = {
+ args: { gaps: 'hole', spanGaps: 'break-10m' },
+ play,
+};
+
+/**
+ * The legend beside the chart, with its series search narrowed to one
+ * service.
+ */
+export const LegendRight: Story = {
+ args: { legend: LegendPosition.right },
+ play: async ({ canvasElement, args }): Promise<void> => {
+ await expectPanel(canvasElement, args);
+ await filterLegend(canvasElement, args);
+ },
+};
+
+/** The dashed SLO line across the time series, with its label. */
+export const Thresholds: Story = {
+ args: { thresholds: true },
+ play,
+};
+
+/** The query ran and matched nothing, which the panel draws as its no-data state. */
+export const NoData: Story = {
+ args: { result: 'empty' },
+ play,
+};
+
+/** Data that came back with a warning, flagged in the panel header. */
+export const Warning: Story = {
+ args: { result: 'warning' },
+ play,
+};
diff --git a/frontend/src/pages/DashboardPage/stories/panels/__story_mockdata__/constants.ts b/frontend/src/pages/DashboardPage/stories/panels/__story_mockdata__/constants.ts
new file mode 100644
index 0000000000..c246738e14
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/stories/panels/__story_mockdata__/constants.ts
@@ -0,0 +1,131 @@
+/**
+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.
+ * Do not hand-edit: regenerate instead.
+ */
+
+import {
+ DashboardtypesHeatmapPaletteDTO as HeatmapPalette,
+ DashboardtypesHeatmapYScaleDTO as HeatmapYScale,
+ DashboardtypesLegendPositionDTO as LegendPosition,
+ DashboardtypesLineStyleDTO as LineStyle,
+ DashboardtypesStackModeDTO as StackMode,
+ DashboardtypesTextAlignDTO as TextAlign,
+} from 'api/generated/services/sigNoz.schemas';
+
+import type { PanelKind } from './types';
+
+export const PANELS_DASHBOARD_ID = 'storybook-panels-1';
+
+export const STORY_PANEL_ID = 'story-panel';
+
+export const PANEL_KINDS = [
+ 'TimeSeries',
+ 'Bar',
+ 'Area',
+ 'Histogram',
+ 'Heatmap',
+ 'Pie',
+ 'Number',
+ 'Table',
+ 'List',
+ 'Text',
+] as const;
+
+export const PANEL_RESULTS = ['data', 'empty', 'warning'] as const;
+
+export const LEGEND_POSITIONS = [
+ LegendPosition.bottom,
+ LegendPosition.right,
+] as const;
+
+export const UNITS = ['none', 'ms', 'bytes'] as const;
+
+export const STACK_MODES = [
+ StackMode.none,
+ StackMode.normal,
+ StackMode.percent,
+] as const;
+
+export const HEATMAP_PALETTES = Object.values(HeatmapPalette);
+
+export const HEATMAP_Y_SCALES = Object.values(HeatmapYScale);
+
+export const HEATMAP_COUNT_RANGES = ['auto', 'fixed'] as const;
+
+/** The colour bar's bounds under the `fixed` count range. */
+export const HEATMAP_FIXED_COUNTS = { min: 5, max: 250 };
+
+export const BUCKET_WIDTHS = ['auto', '10', '50'] as const;
+
+export const TEXT_SAMPLES = ['runbook', 'note', 'blank'] as const;
+
+export const TEXT_ALIGNS = Object.values(TextAlign);
+
+export const Y_SCALES = ['linear', 'log'] as const;
+
+export const LINE_STYLES = Object.values(LineStyle);
+
+export const GAPS = ['none', 'hole'] as const;
+
+export const SPAN_GAPS = ['bridge', 'break-10m'] as const;
+
+/** Points cut out of every series by `hole`: 12 of the 30, a gap past the 10m break. */
+export const HOLE = { from: 10, to: 22 };
+
+export const PANEL_NAME: Record<PanelKind, string> = {
+ TimeSeries: 'p99 latency by service',
+ Bar: 'Errors by service',
+ Area: 'Request rate by service',
+ Histogram: 'Latency distribution',
+ Heatmap: 'Latency heatmap',
+ Pie: 'Traffic share',
+ Number: 'p99 latency',
+ Table: 'Calls by service',
+ List: 'Recent logs',
+ Text: 'Runbook',
+};
+
+/** A colour no series palette draws in, so a canvas probe for it finds only the line. */
+export const THRESHOLD_COLOR = '#00e5ff';
+
+/** Inside every chart kind's y range: the series below oscillate around it. */
+export const CHART_THRESHOLD_VALUE = 200;
+
+/** Below `NUMBER_VALUE`, so the comparison holds. */
+export const NUMBER_THRESHOLD_VALUE = 500;
+
+export const NUMBER_VALUE = 812.6;
+
+/**
+ * Splits the table rows on the `A` column. The `B` column crosses it on other rows,
+ * which the rule must leave unpainted because it targets `A` only.
+ */
+export const TABLE_THRESHOLD_VALUE = 2500;
+
+export const QUERY_NAME = 'A';
+
+/** The aggregation column the table thresholds and units address. */
+export const TABLE_VALUE_COLUMN = QUERY_NAME;
+
+/** The table's second value column, which no threshold targets. */
+export const TABLE_SECOND_COLUMN = 'B';
+
+/** Linear, so `auto` lays the rows out linearly and `log` visibly changes it. */
+export const HEATMAP_BUCKETS = [
+ 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000,
+];
+
+export const HEATMAP_COLUMNS = 30;
+
+export const SERVICES = [
+ 'checkout',
+ 'payments',
+ 'inventory',
+ 'notifications',
+ 'search',
+ 'shipping',
+ 'recommendations',
+ 'auth',
+] as const;
+
+export const MAX_SERIES = SERVICES.length;
diff --git a/frontend/src/pages/DashboardPage/stories/panels/__story_mockdata__/panelDocuments.ts b/frontend/src/pages/DashboardPage/stories/panels/__story_mockdata__/panelDocuments.ts
new file mode 100644
index 0000000000..b991293732
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/stories/panels/__story_mockdata__/panelDocuments.ts
@@ -0,0 +1,73 @@
+/**
+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.
+ * Do not hand-edit: regenerate instead.
+ */
+
+import {
+ DashboardtypesLayoutEnvelopeGithubComPersesSpecGoDashboardGridLayoutSpecDTOKind as GridKind,
+ DashboardtypesPanelKindDTO as PanelKindDTO,
+ DashboardtypesSourceDTO,
+ type GetDashboardV2200,
+} from 'api/generated/services/sigNoz.schemas';
+
+import { documentStore } from '../../__story_mockdata__/documentStore';
+
+import { PANEL_NAME, PANELS_DASHBOARD_ID, STORY_PANEL_ID } from './constants';
+import { panelShape } from './panelPlugins';
+import type { PanelArgs } from './types';
+
+const panelsDashboardResponse = (args: PanelArgs): GetDashboardV2200 => {
+ const { plugin, queries } = panelShape(args);
+
+ return {
+ status: 'success',
+ data: {
+ id: PANELS_DASHBOARD_ID,
+ orgId: 'storybook-org',
+ name: 'Panel gallery',
+ image: '/assets/Icons/circus-tent',
+ schemaVersion: 'v6',
+ source: DashboardtypesSourceDTO.user,
+ locked: false,
+ createdBy: '[email protected]',
+ updatedBy: '[email protected]',
+ createdAt: '2026-05-04T09:12:00Z',
+ updatedAt: '2026-08-21T16:40:00Z',
+ tags: [],
+ spec: {
+ display: { name: 'Panel gallery' },
+ layouts: [
+ {
+ kind: GridKind.Grid,
+ spec: {
+ items: [
+ {
+ x: 0,
+ y: 0,
+ width: 12,
+ height: 8,
+ content: { $ref: `#/spec/panels/${STORY_PANEL_ID}` },
+ },
+ ],
+ },
+ },
+ ],
+ panels: {
+ [STORY_PANEL_ID]: {
+ kind: PanelKindDTO.Panel,
+ spec: { display: { name: PANEL_NAME[args.kind] }, plugin, queries },
+ },
+ },
+ variables: [],
+ },
+ },
+ };
+};
+
+const store = documentStore(panelsDashboardResponse);
+
+export const seedPanelsDocument = store.seed;
+
+export const currentPanelsDocument = store.current;
+
+export const patchPanelsDocument = store.patch;
diff --git a/frontend/src/pages/DashboardPage/stories/panels/__story_mockdata__/panelPlugins.ts b/frontend/src/pages/DashboardPage/stories/panels/__story_mockdata__/panelPlugins.ts
new file mode 100644
index 0000000000..ed07a82477
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/stories/panels/__story_mockdata__/panelPlugins.ts
@@ -0,0 +1,209 @@
+/**
+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.
+ * Do not hand-edit: regenerate instead.
+ */
+
+import {
+ DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpecDTOKind as AreaChartKind,
+ DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpecDTOKind as BarChartKind,
+ DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpecDTOKind as HeatmapKind,
+ DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHistogramPanelSpecDTOKind as HistogramKind,
+ DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesListPanelSpecDTOKind as ListKind,
+ DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesNumberPanelSpecDTOKind as NumberKind,
+ DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesPieChartPanelSpecDTOKind as PieChartKind,
+ DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTablePanelSpecDTOKind as TableKind,
+ DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpecDTOKind as TextKind,
+ DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpecDTOKind as TimeSeriesKind,
+ DashboardtypesStackModeDTO as StackMode,
+ DashboardtypesTextModeDTO as TextMode,
+ Querybuildertypesv5RequestTypeDTO as RequestType,
+ type DashboardtypesPanelPluginDTO,
+ type DashboardtypesQueryDTO,
+} from 'api/generated/services/sigNoz.schemas';
+
+import {
+ HEATMAP_FIXED_COUNTS,
+ TABLE_SECOND_COLUMN,
+ TABLE_VALUE_COLUMN,
+} from './constants';
+import {
+ comparisonThresholds,
+ labelThresholds,
+ logQuery,
+ metricQuery,
+ tableThresholds,
+ TEXT_BODIES,
+} from './panelQueries';
+import type { PanelArgs, PanelUnit } from './types';
+
+interface PanelShape {
+ plugin: DashboardtypesPanelPluginDTO;
+ queries: DashboardtypesQueryDTO[];
+}
+
+const unitOf = (unit: PanelUnit): string | undefined =>
+ unit === 'none' ? undefined : unit;
+
+const timeSeriesQueries = (): DashboardtypesQueryDTO[] => [
+ metricQuery(RequestType.time_series, { grouped: true }),
+];
+
+export const panelShape = (args: PanelArgs): PanelShape => {
+ const formatting = { unit: unitOf(args.unit) };
+ const legend = { position: args.legend };
+ const axes = { isLogScale: args.yScale === 'log' };
+ const thresholds = labelThresholds(args.thresholds);
+ const chartAppearance = {
+ lineStyle: args.lineStyle,
+ showPoints: args.showPoints,
+ spanGaps:
+ args.spanGaps === 'break-10m'
+ ? { fillOnlyBelow: true, fillLessThan: '10m' }
+ : { fillOnlyBelow: false },
+ };
+
+ switch (args.kind) {
+ case 'Bar':
+ return {
+ plugin: {
+ kind: BarChartKind['signoz/BarChartPanel'],
+ spec: {
+ axes,
+ formatting,
+ legend,
+ thresholds,
+ visualization: { stackedBarChart: args.stack !== StackMode.none },
+ },
+ },
+ queries: timeSeriesQueries(),
+ };
+ case 'Area':
+ return {
+ plugin: {
+ kind: AreaChartKind['signoz/AreaChartPanel'],
+ spec: {
+ axes,
+ chartAppearance,
+ formatting,
+ legend,
+ thresholds,
+ visualization: { stack: args.stack },
+ },
+ },
+ queries: timeSeriesQueries(),
+ };
+ case 'Histogram':
+ return {
+ plugin: {
+ kind: HistogramKind['signoz/HistogramPanel'],
+ spec: {
+ legend,
+ histogramBuckets: {
+ bucketWidth:
+ args.bucketWidth === 'auto' ? undefined : Number(args.bucketWidth),
+ },
+ },
+ },
+ queries: timeSeriesQueries(),
+ };
+ case 'Heatmap':
+ return {
+ plugin: {
+ kind: HeatmapKind['signoz/HeatmapPanel'],
+ spec: {
+ formatting,
+ legend,
+ axes: { y: { scale: args.heatmapScale } },
+ chartAppearance: {
+ colors: {
+ palette: args.palette,
+ ...(args.heatmapCounts === 'fixed'
+ ? {
+ minCount: HEATMAP_FIXED_COUNTS.min,
+ maxCount: HEATMAP_FIXED_COUNTS.max,
+ }
+ : {}),
+ },
+ },
+ },
+ },
+ queries: [
+ metricQuery(RequestType.heatmap, { grouped: true, heatmap: true }),
+ ],
+ };
+ case 'Pie':
+ return {
+ plugin: {
+ kind: PieChartKind['signoz/PieChartPanel'],
+ spec: { formatting, legend },
+ },
+ queries: [metricQuery(RequestType.scalar, { grouped: true })],
+ };
+ case 'Number':
+ return {
+ plugin: {
+ kind: NumberKind['signoz/NumberPanel'],
+ spec: {
+ formatting,
+ thresholds: comparisonThresholds(args.thresholds),
+ },
+ },
+ queries: [metricQuery(RequestType.scalar, { grouped: false })],
+ };
+ case 'Table':
+ return {
+ plugin: {
+ kind: TableKind['signoz/TablePanel'],
+ spec: {
+ formatting: {
+ columnUnits:
+ args.columnUnits && formatting.unit
+ ? { [TABLE_VALUE_COLUMN]: formatting.unit }
+ : {},
+ },
+ thresholds: tableThresholds(args.thresholds),
+ },
+ },
+ queries: [
+ metricQuery(RequestType.scalar, { grouped: true }),
+ metricQuery(RequestType.scalar, {
+ grouped: true,
+ name: TABLE_SECOND_COLUMN,
+ metricName: 'signoz_errors',
+ }),
+ ],
+ };
+ case 'List':
+ return {
+ plugin: {
+ kind: ListKind['signoz/ListPanel'],
+ spec: {
+ selectFields: [{ name: 'timestamp' }, { name: 'body' }],
+ },
+ },
+ queries: [logQuery()],
+ };
+ case 'Text':
+ return {
+ plugin: {
+ kind: TextKind['signoz/TextPanel'],
+ spec: {
+ mode: TextMode.markdown,
+ text: TEXT_BODIES[args.textSample],
+ presentation: { textAlign: args.textAlign },
+ headerOptions: args.hideHeader ? { hide: true } : {},
+ },
+ },
+ queries: [],
+ };
+ case 'TimeSeries':
+ default:
+ return {
+ plugin: {
+ kind: TimeSeriesKind['signoz/TimeSeriesPanel'],
+ spec: { axes, chartAppearance, formatting, legend, thresholds },
+ },
+ queries: timeSeriesQueries(),
+ };
+ }
+};
diff --git a/frontend/src/pages/DashboardPage/stories/panels/__story_mockdata__/panelQueries.ts b/frontend/src/pages/DashboardPage/stories/panels/__story_mockdata__/panelQueries.ts
new file mode 100644
index 0000000000..368c3f360f
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/stories/panels/__story_mockdata__/panelQueries.ts
@@ -0,0 +1,148 @@
+/**
+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.
+ * Do not hand-edit: regenerate instead.
+ */
+
+import {
+ DashboardtypesComparisonOperatorDTO as ComparisonOperator,
+ DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBuilderQuerySpecDTOKind as BuilderQueryKind,
+ DashboardtypesThresholdFormatDTO as ThresholdFormat,
+ MetrictypesSpaceAggregationDTO as SpaceAggregation,
+ MetrictypesTimeAggregationDTO as TimeAggregation,
+ Querybuildertypesv5BucketOptionsLinearDTOKind as LinearBuckets,
+ Querybuildertypesv5OrderDirectionDTO as OrderDirection,
+ Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5LogAggregationDTOSignal as LogSignal,
+ Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal as MetricSignal,
+ Querybuildertypesv5RequestTypeDTO as RequestType,
+ type DashboardtypesComparisonThresholdDTO,
+ type DashboardtypesQueryDTO,
+ type DashboardtypesTableThresholdDTO,
+ type DashboardtypesThresholdWithLabelDTO,
+ type Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5LogAggregationDTO as LogBuilderQuery,
+ type Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTO as MetricBuilderQuery,
+} from 'api/generated/services/sigNoz.schemas';
+
+import {
+ CHART_THRESHOLD_VALUE,
+ NUMBER_THRESHOLD_VALUE,
+ QUERY_NAME,
+ TABLE_THRESHOLD_VALUE,
+ TABLE_VALUE_COLUMN,
+ THRESHOLD_COLOR,
+} from './constants';
+import type { TextSample } from './types';
+
+export const labelThresholds = (
+ on: boolean,
+): DashboardtypesThresholdWithLabelDTO[] =>
+ on
+ ? [{ value: CHART_THRESHOLD_VALUE, color: THRESHOLD_COLOR, label: 'SLO' }]
+ : [];
+
+export const comparisonThresholds = (
+ on: boolean,
+): DashboardtypesComparisonThresholdDTO[] =>
+ on
+ ? [
+ {
+ value: NUMBER_THRESHOLD_VALUE,
+ operator: ComparisonOperator.above,
+ color: THRESHOLD_COLOR,
+ format: ThresholdFormat.background,
+ },
+ ]
+ : [];
+
+export const tableThresholds = (
+ on: boolean,
+): DashboardtypesTableThresholdDTO[] =>
+ on
+ ? [
+ {
+ columnName: TABLE_VALUE_COLUMN,
+ value: TABLE_THRESHOLD_VALUE,
+ operator: ComparisonOperator.above,
+ color: THRESHOLD_COLOR,
+ format: ThresholdFormat.background,
+ },
+ ]
+ : [];
+
+export const TEXT_BODIES: Record<TextSample, string> = {
+ runbook: [
+ '# Checkout runbook',
+ '',
+ 'When **p99 latency** crosses the SLO:',
+ '',
+ '- Check the [payments dashboard](https://signoz.io/docs/)',
+ '- Scale the `checkout` deployment',
+ '- Page the on-call',
+ '',
+ '```sh',
+ 'kubectl scale deploy/checkout --replicas=6',
+ '```',
+ ].join('\n'),
+ note: 'Latency panels read from the **checkout** service only.',
+ blank: '',
+};
+
+interface MetricQueryOptions {
+ grouped: boolean;
+ heatmap?: boolean;
+ name?: string;
+ metricName?: string;
+}
+
+export const metricQuery = (
+ requestType: RequestType,
+ {
+ grouped,
+ heatmap,
+ name = QUERY_NAME,
+ metricName = 'signoz_latency',
+ }: MetricQueryOptions,
+): DashboardtypesQueryDTO => {
+ const spec: MetricBuilderQuery = {
+ name,
+ signal: MetricSignal.metrics,
+ aggregations: [
+ {
+ metricName: heatmap ? `${metricName}_bucket` : metricName,
+ spaceAggregation: heatmap ? undefined : SpaceAggregation.p99,
+ timeAggregation: heatmap ? TimeAggregation.increase : TimeAggregation.avg,
+ },
+ ],
+ groupBy: grouped ? [{ name: 'service.name' }] : undefined,
+ legend:
+ grouped && requestType !== RequestType.scalar
+ ? '{{service.name}}'
+ : undefined,
+ bucketOptions: heatmap
+ ? { kind: LinearBuckets.linear, spec: { maxValue: 1000, numBuckets: 10 } }
+ : undefined,
+ };
+
+ return {
+ kind: requestType,
+ spec: {
+ name,
+ plugin: { kind: BuilderQueryKind['signoz/BuilderQuery'], spec },
+ },
+ };
+};
+
+export const logQuery = (): DashboardtypesQueryDTO => {
+ const spec: LogBuilderQuery = {
+ name: QUERY_NAME,
+ signal: LogSignal.logs,
+ order: [{ key: { name: 'timestamp' }, direction: OrderDirection.desc }],
+ };
+
+ return {
+ kind: RequestType.raw,
+ spec: {
+ name: QUERY_NAME,
+ plugin: { kind: BuilderQueryKind['signoz/BuilderQuery'], spec },
+ },
+ };
+};
diff --git a/frontend/src/pages/DashboardPage/stories/panels/__story_mockdata__/panelResponses.ts b/frontend/src/pages/DashboardPage/stories/panels/__story_mockdata__/panelResponses.ts
new file mode 100644
index 0000000000..add90a612d
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/stories/panels/__story_mockdata__/panelResponses.ts
@@ -0,0 +1,226 @@
+/**
+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.
+ * Do not hand-edit: regenerate instead.
+ */
+
+import type { QueryRangeV5200 } from 'api/generated/services/sigNoz.schemas';
+import type { Warning } from 'types/api';
+import type { MetricRangePayloadV5, RawRow } from 'types/api/v5/queryRange';
+
+import {
+ queryRangeV5EmptyResponse,
+ queryRangeV5HeatmapResponse,
+ queryRangeV5RawResponse,
+ queryRangeV5ScalarResponse,
+ queryRangeV5ScalarTableResponse,
+ queryRangeV5TimeSeriesResponse,
+ timeSeriesPoints,
+} from '@/storybook/msw/__story_mockdata__/queryRange';
+
+import {
+ partialDataWarning,
+ type PanelWindow,
+} from '../../__story_mockdata__/panelData';
+
+import {
+ HEATMAP_BUCKETS,
+ HEATMAP_COLUMNS,
+ HOLE,
+ MAX_SERIES,
+ NUMBER_VALUE,
+ QUERY_NAME,
+ SERVICES,
+ TABLE_SECOND_COLUMN,
+} from './constants';
+import type { Gaps, PanelRequest, PanelResponseArgs } from './types';
+
+export const serviceAt = (index: number): string =>
+ index < SERVICES.length
+ ? SERVICES[index]
+ : `${SERVICES[index % SERVICES.length]}-${Math.floor(index / SERVICES.length) + 1}`;
+
+export const TABLE_VALUES = (count: number): number[] =>
+ Array.from({ length: count }, (_unused, index) => 3800 - index * 480);
+
+const TABLE_SECOND_VALUES = (count: number): number[] =>
+ Array.from({ length: count }, (_unused, index) => 2000 + index * 600);
+
+/** Every `query_range` the panel sent since the story mounted, oldest first. */
+const requests: PanelRequest[] = [];
+
+export const recordPanelRequest = (request: PanelRequest): void => {
+ requests.push(request);
+};
+
+export const panelRequests = (): readonly PanelRequest[] => requests;
+
+export const resetPanelRequests = (): void => {
+ requests.length = 0;
+};
+
+/** One service's samples, as the time series response carries them. */
+export const latencyPoints = (
+ { start, end }: PanelWindow,
+ index: number,
+ gaps: Gaps,
+): { timestamp: number; value: number }[] =>
+ timeSeriesPoints({
+ start,
+ end,
+ base: 260 - index * 20,
+ amplitude: 60,
+ seed: index * 3,
+ }).filter(
+ (_point, position) =>
+ gaps === 'none' || position < HOLE.from || position >= HOLE.to,
+ );
+
+/** The series index a service label was generated from. */
+export const serviceIndex = (label: string): number =>
+ Array.from({ length: MAX_SERIES }, (_unused, index) =>
+ serviceAt(index),
+ ).indexOf(label);
+
+const latencySeries = (
+ window: PanelWindow,
+ count: number,
+ gaps: Gaps,
+ warning: Warning | undefined,
+): MetricRangePayloadV5 =>
+ queryRangeV5TimeSeriesResponse(
+ [
+ {
+ queryName: QUERY_NAME,
+ series: Array.from({ length: count }, (_unused, index) => ({
+ labels: [{ key: { name: 'service.name' }, value: serviceAt(index) }],
+ values: latencyPoints(window, index, gaps),
+ })),
+ },
+ ],
+ { warning },
+ );
+
+const heatmapCounts = (column: number, group: number): number[] =>
+ Array.from(
+ { length: HEATMAP_BUCKETS.length + 1 },
+ (_unused, row) =>
+ 1 + ((column * 7 + row * 3 + group * 5) % 17) * (row < 6 ? 3 : 1),
+ );
+
+/** The busiest cell once every group is summed into it, as the grid does. */
+export const heatmapMaxCount = (groups: number): number => {
+ let max = 0;
+ for (let column = 0; column < HEATMAP_COLUMNS; column++) {
+ for (let row = 0; row <= HEATMAP_BUCKETS.length; row++) {
+ let sum = 0;
+ for (let group = 0; group < groups; group++) {
+ sum += heatmapCounts(column, group)[row];
+ }
+ max = Math.max(max, sum);
+ }
+ }
+
+ return max;
+};
+
+const heatmapResponse = (
+ { start, end }: PanelWindow,
+ count: number,
+ warning: Warning | undefined,
+): QueryRangeV5200 => {
+ const stepMs = (end - start) / HEATMAP_COLUMNS;
+
+ return queryRangeV5HeatmapResponse({
+ buckets: HEATMAP_BUCKETS,
+ warning,
+ stepSeconds: Math.max(1, Math.round(stepMs / 1000)),
+ series: Array.from({ length: count }, (_unused, group) => ({
+ labels: [{ key: { name: 'service.name' }, value: serviceAt(group) }],
+ values: Array.from({ length: HEATMAP_COLUMNS }, (_point, column) => ({
+ timestamp: Math.round(start + column * stepMs),
+ values: heatmapCounts(column, group),
+ })),
+ })),
+ });
+};
+
+/** Spaced by the window, newest first, as the `timestamp desc` order asks for. */
+const logRows = (
+ { start, end }: PanelWindow,
+ total: number,
+ offset: number,
+ limit: number,
+): RawRow[] =>
+ Array.from(
+ { length: Math.max(0, Math.min(limit, total - offset)) },
+ (_unused, position) => {
+ const index = offset + position;
+ const service = serviceAt(index % MAX_SERIES);
+
+ return {
+ timestamp: new Date(
+ end - ((end - start) / Math.max(total, 1)) * index,
+ ).toISOString(),
+ data: {
+ id: `storybook-log-${index + 1}`,
+ body: `log line ${index + 1}: ${service} served the request in ${
+ 8 + (index % 9) * 3
+ }ms`,
+ severity_text: index % 5 === 0 ? 'ERROR' : 'INFO',
+ resources_string: { 'service.name': service },
+ },
+ };
+ },
+ );
+
+/** What the panel's `query_range` answers, per kind and result. */
+export const panelQueryResponse = ({
+ kind,
+ result,
+ series,
+ listRows,
+ gaps,
+ window,
+ offset,
+ limit,
+}: PanelResponseArgs): MetricRangePayloadV5 | QueryRangeV5200 => {
+ if (result === 'empty') {
+ return queryRangeV5EmptyResponse();
+ }
+
+ const warning = result === 'warning' ? partialDataWarning() : undefined;
+
+ switch (kind) {
+ case 'Heatmap':
+ return heatmapResponse(window, series, warning);
+ case 'Pie':
+ return queryRangeV5ScalarTableResponse({
+ groupBy: ['service.name'],
+ aggregations: [QUERY_NAME],
+ rows: TABLE_VALUES(series).map((value, index) => [serviceAt(index), value]),
+ warning,
+ });
+ case 'Table': {
+ const second = TABLE_SECOND_VALUES(series);
+
+ return queryRangeV5ScalarTableResponse({
+ groupBy: ['service.name'],
+ aggregations: [QUERY_NAME, TABLE_SECOND_COLUMN],
+ rows: TABLE_VALUES(series).map((value, index) => [
+ serviceAt(index),
+ value,
+ second[index],
+ ]),
+ warning,
+ });
+ }
+ case 'Number':
+ return queryRangeV5ScalarResponse(NUMBER_VALUE, QUERY_NAME, { warning });
+ case 'List':
+ return queryRangeV5RawResponse(logRows(window, listRows, offset, limit), {
+ warning,
+ });
+ default:
+ return latencySeries(window, series, gaps, warning);
+ }
+};
diff --git a/frontend/src/pages/DashboardPage/stories/panels/__story_mockdata__/types.ts b/frontend/src/pages/DashboardPage/stories/panels/__story_mockdata__/types.ts
new file mode 100644
index 0000000000..48965506b6
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/stories/panels/__story_mockdata__/types.ts
@@ -0,0 +1,81 @@
+/**
+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.
+ * Do not hand-edit: regenerate instead.
+ */
+
+import type {
+ DashboardtypesHeatmapPaletteDTO as HeatmapPalette,
+ DashboardtypesHeatmapYScaleDTO as HeatmapYScale,
+ DashboardtypesLegendPositionDTO as LegendPosition,
+ DashboardtypesLineStyleDTO as LineStyle,
+ DashboardtypesStackModeDTO as StackMode,
+ DashboardtypesTextAlignDTO as TextAlign,
+} from 'api/generated/services/sigNoz.schemas';
+
+import type { PanelWindow } from '../../__story_mockdata__/panelData';
+
+import type {
+ BUCKET_WIDTHS,
+ GAPS,
+ HEATMAP_COUNT_RANGES,
+ PANEL_KINDS,
+ PANEL_RESULTS,
+ SPAN_GAPS,
+ TEXT_SAMPLES,
+ UNITS,
+ Y_SCALES,
+} from './constants';
+
+export type PanelKind = (typeof PANEL_KINDS)[number];
+
+export type PanelResult = (typeof PANEL_RESULTS)[number];
+
+export type PanelUnit = (typeof UNITS)[number];
+
+export type HeatmapCountRange = (typeof HEATMAP_COUNT_RANGES)[number];
+
+export type BucketWidth = (typeof BUCKET_WIDTHS)[number];
+
+export type TextSample = (typeof TEXT_SAMPLES)[number];
+
+export type YScale = (typeof Y_SCALES)[number];
+
+export type Gaps = (typeof GAPS)[number];
+
+export type SpanGaps = (typeof SPAN_GAPS)[number];
+
+/** The controls that shape the dashboard document. */
+export interface PanelArgs {
+ kind: PanelKind;
+ legend: LegendPosition;
+ thresholds: boolean;
+ unit: PanelUnit;
+ stack: StackMode;
+ palette: HeatmapPalette;
+ heatmapScale: HeatmapYScale;
+ heatmapCounts: HeatmapCountRange;
+ bucketWidth: BucketWidth;
+ textSample: TextSample;
+ textAlign: TextAlign;
+ hideHeader: boolean;
+ yScale: YScale;
+ lineStyle: LineStyle;
+ showPoints: boolean;
+ spanGaps: SpanGaps;
+ columnUnits: boolean;
+}
+
+/** What one `query_range` call asked for, as the handler reads it. */
+export interface PanelRequest {
+ window: PanelWindow;
+ offset: number;
+ limit: number;
+}
+
+export interface PanelResponseArgs extends PanelRequest {
+ kind: PanelKind;
+ result: PanelResult;
+ series: number;
+ listRows: number;
+ gaps: Gaps;
+}
diff --git a/frontend/src/pages/DashboardPage/stories/panels/panelPlay/args.ts b/frontend/src/pages/DashboardPage/stories/panels/panelPlay/args.ts
new file mode 100644
index 0000000000..b8daf168ba
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/stories/panels/panelPlay/args.ts
@@ -0,0 +1,20 @@
+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
+
+import type { panelsMocks } from '../Panels.stories.mocks';
+
+/** The dashboard document loads before the panel queries, then the chart sizes itself. */
+export const PANEL_LOAD = { timeout: 15000 };
+
+export type PanelPlayArgs = PageStoryArgs<typeof panelsMocks>;
+
+/** Whether a queried panel was answered with something to draw. */
+export const hasData = (args: PanelPlayArgs): boolean => {
+ if (args.dataState !== 'loaded' || args.result === 'empty') {
+ return false;
+ }
+ if (args.kind === 'List') {
+ return args.listRows > 0;
+ }
+
+ return args.kind === 'Number' || args.series > 0;
+};
diff --git a/frontend/src/pages/DashboardPage/stories/panels/panelPlay/distributions.ts b/frontend/src/pages/DashboardPage/stories/panels/panelPlay/distributions.ts
new file mode 100644
index 0000000000..f9da9fb148
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/stories/panels/panelPlay/distributions.ts
@@ -0,0 +1,91 @@
+import { DashboardtypesHeatmapYScaleDTO as HeatmapYScale } from 'api/generated/services/sigNoz.schemas';
+import { getPaletteStops } from 'lib/uPlotV2/plugins/HeatmapPlugin/palettes';
+import { HEATMAP_PALETTE_MAP } from 'pages/DashboardPage/DashboardContainer/Panels/utils/chartAppearance/enumMaps';
+import { expect, waitFor, within } from 'storybook/test';
+import type uPlot from 'uplot';
+
+import {
+ HEATMAP_BUCKETS,
+ HEATMAP_FIXED_COUNTS,
+} from '../__story_mockdata__/constants';
+import { heatmapMaxCount } from '../__story_mockdata__/panelResponses';
+
+import { PANEL_LOAD, type PanelPlayArgs } from './args';
+import { findPlot, toRgb, waitForPlot } from './plot';
+
+const isMultipleOf = (value: number, width: number): boolean =>
+ Math.abs(value / width - Math.round(value / width)) < 1e-6;
+
+export const expectHistogram = async (
+ root: HTMLElement,
+ args: PanelPlayArgs,
+): Promise<void> => {
+ const plot = await waitForPlot(root, args.series);
+ const bins = plot.data[0] as number[];
+
+ // Bins of the values, not timestamps: the x scale is in the series' own unit.
+ await expect(bins.length).toBeGreaterThan(1);
+ await expect(plot.scales.x.max ?? Infinity).toBeLessThan(1e6);
+
+ if (args.bucketWidth !== 'auto') {
+ const width = Number(args.bucketWidth);
+ // Bins start on multiples of the width; empty ones are skipped, so the
+ // closest two starts are exactly one width apart.
+ await expect(bins.filter((bin) => !isMultipleOf(bin, width))).toEqual([]);
+ const steps = bins.slice(1).map((bin, index) => bin - bins[index]);
+ await expect(Math.min(...steps)).toBeCloseTo(width, 6);
+ }
+};
+
+const firstGradientColor = (background: string): string | undefined =>
+ background.match(/rgba?\([^)]+\)/)?.[0];
+
+/** The colour bar's low and high labels, either side of the track. */
+const colorBarLabels = (bar: HTMLElement): string[] =>
+ [...bar.children]
+ .filter((node) => node.tagName === 'SPAN')
+ .slice(-2)
+ .map((node) => node.textContent ?? '');
+
+export const expectHeatmap = async (
+ root: HTMLElement,
+ args: PanelPlayArgs,
+): Promise<void> => {
+ const bar = await within(root).findByTestId('color-bar', {}, PANEL_LOAD);
+ await expect(bar).toHaveTextContent(/count/i);
+
+ const range =
+ args.heatmapCounts === 'fixed'
+ ? HEATMAP_FIXED_COUNTS
+ : { min: 0, max: heatmapMaxCount(args.series) };
+ await waitFor(
+ () =>
+ expect(colorBarLabels(bar)).toEqual([
+ range.min.toLocaleString(),
+ range.max.toLocaleString(),
+ ]),
+ PANEL_LOAD,
+ );
+
+ const isDark = document.body.classList.contains('darkMode');
+ const [lowStop] = getPaletteStops(HEATMAP_PALETTE_MAP[args.palette], isDark);
+ const track = bar.querySelector<HTMLElement>('div');
+ await expect(firstGradientColor(track?.style.background ?? '')).toBe(
+ `rgb(${toRgb(lowStop).join(', ')})`,
+ );
+
+ let plot: uPlot | undefined;
+ await waitFor(async () => {
+ plot = findPlot(root);
+ await expect(plot).toBeDefined();
+ }, PANEL_LOAD);
+ const yMax = plot?.scales.y.max ?? 0;
+ // Log lays rows out on log10 of the bounds; linear on the bounds.
+ if (args.heatmapScale === HeatmapYScale.log) {
+ await expect(yMax).toBeLessThan(10);
+ } else {
+ await expect(yMax).toBeGreaterThanOrEqual(
+ HEATMAP_BUCKETS[HEATMAP_BUCKETS.length - 1],
+ );
+ }
+};
diff --git a/frontend/src/pages/DashboardPage/stories/panels/panelPlay/expectPanel.ts b/frontend/src/pages/DashboardPage/stories/panels/panelPlay/expectPanel.ts
new file mode 100644
index 0000000000..9ab31621d9
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/stories/panels/panelPlay/expectPanel.ts
@@ -0,0 +1,76 @@
+import { expect, within } from 'storybook/test';
+
+import { PANEL_NAME } from '../__story_mockdata__/constants';
+
+import { hasData, PANEL_LOAD, type PanelPlayArgs } from './args';
+import { expectHeatmap, expectHistogram } from './distributions';
+import { expectLineChart } from './lineChart';
+import { expectListPage } from './list';
+import { findPlot } from './plot';
+import { expectNumber, expectPie, expectTable } from './scalars';
+import { expectText } from './text';
+
+const expectNoData = async (
+ root: HTMLElement,
+ args: PanelPlayArgs,
+): Promise<void> => {
+ await within(root).findByTestId(
+ args.kind === 'Number' ? 'number-panel-no-data' : 'panel-no-data',
+ {},
+ PANEL_LOAD,
+ );
+ await expect(findPlot(root)).toBeUndefined();
+};
+
+const KIND_EXPECTATIONS: Record<
+ Exclude<PanelPlayArgs['kind'], 'Text'>,
+ (root: HTMLElement, args: PanelPlayArgs) => Promise<void>
+> = {
+ TimeSeries: expectLineChart,
+ Bar: expectLineChart,
+ Area: expectLineChart,
+ Histogram: expectHistogram,
+ Heatmap: expectHeatmap,
+ Pie: expectPie,
+ Number: expectNumber,
+ Table: expectTable,
+ List: (root, args) => expectListPage(root, args.listRows, 0),
+};
+
+/**
+ * What the one panel on the page must show for the args it was rendered with.
+ * Loading and failed belong to the Data control and are left alone.
+ */
+export const expectPanel = async (
+ root: HTMLElement,
+ args: PanelPlayArgs,
+): Promise<void> => {
+ if (args.dataState !== 'loaded') {
+ return;
+ }
+
+ if (args.kind === 'Text') {
+ await expectText(root, args);
+ return;
+ }
+
+ await within(root).findByText(PANEL_NAME[args.kind], {}, PANEL_LOAD);
+
+ if (!hasData(args)) {
+ await expectNoData(root, args);
+ return;
+ }
+
+ await KIND_EXPECTATIONS[args.kind](root, args);
+
+ // Checked once the data has drawn, so an absent indicator is not one still on its way.
+ if (args.result === 'warning') {
+ await expect(
+ within(root).getByTestId('panel-status-warning'),
+ ).toBeInTheDocument();
+ } else {
+ await expect(
+ within(root).queryByTestId('panel-status-warning'),
+ ).not.toBeInTheDocument();
+ }
+};
diff --git a/frontend/src/pages/DashboardPage/stories/panels/panelPlay/interactions.ts b/frontend/src/pages/DashboardPage/stories/panels/panelPlay/interactions.ts
new file mode 100644
index 0000000000..d697f73391
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/stories/panels/panelPlay/interactions.ts
@@ -0,0 +1,74 @@
+import { expect, userEvent, waitFor, within } from 'storybook/test';
+
+import { serviceAt } from '../__story_mockdata__/panelResponses';
+
+import { hasData, PANEL_LOAD, type PanelPlayArgs } from './args';
+
+/** The second series, so narrowing to it leaves one of several. */
+const SEARCH_TERM = serviceAt(1);
+
+const narrows = (args: PanelPlayArgs): boolean =>
+ hasData(args) && args.series >= 2;
+
+/** Filters the right legend of a line chart down to one series by name. */
+export const filterLegend = async (
+ root: HTMLElement,
+ args: PanelPlayArgs,
+): Promise<void> => {
+ const lineChart = ['TimeSeries', 'Bar', 'Area'].includes(args.kind);
+ if (!lineChart || args.legend !== 'right' || !narrows(args)) {
+ return;
+ }
+
+ const search = await within(root).findByTestId(
+ 'legend-search-input',
+ {},
+ PANEL_LOAD,
+ );
+ await userEvent.type(search, SEARCH_TERM);
+ await waitFor(async () => {
+ const rows = root.querySelectorAll('[data-legend-item-id]');
+ await expect(rows).toHaveLength(1);
+ await expect(rows[0]).toHaveTextContent(SEARCH_TERM);
+ }, PANEL_LOAD);
+ await expect(within(root).getByTestId('legend-status')).toHaveTextContent(
+ `Showing 1 of ${args.series}`,
+ );
+};
+
+const tableRows = (root: HTMLElement): NodeListOf<Element> =>
+ root.querySelectorAll(
+ '[data-testid="table-panel-renderer"] tbody tr.ant-table-row',
+ );
+
+/** Opens the Table's header search, narrows it to one service, then clears it. */
+export const searchTable = async (
+ root: HTMLElement,
+ args: PanelPlayArgs,
+): Promise<void> => {
+ if (args.kind !== 'Table' || !narrows(args)) {
+ return;
+ }
+
+ await userEvent.click(
+ await within(root).findByTestId(
+ 'panel-header-search-trigger',
+ {},
+ PANEL_LOAD,
+ ),
+ );
+ await userEvent.type(
+ await within(root).findByTestId('panel-header-search-input'),
+ SEARCH_TERM,
+ );
+ await waitFor(async () => {
+ await expect(tableRows(root)).toHaveLength(1);
+ await expect(tableRows(root)[0]).toHaveTextContent(SEARCH_TERM);
+ }, PANEL_LOAD);
+
+ await userEvent.click(within(root).getByTestId('panel-header-search-clear'));
+ await waitFor(
+ async () => expect(tableRows(root)).toHaveLength(args.series),
+ PANEL_LOAD,
+ );
+};
diff --git a/frontend/src/pages/DashboardPage/stories/panels/panelPlay/lineChart.ts b/frontend/src/pages/DashboardPage/stories/panels/panelPlay/lineChart.ts
new file mode 100644
index 0000000000..90a1b175d7
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/stories/panels/panelPlay/lineChart.ts
@@ -0,0 +1,157 @@
+import {
+ DashboardtypesLineStyleDTO as LineStyle,
+ DashboardtypesStackModeDTO as StackMode,
+} from 'api/generated/services/sigNoz.schemas';
+import { expect, waitFor, within } from 'storybook/test';
+import type uPlot from 'uplot';
+
+import {
+ CHART_THRESHOLD_VALUE,
+ THRESHOLD_COLOR,
+} from '../__story_mockdata__/constants';
+import {
+ latencyPoints,
+ panelRequests,
+ serviceIndex,
+} from '../__story_mockdata__/panelResponses';
+import type { PanelArgs } from '../__story_mockdata__/types';
+
+import { PANEL_LOAD, type PanelPlayArgs } from './args';
+import { lineCoverage, waitForPlot } from './plot';
+
+const isStacked = ({ kind, stack }: PanelArgs): boolean =>
+ (kind === 'Area' || kind === 'Bar') && stack !== StackMode.none;
+
+const isPercent = ({ kind, stack }: PanelArgs): boolean =>
+ kind === 'Area' && stack === StackMode.percent;
+
+/** Time Series and Area carry `chartAppearance`; Bar draws with its defaults. */
+const hasLineAppearance = ({ kind }: PanelArgs): boolean =>
+ kind === 'TimeSeries' || kind === 'Area';
+
+const nullCount = (plot: uPlot): number =>
+ plot.data
+ .slice(1)
+ .reduce(
+ (count, values) =>
+ count + (values as unknown[]).filter((value) => value === null).length,
+ 0,
+ );
+
+/** Line style, points and gap handling, read off the live series. */
+const expectLineAppearance = async (
+ plot: uPlot,
+ args: PanelPlayArgs,
+): Promise<void> => {
+ const series = plot.series.slice(1);
+ const appearance = hasLineAppearance(args);
+ const dashed = appearance && args.lineStyle === LineStyle.dashed;
+ const breaks = appearance && args.spanGaps === 'break-10m';
+
+ for (const [index, line] of series.entries()) {
+ await expect((line.dash ?? []).length > 0).toBe(dashed);
+ if (appearance) {
+ // A predicate, built so it can also show the isolated points a gap leaves
+ // behind; uPlot only ever calls it with the plot and the series index.
+ const show = line.points?.show as
+ | boolean
+ | ((u: uPlot, seriesIndex: number) => boolean)
+ | undefined;
+ await expect(typeof show === 'function' ? show(plot, index + 1) : show).toBe(
+ args.showPoints,
+ );
+ }
+ // A numeric threshold is applied in data-prep, so uPlot's own bridging is off.
+ await expect(line.spanGaps).toBe(!breaks);
+ }
+
+ // The break is a null inserted into the gap; bridging leaves none.
+ await expect(nullCount(plot) > 0).toBe(breaks && args.gaps === 'hole');
+};
+
+/**
+ * Every series' plotted share against its raw value over the column total. A
+ * percent stack plots running totals from the last series up, so a series' own
+ * share is its value minus the one below it.
+ */
+const expectPercentShares = async (
+ plot: uPlot,
+ args: PanelPlayArgs,
+): Promise<void> => {
+ const request = panelRequests().at(-1);
+ if (!request) {
+ throw new Error('the panel sent no query_range');
+ }
+ const seriesCount = plot.series.length - 1;
+ const raw = plot.series.slice(1).map(({ label }) => {
+ const index = serviceIndex(String(label));
+ return new Map(
+ latencyPoints(request.window, index, args.gaps).map((point) => [
+ Math.round(point.timestamp / 1000),
+ point.value,
+ ]),
+ );
+ });
+ const plotted = plot.data as (number | null)[][];
+
+ let checked = 0;
+ for (const [column, x] of (plot.data[0] as number[]).entries()) {
+ const values = raw.map((byTime) => byTime.get(Math.round(x)));
+ if (values.some((value) => value === undefined)) {
+ continue;
+ }
+ const total = (values as number[]).reduce((sum, value) => sum + value, 0);
+ for (let series = 1; series <= seriesCount; series++) {
+ const below = series < seriesCount ? (plotted[series + 1][column] ?? 0) : 0;
+ const share = (plotted[series][column] ?? 0) - below;
+ await expect(share).toBeCloseTo(
+ ((values[series - 1] as number) / total) * 100,
+ 3,
+ );
+ }
+ checked += 1;
+ }
+ await expect(checked).toBeGreaterThan(0);
+};
+
+export const expectLineChart = async (
+ root: HTMLElement,
+ args: PanelPlayArgs,
+): Promise<void> => {
+ const plot = await waitForPlot(root, args.series);
+
+ // Set from options at construction; uPlot's typings leave it off the instance.
+ const { bands } = plot as uPlot & { bands?: uPlot.Band[] };
+ await expect(bands?.length ?? 0).toBe(isStacked(args) ? args.series - 1 : 0);
+ // A percent stack replaces the y scale with its own 0–100 one.
+ if (!isPercent(args)) {
+ await expect(plot.scales.y.distr).toBe(args.yScale === 'log' ? 3 : 1);
+ }
+ await expectLineAppearance(plot, args);
+ if (args.legend === 'right') {
+ await expect(
+ await within(root).findByTestId('legend-search-input', {}, PANEL_LOAD),
+ ).toBeInTheDocument();
+ }
+ await waitFor(
+ () =>
+ expect(
+ root.querySelectorAll('[data-legend-item-id][aria-checked="true"]'),
+ ).toHaveLength(args.series),
+ PANEL_LOAD,
+ );
+
+ if (isPercent(args)) {
+ await expectPercentShares(plot, args);
+ }
+
+ // The draw hook paints after the plot mounts, so the canvas is polled.
+ await waitFor(async () => {
+ const coverage = lineCoverage(plot, CHART_THRESHOLD_VALUE, THRESHOLD_COLOR);
+ if (args.thresholds && args.stack !== StackMode.percent) {
+ await expect(coverage).toBeGreaterThan(0.4);
+ } else if (!args.thresholds) {
+ await expect(coverage).toBeLessThan(0.1);
+ }
+ }, PANEL_LOAD);
+};
diff --git a/frontend/src/pages/DashboardPage/stories/panels/panelPlay/list.ts b/frontend/src/pages/DashboardPage/stories/panels/panelPlay/list.ts
new file mode 100644
index 0000000000..559e9b37ea
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/stories/panels/panelPlay/list.ts
@@ -0,0 +1,64 @@
+import { expect, userEvent, waitFor, within } from 'storybook/test';
+
+import { panelRequests } from '../__story_mockdata__/panelResponses';
+
+import { hasData, PANEL_LOAD, type PanelPlayArgs } from './args';
+
+/** Rows a List page holds. */
+const LIST_PAGE_SIZE = 25;
+
+const listRowsOnPage = (listRows: number, page: number): number =>
+ Math.max(0, Math.min(LIST_PAGE_SIZE, listRows - page * LIST_PAGE_SIZE));
+
+/**
+ * The page's rows, its first log line and the request that fetched it. With no
+ * total count the app offers Next after any full page, the last one included.
+ */
+export const expectListPage = async (
+ root: HTMLElement,
+ listRows: number,
+ page: number,
+): Promise<void> => {
+ const renderer = await within(root).findByTestId(
+ 'list-panel-renderer',
+ {},
+ PANEL_LOAD,
+ );
+ await waitFor(async () => {
+ await expect(
+ within(renderer).getByTestId('list-panel-page'),
+ ).toHaveTextContent(`Page ${page + 1}`);
+ // Skeleton rows stand in while the next page loads.
+ await expect(
+ renderer.querySelectorAll(
+ 'tbody tr.ant-table-row:not([data-row-key^="skeleton"])',
+ ),
+ ).toHaveLength(listRowsOnPage(listRows, page));
+ }, PANEL_LOAD);
+ await expect(
+ renderer.querySelector('tbody tr.ant-table-row'),
+ ).toHaveTextContent(`log line ${page * LIST_PAGE_SIZE + 1}:`);
+ await expect(within(renderer).getByTestId('list-panel-next')).toHaveAttribute(
+ 'aria-disabled',
+ String(listRowsOnPage(listRows, page) < LIST_PAGE_SIZE),
+ );
+ await expect(panelRequests().at(-1)).toMatchObject({
+ offset: page * LIST_PAGE_SIZE,
+ limit: LIST_PAGE_SIZE,
+ });
+};
+
+/** Walks Next through every page that has rows, checking each one. */
+export const walkListPages = async (
+ root: HTMLElement,
+ args: PanelPlayArgs,
+): Promise<void> => {
+ if (args.kind !== 'List' || !hasData(args)) {
+ return;
+ }
+
+ for (let page = 1; listRowsOnPage(args.listRows, page) > 0; page++) {
+ await userEvent.click(within(root).getByTestId('list-panel-next'));
+ await expectListPage(root, args.listRows, page);
+ }
+};
diff --git a/frontend/src/pages/DashboardPage/stories/panels/panelPlay/plot.ts b/frontend/src/pages/DashboardPage/stories/panels/panelPlay/plot.ts
new file mode 100644
index 0000000000..ea10b20d78
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/stories/panels/panelPlay/plot.ts
@@ -0,0 +1,73 @@
+import type { UPlotHostElement } from 'lib/uPlotV2/components/UPlotChart/utils';
+import { expect, waitFor } from 'storybook/test';
+import type uPlot from 'uplot';
+
+import { PANEL_LOAD } from './args';
+
+export const findPlot = (root: HTMLElement): uPlot | undefined =>
+ [...root.querySelectorAll<UPlotHostElement>('div')].find(
+ (node) => node.__uplot,
+ )?.__uplot;
+
+/** The live uPlot instance, once it has drawn `seriesCount` series. */
+export const waitForPlot = async (
+ root: HTMLElement,
+ seriesCount: number,
+): Promise<uPlot> => {
+ let plot: uPlot | undefined;
+ await waitFor(async () => {
+ plot = findPlot(root);
+ await expect(
+ plot?.series.slice(1).filter((series) => series.show),
+ ).toHaveLength(seriesCount);
+ }, PANEL_LOAD);
+
+ return plot as uPlot;
+};
+
+export const toRgb = (color: string): [number, number, number] => {
+ const probe = document.createElement('canvas').getContext('2d');
+ if (!probe) {
+ throw new Error('no 2d context to resolve the colour');
+ }
+ probe.fillStyle = color;
+ probe.fillRect(0, 0, 1, 1);
+ const [r, g, b] = probe.getImageData(0, 0, 1, 1).data;
+
+ return [r, g, b];
+};
+
+/**
+ * Share (0–1) of the plot row at `value` painted in `color`. Threshold lines are
+ * drawn straight onto the canvas and leave no state on the instance; the line is
+ * 2px, dashed and anti-aliased, so three rows are read and a column counts when
+ * any of them is close.
+ */
+export const lineCoverage = (
+ plot: uPlot,
+ value: number,
+ color: string,
+): number => {
+ const [r, g, b] = toRgb(color);
+ const y = Math.round(plot.valToPos(value, 'y', true));
+ const x = Math.round(plot.bbox.left);
+ const width = Math.round(plot.bbox.width);
+ const { data } = plot.ctx.getImageData(x, y - 1, width, 3);
+ let hits = 0;
+ for (let column = 0; column < width; column++) {
+ for (let row = 0; row < 3; row++) {
+ const i = (row * width + column) * 4;
+ if (
+ data[i + 3] > 0 &&
+ Math.abs(data[i] - r) < 60 &&
+ Math.abs(data[i + 1] - g) < 60 &&
+ Math.abs(data[i + 2] - b) < 60
+ ) {
+ hits += 1;
+ break;
+ }
+ }
+ }
+
+ return width > 0 ? hits / width : 0;
+};
diff --git a/frontend/src/pages/DashboardPage/stories/panels/panelPlay/scalars.ts b/frontend/src/pages/DashboardPage/stories/panels/panelPlay/scalars.ts
new file mode 100644
index 0000000000..22c1aaf104
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/stories/panels/panelPlay/scalars.ts
@@ -0,0 +1,105 @@
+import { getYAxisFormattedValue } from 'components/Graph/yAxisConfig';
+import { expect, waitFor, within } from 'storybook/test';
+
+import {
+ NUMBER_VALUE,
+ TABLE_THRESHOLD_VALUE,
+} from '../__story_mockdata__/constants';
+import {
+ serviceIndex,
+ TABLE_VALUES,
+} from '../__story_mockdata__/panelResponses';
+
+import { PANEL_LOAD, type PanelPlayArgs } from './args';
+
+export const expectPie = async (
+ root: HTMLElement,
+ args: PanelPlayArgs,
+): Promise<void> => {
+ const chart = await within(root).findByTestId('pie-chart', {}, PANEL_LOAD);
+ // The legend's icons are SVGs too; the donut is the first one.
+ const donut = chart.querySelector('svg');
+ await expect(donut?.querySelectorAll('g > path')).toHaveLength(args.series);
+ // The centre shows the slices' sum, formatted as the panel formats values.
+ const total = TABLE_VALUES(args.series).reduce((sum, value) => sum + value, 0);
+ await expect(
+ donut?.querySelector('text[text-anchor="middle"]')?.textContent,
+ ).toBe(getYAxisFormattedValue(String(total), args.unit).replace(/\s+/g, ''));
+};
+
+export const expectNumber = async (
+ root: HTMLElement,
+ args: PanelPlayArgs,
+): Promise<void> => {
+ const value = await within(root).findByTestId(
+ 'number-panel-value',
+ {},
+ PANEL_LOAD,
+ );
+ await expect(value).toHaveTextContent(String(NUMBER_VALUE));
+
+ const renderer = within(root).getByTestId('number-panel-renderer');
+ if (args.unit === 'ms') {
+ await expect(renderer).toHaveTextContent('ms');
+ }
+
+ const filled = [...renderer.querySelectorAll<HTMLElement>('div')].some(
+ (node) => node.style.backgroundColor !== '',
+ );
+ await expect(filled).toBe(args.thresholds);
+};
+
+const isPainted = (cell: HTMLElement): boolean =>
+ cell.style.backgroundColor !== '';
+
+/**
+ * Per row: group cell, the `A` column the threshold targets, then `B`. Only an
+ * `A` cell above the threshold is painted, whatever `B` holds.
+ */
+const expectTableThresholds = async (
+ rows: HTMLElement[],
+ args: PanelPlayArgs,
+): Promise<void> => {
+ const values = TABLE_VALUES(args.series);
+ for (const row of rows) {
+ const cells = [...row.querySelectorAll<HTMLElement>('td')];
+ const value = values[serviceIndex(cells[0].textContent ?? '')];
+ await expect(cells.map(isPainted)).toEqual([
+ false,
+ args.thresholds && value > TABLE_THRESHOLD_VALUE,
+ false,
+ ]);
+ }
+};
+
+export const expectTable = async (
+ root: HTMLElement,
+ args: PanelPlayArgs,
+): Promise<void> => {
+ const renderer = await within(root).findByTestId(
+ 'table-panel-renderer',
+ {},
+ PANEL_LOAD,
+ );
+ await waitFor(
+ () =>
+ expect(renderer.querySelectorAll('tbody tr.ant-table-row')).toHaveLength(
+ args.series,
+ ),
+ PANEL_LOAD,
+ );
+ await expect(within(renderer).getByText('service.name')).toBeInTheDocument();
+
+ const rows = [
+ ...renderer.querySelectorAll<HTMLElement>('tbody tr.ant-table-row'),
+ ];
+ const [, firstValue] = rows[0].querySelectorAll('td');
+ // A unit suffixes the cell (`3.8 s`, `3.71 KiB`); without one it is the bare count.
+ if (args.columnUnits && args.unit !== 'none') {
+ await expect(firstValue).toHaveTextContent(/\d\s?[a-z]+$/i);
+ } else {
+ await expect(firstValue).toHaveTextContent(/^[\d,.]+$/);
+ }
+
+ await expectTableThresholds(rows, args);
+};
diff --git a/frontend/src/pages/DashboardPage/stories/panels/panelPlay/text.ts b/frontend/src/pages/DashboardPage/stories/panels/panelPlay/text.ts
new file mode 100644
index 0000000000..a098c001b7
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/stories/panels/panelPlay/text.ts
@@ -0,0 +1,28 @@
+import { expect, within } from 'storybook/test';
+
+import { PANEL_NAME } from '../__story_mockdata__/constants';
+
+import { PANEL_LOAD, type PanelPlayArgs } from './args';
+
+export const expectText = async (
+ root: HTMLElement,
+ args: PanelPlayArgs,
+): Promise<void> => {
+ const panel = await within(root).findByTestId('text-panel', {}, PANEL_LOAD);
+ const body = within(panel);
+
+ await expect(
+ body.getByRole('heading', { name: 'Checkout runbook' }),
+ ).toBeInTheDocument();
+ await expect(body.getAllByRole('listitem')).toHaveLength(3);
+ await expect(
+ body.getByRole('link', { name: 'payments dashboard' }),
+ ).toBeInTheDocument();
+ await expect(panel.querySelector('pre code')).toHaveTextContent(
+ 'kubectl scale',
+ );
+
+ await expect(getComputedStyle(panel).textAlign).toBe(args.textAlign);
+
+ await expect(within(root).getByText(PANEL_NAME.Text)).toBeInTheDocument();
+};
diff --git a/frontend/src/storybook/msw/__story_mockdata__/queryRange.ts b/frontend/src/storybook/msw/__story_mockdata__/queryRange.ts
index 4d321faa81..0d2ed60c62 100644
--- a/frontend/src/storybook/msw/__story_mockdata__/queryRange.ts
+++ b/frontend/src/storybook/msw/__story_mockdata__/queryRange.ts
@@ -3,6 +3,11 @@
* Do not hand-edit: regenerate instead.
*/
+import {
+ Querybuildertypesv5RequestTypeDTO,
+ type QueryRangeV5200,
+ type Querybuildertypesv5TimeSeriesDTO,
+} from 'api/generated/services/sigNoz.schemas';
import type { Warning } from 'types/api';
import type { MetricRangePayloadV3 } from 'types/api/metrics/getQueryRange';
import type {
@@ -64,6 +69,7 @@ export interface ScalarTableSpec {
/** Query names the aggregation columns answer for, after the group columns. */
aggregations: Array<string | ScalarAggregationColumn>;
rows: unknown[][];
+ warning?: Warning;
}
/**
@@ -76,6 +82,7 @@ export const queryRangeV5ScalarTableResponse = ({
groupBy = [],
aggregations,
rows,
+ warning,
}: ScalarTableSpec): MetricRangePayloadV5 => {
const columns: ColumnDescriptor[] = [
...groupBy.map((name) => ({
@@ -99,6 +106,7 @@ export const queryRangeV5ScalarTableResponse = ({
return {
data: {
+ warning,
type: 'scalar',
data: { results: [{ columns, data: rows }] },
meta: {
@@ -471,3 +479,41 @@ export const queryRangeV3ForRequest = (
body.compositeQuery.panelType === 'table'
? builderTableResponse(body, options)
: builderTimeSeriesResponse(body, options);
+
+interface HeatmapResponseSpec {
+ /** Ascending bucket upper bounds; each point carries one count per bound plus the open-above overflow. */
+ buckets: number[];
+ series: Querybuildertypesv5TimeSeriesDTO[];
+ stepSeconds?: number;
+ queryName?: string;
+ warning?: Warning;
+}
+
+/**
+ * A heatmap panel's answer: the time-series tree with the bucket bounds on the
+ * aggregation's `meta`. `series: []` is the heatmap's own empty body.
+ */
+export const queryRangeV5HeatmapResponse = ({
+ buckets,
+ series,
+ stepSeconds = 60,
+ queryName = 'A',
+ warning,
+}: HeatmapResponseSpec): QueryRangeV5200 => ({
+ status: 'success',
+ data: {
+ warning,
+ type: Querybuildertypesv5RequestTypeDTO.heatmap,
+ data: {
+ results: [
+ { queryName, aggregations: [{ index: 0, meta: { buckets }, series }] },
+ ],
+ },
+ meta: {
+ rowsScanned: 0,
+ bytesScanned: 0,
+ durationMs: 0,
+ stepIntervals: { [queryName]: stepSeconds },
+ },
+ },
+});