Compare commits

...

25 Commits

Author SHA1 Message Date
Vinícius Lourenço
d68e2a6783 test(storybook): move and guard the new banner, trace and log plays 2026-11-17 18:48:45 -03:00
Vinícius Lourenço
3b2271164d test(storybook): move and guard the new settings, integration and LLM plays 2026-11-17 18:48:45 -03:00
Vinícius Lourenço
1c43540536 test(storybook): move and guard the new dashboard, alert and home plays 2026-11-17 18:48:44 -03:00
Vinícius Lourenço
daf63ec00b test(storybook): skip invite, reset and add-card plays when controls remove their target 2026-11-17 18:48:44 -03:00
Vinícius Lourenço
bff65de66f test(storybook): move the feedback plays into a play file 2026-11-17 18:48:44 -03:00
Vinícius Lourenço
66aed28c57 test(storybook): give exception filter keys their own context and data type 2026-11-17 18:48:44 -03:00
Vinícius Lourenço
90d8c88895 test(storybook): name the save and rename view stories after the action 2026-11-17 18:48:44 -03:00
Vinícius Lourenço
d3b349e2a4 test(storybook): move the remaining logs, traces and pods plays into their play files 2026-11-17 18:48:43 -03:00
Vinícius Lourenço
a7bd8288fa test(stories): add sso attribute and claim mapping expanded stories 2026-11-17 18:48:43 -03:00
Vinícius Lourenço
d0f5820962 test(storybook): collect page banner and notice stories under foundations 2026-11-17 18:48:43 -03:00
Vinícius Lourenço
d1d3fef922 test(storybook): add shell banner host stories for fixed footers, drawers and dialogs 2026-11-17 18:48:43 -03:00
Vinícius Lourenço
39e028a548 test(storybook): add shell banner stories for every license, trial and no-auth state 2026-11-17 18:48:43 -03:00
Vinícius Lourenço
3e2de8991b test(stories): add query builder add-on stories with few and many values 2026-11-17 18:48:43 -03:00
Vinícius Lourenço
a894bfd9ec test(storybook): cover the trace details thread tab 2026-11-17 18:48:42 -03:00
Vinícius Lourenço
10e32a9c8d test(storybook): cover workspace domain conflict and onboarding facing issues 2026-11-17 18:48:42 -03:00
Vinícius Lourenço
0b35a26d12 test(storybook): cover the members invite roles dropdown 2026-11-17 18:48:42 -03:00
Vinícius Lourenço
39cde200ef test(storybook): add changelog modal stories for cloud and self-hosted 2026-11-17 18:48:42 -03:00
Vinícius Lourenço
556382005b test(stories): cover the channel edit form, editable and read-only 2026-11-17 18:48:42 -03:00
Vinícius Lourenço
c9673c9bf0 test(stories): add K8s drawer depth and pods log details stories 2026-11-17 18:48:41 -03:00
Manika Malhotra
6bfe47e40f test(stories): cover the states the component migration changes 2026-11-17 18:48:41 -03:00
Pandey
f1f1b14f00 feat(tokenizer): raise default max tokens per user to 20 (#13632)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
#### Description

- Raise `tokenizer.opaque.token.max_per_user` default from 5 to 20.
- MCP clients now authenticate through regular SigNoz sessions, so a
user with a few browsers and MCP clients exceeded 5 and had their oldest
session silently evicted.
- Bump `lastObservedAt` cache expected entries to match (1000 users ×
20); `MaxCost` already fits ~21.8k entries.

Co-authored-by: Vishal Sharma <makeavish786@gmail.com>
2026-11-17 21:04:02 +00:00
Tushar Vats
6480c786be test(ruler): wait for the org alertmanager before creating webhook channels (#13625)
#### Description

- The first ruler test of a session can fail: its rule fires before the
new org's alertmanager is registered (the next 5s sync), `PutAlerts`
fails silently and the ruler only resends after 1m, past the test's 30s
wait.
- `create_webhook_notification_channel` now waits for the org
alertmanager with `wait_for_alertmanager_sync`, as the alertmanager
suite already does.

#### Additional Information

- Seen in
https://github.com/SigNoz/signoz/actions/runs/44092243746/job/134070088185
(`test_threshold_above_at_least_once`).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-11-17 19:07:56 +00:00
Abhi kumar
313de0a00c feat(dashboards): add plugin schema for top list panel (#13084)
#### Description

- Adds `signoz/TopListPanel`: ranks the top N groups by one value as
horizontal bars. Spec mirrors `NumberPanelSpec` (visualization,
formatting, comparison thresholds) plus `appearance` (rank, share, bar
color).
- Allowed query kinds: builder, composite, formula, trace operator and
ClickHouse SQL. PromQL is rejected, including inside a composite.
- Frontend panel and regenerated Orval types follow in #13086.
- Artifact:
https://claude.ai/artifact/QqtPhnEJQsksa3reCWV12d?sk=S0XuyygvJdC1QYsz7grKvA

---------

Co-authored-by: Naman Verma <naman.verma@signoz.io>
2026-11-17 18:18:55 +00:00
Swapnil Nakade
e972f26992 feat(serviceaccount): add resource def to update my service account r… (#13623)
#### Description
- add a resource def to `PUT /api/v1/service_accounts/me`, taking the
service account id from the caller's claims
- why? so the auditor records a service account renaming itself; it
wrote no audit event before
- a self update and an admin update of the same account record the same
resource id

#### Issues closed by this PR
contributes to https://github.com/SigNoz/keystone-pod/issues/7
2026-11-17 14:42:01 +00:00
Vinicius Lourenço
42e84652bf fix(storybook): skip the 5s animation wait on stories with scrollbars (#13492)
#### Description

- OverlayScrollbars animates its scrollbars with `ScrollTimeline`, and
those animations never finish. Storybook waits up to 5s for animations
after every story, so each story with a scroll pane took 5s longer to
capture. `preview-head.html` now removes `ScrollTimeline`, and
OverlayScrollbars falls back to script.
- The `sbshot-visual-diff` skill now says to capture from `pnpm
storybook:build` and to turn off a11y checks during capture. Together
the dev server and the checks added 7 to 12s per story.

#### Additional Information

- CI time does not change: the test runner already skips the animation
wait.
2026-11-17 14:39:03 +00:00
177 changed files with 9417 additions and 982 deletions

View File

@@ -18,7 +18,9 @@ tag <diff> <tag> <story-id>... # what the reviewer should look at
export <diff> --out <dir> # a static site, hostable
```
`<storybook>` is a running dev server (`http://localhost:6006`), a build directory holding `index.json`, or a project directory with `.storybook/`. The frontend has **no `build-storybook` script**, only `storybook dev -p 6006`, so point `capture` at a dev server.
`<storybook>` is a running dev server (`http://localhost:6006`), a build directory holding `index.json`, or a project directory with `.storybook/`. **Capture from a build**: `pnpm storybook:build` in `frontend` (about 2 minutes) writes `storybook-static/`. A dev server serves the preview module by module, which adds 5 to 10 seconds to every story and, with several stories at once, ends in `page.goto: Timeout 30000ms exceeded` retries.
Pass `--globals 'a11y.manual:!true'` to every `capture`. The a11y addon otherwise runs axe after every story, about 2 seconds each, and nothing it does shows in a shot.
## Cover the change with stories first
@@ -30,7 +32,7 @@ Then confirm it worked: the two runs' story counts should differ by exactly the
## Rules that are not optional
**One freshly started Storybook per ref.** Never start one server and switch git branches under it. Vite's HMR reloads the page, but some modules do not re-initialise, so the shot differs silently from a clean boot and the difference looks like a real change. Settle time does not fix this and is not the variable. Use one worktree and one port per ref, and stop each server before the next.
**One freshly started Storybook per ref.** Never start one server and switch git branches under it. Vite's HMR reloads the page, but some modules do not re-initialise, so the shot differs silently from a clean boot and the difference looks like a real change. Settle time does not fix this and is not the variable. Use one worktree and one port per ref, and stop each server before the next. A build made in each ref's worktree has none of this.
**Capture both themes: `--theme dark,light`.** Without it sbshot shoots the story's own default and everything lands in a single `default/` folder, so every regression in the other theme is invisible. Themes double the shot count, so scope with `--stories` or `--title`, never by dropping a theme.

View File

@@ -364,7 +364,7 @@ tokenizer:
interval: 1h
token:
# The maximum number of tokens a user can have. This limits the number of concurrent sessions a user can have.
max_per_user: 5
max_per_user: 20
##################### Flagger #####################
flagger:

View File

@@ -5527,6 +5527,7 @@ components:
signoz/TablePanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTablePanelSpec'
signoz/TextPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpec'
signoz/TimeSeriesPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpec'
signoz/TopListPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec'
propertyName: kind
oneOf:
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpec'
@@ -5541,6 +5542,7 @@ components:
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec'
type: object
DashboardtypesPanelPluginKind:
enum:
@@ -5556,6 +5558,7 @@ components:
- signoz/HeatmapPanel
- signoz/ScatterPlotPanel
- signoz/GeoMapPanel
- signoz/TopListPanel
type: string
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec:
properties:
@@ -5737,6 +5740,21 @@ components:
- kind
- spec
type: object
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec:
properties:
kind:
description: The panel kind.
enum:
- signoz/TopListPanel
type: string
spec:
allOf:
- $ref: '#/components/schemas/DashboardtypesTopListPanelSpec'
description: The options for this panel kind. {} accepts every default.
required:
- kind
- spec
type: object
DashboardtypesPanelSpec:
properties:
display:
@@ -6499,6 +6517,43 @@ components:
last_6_hr, last_1_day, last_3_days, last_1_week or last_1_month pin a
fixed window.'
type: object
DashboardtypesTopListAppearance:
properties:
barColor:
description: Hex color of every bar; a matching background threshold overrides
it.
type: string
showRank:
description: Numbers each row by its position in the list.
type: boolean
showShare:
description: Shows each row's share of the listed rows' total.
type: boolean
required:
- barColor
type: object
DashboardtypesTopListPanelSpec:
properties:
appearance:
allOf:
- $ref: '#/components/schemas/DashboardtypesTopListAppearance'
description: Rank, share and bar color options.
formatting:
allOf:
- $ref: '#/components/schemas/DashboardtypesPanelFormatting'
description: Unit and decimal precision of the values.
thresholds:
description: Rules that recolor a row when its value compares to a threshold
as specified.
items:
$ref: '#/components/schemas/DashboardtypesComparisonThreshold'
nullable: true
type: array
visualization:
allOf:
- $ref: '#/components/schemas/DashboardtypesBasicVisualization'
description: The time range the rows are computed over.
type: object
DashboardtypesUpdatableDashboardV2:
properties:
image:

View File

@@ -34,6 +34,12 @@
pylon: { enabled: false, appId: '', identitySecret: '' },
},
};
// OverlayScrollbars drives its handles with scroll-driven animations when the
// browser has `ScrollTimeline`. Those never finish, and Storybook waits up to
// 5s for running animations after every `play`, so each story with a scroller
// would pay the full 5s. Without it the handles are positioned from script.
delete window.ScrollTimeline;
</script>
<script>

View File

@@ -7190,6 +7190,63 @@ export interface DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDa
spec: DashboardtypesGeoMapPanelSpecDTO;
}
/**
* The panel kind.
*/
export enum DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTOKind {
'signoz/TopListPanel' = 'signoz/TopListPanel',
}
export interface DashboardtypesTopListAppearanceDTO {
/**
* @type string
* @description Hex color of every bar; a matching background threshold overrides it.
*/
barColor: string;
/**
* @type boolean
* @description Numbers each row by its position in the list.
*/
showRank?: boolean;
/**
* @type boolean
* @description Shows each row's share of the listed rows' total.
*/
showShare?: boolean;
}
export interface DashboardtypesTopListPanelSpecDTO {
/**
* @description Rank, share and bar color options.
*/
appearance?: DashboardtypesTopListAppearanceDTO;
/**
* @description Unit and decimal precision of the values.
*/
formatting?: DashboardtypesPanelFormattingDTO;
/**
* @type array,null
* @description Rules that recolor a row when its value compares to a threshold as specified.
*/
thresholds?: DashboardtypesComparisonThresholdDTO[] | null;
/**
* @description The time range the rows are computed over.
*/
visualization?: DashboardtypesBasicVisualizationDTO;
}
export interface DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTO {
/**
* @enum signoz/TopListPanel
* @type string
* @description The panel kind.
*/
kind: DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTOKind;
/**
* @description The options for this panel kind. {} accepts every default.
*/
spec: DashboardtypesTopListPanelSpecDTO;
}
export type DashboardtypesPanelPluginDTO =
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpecDTO
@@ -7202,7 +7259,8 @@ export type DashboardtypesPanelPluginDTO =
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTO;
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTO;
export enum Querybuildertypesv5RequestTypeDTO {
scalar = 'scalar',
@@ -8490,6 +8548,7 @@ export enum DashboardtypesPanelPluginKindDTO {
'signoz/HeatmapPanel' = 'signoz/HeatmapPanel',
'signoz/ScatterPlotPanel' = 'signoz/ScatterPlotPanel',
'signoz/GeoMapPanel' = 'signoz/GeoMapPanel',
'signoz/TopListPanel' = 'signoz/TopListPanel',
}
/**
* The RFC 6902 operations, applied in order against the dashboard's postable shape.

View File

@@ -55,6 +55,7 @@ export function mapPanelTypeToRequestType(panelType: PANEL_TYPES): RequestType {
case PANEL_TYPES.PIE:
case PANEL_TYPES.VALUE:
case PANEL_TYPES.GEO_MAP:
case PANEL_TYPES.TOP_LIST:
return 'scalar';
case PANEL_TYPES.TRACE:
return 'trace';
@@ -279,7 +280,8 @@ export function createAggregation(
panelType === PANEL_TYPES.SCATTER ||
panelType === PANEL_TYPES.PIE ||
panelType === PANEL_TYPES.VALUE ||
panelType === PANEL_TYPES.GEO_MAP);
panelType === PANEL_TYPES.GEO_MAP ||
panelType === PANEL_TYPES.TOP_LIST);
if (queryData.dataSource === DataSource.METRICS) {
return [

View File

@@ -0,0 +1,51 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { createAppContextMock } from 'tests/fixtures/appContextMock';
import { LicensePlatform } from 'types/api/licensesV3/getActive';
import { USER_ROLES } from 'types/roles';
import { fn } from 'storybook/test';
import { storyChangelog } from './__story_mockdata__/changelog';
import {
showsCloudChangelog,
showsSelfHostedChangelog,
} from './__story_mockdata__/changelogModal.play';
import ChangelogModal from '../ChangelogModal';
const { activeLicense } = createAppContextMock(USER_ROLES.ADMIN);
/** `AppLayout` opens it one second after load, for a version the user has not seen. */
const meta = {
title: 'Components/Changelog Modal',
component: ChangelogModal,
tags: ['play'],
parameters: { signoz: {} },
args: {
changelog: storyChangelog,
onClose: fn(),
},
} satisfies Meta<typeof ChangelogModal>;
export default meta;
type Story = StoryObj<typeof meta>;
/** Cloud workspaces update on their own, so the footer has no update actions. */
export const Cloud: Story = {
play: showsCloudChangelog,
};
/** Self-hosted workspaces get "Skip for now" and "Update my workspace". */
export const SelfHosted: Story = {
parameters: {
signoz: {
appContext: {
activeLicense: activeLicense && {
...activeLicense,
platform: LicensePlatform.SELF_HOSTED,
},
},
},
},
play: showsSelfHostedChangelog,
};

View File

@@ -0,0 +1,67 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import {
ChangelogSchema,
DeploymentType,
} from 'types/api/changelog/getChangelogByVersion';
const TIMESTAMP = '2026-11-03T12:00:00Z';
function feature(
id: number,
title: string,
description: string,
): ChangelogSchema['features'][number] {
return {
id,
documentId: `feature-${id}`,
title,
description,
media: null,
sort_order: id,
createdAt: TIMESTAMP,
updatedAt: TIMESTAMP,
publishedAt: TIMESTAMP,
deployment_type: DeploymentType.ALL,
};
}
/** Long enough to scroll, so the "Scroll for more" button shows. */
export const storyChangelog: ChangelogSchema = {
id: 1,
documentId: 'changelog-v0.99.0',
version: 'v0.99.0',
release_date: '2026-11-03',
createdAt: TIMESTAMP,
updatedAt: TIMESTAMP,
publishedAt: TIMESTAMP,
features: [
feature(
1,
'Dashboard sections',
'Group panels into **sections** you can collapse, rename and drag. Existing dashboards move into a single section the first time you edit them.',
),
feature(
2,
'Service accounts',
'Create service accounts with their own API keys and roles. Keys can expire, and you can revoke them without touching the account. See the [docs](https://signoz.io/docs/) for the API.',
),
feature(
3,
'Faster log search',
'Full-text search over log bodies now uses a token index:\n\n- queries over a day of logs return up to 4x faster\n- `has()` and `hasToken()` use the same index\n- the old behaviour stays behind a setting for a release',
),
feature(
4,
'Routing policies',
'Send an alert to a channel based on its labels instead of picking the channel in every rule. Policies are evaluated in order and the first match wins.',
),
],
bug_fixes:
'- Fixed the time picker losing the selected range after a refresh.\n- Fixed trace waterfall rows overlapping when a span name wraps.\n- Fixed CSV export dropping columns with dots in their names.',
maintenance:
'- Upgraded the OpenTelemetry collector to the latest release.\n- Reduced the memory used by the query service on large dashboards.',
};

View File

@@ -0,0 +1,39 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, screen, waitFor } from 'storybook/test';
import { isCloudShell } from '@/storybook/globals/appShellMocks';
const TITLE = /What’s New ⎯ Changelog : November 3, 2026/;
interface PlayContext {
args: Record<string, unknown>;
}
export const showsCloudChangelog = async ({
args,
}: PlayContext): Promise<void> => {
await screen.findByRole('dialog', { name: TITLE });
// The License and Banner controls decide the platform, which decides the footer.
if (isCloudShell(args)) {
await expect(
screen.queryByRole('button', { name: /Skip for now/ }),
).not.toBeInTheDocument();
return;
}
await screen.findByRole('button', { name: /Skip for now/ });
};
export const showsSelfHostedChangelog = async (): Promise<void> => {
await screen.findByRole('dialog', { name: TITLE });
await waitFor(() =>
expect(
screen.getByRole('button', { name: /Update my workspace/ }),
).toBeVisible(),
);
};

View File

@@ -12,7 +12,13 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
import { get, isEmpty } from 'lodash-es';
import { ChevronUp } from '@signozhq/icons';
import { Querybuildertypesv5BucketOptionsDTO } from 'api/generated/services/sigNoz.schemas';
import {
Querybuildertypesv5BucketOptionsDTO,
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
Querybuildertypesv5QueryEnvelopeFormulaDTOType,
Querybuildertypesv5QueryEnvelopeTraceOperatorDTOType,
} from 'api/generated/services/sigNoz.schemas';
import { isLoneBuilderQuery } from 'lib/query/builderEnvelope';
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import { MetricAggregation } from 'types/api/v5/queryRange';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
@@ -147,10 +153,34 @@ function QueryAddOns({
[resolvedFields],
);
// A panel's default limit applies only to a lone query: per-query limits can keep
// different groups and break a formula's join.
const isLoneQuery = useMemo(
() =>
isLoneBuilderQuery([
...(currentQuery.builder?.queryData ?? [query]).map((data) => ({
type:
data.builderQueryType ??
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
})),
...(currentQuery.builder?.queryFormulas ?? []).map(() => ({
type: Querybuildertypesv5QueryEnvelopeFormulaDTOType.builder_formula,
})),
...(currentQuery.builder?.queryTraceOperator ?? []).map(() => ({
type:
Querybuildertypesv5QueryEnvelopeTraceOperatorDTOType.builder_trace_operator,
})),
]),
[currentQuery.builder, query],
);
const placeholderOf = useCallback(
(key: InputAddOnField): string =>
resolvedFields.get(key)?.placeholder ?? ADD_ON_DEFINITIONS[key].placeholder,
[resolvedFields],
(key === QueryBuilderField.Limit && !isLoneQuery
? undefined
: resolvedFields.get(key)?.placeholder) ??
ADD_ON_DEFINITIONS[key].placeholder,
[resolvedFields, isLoneQuery],
);
const isDisabled = useCallback(

View File

@@ -67,7 +67,9 @@ function QueryAggregationOptions({
onChange={onChange}
queryData={queryData}
maxAggregations={
panelType === PANEL_TYPES.VALUE || panelType === PANEL_TYPES.PIE
panelType === PANEL_TYPES.VALUE ||
panelType === PANEL_TYPES.PIE ||
panelType === PANEL_TYPES.TOP_LIST
? 1
: undefined
}

View File

@@ -7,6 +7,7 @@ const SCALAR_PANEL_TYPES: ReadonlySet<string> = new Set<string>([
PANEL_TYPES.PIE,
PANEL_TYPES.VALUE,
PANEL_TYPES.GEO_MAP,
PANEL_TYPES.TOP_LIST,
]);
export function isScalarPanelType(panelType?: string | null): boolean {

View File

@@ -15,6 +15,9 @@ import QueryAddOns from '../QueryV2/QueryAddOns/QueryAddOns';
// Mocks: only what is required for this component to render and for us to assert handler calls
const mockHandleChangeQueryData = jest.fn();
const mockHandleSetQueryData = jest.fn();
let mockCurrentQuery: { unit: string | undefined; builder?: unknown } = {
unit: undefined,
};
jest.mock('hooks/queryBuilder/useQueryBuilderOperations', () => ({
useQueryOperations: (): {
@@ -27,10 +30,10 @@ jest.mock('hooks/queryBuilder/useQueryBuilderOperations', () => ({
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
useQueryBuilder: (): {
handleSetQueryData: typeof mockHandleSetQueryData;
currentQuery: { unit: string | undefined };
currentQuery: typeof mockCurrentQuery;
} => ({
handleSetQueryData: mockHandleSetQueryData,
currentQuery: { unit: undefined },
currentQuery: mockCurrentQuery,
}),
}));
@@ -229,6 +232,77 @@ describe('QueryAddOns', () => {
);
});
describe('a pinned limit with a default', () => {
const renderPinnedLimit = (): void => {
render(
<QueryAddOns
query={baseQuery()}
version="v5"
isRawQuery={false}
showReduceTo={false}
panelType={PANEL_TYPES.TOP_LIST}
index={0}
fieldsConfig={{
[QueryBuilderField.Limit]: {
state: 'pinned',
placeholder: 'Default 10',
},
}}
isForTraceOperator={false}
/>,
);
};
afterEach(() => {
mockCurrentQuery = { unit: undefined };
});
it('is open with its default as the placeholder', () => {
renderPinnedLimit();
expect(screen.getByTestId('input-Limit')).toHaveAttribute(
'placeholder',
'Default 10',
);
});
it('drops the default for an AI query, which the request leaves unlimited', () => {
mockCurrentQuery = {
unit: undefined,
builder: {
queryData: [{ ...baseQuery(), builderQueryType: 'builder_ai_query' }],
queryFormulas: [],
queryTraceOperator: [],
},
};
renderPinnedLimit();
expect(screen.getByTestId('input-Limit')).toHaveAttribute(
'placeholder',
'Enter limit',
);
});
it('drops the default once a formula joins the query', () => {
mockCurrentQuery = {
unit: undefined,
builder: {
queryData: [baseQuery()],
queryFormulas: [{ expression: 'A * 2' }],
queryTraceOperator: [],
},
};
renderPinnedLimit();
expect(screen.getByTestId('input-Limit')).toHaveAttribute(
'placeholder',
'Enter limit',
);
});
});
it('auto-opens Order By and Limit when present in query', () => {
const query = baseQuery({
orderBy: [{ columnName: 'duration', order: 'desc' }],

View File

@@ -0,0 +1,77 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { withCanvas } from '@/storybook/decorators/withCanvas';
import { QueryBuilderV2 } from '../QueryBuilderV2';
import {
metricsFewGroupBy,
metricsManyGroupBy,
tracesFewAddOns,
tracesManyAddOns,
} from './__story_mockdata__/queryBuilderAddOns';
import {
expectMetricsGroupBy,
expectTracesAddOnsOpen,
} from './__story_mockdata__/queryBuilderAddOns.play';
import {
DEFAULT_ARGS,
PANEL_EDITOR_ARGS,
PANEL_EDITOR_PATH,
routeWith,
} from './QueryBuilderV2.stories.mocks';
import QueryProbe from './QueryProbe';
/**
* The add-ons a query opens with values already set: group by, having, order
* by, limit and legend format side by side, with one value each and with
* enough to wrap.
*/
const meta = {
title: 'Components/Query Builder/Add-ons',
component: QueryBuilderV2,
tags: ['play'],
decorators: [withCanvas({ maxWidth: 1100 })],
args: { ...DEFAULT_ARGS, ...PANEL_EDITOR_ARGS },
render: (args): JSX.Element => (
<>
<QueryBuilderV2 {...args} />
<QueryProbe />
</>
),
} satisfies Meta<typeof QueryBuilderV2>;
export default meta;
type Story = StoryObj<typeof meta>;
/** Traces with every add-on open, one value in each. */
export const FewValues: Story = {
parameters: {
signoz: { route: routeWith(PANEL_EDITOR_PATH, tracesFewAddOns) },
},
play: expectTracesAddOnsOpen(1),
};
/** Traces with every add-on open and filled past one line. */
export const ManyValues: Story = {
parameters: {
signoz: { route: routeWith(PANEL_EDITOR_PATH, tracesManyAddOns) },
},
play: expectTracesAddOnsOpen(9),
};
/** A histogram grouped by one key, beside the aggregation selects. */
export const MetricsFewGroupBy: Story = {
parameters: {
signoz: { route: routeWith(PANEL_EDITOR_PATH, metricsFewGroupBy) },
},
play: expectMetricsGroupBy(1),
};
/** A histogram grouped by enough keys to wrap the group-by select. */
export const MetricsManyGroupBy: Story = {
parameters: {
signoz: { route: routeWith(PANEL_EDITOR_PATH, metricsManyGroupBy) },
},
play: expectMetricsGroupBy(7),
};

View File

@@ -8,16 +8,50 @@ import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { TelemetrytypesSignalDTO } from 'api/generated/services/sigNoz.schemas';
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import {
BaseAutocompleteData,
DataTypes,
} from 'types/api/queryBuilder/queryAutocompleteResponse';
import { IBuilderQuery, Query } from 'types/api/queryBuilder/queryBuilderData';
import type { QueryBuilderV2 } from '../QueryBuilderV2';
import {
mergeQueryBuilderFieldsConfig,
RAW_QUERY_FIELDS,
resolveQueryBuilderFields,
} from '../queryBuilderFields.utils';
import { BASE_ADD_ONS } from '../QueryV2/QueryAddOns/constants';
type QueryBuilderProps = Parameters<typeof QueryBuilderV2>[0];
export type QueryBuilderProps = Parameters<typeof QueryBuilderV2>[0];
/** The builder's provider reads its starting query from the URL, as every host seeds it. */
export const routeWith = (path: string, query: Query): string =>
`${path}?compositeQuery=${encodeURIComponent(JSON.stringify(query))}`;
/** `query` with its first builder query's fields replaced by `fields`. */
export const queryWith = (
query: Query,
fields: Partial<IBuilderQuery>,
): Query => ({
...query,
builder: {
...query.builder,
queryData: [{ ...query.builder.queryData[0], ...fields }],
},
});
/** A group-by key as the builder stores it: `id` is the select's option value. */
export const groupByKey = (
key: string,
type = 'tag',
dataType: DataTypes = DataTypes.String,
): BaseAutocompleteData => ({
key,
dataType,
type,
id: `${key}--${dataType}--${type}`,
});
export const meterQuery: Query = {
...initialQueriesMap.metrics,
builder: {
@@ -132,3 +166,30 @@ export const DEFAULT_ARGS: Partial<QueryBuilderProps> = {
panelType: PANEL_TYPES.TIME_SERIES,
version: 'v3',
};
/**
* A where-clause view has no add-ons and a Value panel offers the legend
* alone; a raw query or a fields config hides or disables the rest.
*/
export const offersEveryAddOn = (args: Partial<QueryBuilderProps>): boolean => {
if (args.showOnlyWhereClause || args.panelType === PANEL_TYPES.VALUE) {
return false;
}
const resolved = resolveQueryBuilderFields(
BASE_ADD_ONS.map((addOn) => addOn.key),
mergeQueryBuilderFieldsConfig(
args.isRawQuery ? RAW_QUERY_FIELDS : undefined,
args.fieldsConfig,
),
);
return [...resolved.values()].every(
({ hidden, disabled }) => !hidden && !disabled,
);
};
/** A metrics query's group by sits in the aggregation row, which a where-clause view drops. */
export const showsAggregationGroupBy = (
args: Partial<QueryBuilderProps>,
): boolean => !args.showOnlyWhereClause;

View File

@@ -0,0 +1,62 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, waitFor, within } from 'storybook/test';
import {
offersEveryAddOn,
type QueryBuilderProps,
showsAggregationGroupBy,
} from '../QueryBuilderV2.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: Partial<QueryBuilderProps>;
}
const TRACES_ADD_ONS = [
'group-by-content',
'having-content',
'order-by-content',
'limit-content',
'legend-format-content',
];
const groupByTags = (scope: HTMLElement): string[] =>
Array.from(
within(scope)
.getByTestId('group-by')
.querySelectorAll('.ant-select-selection-item'),
).map((tag) => tag.textContent ?? '');
/** Every add-on the seeded query fills opens on mount, group by with all its keys. */
export const expectTracesAddOnsOpen =
(groupByCount: number) =>
async ({ canvasElement, args }: PlayContext): Promise<void> => {
if (!offersEveryAddOn(args)) {
return;
}
const query = within(canvasElement).getByTestId('query-A');
await waitFor(async () => {
for (const testId of TRACES_ADD_ONS) {
await expect(within(query).getByTestId(testId)).toBeVisible();
}
});
const groupBy = within(query).getByTestId('group-by-content');
await waitFor(() => expect(groupByTags(groupBy)).toHaveLength(groupByCount));
};
/** The aggregation row's group by shows every seeded key. */
export const expectMetricsGroupBy =
(groupByCount: number) =>
async ({ canvasElement, args }: PlayContext): Promise<void> => {
if (!showsAggregationGroupBy(args)) {
return;
}
const query = within(canvasElement).getByTestId('query-A');
await waitFor(() => expect(groupByTags(query)).toHaveLength(groupByCount));
};

View File

@@ -0,0 +1,73 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { initialQueriesMap } from 'constants/queryBuilder';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { groupByKey, queryWith } from '../QueryBuilderV2.stories.mocks';
/** Every traces add-on holding one short value. */
export const tracesFewAddOns: Query = queryWith(initialQueriesMap.traces, {
groupBy: [groupByKey('service.name', 'resource')],
having: { expression: 'count() > 10' },
orderBy: [{ columnName: 'count()', order: 'desc' }],
limit: 10,
legend: '{{service.name}}',
});
/** Every traces add-on filled past one line, so group by and order by wrap. */
export const tracesManyAddOns: Query = queryWith(initialQueriesMap.traces, {
groupBy: [
groupByKey('service.name', 'resource'),
groupByKey('deployment.environment', 'resource'),
groupByKey('host.name', 'resource'),
groupByKey('name', ''),
groupByKey('http.method'),
groupByKey('http.route'),
groupByKey('response_status_code'),
groupByKey('rpc.method'),
groupByKey('hasError', '', DataTypes.bool),
],
having: {
expression: 'count() > 10 AND count() < 5000 AND count() != 250',
},
orderBy: [
{ columnName: 'count()', order: 'desc' },
{ columnName: 'service.name', order: 'asc' },
{ columnName: 'http.route', order: 'asc' },
],
limit: 100,
legend:
'{{service.name}} {{deployment.environment}} {{http.method}} {{http.route}}',
});
const histogramWith = (keys: string[]): Query =>
queryWith(initialQueriesMap.metrics, {
aggregations: [
{
metricName: 'signoz_latency_bucket',
temporality: '',
timeAggregation: '',
spaceAggregation: 'p90',
reduceTo: undefined,
},
],
groupBy: keys.map((key) => groupByKey(key)),
});
/** A histogram grouped by one key in the aggregation row. */
export const metricsFewGroupBy: Query = histogramWith(['service_name']);
/** A histogram grouped by enough keys to wrap the aggregation row's select. */
export const metricsManyGroupBy: Query = histogramWith([
'service_name',
'operation',
'status_code',
'le',
'resource_deployment.environment',
'resource_host.name',
'resource_k8s.cluster.name',
]);

View File

@@ -98,6 +98,15 @@ export const noSavedFiltersHandler = rest.get(
),
);
export const noSavedTracesFiltersHandler = rest.get(
'http://localhost/api/v2/quick_filters/traces',
(_req, res, ctx) =>
res(
ctx.status(200),
ctx.json(quickFiltersResponse(QuickfiltertypesSourceDTO.traces, [])),
),
);
export const loadingFiltersHandlers = [
rest.get('http://localhost/api/v2/quick_filters/logs', (_req, res, ctx) =>
res(ctx.delay('infinite')),

View File

@@ -1,6 +1,7 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import type { ComponentProps, ComponentType } from 'react';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { withCanvas } from '@/storybook/decorators/withCanvas';
import type { GlobalMockArgs } from '@/storybook/globals';
@@ -16,8 +17,9 @@ import {
queryBuilder,
selectedServiceQueryBuilder,
noSavedFiltersHandler,
noSavedTracesFiltersHandler,
} from './QuickFilters.stories.mocks';
import { QuickFiltersSource } from '../types';
import { FiltersType, QuickFiltersSource } from '../types';
const meta = {
title: 'Components/Quick Filters',
@@ -110,6 +112,29 @@ export const SelectedExpandedCheckbox: Story = {
},
};
/** The duration min/max row, which a checkbox-only config never reaches. */
export const DurationFilter: Story = {
args: {
quickFilterSource: QuickFiltersSource.TRACES_EXPLORER,
config: [
...checkboxConfig,
{
attributeKey: {
dataType: DataTypes.Float64,
key: 'duration_nano',
type: '',
},
defaultOpen: true,
title: 'Duration',
type: FiltersType.DURATION,
},
],
},
parameters: {
msw: { handlers: [noSavedTracesFiltersHandler, ...handlers] },
},
};
/**
* Every tooltip the panel renders, held open: the reveal on each truncated
* filter value. Nothing bounds those values, so the panel is answered with

View File

@@ -35,6 +35,7 @@ export const getComponentForPanelType = (
// V2-only kind; it renders through the V2 panel registry.
[PANEL_TYPES.HEATMAP]: null,
[PANEL_TYPES.GEO_MAP]: null,
[PANEL_TYPES.TOP_LIST]: null,
// Dashboards v2 renders this kind; nothing reaches the V1 chart map for it.
[PANEL_TYPES.TEXT]: null,
[PANEL_TYPES.SCATTER]: null,

View File

@@ -341,6 +341,7 @@ export enum PANEL_TYPES {
HISTOGRAM = 'histogram',
HEATMAP = 'heatmap',
GEO_MAP = 'geo_map',
TOP_LIST = 'top_list',
TEXT = 'text',
EMPTY_WIDGET = 'EMPTY_WIDGET',
}

View File

@@ -16,13 +16,42 @@ import {
} from './K8sBaseDetails.stories.mocks';
import type { K8sBaseDetailsProps } from './types';
import {
DrawerHistoryEntry,
getDrawerHistoryDepth,
pushDrawerHistory,
resetDrawerHistory,
useDrawerHistoryStore,
} from './useDrawerHistoryStore';
type DrawerArgs = PageStoryArgs<typeof drawerMocks> &
K8sBaseDetailsProps<unknown>;
K8sBaseDetailsProps<unknown> & { earlierSteps?: number };
const TRAIL: DrawerHistoryEntry[] = [
{
category: InfraMonitoringEntity.CLUSTERS,
label: 'mgmt',
queryKeyPrefix: 'cluster',
},
{
category: InfraMonitoringEntity.NAMESPACES,
label: 'generator',
queryKeyPrefix: 'namespace',
},
{
category: InfraMonitoringEntity.DEPLOYMENTS,
label: 'app-demo-loadgenerator',
queryKeyPrefix: 'deployment',
},
{
category: InfraMonitoringEntity.NODES,
label: NODE_NAME,
queryKeyPrefix: 'node',
},
].map(({ category, label, queryKeyPrefix }) => ({
params: { selectedItem: label, category },
category,
label,
entity: { name: label },
queryKeyPrefix,
}));
const route = `/infrastructure-monitoring/kubernetes?${INFRA_MONITORING_K8S_PARAMS_KEYS.CATEGORY}=pods&${INFRA_MONITORING_K8S_PARAMS_KEYS.SELECTED_ITEM}=${POD_UID}`;
@@ -33,19 +62,13 @@ const meta = {
decorators: [
(Story, context): JSX.Element => {
// The back control appears only for a resource opened from another
const depth = getDrawerHistoryDepth();
if (context.args.openedFromANode && depth === 0) {
pushDrawerHistory({
params: { selectedItem: NODE_NAME, category: InfraMonitoringEntity.NODES },
category: InfraMonitoringEntity.NODES,
label: NODE_NAME,
entity: { nodeName: NODE_NAME },
queryKeyPrefix: 'node',
const steps =
context.args.earlierSteps ?? (context.args.openedFromANode ? 1 : 0);
if (getDrawerHistoryDepth() !== steps) {
useDrawerHistoryStore.setState({
entries: TRAIL.slice(TRAIL.length - steps),
});
}
if (!context.args.openedFromANode && depth > 0) {
resetDrawerHistory();
}
return <Story />;
},
@@ -60,3 +83,19 @@ type Story = StoryObj<DrawerArgs>;
export const Default: Story = {
args: { ...podEntityConfig.details } as Partial<DrawerArgs> as DrawerArgs,
};
/** A pod drilled through a cluster, namespace, deployment and node, so the back control names the node. */
export const DeepTrail: Story = {
args: {
...podEntityConfig.details,
earlierSteps: 4,
} as Partial<DrawerArgs> as DrawerArgs,
};
/** A pod opened from the list, so the header shows the close control in place of back. */
export const OpenedFromTheList: Story = {
args: {
...podEntityConfig.details,
openedFromANode: false,
} as Partial<DrawerArgs> as DrawerArgs,
};

View File

@@ -33,6 +33,7 @@ export const PANEL_TYPES_VS_FULL_VIEW_TABLE: PanelTypeAndGraphManagerVisibilityP
HISTOGRAM: false,
HEATMAP: false,
GEO_MAP: false,
TOP_LIST: false,
TEXT: false,
EMPTY_WIDGET: false,
};

View File

@@ -25,4 +25,5 @@ export const PanelTypeVsPanelWrapper = {
// V2-only kind; it renders through the V2 panel registry.
[PANEL_TYPES.HEATMAP]: null,
[PANEL_TYPES.GEO_MAP]: null,
[PANEL_TYPES.TOP_LIST]: null,
};

View File

@@ -32,6 +32,17 @@ export function isAIBuilderEnvelope(
);
}
/** Exactly one `builder_query`: the only request a panel's default row limit applies to. */
export function isLoneBuilderQuery<T extends { type: string }>(
envelopes: T[],
): envelopes is [Extract<T, Querybuildertypesv5QueryEnvelopeBuilderDTO>] {
return (
envelopes.length === 1 &&
envelopes[0].type ===
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query
);
}
const BUILDER_PLUGIN_KINDS: string[] = [
DashboardtypesQueryPluginKindDTO['signoz/BuilderQuery'],
DashboardtypesQueryPluginKindDTO['signoz/AIBuilderQuery'],

View File

@@ -18,6 +18,7 @@ export type PartialPanelTypes = {
[PANEL_TYPES.HISTOGRAM]: 'histogram';
[PANEL_TYPES.HEATMAP]: 'heatmap';
[PANEL_TYPES.GEO_MAP]: 'geo_map';
[PANEL_TYPES.TOP_LIST]: 'top_list';
};
export type BuilderField = keyof IBuilderQuery;
@@ -154,6 +155,7 @@ export const panelTypeDataSourceFormValuesMap: Record<
[PANEL_TYPES.PIE]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.SCATTER]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.GEO_MAP]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.TOP_LIST]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.VALUE]: bySource(SINGLE_VALUE, SINGLE_VALUE_METRICS),
[PANEL_TYPES.LIST]: bySource(RAW_ROWS, RAW_ROWS_METRICS),
};

View File

@@ -1,14 +1,9 @@
import { useMemo } from 'react';
import cx from 'classnames';
import { Pin } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Typography } from '@signozhq/ui/typography';
import { ScatterTooltipProps } from '../types';
import TooltipCard from './components/TooltipCard/TooltipCard';
import { buildChannelRows, resolveHoveredPoint } from './scatterTooltipContent';
import Styles from './ScatterTooltip.module.scss';
/** Own component: the shared Tooltip lists one row per series at a shared x. */
export default function ScatterTooltip({
uPlotInstance,
@@ -50,90 +45,18 @@ export default function ScatterTooltip({
}
return (
<div
className={cx(Styles.container, { [Styles.pinned]: isPinned })}
data-pinned={isPinned}
data-testid="scatter-tooltip"
>
<div className={Styles.header}>
<span
className={Styles.marker}
style={{
backgroundColor: hoveredPoint.color,
borderColor: hoveredPoint.color,
}}
/>
<Typography.Text
as="span"
className={Styles.title}
title={hoveredPoint.label}
testId="scatter-tooltip-title"
>
{hoveredPoint.label}
</Typography.Text>
{isPinned && (
<Button
variant="ghost"
color="secondary"
size="sm"
prefix={<Pin size={12} />}
testId="scatter-tooltip-status"
>
Pinned
</Button>
)}
</div>
<span className={Styles.divider} />
<div className={Styles.rows}>
{rows.map((row) => (
<div
key={row.label}
className={Styles.row}
data-testid="scatter-tooltip-row"
>
<Typography.Text as="span" className={Styles.rowLabel}>
{row.label}
</Typography.Text>
<Typography.Text as="span" className={Styles.rowValue}>
{row.value}
</Typography.Text>
</div>
))}
</div>
{labels.length > 0 && (
<>
<span className={Styles.divider} />
<div className={Styles.rows}>
{labels.map((label) => (
<div
key={label.key}
className={cx(Styles.row, Styles.rowMuted)}
data-testid="scatter-tooltip-label"
>
<Typography.Text
as="span"
className={Styles.rowLabel}
title={label.key}
>
{label.key}
</Typography.Text>
<Typography.Text
as="span"
className={Styles.rowValue}
title={label.value}
>
{label.value}
</Typography.Text>
</div>
))}
</div>
</>
)}
{renderTooltipFooter?.({ isPinned, dismiss })}
</div>
<TooltipCard
title={hoveredPoint.label}
color={hoveredPoint.color}
rows={rows.map((row) => ({ key: row.label, ...row }))}
mutedRows={labels.map((label) => ({
key: label.key,
label: label.key,
value: label.value,
}))}
isPinned={isPinned}
footer={renderTooltipFooter?.({ isPinned, dismiss })}
testId="scatter-tooltip"
/>
);
}

View File

@@ -49,7 +49,7 @@
font-family: var(--font-mono);
font-size: var(--font-size-xs);
font-weight: 600;
color: var(--text-vanilla-100);
color: var(--l1-foreground);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
@@ -70,11 +70,11 @@
font-family: var(--font-mono);
font-size: var(--font-size-xs);
font-variant-numeric: tabular-nums;
color: var(--text-vanilla-100);
color: var(--l1-foreground);
}
.rowMuted {
color: var(--text-vanilla-400);
color: var(--l3-foreground);
}
.rowLabel {

View File

@@ -0,0 +1,119 @@
import type { ReactNode } from 'react';
import cx from 'classnames';
import { Pin } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Typography } from '@signozhq/ui/typography';
import Styles from './TooltipCard.module.scss';
export interface TooltipCardRow {
key: string;
label: string;
value: string;
}
interface TooltipCardProps {
title: string;
/** The marker beside the title, matching the item's mark on the chart. */
color: string;
/** What the item says. */
rows: TooltipCardRow[];
/** What names the item, below the rows and muted. */
mutedRows?: TooltipCardRow[];
isPinned?: boolean;
footer?: ReactNode;
/** Prefixes the test ids of the title, status, rows and muted rows. */
testId: string;
}
/** One item's tooltip: a marked title, then label/value rows, on the shared tooltip surface. */
export default function TooltipCard({
title,
color,
rows,
mutedRows = [],
isPinned = false,
footer,
testId,
}: TooltipCardProps): JSX.Element {
return (
<div
className={cx(Styles.container, { [Styles.pinned]: isPinned })}
data-pinned={isPinned}
data-testid={testId}
>
<div className={Styles.header}>
<span
className={Styles.marker}
style={{ backgroundColor: color, borderColor: color }}
/>
<Typography.Text
as="span"
className={Styles.title}
title={title}
testId={`${testId}-title`}
>
{title}
</Typography.Text>
{isPinned && (
<Button
variant="ghost"
color="secondary"
size="sm"
prefix={<Pin size={12} />}
testId={`${testId}-status`}
>
Pinned
</Button>
)}
</div>
<span className={Styles.divider} />
<div className={Styles.rows}>
{rows.map((row) => (
<div key={row.key} className={Styles.row} data-testid={`${testId}-row`}>
<Typography.Text as="span" className={Styles.rowLabel}>
{row.label}
</Typography.Text>
<Typography.Text as="span" className={Styles.rowValue}>
{row.value}
</Typography.Text>
</div>
))}
</div>
{mutedRows.length > 0 && (
<>
<span className={Styles.divider} />
<div className={Styles.rows}>
{mutedRows.map((row) => (
<div
key={row.key}
className={cx(Styles.row, Styles.rowMuted)}
data-testid={`${testId}-label`}
>
<Typography.Text
as="span"
className={Styles.rowLabel}
title={row.label}
>
{row.label}
</Typography.Text>
<Typography.Text
as="span"
className={Styles.rowValue}
title={row.value}
>
{row.value}
</Typography.Text>
</div>
))}
</div>
</>
)}
{footer}
</div>
);
}

View File

@@ -8,7 +8,7 @@ import removeSessionStorage from 'api/browser/sessionstorage/remove';
import ROUTES from 'constants/routes';
import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';
import { rest, type RequestHandler } from 'msw';
import { expect, userEvent, waitFor, within } from 'storybook/test';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import {
choiceControl,
@@ -20,6 +20,7 @@ import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import { globalConfigResponse } from '@/storybook/msw/__story_mockdata__/appShell';
import { dashboardsForUserResponse } from '@/storybook/msw/__story_mockdata__/dashboards';
import type { MockResolver } from '@/storybook/msw/types';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
AGENT_STATES,
@@ -86,6 +87,15 @@ const onBothBases = (
const ok: MockResolver = (_req, res, ctx) => res(ctx.status(200), ctx.json({}));
/** The sidebar always lists the open conversation, which the thread list answers first. */
const listedConversations = ({
conversation,
history,
}: {
conversation: boolean;
history: number;
}): number => (conversation ? Math.max(1, history) : history);
const startedExecution: MockResolver = (_req, res, ctx) =>
res(ctx.status(200), ctx.json({ executionId: EXECUTION_ID }));
@@ -153,10 +163,7 @@ export const aiAssistantMocks = defineStoryMocks({
: // A thread the sidebar does not list is one the server does not
// know, and the store drops those, so an open conversation is
// always the first row.
threadListResponse(
values.conversation ? Math.max(1, values.history) : values.history,
false,
),
threadListResponse(listedConversations(values), false),
),
),
...onBothBases(
@@ -327,3 +334,42 @@ export const failVoiceInput = (error: 'network' | 'not-allowed'): void => {
window as unknown as { webkitSpeechRecognition: StorySpeechRecognition }
).webkitSpeechRecognition.listening?.onerror?.({ error });
};
export type AIAssistantArgs = PageStoryArgs<typeof aiAssistantMocks>;
/** The thread list answers through the Data control, and an empty one leaves no row to act on. */
export const showsConversationRows = (args: AIAssistantArgs): boolean =>
args.dataState === 'loaded' && listedConversations(args) > 0;
/** The form comes with the thread detail, which a new conversation never fetches. */
export const hasPendingClarification = (args: AIAssistantArgs): boolean =>
args.conversation &&
args.dataState === 'loaded' &&
!!threadDetailResponse(args.contents, args.agent).pendingClarification;
/** The thread list resolves before the thread does, which outlasts the 1s default. */
export const untilLoaded = { timeout: 15_000 };
/** How long what a click opened has to stay on screen to count as open. */
const HOLD_MS = 1_000;
/**
* Click something, and keep clicking until what it opens is on screen. The
* message list remounts its items while it measures a freshly loaded thread, so
* a single click can land on a row that is about to be replaced, taking the
* state it just set with it. The replacement can land after that state has
* rendered, so it has to still be there `HOLD_MS` later.
*/
export const clickUntil = async (
find: () => Promise<HTMLElement>,
opens: RegExp,
): Promise<void> => {
await waitFor(async () => {
await userEvent.click(await find());
await screen.findByText(opens, undefined, { timeout: 1_000 });
await new Promise((resolve) => {
setTimeout(resolve, HOLD_MS);
});
screen.getByText(opens);
}, untilLoaded);
};

View File

@@ -1,7 +1,7 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import ROUTES from 'constants/routes';
import { renderAtRoute } from '@/storybook/renderAtRoute';
import { screen, userEvent, waitFor, within } from 'storybook/test';
import { screen, userEvent, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
@@ -9,13 +9,19 @@ import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import AIAssistantPage from '../AIAssistantPage';
import {
aiAssistantMocks,
clickUntil,
failVoiceInput,
forgetVoiceFailure,
longActionTooltipHandlers,
speak,
startVoiceInput,
untilLoaded,
} from './AIAssistantPage.stories.mocks';
import type { ThreadPart } from './__story_mockdata__/aiAssistant';
import {
openClarificationSelect,
renameConversation,
} from './__story_mockdata__/aiAssistant.play';
type AIAssistantArgs = PageStoryArgs<typeof aiAssistantMocks>;
@@ -47,33 +53,6 @@ export default meta;
type Story = StoryObj<AIAssistantArgs>;
/** The thread list resolves before the thread does, which outlasts the 1s default. */
const untilLoaded = { timeout: 15_000 };
/** How long what a click opened has to stay on screen to count as open. */
const HOLD_MS = 1_000;
/**
* Click something, and keep clicking until what it opens is on screen. The
* message list remounts its items while it measures a freshly loaded thread, so
* a single click can land on a row that is about to be replaced, taking the
* state it just set with it. The replacement can land after that state has
* rendered, so it has to still be there `HOLD_MS` later.
*/
const clickUntil = async (
find: () => Promise<HTMLElement>,
opens: RegExp,
): Promise<void> => {
await waitFor(async () => {
await userEvent.click(await find());
await screen.findByText(opens, undefined, { timeout: 1_000 });
await new Promise((resolve) => {
setTimeout(resolve, HOLD_MS);
});
screen.getByText(opens);
}, untilLoaded);
};
/** The blocks the agent renders as cards the user answers in place. */
const INTERACTIVE: ThreadPart[] = [
'question',
@@ -139,6 +118,12 @@ export const AwaitingClarification: Story = {
args: { agent: 'awaiting-clarification', contents: BRIEF },
};
/** The severity select open, including the free-text option the form's Select renders. */
export const ClarificationSelectOpen: Story = {
args: { agent: 'awaiting-clarification', contents: BRIEF },
play: openClarificationSelect,
};
/** Reopening the page on a thread that has not come back yet. */
export const LoadingThread: Story = {
args: { dataState: 'loading' },
@@ -231,6 +216,11 @@ export const NegativeFeedback: Story = {
},
};
/** Renaming a thread: the title input the row swaps in. */
export const ConversationRename: Story = {
play: renameConversation,
};
/** What a conversation row offers: rename, a link to it, and archiving. */
export const ConversationActions: Story = {
play: async ({ canvasElement }): Promise<void> => {

View File

@@ -0,0 +1,70 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { screen, userEvent, waitFor, within } from 'storybook/test';
import {
type AIAssistantArgs,
clickUntil,
hasPendingClarification,
showsConversationRows,
untilLoaded,
} from '../AIAssistantPage.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: AIAssistantArgs;
}
export const openClarificationSelect = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!hasPendingClarification(args)) {
return;
}
const canvas = within(canvasElement);
// Open from the keyboard, and retry: the message list remounts its items
// while it measures the thread, which can close the popup again. The
// "Other" checkbox in the Notify field carries the same text, so assert
// on the popup's option role.
await waitFor(async () => {
const severityLabel = canvas.getByText('Severity');
const field = severityLabel.closest('div');
if (!field) {
throw new Error('Severity field is not in the clarification form');
}
within(field).getByRole('combobox').focus();
await userEvent.keyboard('{Enter}');
await screen.findByRole(
'option',
{ name: 'Other (type your own)' },
{ timeout: 1_000 },
);
}, untilLoaded);
};
export const renameConversation = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!showsConversationRows(args)) {
return;
}
await clickUntil(async () => {
const [actions] = await within(canvasElement).findAllByLabelText(
/conversation actions/i,
undefined,
untilLoaded,
);
return actions;
}, /^Rename$/);
await userEvent.click(screen.getByText('Rename'));
await within(canvasElement).findByDisplayValue(/checkout p99 regression/i);
};

View File

@@ -121,12 +121,12 @@ export const RailCollapsed: Story = {
};
/** The popover that names the current filters as a new saved view. */
export const SaveViewPopover: Story = {
export const SaveView: Story = {
play: openSaveViewPopover,
};
/** A saved view's rename popover, opened from its row. */
export const RenameViewPopover: Story = {
export const RenameView: Story = {
play: openRenameViewPopover,
};

View File

@@ -3,11 +3,18 @@
* Do not hand-edit: regenerate instead.
*/
import {
buildNotificationChannelReadPermission,
buildNotificationChannelUpdatePermission,
NotificationChannelCreatePermission,
} from 'lib/authz/hooks/useAuthZ/permissions/notification-channel.permissions';
import { rest } from 'msw';
import { grantsAll } from '@/storybook/access/access';
import { choiceControl } from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import type { MockResolver } from '@/storybook/msw/types';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
CHANNEL_ACTION_OUTCOMES,
@@ -21,6 +28,10 @@ import {
WEBHOOK_AUTHS,
type WebhookAuthChoice,
} from '../../stories/__story_mockdata__/alerts';
import {
recordChannelTestRequest,
resetChannelTestRequests,
} from './__story_mockdata__/channelsEdit';
const STORY_CHANNEL_ID = '1';
@@ -87,6 +98,13 @@ export const channelsEditMocks = defineStoryMocks({
: resolveChannelActionSuccess,
),
rest.post(
'http://localhost/api/v2/notification_channels/test',
async (req) => {
recordChannelTestRequest(await req.json());
},
),
rest.post(
'http://localhost/api/v2/notification_channels/test',
values.testOutcome === 'fails'
@@ -95,4 +113,42 @@ export const channelsEditMocks = defineStoryMocks({
),
],
config: () => ({ route: `/alerts/channels/edit/${STORY_CHANNEL_ID}` }),
effect: () => resetChannelTestRequests(),
});
export type ChannelsEditArgs = PageStoryArgs<typeof channelsEditMocks>;
type ChannelFormState = 'absent' | 'readOnly' | 'editable';
/**
* The form needs the saved channel and `read`. Without `update` it renders
* read-only, and a check that fails rather than denies leaves it editable.
*/
export const channelFormState = (args: ChannelsEditArgs): ChannelFormState => {
if (args.dataState !== 'loaded') {
return 'absent';
}
if (args.authzState === 'error') {
return 'editable';
}
const read = buildNotificationChannelReadPermission(STORY_CHANNEL_ID);
if (!grantsAll(args, read)) {
return 'absent';
}
return grantsAll(
args,
read,
buildNotificationChannelUpdatePermission(STORY_CHANNEL_ID),
)
? 'editable'
: 'readOnly';
};
/** A test send is a create on the collection; a failed check leaves it enabled. */
export const canTestChannel = (args: ChannelsEditArgs): boolean =>
args.authzState === 'error' ||
grantsAll(args, NotificationChannelCreatePermission);

View File

@@ -4,6 +4,11 @@ import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
expectEditableForm,
expectJiraAdvancedFields,
expectJiraConnectionFields,
} from './__story_mockdata__/channelsEdit.play';
import { channelsEditMocks } from './ChannelsEdit.stories.mocks';
import AlertList from '../../index';
@@ -36,8 +41,10 @@ type Story = StoryObj<ChannelsEditArgs>;
/**
* A saved notification channel opened for editing: the name and the type are
* fixed, and the integration's own settings are filled from what was stored.
* The Channel type control swaps the integration, and typing into any field
* unlocks Save.
*/
export const Default: Story = {};
export const Default: Story = { play: expectEditableForm };
/** Mutation: clearing the required webhook URL surfaces the form's validation feedback. */
export const InvalidRequiredFields: Story = {
@@ -110,21 +117,25 @@ export const SaveFailure: Story = {
*/
export const PagerDuty: Story = {
args: { channelType: 'pagerduty' },
play: expectEditableForm,
};
/** The webhook channel, saved with basic auth on the outgoing request. */
export const Webhook: Story = {
args: { channelType: 'webhook' },
play: expectEditableForm,
};
/** The webhook channel saved with a bearer token: only the token field shows. */
export const WebhookBearerToken: Story = {
args: { channelType: 'webhook', webhookAuth: 'bearer' },
play: expectEditableForm,
};
/** The webhook channel saved without credentials: the auth option is None. */
export const WebhookWithoutAuth: Story = {
args: { channelType: 'webhook', webhookAuth: 'none' },
play: expectEditableForm,
};
/**
@@ -133,6 +144,7 @@ export const WebhookWithoutAuth: Story = {
*/
export const Opsgenie: Story = {
args: { channelType: 'opsgenie' },
play: expectEditableForm,
};
/**
@@ -141,6 +153,7 @@ export const Opsgenie: Story = {
*/
export const Email: Story = {
args: { channelType: 'email' },
play: expectEditableForm,
};
/**
@@ -149,11 +162,13 @@ export const Email: Story = {
*/
export const MicrosoftTeams: Story = {
args: { channelType: 'msteams' },
play: expectEditableForm,
};
/** The Google Chat channel, filled from the space's incoming webhook. */
export const GoogleChat: Story = {
args: { channelType: 'googlechat' },
play: expectEditableForm,
};
/**
@@ -163,17 +178,7 @@ export const GoogleChat: Story = {
*/
export const Jira: Story = {
args: { channelType: 'jira' },
play: async ({ canvasElement }): Promise<void> => {
// the advanced fields have their own card now, so nothing has to be
// expanded before they can be read
await expect(
await within(canvasElement).findByTestId(
'jira-reopen-duration-textbox',
undefined,
{ timeout: 15_000 },
),
).toBeVisible();
},
play: expectJiraAdvancedFields,
};
/**
@@ -183,17 +188,7 @@ export const Jira: Story = {
*/
export const JiraSelfHosted: Story = {
args: { channelType: 'jira', jiraDeployment: 'selfhosted' },
play: async ({ canvasElement }): Promise<void> => {
const canvas = within(canvasElement);
await expect(
await canvas.findByTestId('jira-pat-textbox', undefined, {
timeout: 15_000,
}),
).toHaveValue('story-jira-pat');
await expect(
canvas.queryByTestId('jira-email-textbox'),
).not.toBeInTheDocument();
},
play: expectJiraConnectionFields,
};
/**
@@ -202,6 +197,7 @@ export const JiraSelfHosted: Story = {
*/
export const JiraServiceManagementOps: Story = {
args: { channelType: 'jsmops' },
play: expectEditableForm,
};
/**
@@ -210,9 +206,11 @@ export const JiraServiceManagementOps: Story = {
*/
export const IncidentIO: Story = {
args: { channelType: 'incidentio' },
play: expectEditableForm,
};
/** A Telegram channel, with its bot token masked behind the password field. */
export const Telegram: Story = {
args: { channelType: 'telegram' },
play: expectEditableForm,
};

View File

@@ -0,0 +1,240 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, userEvent, waitFor, within } from 'storybook/test';
import { channelSpec } from '../../../stories/__story_mockdata__/alerts';
import { expectDisabled, PAGE_LOAD } from '../../../stories/channelAuthz';
import {
canTestChannel,
channelFormState,
type ChannelsEditArgs,
} from '../ChannelsEdit.stories.mocks';
import { channelTestRequests } from './channelsEdit';
interface PlayContext {
canvasElement: HTMLElement;
args: ChannelsEditArgs;
}
/** Native text controls only: the switches and radios keep a hidden input of their own. */
const FIELD_SELECTOR =
'form input:not([aria-hidden="true"]):not([type="hidden"]), form textarea';
const allFields = (canvasElement: HTMLElement): HTMLElement[] =>
Array.from(canvasElement.querySelectorAll<HTMLElement>(FIELD_SELECTOR));
/** A saved channel's name is fixed, so it is off whether or not the form is. */
const editableFields = (canvasElement: HTMLElement): HTMLElement[] =>
allFields(canvasElement).filter((field) => field.id !== 'channel-name');
const SLACK_ROW_BUTTONS = /^slack-(field|action)-(remove-\d+|add)$/;
const slackRowButtons = (canvasElement: HTMLElement): HTMLElement[] =>
within(canvasElement).queryAllByTestId(SLACK_ROW_BUTTONS);
export const expectEditableForm = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (channelFormState(args) !== 'editable') {
return;
}
const save = await within(canvasElement).findByTestId(
'save-channel-button',
undefined,
PAGE_LOAD,
);
await waitFor(
() => expect(editableFields(canvasElement).length).toBeGreaterThan(0),
PAGE_LOAD,
);
for (const field of editableFields(canvasElement)) {
await expect(field).toBeEnabled();
}
await expect(save).toHaveAttribute('aria-disabled', 'true');
await userEvent.type(editableFields(canvasElement)[0], 'x');
await waitFor(
() => expect(save).toHaveAttribute('aria-disabled', 'false'),
PAGE_LOAD,
);
};
/**
* The permission check answers after the form has mounted editable, so the
* fields are polled until they lock rather than read once.
*/
export const expectReadOnlyForm = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (channelFormState(args) !== 'readOnly') {
return;
}
const canvas = within(canvasElement);
const save = await canvas.findByTestId(
'save-channel-button',
undefined,
PAGE_LOAD,
);
await waitFor(() => {
const fields = allFields(canvasElement);
void expect(fields.length).toBeGreaterThan(1);
fields.forEach((field) => {
void expect(field).toBeDisabled();
});
}, PAGE_LOAD);
await expect(save).toHaveAttribute('aria-disabled', 'true');
if (args.channelType === 'slack') {
const buttons = slackRowButtons(canvasElement);
const fieldCount = allFields(canvasElement).length;
// two field rows, one action row, and an add button for each list
await expect(buttons).toHaveLength(5);
for (const button of buttons) {
await userEvent.click(button);
}
await expect(slackRowButtons(canvasElement)).toHaveLength(5);
await expect(allFields(canvasElement)).toHaveLength(fieldCount);
}
};
/**
* Switching the mode swaps which credential fields render, so a click that
* landed would change how many fields the form holds.
*/
export const expectModeRadioLocked = async (
context: PlayContext,
channelType: ChannelsEditArgs['channelType'],
radio: RegExp,
): Promise<void> => {
const { canvasElement, args } = context;
if (
args.channelType !== channelType ||
channelFormState(args) !== 'readOnly'
) {
return;
}
await expectReadOnlyForm(context);
const fieldCount = allFields(canvasElement).length;
await userEvent.click(
within(canvasElement).getByRole('radio', { name: radio }),
);
await expect(allFields(canvasElement)).toHaveLength(fieldCount);
};
export const expectWebhookAuthLocked = (context: PlayContext): Promise<void> =>
expectModeRadioLocked(context, 'webhook', /bearer/i);
export const expectJiraDeploymentLocked = (
context: PlayContext,
): Promise<void> => expectModeRadioLocked(context, 'jira', /self-hosted/i);
export const expectReadOnlyFormTestLocked = async (
context: PlayContext,
): Promise<void> => {
const { canvasElement, args } = context;
await expectReadOnlyForm(context);
if (channelFormState(args) !== 'readOnly') {
return;
}
await expectDisabled(
await within(canvasElement).findByTestId('test-channel-button'),
!canTestChannel(args),
);
};
export const sendSavedConfig = async (context: PlayContext): Promise<void> => {
const { canvasElement, args } = context;
if (channelFormState(args) !== 'readOnly' || !canTestChannel(args)) {
return;
}
await expectReadOnlyForm(context);
const test = await within(canvasElement).findByTestId('test-channel-button');
await waitFor(
() => expect(test).toHaveAttribute('aria-disabled', 'false'),
PAGE_LOAD,
);
await userEvent.click(test);
await waitFor(() => expect(channelTestRequests()).toHaveLength(1), PAGE_LOAD);
await expect(channelTestRequests()[0].config).toMatchObject({
kind: args.channelType,
spec: channelSpec(args.channelType, args.webhookAuth, args.jiraDeployment),
});
};
export const expectJiraAdvancedFields = async (
context: PlayContext,
): Promise<void> => {
const { canvasElement, args } = context;
await expectEditableForm(context);
if (args.channelType !== 'jira' || channelFormState(args) === 'absent') {
return;
}
// the advanced fields have their own card now, so nothing has to be
// expanded before they can be read
await expect(
await within(canvasElement).findByTestId(
'jira-reopen-duration-textbox',
undefined,
{ timeout: 15_000 },
),
).toBeVisible();
};
export const expectJiraConnectionFields = async (
context: PlayContext,
): Promise<void> => {
const { canvasElement, args } = context;
await expectEditableForm(context);
if (args.channelType !== 'jira' || channelFormState(args) === 'absent') {
return;
}
const canvas = within(canvasElement);
if (args.jiraDeployment === 'selfhosted') {
await expect(
await canvas.findByTestId('jira-pat-textbox', undefined, {
timeout: 15_000,
}),
).toHaveValue('story-jira-pat');
await expect(
canvas.queryByTestId('jira-email-textbox'),
).not.toBeInTheDocument();
return;
}
await canvas.findByTestId('jira-email-textbox', undefined, {
timeout: 15_000,
});
await expect(canvas.queryByTestId('jira-pat-textbox')).not.toBeInTheDocument();
};

View File

@@ -0,0 +1,22 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import type { AlertmanagertypesTestableNotificationChannelDTO } from 'api/generated/services/sigNoz.schemas';
/** Every test send the form made since the story mounted, oldest first. */
const testRequests: AlertmanagertypesTestableNotificationChannelDTO[] = [];
export const recordChannelTestRequest = (
request: AlertmanagertypesTestableNotificationChannelDTO,
): void => {
testRequests.push(request);
};
export const channelTestRequests =
(): readonly AlertmanagertypesTestableNotificationChannelDTO[] => testRequests;
export const resetChannelTestRequests = (): void => {
testRequests.length = 0;
};

View File

@@ -13,6 +13,13 @@ import {
READ,
UPDATE,
} from '../../../stories/channelAuthz';
import {
expectJiraDeploymentLocked,
expectReadOnlyForm,
expectReadOnlyFormTestLocked,
expectWebhookAuthLocked,
sendSavedConfig,
} from '../__story_mockdata__/channelsEdit.play';
import { channelsEditMocks } from '../ChannelsEdit.stories.mocks';
import AlertList from '../../../index';
@@ -56,18 +63,12 @@ export const NoRead: Story = {
/**
* Reading is enough to open the page, so losing `update` alone leaves it
* standing read-only: the fields go disabled and Save is locked, not hidden.
* standing read-only: every field goes disabled and Save is locked, not hidden.
* The Channel type control walks the same check across every integration.
*/
export const NoUpdate: Story = {
args: { revoked: [UPDATE] },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expectDisabled(
await canvas.findByTestId('save-channel-button', undefined, PAGE_LOAD),
);
await expectDisabled(await canvas.findByTestId('slack-channel-textbox'));
},
play: expectReadOnlyForm,
};
/**
@@ -101,15 +102,17 @@ export const NoCreate: Story = {
*/
export const ReadOnly: Story = {
args: { revoked: [UPDATE, CREATE, DELETE] },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
play: expectReadOnlyFormTestLocked,
};
await expectDisabled(
await canvas.findByTestId('save-channel-button', undefined, PAGE_LOAD),
);
await expectDisabled(await canvas.findByTestId('test-channel-button'));
await expectDisabled(await canvas.findByTestId('slack-channel-textbox'));
},
/**
* Read-only keeps Test: sending is a create on the collection, so a reader who
* cannot edit the channel can still test it. The request carries the saved
* config.
*/
export const NoUpdateTest: Story = {
args: { revoked: [UPDATE] },
play: sendSavedConfig,
};
/**
@@ -145,6 +148,25 @@ export const TelegramReadOnly: Story = {
},
};
/**
* The same denial on a webhook saved with basic auth. The credential fields are
* off, and so is the radio that would swap them for a bearer token.
*/
export const WebhookReadOnly: Story = {
args: { channelType: 'webhook', revoked: [UPDATE, CREATE, DELETE] },
play: expectWebhookAuthLocked,
};
/**
* The same denial on a Jira Cloud channel. Every field is off, including the
* advanced ones, and so is the radio that would swap the Atlassian email and API
* token for a personal access token.
*/
export const JiraReadOnly: Story = {
args: { channelType: 'jira', revoked: [UPDATE, CREATE, DELETE] },
play: expectJiraDeploymentLocked,
};
/** No channel permission at all: the page is denied before the form exists. */
export const NoChannelAccess: Story = {
args: { revoked: NOTIFICATION_CHANNEL },

View File

@@ -954,7 +954,7 @@ const CHANNEL_SPECS: Record<ChannelType, Record<string, unknown>> = {
},
};
const channelSpec = (
export const channelSpec = (
type: ChannelType,
webhookAuth: WebhookAuthChoice,
jiraDeployment: JiraDeploymentChoice,

View File

@@ -120,17 +120,6 @@ export const QuickFiltersSettingsDirty: Story = {
play: dirtyQuickFiltersSettings,
};
/**
* The same panel with a banner above the shell. The banner takes 48px off the
* layout, so this is the case where the footer used to be pushed off screen:
* the panel is sized from the filters pane rather than the viewport, which
* keeps Save changes reachable.
*/
export const QuickFiltersSettingsWithBanner: Story = {
args: { banner: 'trial-expiry' },
play: dirtyQuickFiltersSettings,
};
/** The resource filter opened: every key the exceptions can be narrowed by. */
export const FilterKeySuggestions: Story = {
play: async ({ canvasElement }): Promise<void> => {

View File

@@ -14,14 +14,9 @@ import type {
GetQuickFilters200,
TelemetrytypesTelemetryFieldKeyDTO,
} from 'api/generated/services/sigNoz.schemas';
import {
type BaseAutocompleteData,
DataTypes,
} from 'types/api/queryBuilder/queryAutocompleteResponse';
import type { Exception, Order, OrderBy } from 'types/api/errors/getAll';
import type { IAttributeValuesResponse } from 'types/api/queryBuilder/getAttributesValues';
import { fieldKeysResponse } from '@/storybook/msw/__story_mockdata__/fields';
import { quickFiltersResponse } from '@/storybook/msw/__story_mockdata__/quickFilters';
export interface ExceptionShape {
@@ -298,28 +293,43 @@ export const exceptionAttributeValuesResponse = (
};
};
const ATTRIBUTE_KEYS: BaseAutocompleteData[] = [
...QUICK_FILTERS.map(({ name, fieldDataType, fieldContext }) => ({
key: name,
dataType: fieldDataType === bool ? DataTypes.bool : DataTypes.String,
type: fieldContext === attribute ? 'tag' : String(fieldContext),
})),
{ key: 'service.namespace', dataType: DataTypes.String, type: 'resource' },
{ key: 'k8s.pod.name', dataType: DataTypes.String, type: 'resource' },
{ key: 'k8s.cluster.name', dataType: DataTypes.String, type: 'resource' },
{ key: 'cloud.region', dataType: DataTypes.String, type: 'resource' },
const ATTRIBUTE_KEYS: TelemetrytypesTelemetryFieldKeyDTO[] = [
...QUICK_FILTERS,
{
name: 'service.namespace',
fieldDataType: stringType,
fieldContext: resource,
},
{ name: 'k8s.pod.name', fieldDataType: stringType, fieldContext: resource },
{
name: 'k8s.cluster.name',
fieldDataType: stringType,
fieldContext: resource,
},
{ name: 'cloud.region', fieldDataType: stringType, fieldContext: resource },
];
/** The quick filter settings panel lists its "other filters" from `/fields/keys`. */
/**
* The resource filter and the quick filter settings panel both list keys from
* `/fields/keys`; each key keeps its own context and data type.
*/
export const exceptionFieldKeysResponse = (
searchText: string | null,
): GetFieldsKeys200 => {
const search = (searchText ?? '').toLowerCase();
return fieldKeysResponse(
ATTRIBUTE_KEYS.map(({ key }) => key).filter((key) =>
key.toLowerCase().includes(search),
),
{ signal: TelemetrytypesSignalDTO.logs, fieldContext: resource },
);
return {
status: 'success',
data: {
complete: true,
keys: Object.fromEntries(
ATTRIBUTE_KEYS.filter(({ name }) =>
name.toLowerCase().includes(search),
).map((key) => [
key.name,
[{ ...key, signal: TelemetrytypesSignalDTO.traces }],
]),
),
},
};
};

View File

@@ -182,14 +182,3 @@ export const QuickFiltersSettings: Story = {
export const QuickFiltersSettingsDirty: Story = {
play: dirtyQuickFiltersSettings,
};
/**
* The same panel with a banner above the shell. The banner takes 48px off the
* layout, so this is the case where the footer used to be pushed off screen:
* the panel is sized from the filters pane rather than the viewport, which
* keeps Save changes reachable.
*/
export const QuickFiltersSettingsWithBanner: Story = {
args: { banner: 'trial-expiry' },
play: dirtyQuickFiltersSettings,
};

View File

@@ -59,28 +59,6 @@ export const AnomalyAlert: Story = {
args: { alertMode: 'anomaly' },
};
/**
* An anomaly alert handed to routing policies: the channel picker leaves the
* condition, and the banner points at the policies that route it instead.
*/
export const AnomalyAlertRoutingPolicies: Story = {
args: { alertMode: 'anomaly' },
play: async ({ canvasElement }): Promise<void> => {
const canvas = within(canvasElement);
await userEvent.click(
await canvas.findByTestId('routing-policies-switch', undefined, {
timeout: 15_000,
}),
);
await waitFor(() =>
expect(
canvas.queryByTestId('threshold-notification-channel-select'),
).not.toBeInTheDocument(),
);
},
};
/**
* The match-type tooltip on the threshold sentence: a paragraph on what an
* aggregated data point is, a worked example over five of them, and the docs

View File

@@ -0,0 +1,40 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, userEvent, waitFor, within } from 'storybook/test';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import type { createAlertMocks } from '../CreateAlert.stories.mocks';
type CreateAlertArgs = PageStoryArgs<typeof createAlertMocks>;
interface PlayContext {
canvasElement: HTMLElement;
args: Pick<CreateAlertArgs, 'alertMode'>;
}
const untilLoaded = { timeout: 15_000 };
/** Every rule type carries the banner; only the type picker has no form. */
export const enableRoutingPolicies = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.alertMode === 'select-type') {
return;
}
const canvas = within(canvasElement);
await userEvent.click(
await canvas.findByTestId('routing-policies-switch', undefined, untilLoaded),
);
await waitFor(() =>
expect(
canvas.queryByTestId('threshold-notification-channel-select'),
).not.toBeInTheDocument(),
);
};

View File

@@ -26,6 +26,22 @@ export const SWITCH_SKETCHES = {
))}
</SketchSvg>
),
rank: (
<SketchSvg>
{[5, 11, 17].map((y, index) => (
<g key={y}>
<circle cx={4} cy={y} r={1.2} fill="var(--l3-foreground)" />
<path d={`M9 ${y} H${36 - index * 9}`} />
</g>
))}
</SketchSvg>
),
share: (
<SketchSvg>
<path d="M3 11 H37" strokeDasharray="3 3" />
<rect x={3} y={8} width={22} height={6} fill="var(--l3-foreground)" />
</SketchSvg>
),
combine: (
<SketchSvg>
<rect x={4} y={10} width={6} height={10} />

View File

@@ -26,6 +26,7 @@ import { fitBubbleRadius } from 'pages/DashboardPage/DashboardContainer/Panels/k
import type { SeededPluginSpec } from 'pages/DashboardPage/DashboardContainer/Panels/utils/buildPluginSpec';
import type { SectionEditorContext } from './sectionContext';
import AppearanceSection from './sections/AppearanceSection/AppearanceSection';
import AxesSection from './sections/AxesSection/AxesSection';
import BucketsSection from './sections/BucketsSection/BucketsSection';
import ChartAppearanceSection from './sections/ChartAppearanceSection/ChartAppearanceSection';
@@ -151,6 +152,13 @@ export const SECTION_REGISTRY: {
update: (spec, chartAppearance): PanelSpec =>
updatePluginSlice(spec, 'chartAppearance', chartAppearance),
},
[SectionKind.Appearance]: {
Component: AppearanceSection,
get: (spec): SectionSpecMap[SectionKind.Appearance] | undefined =>
getPluginSlice<SectionSpecMap[SectionKind.Appearance]>(spec, 'appearance'),
update: (spec, appearance): PanelSpec =>
updatePluginSlice(spec, 'appearance', appearance),
},
[SectionKind.Visualization]: {
Component: VisualizationSection,
get: (spec): PanelVisualizationSlice | undefined =>

View File

@@ -0,0 +1,65 @@
import type {
SectionEditorProps,
SectionKind,
} from 'pages/DashboardPage/DashboardContainer/Panels/types/sections';
import ConfigSwitch from '../../controls/ConfigSwitch/ConfigSwitch';
import { SWITCH_SKETCHES } from '../../controls/drawings/switchSketches';
import { createFieldResetter } from '../../utils/changes';
import BarColorField from './BarColorField';
import { DEFAULT_BAR_COLOR } from './barColorOptions';
/**
* Edits the `appearance` slice of a Top List panel spec: bar color, row numbers and
* each row's share of the listed total. Each control is gated by its `controls` flag.
*/
function AppearanceSection({
value,
savedValue,
controls,
onChange,
}: SectionEditorProps<SectionKind.Appearance>): JSX.Element {
const reset = createFieldResetter(value, savedValue, onChange);
const appearance = {
...value,
barColor: value?.barColor || DEFAULT_BAR_COLOR,
};
return (
<>
{controls.barColor && (
<BarColorField
{...reset('barColor')}
value={appearance.barColor}
onChange={(barColor): void => onChange({ ...appearance, barColor })}
/>
)}
{controls.showRank && (
<ConfigSwitch
testId="panel-editor-v2-show-rank"
title="Show rank"
description="Numbers each row by its position."
sketch={SWITCH_SKETCHES.rank}
changed={reset('showRank').changed}
value={appearance.showRank ?? false}
onChange={(showRank): void => onChange({ ...appearance, showRank })}
/>
)}
{controls.showShare && (
<ConfigSwitch
testId="panel-editor-v2-show-share"
title="Show share of total"
description="Each row's percentage of the listed rows' sum. Suits counts and sums, not averages or percentiles."
sketch={SWITCH_SKETCHES.share}
changed={reset('showShare').changed}
value={appearance.showShare ?? false}
onChange={(showShare): void => onChange({ ...appearance, showShare })}
/>
)}
</>
);
}
export default AppearanceSection;

View File

@@ -0,0 +1,42 @@
import ColorSwatches from '../../controls/ColorSwatches/ColorSwatches';
import ConfigField from '../../controls/ConfigField/ConfigField';
import type { FieldResetProps } from '../../utils/changes';
import { BAR_COLOR_OPTIONS, findBarColorPreset } from './barColorOptions';
interface BarColorFieldProps extends Partial<FieldResetProps> {
value: string;
onChange: (barColor: string) => void;
}
function BarColorField({
value,
onChange,
changed,
onReset,
}: BarColorFieldProps): JSX.Element {
const preset = findBarColorPreset(value);
return (
<ConfigField
label="Bar color"
help="Fills every row's bar."
changed={changed}
onReset={onReset}
>
<ColorSwatches
testId="panel-editor-v2-bar-color"
label="Bar color"
value={preset}
options={BAR_COLOR_OPTIONS}
onChange={onChange}
custom={{
value: preset ? undefined : value,
initial: value,
onChange,
}}
/>
</ConfigField>
);
}
export default BarColorField;

View File

@@ -0,0 +1,93 @@
import { Color } from '@signozhq/design-tokens';
import { TooltipProvider } from '@signozhq/ui/tooltip';
import type {
SectionEditorProps,
SectionKind,
} from 'pages/DashboardPage/DashboardContainer/Panels/types/sections';
import {
render as renderWithProviders,
screen,
userEvent,
} from 'tests/test-utils';
import AppearanceSection from '../AppearanceSection';
type OnChange = SectionEditorProps<SectionKind.Appearance>['onChange'];
// Color swatches use a radix tooltip, which needs a TooltipProvider ancestor.
const render = (ui: JSX.Element): ReturnType<typeof renderWithProviders> =>
renderWithProviders(<TooltipProvider>{ui}</TooltipProvider>);
describe('AppearanceSection', () => {
it('renders only the controls whose flag is set', () => {
render(
<AppearanceSection
value={undefined}
controls={{ showRank: true }}
onChange={jest.fn()}
/>,
);
expect(screen.getByTestId('panel-editor-v2-show-rank')).toBeInTheDocument();
expect(
screen.queryByTestId('panel-editor-v2-show-share'),
).not.toBeInTheDocument();
});
it.each([
{ testId: 'panel-editor-v2-show-rank', field: 'showRank' },
{ testId: 'panel-editor-v2-show-share', field: 'showShare' },
])('toggles $field through onChange', async ({ testId, field }) => {
const user = userEvent.setup();
const onChange = jest.fn() as jest.MockedFunction<OnChange>;
render(
<AppearanceSection
value={{ showRank: false, showShare: false, barColor: '#4E74F8' }}
controls={{ showRank: true, showShare: true }}
onChange={onChange}
/>,
);
await user.click(screen.getByTestId(testId));
expect(onChange).toHaveBeenCalledWith({
showRank: false,
showShare: false,
barColor: '#4E74F8',
[field]: true,
});
});
it('picks a bar color, keeping the other fields', async () => {
const user = userEvent.setup();
const onChange = jest.fn() as jest.MockedFunction<OnChange>;
render(
<AppearanceSection
value={{ showRank: true, barColor: '#4E74F8' }}
controls={{ barColor: true }}
onChange={onChange}
/>,
);
await user.click(screen.getByTestId('panel-editor-v2-bar-color-forest'));
expect(onChange).toHaveBeenCalledWith({
showRank: true,
barColor: Color.BG_FOREST_500,
});
});
it('shows the default bar color when the spec has none', () => {
render(
<AppearanceSection
value={undefined}
controls={{ barColor: true }}
onChange={jest.fn()}
/>,
);
expect(
screen.getByTestId('panel-editor-v2-bar-color-robin').querySelector('input'),
).toBeChecked();
});
});

View File

@@ -0,0 +1,26 @@
import { Color } from '@signozhq/design-tokens';
import type { ColorSwatchOption } from '../../controls/ColorSwatches/ColorSwatches';
export const BAR_COLOR_OPTIONS: ColorSwatchOption<string>[] = [
{ id: 'robin', color: Color.BG_ROBIN_500 },
{ id: 'aqua', color: Color.BG_AQUA_500 },
{ id: 'forest', color: Color.BG_FOREST_500 },
{ id: 'amber', color: Color.BG_AMBER_500 },
{ id: 'sienna', color: Color.BG_SIENNA_500 },
].map(({ id, color }) => ({
value: color,
id,
label: id.charAt(0).toUpperCase() + id.slice(1),
fill: color,
}));
/** Matches the server's default for an unset `appearance.barColor`. */
export const DEFAULT_BAR_COLOR = Color.BG_ROBIN_500;
/** The preset a hex matches, ignoring case. */
export function findBarColorPreset(hex: string): string | undefined {
return BAR_COLOR_OPTIONS.find(
(option) => option.value.toLowerCase() === hex.toLowerCase(),
)?.value;
}

View File

@@ -37,6 +37,7 @@ const EXPECTED_QUERY_TYPES: Record<PanelKind, EQueryType[]> = {
'signoz/HeatmapPanel': [QUERY_BUILDER, CLICKHOUSE, PROM],
'signoz/PieChartPanel': [QUERY_BUILDER, CLICKHOUSE],
'signoz/GeoMapPanel': [QUERY_BUILDER, CLICKHOUSE],
'signoz/TopListPanel': [QUERY_BUILDER, CLICKHOUSE],
'signoz/TablePanel': [QUERY_BUILDER, CLICKHOUSE],
'signoz/ListPanel': [QUERY_BUILDER],
'signoz/ScatterPlotPanel': [QUERY_BUILDER, CLICKHOUSE],
@@ -85,6 +86,7 @@ const EXPECTED_QUERY_MODES: Record<PanelKind, QueryMode[]> = {
'signoz/ListPanel': [QUERY_BUILDER, QueryMode.AI_QUERY_BUILDER],
'signoz/ScatterPlotPanel': [QUERY_BUILDER, CLICKHOUSE],
'signoz/GeoMapPanel': [QUERY_BUILDER, CLICKHOUSE],
'signoz/TopListPanel': [QUERY_BUILDER, CLICKHOUSE],
'signoz/TextPanel': [],
};
@@ -98,6 +100,7 @@ const EXPECTED_SIGNALS: Record<PanelKind, TelemetrytypesSignalDTO[]> = {
'signoz/HeatmapPanel': [metrics],
'signoz/PieChartPanel': [metrics, logs, traces],
'signoz/GeoMapPanel': [metrics, logs, traces],
'signoz/TopListPanel': [metrics, logs, traces],
'signoz/TablePanel': [metrics, logs, traces],
// List renders raw rows; metrics produce no row data.
'signoz/ListPanel': [logs, traces],
@@ -164,6 +167,14 @@ const EXPECTED_QUERY_CAPABILITIES: Partial<
orderTiebreaker: false,
serverPaginated: false,
},
'signoz/TopListPanel': {
requestType: scalar,
formatTableResultForUI: false,
bucketedStepInterval: false,
orderTiebreaker: false,
serverPaginated: false,
defaultRowLimit: 10,
},
// Only Table, Scatter Plot and Geo Map ask the server to join their scalar results into UI rows.
'signoz/TablePanel': {
requestType: scalar,

View File

@@ -0,0 +1,102 @@
import { useCallback, useMemo } from 'react';
import NoData from '../../components/NoData/NoData';
import PanelStyles from '../../panel.module.scss';
import type { PanelRendererProps } from '../../types/rendererProps';
import { resolveDecimalPrecision } from '../../utils/chartAppearance/resolvers';
import { enrichPieClick } from '../../utils/drilldown/enrichPieClick';
import { getBuilderQueries } from '../../utils/getBuilderQueries';
import { getPanelTimeRange } from '../../utils/getPanelTimeRange';
import { mapNumberThresholds } from '../NumberPanel/utils';
import TopList from './components/TopList/TopList';
import { LABEL_NAME_SEPARATOR, prepareTopListData } from './utils/prepareData';
import type { TopListRow } from './types';
import { ACCENT_COLOR, type RowColors } from './utils/rowDisplay';
function TopListPanelRenderer({
panelId,
panel,
data,
isFetching,
refetch,
onClick,
enableDrillDown,
}: PanelRendererProps<'signoz/TopListPanel'>): JSX.Element {
const spec = panel.spec.plugin.spec;
const { rows, valueName, labelColumnNames } = useMemo(
() => prepareTopListData(data),
[data],
);
const thresholds = useMemo(
() => mapNumberThresholds(spec.thresholds),
[spec.thresholds],
);
const precision = useMemo(
() => resolveDecimalPrecision(spec.formatting?.decimalPrecision),
[spec.formatting?.decimalPrecision],
);
const builderQueries = useMemo(
() => getBuilderQueries(panel.spec.queries || []),
[panel.spec.queries],
);
const handleSelect = useCallback(
(
row: TopListRow,
colors: RowColors,
coordinates: { x: number; y: number },
): void => {
if (!onClick) {
return;
}
const payload = enrichPieClick({
slice: {
label: row.label,
value: row.value ?? 0,
color: colors.barColor ?? ACCENT_COLOR,
queryName: row.queryName,
labels: row.labels,
},
builderQueries,
coordinates,
timeRange: getPanelTimeRange(data.requestPayload),
});
if (payload) {
onClick(payload);
}
},
[onClick, builderQueries, data.requestPayload],
);
return (
<div
data-testid="top-list-panel-renderer"
className={PanelStyles.panelContainer}
>
{rows.length === 0 ? (
<NoData isFetching={isFetching} onRetry={refetch} panel={panel} />
) : (
<TopList
panelId={panelId}
rows={rows}
valueName={valueName}
labelName={labelColumnNames.join(LABEL_NAME_SEPARATOR)}
unit={spec.formatting?.unit}
precision={precision}
thresholds={thresholds}
barColor={spec.appearance?.barColor ?? undefined}
showRank={spec.appearance?.showRank}
showShare={spec.appearance?.showShare}
onSelect={enableDrillDown ? handleSelect : undefined}
/>
)}
</div>
);
}
export default TopListPanelRenderer;

View File

@@ -0,0 +1,188 @@
import {
DashboardtypesComparisonOperatorDTO,
DashboardtypesThresholdFormatDTO,
} from 'api/generated/services/sigNoz.schemas';
import { PanelMode } from 'lib/visualization/panels/types';
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import { render, screen, userEvent } from 'tests/test-utils';
import type { PanelRendererProps } from '../../../types/rendererProps';
import TopListPanelRenderer from '../Renderer';
import {
groupColumn,
scalarResponse,
topListPanel as panelWith,
valueColumn,
} from './fixtures';
import { mockListLayout } from './mockListLayout';
function dataWith(rows: [string, number][]): PanelQueryData {
return {
response: scalarResponse([
{
queryName: 'A',
columns: [groupColumn('service.name'), valueColumn()],
data: rows,
},
]),
requestPayload: undefined,
legendMap: {},
};
}
const SERVICES: [string, number][] = [
['checkout', 50],
['payment', 100],
['auth', 25],
];
function renderPanel(
props: Partial<PanelRendererProps<'signoz/TopListPanel'>>,
): ReturnType<typeof render> {
return render(
<TopListPanelRenderer
panelId="panel-1"
panel={panelWith({})}
data={dataWith(SERVICES)}
isFetching={false}
error={null}
panelMode={PanelMode.DASHBOARD_VIEW}
{...props}
/>,
);
}
type OnClick = NonNullable<
PanelRendererProps<'signoz/TopListPanel'>['onClick']
>;
const rowLabels = (): string[] =>
screen
.getAllByTestId('top-list-row')
.map(
(row) =>
row.getAttribute('aria-label') ??
row.closest('li')?.getAttribute('aria-label') ??
'',
);
mockListLayout();
describe('TopListPanelRenderer', () => {
it('ranks rows by value with bars relative to the largest value', () => {
renderPanel({});
expect(rowLabels()).toStrictEqual([
'payment: 100',
'checkout: 50',
'auth: 25',
]);
expect(
screen.getAllByTestId('top-list-row-fill').map((fill) => fill.style.width),
).toStrictEqual(['100%', '50%', '25%']);
});
it('formats values with the panel unit', () => {
renderPanel({ panel: panelWith({ formatting: { unit: 'ms' } }) });
expect(screen.getAllByTestId('top-list-row-value')[0]).toHaveTextContent(
'100 ms',
);
});
it('recolours the bar for a background threshold and the value for a text threshold', () => {
renderPanel({
panel: panelWith({
thresholds: [
{
color: '#F1575F',
operator: DashboardtypesComparisonOperatorDTO.above,
value: 90,
format: DashboardtypesThresholdFormatDTO.background,
},
{
color: '#F5B225',
operator: DashboardtypesComparisonOperatorDTO.above,
value: 40,
format: DashboardtypesThresholdFormatDTO.text,
},
],
}),
});
const [paymentFill, checkoutFill] =
screen.getAllByTestId('top-list-row-fill');
const [paymentValue, checkoutValue] =
screen.getAllByTestId('top-list-row-value');
expect(paymentFill.style.getPropertyValue('--fill-color')).toBe('#F1575F');
expect(paymentValue.style.color).toBe('');
expect(checkoutValue).toHaveStyle({ color: '#F5B225' });
expect(checkoutFill.style.getPropertyValue('--fill-color')).toBe('');
});
it('opens the drilldown with the clicked row', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onClick = jest.fn() as jest.MockedFunction<OnClick>;
renderPanel({ onClick, enableDrillDown: true });
await user.pointer({
keys: '[MouseLeft]',
target: screen.getAllByTestId('top-list-row')[1],
coords: { clientX: 10, clientY: 20 },
});
expect(onClick).toHaveBeenCalledTimes(1);
expect(onClick.mock.calls[0][0]).toMatchObject({
coordinates: { x: 10, y: 20 },
context: { queryName: 'A', label: 'checkout' },
});
});
it('anchors the drilldown under the row when opened from the keyboard', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onClick = jest.fn() as jest.MockedFunction<OnClick>;
renderPanel({ onClick, enableDrillDown: true });
const row = screen.getAllByTestId('top-list-row')[0];
jest
.spyOn(row, 'getBoundingClientRect')
.mockReturnValue({ left: 30, bottom: 60 } as DOMRect);
row.focus();
await user.keyboard('{Enter}');
expect(onClick.mock.calls[0][0]).toMatchObject({
coordinates: { x: 30, y: 60 },
context: { label: 'payment' },
});
});
it('does not drill down when drilldown is disabled', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onClick = jest.fn() as jest.MockedFunction<OnClick>;
renderPanel({ onClick });
await user.click(screen.getAllByTestId('top-list-row')[0]);
expect(onClick).not.toHaveBeenCalled();
});
it('moves focus between rows with the arrow keys', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderPanel({ enableDrillDown: true, onClick: jest.fn() });
const rows = screen.getAllByTestId('top-list-row');
rows[0].focus();
await user.keyboard('{ArrowDown}');
expect(rows[1]).toHaveFocus();
await user.keyboard('{ArrowUp}');
expect(rows[0]).toHaveFocus();
});
it('renders No Data when the query returns no rows', () => {
renderPanel({ data: dataWith([]) });
expect(screen.getByTestId('panel-no-data')).toBeInTheDocument();
expect(screen.queryByTestId('top-list')).not.toBeInTheDocument();
});
});

View File

@@ -0,0 +1,379 @@
import { act, render, screen, userEvent } from 'tests/test-utils';
import TopList from '../components/TopList/TopList';
import { HEADER_HEIGHT, LIST_PADDING_Y, ROW_GAP } from '../constants';
import { mockListLayout } from './mockListLayout';
import type { TopListRow } from '../types';
function rowsOf(count: number): TopListRow[] {
return Array.from({ length: count }, (_, index) => ({
key: `A-${index}`,
label: `service-${index}`,
isEmptyLabel: false,
value: count - index,
rawValue: count - index,
ratio: (count - index) / count,
share: null,
queryName: 'A',
labels: { 'service.name': `service-${index}` },
}));
}
const renderList = (
count: number,
{ clickable = false } = {},
): ReturnType<typeof render> =>
render(
<TopList
panelId="panel-1"
rows={rowsOf(count)}
valueName="count()"
thresholds={[]}
onSelect={clickable ? jest.fn() : undefined}
/>,
);
const renderedRows = (): HTMLElement[] =>
screen.queryAllByTestId('top-list-row');
mockListLayout();
const focusedRowIndex = (): string | null =>
document.activeElement?.getAttribute('data-row-index') ?? null;
// Moving focus can scroll the window first, and the target row mounts a frame later.
let user: ReturnType<typeof userEvent.setup>;
beforeEach(() => {
user = userEvent.setup({ pointerEventsCheck: 0 });
});
async function pressKey(key: string): Promise<void> {
await user.keyboard(`{${key}}`);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 100));
});
}
const hover = (element: Element): Promise<void> => user.hover(element);
describe('TopList', () => {
it('renders every row of a list that fits', () => {
renderList(5);
expect(renderedRows()).toHaveLength(5);
});
it.each([100, 1000])('renders only a window of a %i-row list', (count) => {
renderList(count);
const rendered = renderedRows().length;
expect(rendered).toBeGreaterThan(0);
expect(rendered).toBeLessThan(40);
});
it('jumps to the first and last rows with Home and End', async () => {
renderList(20, { clickable: true });
renderedRows()[5].focus();
await pressKey('End');
expect(focusedRowIndex()).toBe('19');
await pressKey('Home');
expect(focusedRowIndex()).toBe('0');
});
it('stays put at the ends of the list', async () => {
renderList(3, { clickable: true });
const rows = renderedRows();
rows[0].focus();
await pressKey('ArrowUp');
expect(rows[0]).toHaveFocus();
});
it('numbers rows and shows their share when asked', () => {
const rows = rowsOf(2).map((row, index) => ({
...row,
share: index === 0 ? 2 / 3 : 1 / 3,
}));
render(
<TopList
panelId="panel-1"
rows={rows}
valueName="count()"
thresholds={[]}
showRank
showShare
/>,
);
expect(
screen.getAllByTestId('top-list-row-rank').map((rank) => rank.textContent),
).toStrictEqual(['1', '2']);
expect(
screen
.getAllByTestId('top-list-row-share')
.map((share) => share.textContent),
).toStrictEqual(['67%', '33%']);
});
it('paints bars the panel color unless a background threshold matches', () => {
render(
<TopList
panelId="panel-1"
rows={rowsOf(2)}
valueName="count()"
barColor="#00C853"
thresholds={[
{ value: 2, operator: '>=', color: 'Red', format: 'background' },
]}
/>,
);
const fills = screen.getAllByTestId('top-list-row-fill');
expect(fills[0].style.getPropertyValue('--fill-color')).not.toBe('#00C853');
expect(fills[1].style.getPropertyValue('--fill-color')).toBe('#00C853');
});
it('heads the columns that are shown', () => {
render(
<TopList
panelId="panel-1"
rows={rowsOf(2)}
valueName="count()"
labelName="service.name"
thresholds={[]}
showRank
showShare
/>,
);
expect(screen.getByTestId('top-list-header').textContent).toBe(
'#service.nameSharecount()',
);
});
it('explains a header on hover with its full name', async () => {
render(
<TopList
panelId="panel-1"
rows={rowsOf(2)}
valueName="sum(signoz_calls_total)"
labelName="service.name"
thresholds={[]}
/>,
);
await hover(screen.getByTestId('top-list-header-value'));
const tooltip = await screen.findAllByTestId(
'top-list-header-tooltip',
{},
{ timeout: 2000 },
);
expect(tooltip[0]).toHaveTextContent(
'sum(signoz_calls_total)The value each row is ranked by.',
);
});
it('follows the pointer with the hovered row in the tooltip', async () => {
const rows = rowsOf(2).map((row) => ({ ...row, share: 0.5 }));
render(
<TopList
panelId="panel-1"
rows={rows}
valueName="count()"
thresholds={[]}
showShare
/>,
);
await hover(renderedRows()[1]);
await expect(
screen.findByTestId('top-list-tooltip-title'),
).resolves.toHaveTextContent('service-1');
expect(
screen.getAllByTestId('top-list-tooltip-row').map((row) => row.textContent),
).toStrictEqual(['count()1', 'Share of listed total50%']);
});
it('hides the tooltip over the empty space below the rows', async () => {
renderList(2);
await hover(renderedRows()[1]);
await screen.findByTestId('top-list-tooltip');
await hover(screen.getByTestId('top-list'));
expect(screen.queryByTestId('top-list-tooltip')).not.toBeInTheDocument();
});
it('hides the tooltip when the pointer leaves the list', async () => {
renderList(2);
await hover(renderedRows()[0]);
await screen.findByTestId('top-list-tooltip');
await user.unhover(screen.getByTestId('top-list').parentElement as Element);
expect(screen.queryByTestId('top-list-tooltip')).not.toBeInTheDocument();
});
it('hints at drilldown, not pinning, when rows are clickable', async () => {
render(
<TopList
panelId="panel-1"
rows={rowsOf(2)}
valueName="count()"
thresholds={[]}
onSelect={jest.fn()}
/>,
);
await hover(renderedRows()[0]);
const footer = await screen.findByTestId('uplot-tooltip-footer');
expect(footer).toHaveTextContent('Click to drilldown');
expect(footer).not.toHaveTextContent('to pin the tooltip');
});
it('leaves the footer out when rows are not clickable', async () => {
renderList(2);
await hover(renderedRows()[0]);
await screen.findByTestId('top-list-tooltip');
expect(screen.queryByTestId('uplot-tooltip-footer')).not.toBeInTheDocument();
});
it('shows neither rank nor share by default', () => {
renderList(3);
expect(screen.queryByTestId('top-list-row-rank')).not.toBeInTheDocument();
expect(screen.queryByTestId('top-list-row-share')).not.toBeInTheDocument();
});
it('cuts the middle out of a label wider than its bar', () => {
// 100px bar, 17px of label inset, 10px per character: 8 characters fit.
jest.spyOn(Element.prototype, 'clientWidth', 'get').mockReturnValue(100);
jest.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({
font: '',
measureText: (text: string) => ({ width: text.length * 10 }),
} as unknown as CanvasRenderingContext2D);
renderList(1, { clickable: true });
expect(screen.getByTestId('top-list-row-label')).toHaveTextContent(
'serv…e-0',
);
expect(renderedRows()[0]).toHaveAttribute('aria-label', 'service-0: 1');
});
it('focuses a row that was out of view once it renders', async () => {
renderList(1000, { clickable: true });
renderedRows()[0].focus();
await pressKey('End');
expect(focusedRowIndex()).toBe('999');
});
it('scrolls a row moved to below the view fully into it', async () => {
renderList(100, { clickable: true });
const container = screen.getByTestId('top-list').parentElement as HTMLElement;
const rowHeight = parseInt(
screen.getByTestId('top-list').style.getPropertyValue('--row-height'),
10,
);
const rowsTop = LIST_PADDING_Y / 2 + HEADER_HEIGHT + ROW_GAP;
const rowBottom = (index: number): number =>
rowsTop + index * (rowHeight + ROW_GAP) + rowHeight;
const firstHidden = Array.from({ length: 100 }, (_, index) => index).find(
(index) => rowBottom(index) > container.clientHeight,
) as number;
(
container.querySelector(
`[data-row-index="${firstHidden - 1}"]`,
) as HTMLElement
).focus();
await pressKey('ArrowDown');
expect(focusedRowIndex()).toBe(String(firstHidden));
expect(container.scrollTop + container.clientHeight).toBeGreaterThanOrEqual(
rowBottom(firstHidden),
);
});
it('makes one row the Tab stop and moves it with focus', async () => {
renderList(5, { clickable: true });
const tabStops = (): string[] =>
renderedRows()
.filter((row) => row.tabIndex === 0)
.map((row) => row.getAttribute('data-row-index') as string);
expect(tabStops()).toStrictEqual(['0']);
renderedRows()[0].focus();
await pressKey('ArrowDown');
expect(tabStops()).toStrictEqual(['1']);
});
it('moves through rows that are not clickable by keyboard', async () => {
renderList(20);
renderedRows()[0].focus();
await pressKey('End');
expect(focusedRowIndex()).toBe('19');
});
it('positions each row in the whole list', () => {
renderList(100);
const [first] = renderedRows();
expect(first.closest('li')).toHaveAttribute('aria-posinset', '1');
expect(first.closest('li')).toHaveAttribute('aria-setsize', '100');
});
it('renders rows that are not clickable as plain list items', () => {
renderList(3);
expect(renderedRows().map((row) => row.tagName)).toStrictEqual([
'DIV',
'DIV',
'DIV',
]);
expect(renderedRows()[0].closest('li')).toHaveAttribute(
'aria-label',
'service-0: 3',
);
});
it('keeps the tooltip on the hovered row when a refetch reorders the rows', async () => {
const rows = rowsOf(3);
const { rerender } = render(
<TopList
panelId="panel-1"
rows={rows}
valueName="count()"
thresholds={[]}
/>,
);
await hover(renderedRows()[1]);
await expect(
screen.findByTestId('top-list-tooltip-title'),
).resolves.toHaveTextContent('service-1');
rerender(
<TopList
panelId="panel-1"
rows={[rows[1], rows[0], rows[2]]}
valueName="count()"
thresholds={[]}
/>,
);
expect(screen.getByTestId('top-list-tooltip-title')).toHaveTextContent(
'service-1',
);
});
});

View File

@@ -0,0 +1,109 @@
import {
DashboardtypesPanelKindDTO,
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTOKind as TopListPluginKind,
Querybuildertypesv5ColumnTypeDTO,
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal as MetricSignal,
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregationDTOSignal as TraceSignal,
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
Querybuildertypesv5QueryEnvelopeFormulaDTOType,
Querybuildertypesv5RequestTypeDTO,
type DashboardtypesTopListAppearanceDTO,
type DashboardtypesTopListPanelSpecDTO,
type Querybuildertypesv5ColumnDescriptorDTO,
type Querybuildertypesv5MetricAggregationDTO,
type Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregationDTO as TraceQuerySpec,
type Querybuildertypesv5QueryEnvelopeBuilderDTO,
type Querybuildertypesv5QueryEnvelopeDTO,
type Querybuildertypesv5QueryEnvelopeFormulaDTO,
type Querybuildertypesv5QueryRangeRequestDTO,
type Querybuildertypesv5ScalarDataDTO,
type Querybuildertypesv5TraceAggregationDTO,
type QueryRangeV5200,
} from 'api/generated/services/sigNoz.schemas';
import type { PanelOfKind } from '../../../types/rendererProps';
export function topListPanel(
spec: DashboardtypesTopListPanelSpecDTO = {},
): PanelOfKind<'signoz/TopListPanel'> {
return {
kind: DashboardtypesPanelKindDTO.Panel,
spec: {
display: { name: 'Top services' },
plugin: { kind: TopListPluginKind['signoz/TopListPanel'], spec },
queries: [],
},
};
}
export const appearance = (
overrides: Partial<DashboardtypesTopListAppearanceDTO> = {},
): DashboardtypesTopListAppearanceDTO => ({
barColor: '#4E74F8',
...overrides,
});
export const groupColumn = (
name: string,
queryName = 'A',
): Querybuildertypesv5ColumnDescriptorDTO => ({
name,
queryName,
columnType: Querybuildertypesv5ColumnTypeDTO.group,
});
export const valueColumn = (
name = '__result',
aggregationIndex = 0,
queryName = 'A',
): Querybuildertypesv5ColumnDescriptorDTO => ({
name,
queryName,
columnType: Querybuildertypesv5ColumnTypeDTO.aggregation,
aggregationIndex,
});
export function scalarResponse(
results: Querybuildertypesv5ScalarDataDTO[],
): QueryRangeV5200 {
return {
status: 'success',
data: {
type: Querybuildertypesv5RequestTypeDTO.scalar,
data: { results },
},
};
}
export const requestWith = (
queries: Querybuildertypesv5QueryEnvelopeDTO[],
): Querybuildertypesv5QueryRangeRequestDTO => ({
compositeQuery: { queries },
});
export const builderQuery = (
spec: Omit<TraceQuerySpec, 'signal'>,
): Querybuildertypesv5QueryEnvelopeBuilderDTO => ({
type: Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
spec: { signal: TraceSignal.traces, ...spec },
});
export const traceQuery = (
aggregation: Querybuildertypesv5TraceAggregationDTO,
): Querybuildertypesv5QueryEnvelopeBuilderDTO =>
builderQuery({ name: 'A', aggregations: [aggregation] });
export const metricQuery = (
aggregation: Querybuildertypesv5MetricAggregationDTO,
): Querybuildertypesv5QueryEnvelopeBuilderDTO => ({
type: Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
spec: { name: 'A', signal: MetricSignal.metrics, aggregations: [aggregation] },
});
export const formulaQuery = (
name: string,
expression: string,
): Querybuildertypesv5QueryEnvelopeFormulaDTO => ({
type: Querybuildertypesv5QueryEnvelopeFormulaDTOType.builder_formula,
spec: { name, expression },
});

View File

@@ -0,0 +1,70 @@
const CONTAINER_HEIGHT = 280;
const CONTAINER_WIDTH = 600;
const ROW_HEIGHT = 28;
const SCROLL_HEIGHT = ROW_HEIGHT * 1000;
const heightOf = (element: Element): number =>
element.hasAttribute('data-index') ? ROW_HEIGHT : CONTAINER_HEIGHT;
/**
* jsdom has no layout, so the virtualized list would render no rows. Gives the scroll
* container and the measured rows (`data-index`) real heights, and makes `scrollTo`
* move `scrollTop` and fire `scroll` the way a browser does.
*/
export function mockListLayout(): void {
const originalScrollTo = Object.getOwnPropertyDescriptor(
Element.prototype,
'scrollTo',
);
beforeEach(() => {
jest
.spyOn(HTMLElement.prototype, 'getBoundingClientRect')
.mockImplementation(function rect(this: HTMLElement): DOMRect {
const height = heightOf(this);
return {
width: CONTAINER_WIDTH,
height,
top: 0,
left: 0,
bottom: height,
right: CONTAINER_WIDTH,
x: 0,
y: 0,
toJSON: () => ({}),
};
});
jest
.spyOn(HTMLElement.prototype, 'offsetHeight', 'get')
.mockImplementation(function height(this: HTMLElement): number {
return heightOf(this);
});
jest
.spyOn(HTMLElement.prototype, 'offsetWidth', 'get')
.mockReturnValue(CONTAINER_WIDTH);
jest
.spyOn(Element.prototype, 'clientHeight', 'get')
.mockReturnValue(CONTAINER_HEIGHT);
jest
.spyOn(Element.prototype, 'scrollHeight', 'get')
.mockReturnValue(SCROLL_HEIGHT);
Element.prototype.scrollTo = function scrollTo(
this: Element,
options?: ScrollToOptions | number,
): void {
if (typeof options === 'object' && options.top !== undefined) {
this.scrollTop = options.top;
this.dispatchEvent(new Event('scroll'));
}
};
});
afterEach(() => {
jest.restoreAllMocks();
if (originalScrollTo) {
Object.defineProperty(Element.prototype, 'scrollTo', originalScrollTo);
} else {
delete (Element.prototype as Partial<Element>).scrollTo;
}
});
}

View File

@@ -0,0 +1,64 @@
@use '../../../../../../../../styles/scrollbar' as *;
.container {
flex: 1;
min-height: 0;
overflow-y: auto;
@include custom-scrollbar;
}
// Rows share these columns through subgrid; the shown ones are set inline. Vertical
// padding is set inline too, where it also stands in for unrendered rows.
.list {
display: grid;
align-content: start;
column-gap: 10px;
row-gap: 1px;
margin: 0;
padding-inline: 4px;
list-style: none;
}
// Zero-height row holding the widest value, so the shared columns keep
// their size while rows scroll in and out of the rendered window. The negative
// margin cancels the row gap after it.
.sizer {
display: grid;
grid-column: 1 / -1;
grid-template-columns: subgrid;
height: 0;
margin-bottom: -1px;
padding: 0 8px;
overflow: hidden;
visibility: hidden;
white-space: nowrap;
}
.sizerValue {
font-size: 12px;
font-weight: var(--font-weight-medium);
font-variant-numeric: tabular-nums;
}
.sizerMuted {
font-size: 12px;
font-variant-numeric: tabular-nums;
}
// Measured for label truncation, so it carries the label's font.
.sizerBar {
font-size: 12px;
}
// Lets the pointer pass through to the rows underneath; otherwise the tooltip catches
// it and stops following.
// Sized to its content like the chart tooltips, up to TooltipPlugin's maxWidth/maxHeight;
// the floor keeps a short one from collapsing narrower than a scatter tooltip.
.tooltip {
width: max-content;
min-width: 320px;
max-width: 450px;
max-height: 600px;
overflow: auto;
pointer-events: none;
}

View File

@@ -0,0 +1,201 @@
import {
type CSSProperties,
useCallback,
useMemo,
useRef,
useState,
} from 'react';
import type { PrecisionOption } from 'components/Graph/types';
import { useResizeObserver } from 'hooks/useDimensions';
import TooltipFooter from 'lib/visualization/panels/components/TooltipFooter';
import type { PanelThreshold } from '../../../../types/threshold';
import { HEADER_HEIGHT, LIST_PADDING_Y } from '../../constants';
import { useLabelFitter } from '../../hooks/useLabelFitter';
import { useTopListTooltip } from '../../hooks/useTopListTooltip';
import { useTopListVirtualizer } from '../../hooks/useTopListVirtualizer';
import type { TopListRow as TopListRowData } from '../../types';
import {
getGridColumns,
getNavigationTarget,
getRowHeight,
getWidestShare,
getWidestValue,
type RowColors,
} from '../../utils/rowDisplay';
import TopListHeader from '../TopListHeader/TopListHeader';
import TopListRow from '../TopListRow/TopListRow';
import TopListTooltip from '../TopListTooltip/TopListTooltip';
import styles from './TopList.module.scss';
const RESIZE_DEBOUNCE_MS = 100;
interface TopListProps {
/** Identifies the panel in tooltip analytics. */
panelId: string;
rows: TopListRowData[];
/** What the values measure, named in each row's tooltip. */
valueName: string;
/** Heads the label column: the group-by keys behind each label. */
labelName?: string;
unit?: string;
precision?: PrecisionOption;
thresholds: PanelThreshold[];
/** Bar color where no threshold recolours it; unset uses the accent. */
barColor?: string;
showRank?: boolean;
showShare?: boolean;
onSelect?: (
row: TopListRowData,
colors: RowColors,
coordinates: { x: number; y: number },
) => void;
}
function TopList({
panelId,
rows,
valueName,
labelName = '',
unit,
precision,
thresholds,
barColor,
showRank = false,
showShare = false,
onSelect,
}: TopListProps): JSX.Element {
const containerRef = useRef<HTMLDivElement>(null);
const sizerBarRef = useRef<HTMLSpanElement>(null);
const fitLabel = useLabelFitter(sizerBarRef);
const tooltip = useTopListTooltip();
const hoveredRow = useMemo(
() =>
tooltip.rowKey === null
? undefined
: rows.find((row) => row.key === tooltip.rowKey),
[rows, tooltip.rowKey],
);
const { height } = useResizeObserver(containerRef, RESIZE_DEBOUNCE_MS);
const rowHeight = getRowHeight(rows.length, height - HEADER_HEIGHT);
const { virtualItems, paddingTop, paddingBottom, focusRow } =
useTopListVirtualizer({ count: rows.length, rowHeight, containerRef });
const [focusedIndex, setFocusedIndex] = useState(0);
// The focused row may be scrolled out of the rendered window; the list stays reachable by Tab.
const tabStop = virtualItems.some(({ index }) => index === focusedIndex)
? focusedIndex
: virtualItems[0]?.index;
const widestValue = useMemo(
() => getWidestValue(rows, unit, precision),
[rows, unit, precision],
);
const widestShare = useMemo(
() => (showShare ? getWidestShare(rows) : ''),
[rows, showShare],
);
const handleNavigate = useCallback(
(index: number, key: string): boolean => {
const target = getNavigationTarget(index, key, rows.length);
if (target === null) {
return false;
}
focusRow(target);
return true;
},
[rows.length, focusRow],
);
const listStyle = {
'--row-height': `${rowHeight}px`,
'--header-height': `${HEADER_HEIGHT}px`,
gridTemplateColumns: getGridColumns(showRank, showShare),
paddingTop: LIST_PADDING_Y / 2 + paddingTop,
paddingBottom: LIST_PADDING_Y / 2 + paddingBottom,
} as CSSProperties;
return (
<div
ref={containerRef}
className={styles.container}
onScroll={tooltip.hide}
onMouseLeave={tooltip.hide}
onMouseMove={tooltip.hideOffRow}
>
<ol
ref={tooltip.listRef}
data-testid="top-list"
className={styles.list}
style={listStyle}
>
<TopListHeader
valueName={valueName}
labelName={labelName}
showRank={showRank}
showShare={showShare}
/>
<li aria-hidden className={styles.sizer}>
{showRank && (
<span className={styles.sizerMuted}>{String(rows.length)}</span>
)}
<span ref={sizerBarRef} className={styles.sizerBar} />
{showShare && <span className={styles.sizerMuted}>{widestShare}</span>}
<span className={styles.sizerValue}>{widestValue}</span>
</li>
{virtualItems.map(({ index }) => (
<TopListRow
key={rows[index].key}
row={rows[index]}
index={index}
count={rows.length}
isTabStop={index === tabStop}
unit={unit}
precision={precision}
thresholds={thresholds}
barColor={barColor}
showRank={showRank}
showShare={showShare}
fitLabel={fitLabel}
onHover={tooltip.show}
onSelect={onSelect}
onNavigate={handleNavigate}
onFocus={setFocusedIndex}
/>
))}
</ol>
{hoveredRow && (
<tooltip.TooltipInPortal
top={tooltip.top}
left={tooltip.left}
unstyled
applyPositionStyle
className={styles.tooltip}
>
<TopListTooltip
row={hoveredRow}
valueName={valueName}
unit={unit}
precision={precision}
thresholds={thresholds}
barColor={barColor}
showShare={showShare}
footer={
onSelect && (
<TooltipFooter
id={panelId}
isPinned={false}
canPin={false}
dismiss={tooltip.hide}
/>
)
}
/>
</tooltip.TooltipInPortal>
)}
</div>
);
}
export default TopList;

View File

@@ -0,0 +1,17 @@
import styles from './TopListHeader.module.scss';
interface HeaderTooltipProps {
name: string;
description: string;
}
function HeaderTooltip({ name, description }: HeaderTooltipProps): JSX.Element {
return (
<div data-testid="top-list-header-tooltip" className={styles.tooltip}>
<span className={styles.tooltipName}>{name}</span>
<span className={styles.tooltipDescription}>{description}</span>
</div>
);
}
export default HeaderTooltip;

View File

@@ -0,0 +1,55 @@
// Stays on top while rows scroll under it, so it needs the panel's surface.
.header {
position: sticky;
top: 0;
z-index: 1;
display: grid;
grid-column: 1 / -1;
grid-template-columns: subgrid;
align-items: center;
height: var(--header-height);
padding: 0 8px;
border-bottom: 1px solid var(--l1-border);
background: var(--l2-background);
font-size: 12px;
line-height: 16px;
color: var(--l3-foreground);
white-space: nowrap;
}
// Capped so a long value name doesn't widen its column past the values.
.cell {
justify-self: end;
max-width: 120px;
overflow: hidden;
text-align: right;
text-overflow: ellipsis;
cursor: default;
}
// Lines up with the labels inside the bars.
.label {
justify-self: start;
max-width: 100%;
min-width: 0;
padding: 0 8px;
overflow: hidden;
text-overflow: ellipsis;
cursor: default;
}
.tooltip {
display: flex;
flex-direction: column;
gap: 2px;
max-width: 280px;
}
.tooltipName {
font-weight: var(--font-weight-medium);
word-break: break-word;
}
.tooltipDescription {
color: var(--l2-foreground);
}

View File

@@ -0,0 +1,74 @@
import { Tooltip } from '@signozhq/ui/tooltip';
import HeaderTooltip from './HeaderTooltip';
import styles from './TopListHeader.module.scss';
interface TopListHeaderProps {
valueName: string;
/** The group-by keys behind each label; empty when the query has no group-by. */
labelName: string;
showRank: boolean;
showShare: boolean;
}
function TopListHeader({
valueName,
labelName,
showRank,
showShare,
}: TopListHeaderProps): JSX.Element {
return (
<li aria-hidden data-testid="top-list-header" className={styles.header}>
{showRank && (
<Tooltip
title={<HeaderTooltip name="Rank" description="Position in the list." />}
>
<span className={styles.cell}>#</span>
</Tooltip>
)}
{labelName ? (
<Tooltip
title={
<HeaderTooltip
name={labelName}
description="The group each row stands for."
/>
}
align="start"
>
<span className={styles.label}>{labelName}</span>
</Tooltip>
) : (
<span />
)}
{showShare && (
<Tooltip
title={
<HeaderTooltip
name="Share"
description="Each row's value as a percentage of the listed rows' total."
/>
}
>
<span className={styles.cell}>Share</span>
</Tooltip>
)}
<Tooltip
title={
<HeaderTooltip
name={valueName}
description="The value each row is ranked by."
/>
}
align="end"
>
<span data-testid="top-list-header-value" className={styles.cell}>
{valueName}
</span>
</Tooltip>
</li>
);
}
export default TopListHeader;

View File

@@ -0,0 +1,116 @@
.item {
display: grid;
grid-column: 1 / -1;
grid-template-columns: subgrid;
}
.row {
display: grid;
grid-column: 1 / -1;
grid-template-columns: subgrid;
align-items: center;
height: var(--row-height);
padding: 0 8px;
border: 0;
border-radius: 2px;
outline: 1px solid transparent;
outline-offset: -1px;
background: transparent;
font: inherit;
text-align: left;
transition: background-color 120ms;
// The panel surface is --l2-background, so the hovered row sits a level above it.
&:hover {
background: var(--l3-background);
}
&:focus-visible {
outline-color: var(--bg-robin-500);
}
}
.isInteractive {
cursor: pointer;
}
.value {
font-size: 12px;
line-height: 16px;
font-weight: var(--font-weight-medium);
color: var(--l1-foreground);
text-align: right;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
// Rank and share: supporting numbers beside the value.
.muted {
font-size: 12px;
line-height: 16px;
color: var(--l3-foreground);
text-align: right;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.isNonNumeric {
color: var(--l3-foreground);
}
// The label sits on the bar, spanning the whole column so it isn't cut at the fill.
// The track sits a level above the panel surface (--l2-background).
.bar {
position: relative;
display: flex;
align-items: center;
min-width: 0;
height: calc(var(--row-height) - 4px);
border-radius: 2px;
background: var(--l3-background);
transition: background-color 120ms;
.row:hover & {
background: var(--l3-background-hover);
}
}
.fill {
position: absolute;
inset: 0 auto 0 0;
border-radius: 2px;
background: color-mix(in srgb, var(--bg-robin-500) 35%, transparent);
.row:hover & {
background: color-mix(in srgb, var(--bg-robin-500) 48%, transparent);
}
}
.hasFillColor {
background: color-mix(in srgb, var(--fill-color) 35%, transparent);
.row:hover & {
background: color-mix(in srgb, var(--fill-color) 48%, transparent);
}
}
.label {
position: relative;
min-width: 0;
padding: 0 8px;
overflow: hidden;
font-size: 12px;
line-height: 16px;
color: var(--l2-foreground);
white-space: nowrap;
text-overflow: ellipsis;
.row:hover & {
color: var(--l1-foreground);
}
}
.isEmptyLabel {
font-style: italic;
color: var(--l3-foreground);
}

View File

@@ -0,0 +1,193 @@
import {
type CSSProperties,
memo,
useMemo,
type KeyboardEvent as ReactKeyboardEvent,
type MouseEvent as ReactMouseEvent,
} from 'react';
import cx from 'classnames';
import type { PrecisionOption } from 'components/Graph/types';
import type { PanelThreshold } from '../../../../types/threshold';
import type { TopListRow as TopListRowData } from '../../types';
import {
formatRowValue,
formatShare,
resolveRowColors,
type RowColors,
} from '../../utils/rowDisplay';
import styles from './TopListRow.module.scss';
interface TopListRowProps {
row: TopListRowData;
/** Position in the ranked list. */
index: number;
/** Rows in the list, rendered or not. */
count: number;
/** The list's one Tab stop; arrow keys move it. */
isTabStop: boolean;
unit?: string;
precision?: PrecisionOption;
thresholds: PanelThreshold[];
/** Bar color where no threshold recolours it; unset uses the accent. */
barColor?: string;
showRank: boolean;
showShare: boolean;
/** Shortens a label to fit its bar. */
fitLabel: (label: string) => string;
/** Moves the list's tooltip to this row, at the pointer. */
onHover: (rowKey: string, event: ReactMouseEvent<HTMLElement>) => void;
onSelect?: (
row: TopListRowData,
colors: RowColors,
coordinates: { x: number; y: number },
) => void;
/** Handles a navigation key; returns whether it moved focus. */
onNavigate: (index: number, key: string) => boolean;
onFocus: (index: number) => void;
}
function TopListRow({
row,
index,
count,
isTabStop,
unit,
precision,
thresholds,
barColor,
showRank,
showShare,
fitLabel,
onHover,
onSelect,
onNavigate,
onFocus,
}: TopListRowProps): JSX.Element {
const displayValue = useMemo(
() => formatRowValue(row, unit, precision),
[row, unit, precision],
);
const colors = useMemo(
() => resolveRowColors(row.value, thresholds, unit, barColor),
[row.value, thresholds, unit, barColor],
);
const displayShare = showShare ? formatShare(row.share) : null;
const knownShare =
displayShare !== null && row.share !== null ? displayShare : undefined;
const displayLabel = useMemo(() => fitLabel(row.label), [fitLabel, row.label]);
const handleClick = (event: ReactMouseEvent<HTMLButtonElement>): void => {
if (!onSelect) {
return;
}
// Enter/Space clicks carry no pointer position; anchor the menu under the row.
if (event.detail === 0) {
const { left, bottom } = event.currentTarget.getBoundingClientRect();
onSelect(row, colors, { x: left, y: bottom });
return;
}
onSelect(row, colors, { x: event.clientX, y: event.clientY });
};
const handleMouseMove = (event: ReactMouseEvent<HTMLElement>): void =>
onHover(row.key, event);
const handleKeyDown = (event: ReactKeyboardEvent<HTMLElement>): void => {
if (onNavigate(index, event.key)) {
event.preventDefault();
}
};
const ariaLabel = `${row.label}: ${displayValue}${
knownShare ? `, ${knownShare} of listed total` : ''
}`;
const content = (
<>
{showRank && (
<span data-testid="top-list-row-rank" className={styles.muted}>
{index + 1}
</span>
)}
<span className={styles.bar}>
<span
data-testid="top-list-row-fill"
className={cx(styles.fill, {
[styles.hasFillColor]: !!colors.barColor,
})}
style={
{
width: `${row.ratio * 100}%`,
'--fill-color': colors.barColor,
} as CSSProperties
}
/>
<span
data-testid="top-list-row-label"
className={cx(styles.label, { [styles.isEmptyLabel]: row.isEmptyLabel })}
>
{displayLabel}
</span>
</span>
{displayShare && (
<span data-testid="top-list-row-share" className={styles.muted}>
{displayShare}
</span>
)}
<span
data-testid="top-list-row-value"
className={cx(styles.value, {
[styles.isNonNumeric]: row.value === null,
})}
style={{ color: colors.valueColor }}
>
{displayValue}
</span>
</>
);
return (
<li
className={styles.item}
aria-setsize={count}
aria-posinset={index + 1}
aria-label={onSelect ? undefined : ariaLabel}
>
{onSelect ? (
<button
type="button"
aria-haspopup="menu"
aria-label={ariaLabel}
tabIndex={isTabStop ? 0 : -1}
data-row-index={index}
data-testid="top-list-row"
className={cx(styles.row, styles.isInteractive)}
onClick={handleClick}
onMouseMove={handleMouseMove}
onKeyDown={handleKeyDown}
onFocus={(): void => onFocus(index)}
>
{content}
</button>
) : (
// Focusable without an action so the keyboard can still walk the list.
// oxlint-disable-next-line jsx-a11y/no-static-element-interactions
<div
// oxlint-disable-next-line jsx-a11y/no-noninteractive-tabindex
tabIndex={isTabStop ? 0 : -1}
data-row-index={index}
data-testid="top-list-row"
className={styles.row}
onMouseMove={handleMouseMove}
onKeyDown={handleKeyDown}
onFocus={(): void => onFocus(index)}
>
{content}
</div>
)}
</li>
);
}
export default memo(TopListRow);

View File

@@ -0,0 +1,55 @@
import { type ReactNode, useMemo } from 'react';
import type { PrecisionOption } from 'components/Graph/types';
import TooltipCard from 'lib/uPlotV2/components/Tooltip/components/TooltipCard/TooltipCard';
import type { PanelThreshold } from '../../../../types/threshold';
import type { TopListRow } from '../../types';
import {
ACCENT_COLOR,
getTooltipContent,
resolveRowColors,
} from '../../utils/rowDisplay';
interface TopListTooltipProps {
row: TopListRow;
/** What the values measure. */
valueName: string;
unit?: string;
precision?: PrecisionOption;
thresholds: PanelThreshold[];
/** Bar color where no threshold recolours it; unset uses the accent. */
barColor?: string;
showShare: boolean;
/** Hints for what a click does; none when rows aren't clickable. */
footer?: ReactNode;
}
function TopListTooltip({
row,
valueName,
unit,
precision,
thresholds,
barColor,
showShare,
footer,
}: TopListTooltipProps): JSX.Element {
const { rows, mutedRows } = useMemo(
() => getTooltipContent(row, { valueName, unit, precision, showShare }),
[row, valueName, unit, precision, showShare],
);
const colors = resolveRowColors(row.value, thresholds, unit, barColor);
return (
<TooltipCard
title={row.label}
color={colors.barColor ?? ACCENT_COLOR}
rows={rows}
mutedRows={mutedRows}
footer={footer}
testId="top-list-tooltip"
/>
);
}
export default TopListTooltip;

View File

@@ -0,0 +1,10 @@
/** Groups shown when the query sets no limit. */
export const DEFAULT_LIMIT = 10;
/** Row heights by density, roomiest first: comfortable, default, compact. */
export const ROW_HEIGHTS = [32, 28, 24] as const;
export const DEFAULT_ROW_HEIGHT = 28;
export const ROW_GAP = 1;
/** The list's top and bottom padding combined. */
export const LIST_PADDING_Y = 12;
/** The sticky column header row. */
export const HEADER_HEIGHT = 24;

View File

@@ -0,0 +1,72 @@
import { ChartBarDecreasing } from '@signozhq/icons';
import { QueryBuilderField } from 'components/QueryBuilderV2/queryBuilderFields.types';
import type { PanelDefinition } from '../../types/panelDefinition';
import { QueryModeKind } from '../../types/panelCapabilities';
import QueryBuilderEditorPane from 'pages/DashboardPage/DashboardContainer/PanelEditor/PanelEditorQueryBuilder/QueryBuilderEditorPane';
import Renderer from './Renderer';
import { DEFAULT_LIMIT } from './constants';
import { sections } from './sections';
import { getTopListDataWarning } from './utils/warnings';
import {
Querybuildertypesv5RequestTypeDTO,
TelemetrytypesSignalDTO,
} from 'api/generated/services/sigNoz.schemas';
import { QueryMode } from 'types/api/queryBuilder/queryBuilderData';
export const definition: PanelDefinition<'signoz/TopListPanel'> = {
kind: 'signoz/TopListPanel',
displayName: 'Top List',
mode: 'query',
icon: ChartBarDecreasing,
Renderer,
EditorPane: QueryBuilderEditorPane,
sections,
supportedQueryModesKindMap: {
[QueryMode.QUERY_BUILDER]: {
kind: QueryModeKind.SIGNAL,
signals: [
TelemetrytypesSignalDTO.metrics,
TelemetrytypesSignalDTO.logs,
TelemetrytypesSignalDTO.traces,
],
},
[QueryMode.CLICKHOUSE]: { kind: QueryModeKind.SIGNAL_LESS },
},
queryBuilderFields: {
// A list without a group by is a single row.
[QueryBuilderField.GroupBy]: { state: 'pinned' },
// Picks top or bottom N on the server; a client-side flip would show the top N reversed.
[QueryBuilderField.OrderBy]: {
state: 'pinned',
placeholder: 'Default highest first',
},
[QueryBuilderField.Limit]: {
state: 'pinned',
placeholder: `Default ${DEFAULT_LIMIT} for Top List`,
},
// Ignored for logs and traces scalars; for metrics they apply before reduceTo.
[QueryBuilderField.Functions]: { state: 'hidden' },
},
queryCapabilities: {
requestType: Querybuildertypesv5RequestTypeDTO.scalar,
formatTableResultForUI: false,
bucketedStepInterval: false,
orderTiebreaker: false,
serverPaginated: false,
defaultRowLimit: DEFAULT_LIMIT,
},
// Formulas join their inputs on group values, so every query groups by the same keys.
syncedQueryBuilderFields: [QueryBuilderField.GroupBy],
getDataWarning: getTopListDataWarning,
actions: {
view: true,
edit: true,
clone: true,
download: { csv: true, png: true, svg: true },
createAlert: false,
search: false,
drilldown: true,
},
};

View File

@@ -0,0 +1,53 @@
import { type RefObject, useCallback, useMemo } from 'react';
import { useResizeObserver } from 'hooks/useDimensions';
import { truncateMiddle } from '../utils/rowDisplay';
/** The label's horizontal padding inside the bar, plus a pixel for canvas/DOM rounding. */
const LABEL_INSET_X = 17;
const RESIZE_DEBOUNCE_MS = 100;
let canvasContext: CanvasRenderingContext2D | null | undefined;
function getCanvasContext(): CanvasRenderingContext2D | null {
if (canvasContext === undefined) {
canvasContext = document.createElement('canvas').getContext('2d');
}
return canvasContext;
}
/**
* Middle-truncates labels to the bar column, measured on `barRef`, which must carry the
* label's font. Labels pass through unchanged until the column has a width.
*/
export function useLabelFitter(
barRef: RefObject<HTMLElement>,
): (label: string) => string {
const { width } = useResizeObserver(barRef, RESIZE_DEBOUNCE_MS);
const maxWidth = width - LABEL_INSET_X;
const font = useMemo(() => {
const node = barRef.current;
if (!node || maxWidth <= 0) {
return null;
}
const { fontWeight, fontSize, fontFamily } = getComputedStyle(node);
return `${fontWeight} ${fontSize} ${fontFamily}`;
}, [barRef, maxWidth]);
return useCallback(
(label: string): string => {
const context = font ? getCanvasContext() : null;
if (!context || !font) {
return label;
}
context.font = font;
return truncateMiddle(
label,
maxWidth,
(value) => context.measureText(value).width,
);
},
[font, maxWidth],
);
}

View File

@@ -0,0 +1,78 @@
import {
type FC,
type MouseEvent as ReactMouseEvent,
useCallback,
useRef,
} from 'react';
import { useTooltip, useTooltipInPortal } from '@visx/tooltip';
import type { TooltipInPortalProps } from '@visx/tooltip/lib/hooks/useTooltipInPortal';
/** Above the dashboard grid, like the chart tooltips. */
const TOOLTIP_Z_INDEX = 1000;
interface TopListTooltip {
/** The hovered row's key, or null when the tooltip is hidden. */
rowKey: string | null;
top?: number;
left?: number;
show: (rowKey: string, event: ReactMouseEvent<HTMLElement>) => void;
hide: () => void;
/** Hides the tooltip when the pointer is over the list but not on a row. */
hideOffRow: (event: ReactMouseEvent<HTMLElement>) => void;
/** The element the tooltip is positioned against. */
listRef: (element: HTMLElement | null) => void;
TooltipInPortal: FC<TooltipInPortalProps>;
}
/** One tooltip for the whole list, following the pointer the way the chart tooltips do. */
export function useTopListTooltip(): TopListTooltip {
const {
tooltipOpen,
tooltipData,
tooltipTop,
tooltipLeft,
showTooltip,
hideTooltip,
} = useTooltip<string>();
const { containerRef, containerBounds, TooltipInPortal } = useTooltipInPortal({
scroll: true,
detectBounds: true,
zIndex: TOOLTIP_Z_INDEX,
});
// Read at event time so `show` stays stable for the memoised rows.
const boundsRef = useRef(containerBounds);
boundsRef.current = containerBounds;
const show = useCallback(
(rowKey: string, event: ReactMouseEvent<HTMLElement>): void => {
const { left, top } = boundsRef.current;
showTooltip({
tooltipData: rowKey,
tooltipLeft: event.clientX - left,
tooltipTop: event.clientY - top,
});
},
[showTooltip],
);
const hideOffRow = useCallback(
(event: ReactMouseEvent<HTMLElement>): void => {
if (!(event.target as Element).closest('[data-row-index]')) {
hideTooltip();
}
},
[hideTooltip],
);
return {
rowKey: tooltipOpen ? (tooltipData ?? null) : null,
top: tooltipTop,
left: tooltipLeft,
show,
hide: hideTooltip,
hideOffRow,
listRef: containerRef,
TooltipInPortal,
};
}

View File

@@ -0,0 +1,92 @@
import { type RefObject, useCallback, useEffect, useRef } from 'react';
import { useVirtualizer, type VirtualItem } from '@tanstack/react-virtual';
import { HEADER_HEIGHT, LIST_PADDING_Y, ROW_GAP } from '../constants';
const OVERSCAN = 10;
/** Size assumed until the container is measured, so the first paint isn't empty. */
const INITIAL_RECT = { width: 0, height: 600 };
/** Frames to wait for a scrolled-to row to mount before giving up on focusing it. */
const FOCUS_RETRY_FRAMES = 10;
/** The first row's offset in the container: the list's top padding, the header and the gap below it. */
const ROWS_OFFSET = LIST_PADDING_Y / 2 + HEADER_HEIGHT + ROW_GAP;
interface UseTopListVirtualizerArgs {
count: number;
rowHeight: number;
containerRef: RefObject<HTMLDivElement>;
}
interface TopListVirtualizer {
/** The rows to render: those in view plus an overscan either side. */
virtualItems: VirtualItem[];
/** Space standing in for the rows above and below the rendered window. */
paddingTop: number;
paddingBottom: number;
/** Scrolls the row into view if needed, then focuses it. */
focusRow: (index: number) => void;
}
export function useTopListVirtualizer({
count,
rowHeight,
containerRef,
}: UseTopListVirtualizerArgs): TopListVirtualizer {
const virtualizer = useVirtualizer({
count,
getScrollElement: () => containerRef.current,
estimateSize: () => rowHeight,
gap: ROW_GAP,
scrollMargin: ROWS_OFFSET,
// Keeps a row scrolled to from landing under the sticky header.
scrollPaddingStart: HEADER_HEIGHT,
scrollPaddingEnd: LIST_PADDING_Y / 2,
overscan: OVERSCAN,
initialRect: INITIAL_RECT,
});
const focusFrame = useRef<number>();
// Every row takes the density's height, so a density change re-lays out every row.
useEffect(() => {
virtualizer.measure();
}, [virtualizer, rowHeight]);
useEffect(() => (): void => cancelAnimationFrame(focusFrame.current ?? 0), []);
const focusRow = useCallback(
(index: number): void => {
cancelAnimationFrame(focusFrame.current ?? 0);
virtualizer.scrollToIndex(index, { align: 'auto' });
let attempts = 0;
const tryFocus = (): void => {
const row = containerRef.current?.querySelector<HTMLElement>(
`[data-row-index="${index}"]`,
);
if (row) {
// The virtualizer already scrolled; a native focus scroll would fight it.
row.focus({ preventScroll: true });
return;
}
if (attempts < FOCUS_RETRY_FRAMES) {
attempts += 1;
focusFrame.current = requestAnimationFrame(tryFocus);
}
};
tryFocus();
},
[virtualizer, containerRef],
);
const virtualItems = virtualizer.getVirtualItems();
const first = virtualItems[0];
const last = virtualItems[virtualItems.length - 1];
return {
virtualItems,
// Item offsets include the scroll margin; the total size doesn't.
paddingTop: first ? first.start - ROWS_OFFSET : 0,
paddingBottom: last
? virtualizer.getTotalSize() - (last.end - ROWS_OFFSET)
: 0,
focusRow,
};
}

View File

@@ -0,0 +1,22 @@
import {
SectionKind,
ThresholdVariant,
type SectionConfig,
} from '../../types/sections';
export const sections: SectionConfig[] = [
{
kind: SectionKind.Visualization,
controls: { switchPanelKind: true, timePreference: true },
},
{
kind: SectionKind.Appearance,
controls: { showRank: true, showShare: true, barColor: true },
},
{ kind: SectionKind.Formatting, controls: { unit: true, decimals: true } },
{
kind: SectionKind.Thresholds,
controls: { variant: ThresholdVariant.COMPARISON },
},
{ kind: SectionKind.ContextLinks },
];

View File

@@ -0,0 +1,38 @@
export interface TopListRow {
/**
* Unique per row and built from its group values, so it follows the row across
* refetches; labels can repeat (e.g. a legend with no `{{…}}`).
*/
key: string;
label: string;
/** True when every group value behind the label was missing, or the legend filled to blank. */
isEmptyLabel: boolean;
/** The ranked value, or null when the cell isn't a finite number ("NaN", "Inf", "n/a", null). */
value: number | null;
/** The cell as the server sent it, shown when `value` is null. */
rawValue: unknown;
/** Bar length: `value` over the largest positive value, 0–1. Zero for values ≤ 0 and null. */
ratio: number;
/** `value` over the sum of every row's value; null for null values and when any value is negative. */
share: number | null;
/** Source query, the drilldown target. */
queryName: string;
/** Group-by key → value, the drilldown filters. */
labels: Record<string, string>;
}
export interface TopListData {
rows: TopListRow[];
/** Group-by columns behind each label; empty when the query has no group-by. */
labelColumnNames: string[];
/** The ranked value column. */
valueColumnName: string;
/** What the ranked value measures. Unlike `valueColumnName`, never the legend template. */
valueName: string;
/** Value columns after the first, which the ranking ignores. */
ignoredValueColumns: string[];
/** Other enabled queries and formulas, which the ranking ignores. */
ignoredResults: string[];
/** The group-by key the ranked query orders by, when it orders by one instead of its value. */
orderedByGroupKey: string | null;
}

View File

@@ -0,0 +1,110 @@
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import {
groupColumn,
requestWith,
scalarResponse,
topListPanel as panelWith,
traceQuery,
valueColumn,
} from '../../__tests__/fixtures';
import { getTopListCsvRows } from '../csv';
function dataWith(groupColumns: string[], rows: unknown[][]): PanelQueryData {
return {
response: scalarResponse([
{
queryName: 'A',
columns: [...groupColumns.map((name) => groupColumn(name)), valueColumn()],
data: rows,
},
]),
requestPayload: undefined,
legendMap: {},
};
}
describe('getTopListCsvRows', () => {
it('exports the rows in ranked order with formatted values', () => {
const data = dataWith(
['service.name'],
[
['auth', 25],
['payment', 1500],
],
);
expect(
getTopListCsvRows(panelWith({ formatting: { unit: 'ms' } }), data),
).toStrictEqual([
{ 'service.name': 'payment', A: '1.5 s' },
{ 'service.name': 'auth', A: '25 ms' },
]);
});
it('names the label column after every group-by key', () => {
const data = dataWith(['http.route', 'region'], [['GET /orders', 'eu', 3]]);
expect(Object.keys(getTopListCsvRows(panelWith({}), data)[0])).toStrictEqual([
'http.route, region',
'A',
]);
});
it('heads the value column with what it measures, not the legend template', () => {
const data = {
...dataWith(['service.name'], [['auth', 25]]),
legendMap: { A: '{{service.name}}' },
};
expect(getTopListCsvRows(panelWith({}), data)).toStrictEqual([
{ 'service.name': 'auth', A: '25' },
]);
});
it('falls back to a generic label header without a group-by', () => {
const data = dataWith([], [[42]]);
expect(getTopListCsvRows(panelWith({}), data)).toStrictEqual([
{ Label: 'A', A: '42' },
]);
});
it('adds rank and share columns when the panel shows them', () => {
const data = dataWith(
['service.name'],
[
['auth', 25],
['payment', 75],
],
);
const panel = panelWith({
appearance: { showRank: true, showShare: true, barColor: '#4E74F8' },
});
expect(getTopListCsvRows(panel, data)).toStrictEqual([
{ Rank: '1', 'service.name': 'payment', A: '75', Share: '75%' },
{ Rank: '2', 'service.name': 'auth', A: '25', Share: '25%' },
]);
});
it('suffixes a header that repeats another instead of overwriting its column', () => {
const data = {
...dataWith(['Rank'], [['auth', 25]]),
requestPayload: requestWith([
traceQuery({ expression: 'count()', alias: 'Share' }),
]),
};
const panel = panelWith({
appearance: { showRank: true, showShare: true, barColor: '#4E74F8' },
});
expect(getTopListCsvRows(panel, data)).toStrictEqual([
{ Rank: '1', 'Rank (2)': 'auth', Share: '25', 'Share (2)': '100%' },
]);
});
it('exports nothing for an empty result', () => {
expect(getTopListCsvRows(panelWith({}), dataWith([], []))).toStrictEqual([]);
});
});

View File

@@ -0,0 +1,285 @@
import {
MetrictypesSpaceAggregationDTO,
Querybuildertypesv5OrderDirectionDTO,
type Querybuildertypesv5MetricAggregationDTO,
type Querybuildertypesv5QueryEnvelopeDTO,
type Querybuildertypesv5TraceAggregationDTO,
} from 'api/generated/services/sigNoz.schemas';
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import {
appearance,
builderQuery,
formulaQuery as formula,
groupColumn,
metricQuery,
requestWith,
scalarResponse,
topListPanel,
traceQuery,
valueColumn,
} from '../../__tests__/fixtures';
import { prepareTopListData } from '../prepareData';
import { getTopListDataWarning } from '../warnings';
const panel = topListPanel();
interface Result {
queryName: string;
rows: [string, number][];
}
function dataWith(
results: Result[],
queries: Querybuildertypesv5QueryEnvelopeDTO[],
): PanelQueryData {
return {
response: scalarResponse(
results.map(({ queryName, rows }) => ({
queryName,
columns: [
groupColumn('service.name', queryName),
valueColumn('__result', 0, queryName),
],
data: rows,
})),
),
requestPayload: requestWith(queries),
legendMap: {},
};
}
const query = (
name: string,
limit?: number,
): Querybuildertypesv5QueryEnvelopeDTO => builderQuery({ name, limit });
type Aggregation =
| Querybuildertypesv5TraceAggregationDTO
| Querybuildertypesv5MetricAggregationDTO;
/** Metrics aggregate a metric, traces and logs an expression. */
const isMetric = (
aggregation: Aggregation,
): aggregation is Querybuildertypesv5MetricAggregationDTO =>
'metricName' in aggregation;
const aggregated = (
aggregation: Aggregation,
): Querybuildertypesv5QueryEnvelopeDTO =>
isMetric(aggregation) ? metricQuery(aggregation) : traceQuery(aggregation);
const A: Result = { queryName: 'A', rows: [['checkout', 10]] };
const B: Result = { queryName: 'B', rows: [['checkout', 2]] };
const F1: Result = { queryName: 'F1', rows: [['checkout', 5]] };
describe('top list with several queries', () => {
it('ranks the first query in builder order, whatever order the response lists them in', () => {
const data = dataWith(
[F1, B, A],
[query('A'), query('B'), formula('F1', 'A / B')],
);
const { rows, ignoredResults } = prepareTopListData(data);
expect(rows.map((row) => [row.queryName, row.value])).toStrictEqual([
['A', 10],
]);
expect(ignoredResults).toStrictEqual(['B', 'F1']);
});
it('ranks the formula when its inputs are disabled', () => {
// The server leaves disabled queries out of the response.
const data = dataWith([F1], [query('A'), query('B'), formula('F1', 'A / B')]);
expect(prepareTopListData(data).rows[0].queryName).toBe('F1');
expect(getTopListDataWarning(panel, data)).toBeNull();
});
it('names the results the ranking leaves out', () => {
const data = dataWith([A, B], [query('A'), query('B')]);
expect(getTopListDataWarning(panel, data)?.messages).toStrictEqual([
'The list ranks "A" only; "B" is not shown. Disable the queries you don\'t want to rank.',
]);
});
it('warns when a formula reads inputs cut to their own limit', () => {
const data = dataWith(
[F1],
[query('A', 10), query('B', 10), query('C', 5), formula('F1', 'A / B')],
);
expect(getTopListDataWarning(panel, data)?.messages).toStrictEqual([
'"A", "B" are limited before the formula combines them, so the formula only sees groups in every input\'s top N. Set the limit on the formula instead.',
]);
});
it('stays quiet about limited formula inputs when the list ranks a query', () => {
const data = dataWith(
[A],
[query('A', 10), query('B', 10), formula('F1', 'A / B')],
);
expect(prepareTopListData(data).rows[0].queryName).toBe('A');
expect(getTopListDataWarning(panel, data)).toBeNull();
});
it("lists rows in the query's ascending order for a bottom N", () => {
const data = dataWith(
[
{
queryName: 'A',
rows: [
['checkout', 10],
['auth', 2],
['search', 5],
],
},
],
[
builderQuery({
name: 'A',
order: [
{
key: { name: 'count()' },
direction: Querybuildertypesv5OrderDirectionDTO.asc,
},
],
}),
],
);
expect(prepareTopListData(data).rows.map((row) => row.value)).toStrictEqual([
2, 5, 10,
]);
});
it('warns when the query orders by a group key instead of the value', () => {
const data = dataWith(
[
{
queryName: 'A',
rows: [
['auth', 2],
['checkout', 10],
],
},
],
[
builderQuery({
name: 'A',
groupBy: [{ name: 'service.name' }],
order: [
{
key: { name: 'service.name' },
direction: Querybuildertypesv5OrderDirectionDTO.asc,
},
],
}),
],
);
const { rows } = prepareTopListData(data);
expect(rows.map((row) => row.value)).toStrictEqual([10, 2]);
expect(getTopListDataWarning(panel, data)?.messages).toStrictEqual([
'The query orders by "service.name", so the list shows the first groups by that key rather than the top values. Order by the value instead.',
]);
});
});
describe('top list value name', () => {
it.each([
{
scenario: 'an alias',
aggregation: { alias: 'requests', expression: 'count()' },
expected: 'requests',
},
{
scenario: 'an expression',
aggregation: { expression: 'p99(duration_nano)' },
expected: 'p99(duration_nano)',
},
{
scenario: 'a metric',
aggregation: {
metricName: 'signoz_calls_total',
spaceAggregation: MetrictypesSpaceAggregationDTO.sum,
},
expected: 'sum(signoz_calls_total)',
},
])('names the value after $scenario', ({ aggregation, expected }) => {
expect(
prepareTopListData(dataWith([A], [aggregated(aggregation)])).valueName,
).toBe(expected);
});
it('names a ranked formula after its expression', () => {
const data = dataWith([F1], [query('A'), query('B'), formula('F1', 'A / B')]);
expect(prepareTopListData(data).valueName).toBe('A / B');
});
it('falls back to the query name with nothing to describe it', () => {
expect(prepareTopListData(dataWith([A], [query('A')])).valueName).toBe('A');
});
});
describe('share of total warning', () => {
const sharePanel = topListPanel({
appearance: appearance({ showShare: true }),
});
const shareMessage = (data: PanelQueryData): string | undefined =>
getTopListDataWarning(sharePanel, data)?.messages?.find((message) =>
message.startsWith('Share of total'),
);
it.each([
{
scenario: 'a percentile',
aggregation: { expression: 'p99(duration_nano)' },
},
{ scenario: 'an average', aggregation: { expression: 'avg(duration_nano)' } },
{ scenario: 'a maximum', aggregation: { expression: 'max(duration_nano)' } },
{
scenario: 'a metric averaged across series',
aggregation: {
metricName: 'cpu',
spaceAggregation: MetrictypesSpaceAggregationDTO.avg,
},
},
])('warns when ranking $scenario', ({ aggregation }) => {
expect(shareMessage(dataWith([A], [aggregated(aggregation)]))).toBeDefined();
});
it.each([
{ scenario: 'a count', aggregation: { expression: 'count()' } },
{ scenario: 'a sum', aggregation: { expression: 'sum(bytes)' } },
{
scenario: 'a metric summed across series',
aggregation: {
metricName: 'signoz_calls_total',
spaceAggregation: MetrictypesSpaceAggregationDTO.sum,
},
},
])('stays quiet when ranking $scenario', ({ aggregation }) => {
expect(
shareMessage(dataWith([A], [aggregated(aggregation)])),
).toBeUndefined();
});
it('stays quiet for a formula, whose aggregation it cannot tell', () => {
const data = dataWith([F1], [query('A'), query('B'), formula('F1', 'A / B')]);
expect(shareMessage(data)).toBeUndefined();
});
it('stays quiet when the panel does not show shares', () => {
const data = dataWith(
[A],
[aggregated({ expression: 'p99(duration_nano)' })],
);
expect(getTopListDataWarning(panel, data)).toBeNull();
});
});

View File

@@ -0,0 +1,333 @@
import type {
PanelTable,
PanelTableColumn,
} from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import { EMPTY_LABEL, prepareTopListRows } from '../prepareData';
const groupColumn = (name: string): PanelTableColumn => ({
name,
id: name,
queryName: 'A',
isValueColumn: false,
});
const valueColumn = (name = 'count()'): PanelTableColumn => ({
name,
id: name,
queryName: 'A',
isValueColumn: true,
});
function serviceTable(
rows: [unknown, unknown][],
overrides: Partial<PanelTable> = {},
): PanelTable {
return {
queryName: 'A',
legend: '',
columns: [groupColumn('service.name'), valueColumn()],
rows: rows.map(([service, value]) => ({
data: { 'service.name': service, 'count()': value },
})),
...overrides,
};
}
const summarize = (table: PanelTable): [string, number | null, number][] =>
prepareTopListRows([table]).rows.map((row) => [
row.label,
row.value,
row.ratio,
]);
describe('prepareTopListRows', () => {
it('ranks rows by value, descending, with bars relative to the largest value', () => {
const table = serviceTable([
['auth', 30],
['payment', 40],
['checkout', 10],
]);
expect(summarize(table)).toStrictEqual([
['payment', 40, 1],
['auth', 30, 0.75],
['checkout', 10, 0.25],
]);
});
it('breaks ties by label so the order is stable across refreshes', () => {
const table = serviceTable([
['search', 5],
['auth', 5],
['checkout', 5],
]);
expect(summarize(table).map(([label]) => label)).toStrictEqual([
'auth',
'checkout',
'search',
]);
});
it('keeps non-numeric values without a bar, sorted last, with the raw cell for display', () => {
const table = serviceTable([
['nan', 'NaN'],
['inf', 'Inf'],
['missing', 'n/a'],
['null', null],
['ok', 7],
]);
const { rows } = prepareTopListRows([table]);
expect(rows.map((row) => [row.label, row.value, row.ratio])).toStrictEqual([
['ok', 7, 1],
['inf', null, 0],
['missing', null, 0],
['nan', null, 0],
['null', null, 0],
]);
expect(rows[1].rawValue).toBe('Inf');
});
it('keeps zero and negative values with an empty bar', () => {
const table = serviceTable([
['down', -4],
['flat', 0],
['up', 8],
]);
expect(summarize(table)).toStrictEqual([
['up', 8, 1],
['flat', 0, 0],
['down', -4, 0],
]);
});
it('shows rows with empty bars when no value is positive', () => {
const table = serviceTable([
['a', 0],
['b', -1],
]);
expect(summarize(table)).toStrictEqual([
['a', 0, 0],
['b', -1, 0],
]);
});
it('gives each numeric row its share of the total', () => {
const table = serviceTable([
['auth', 30],
['payment', 60],
['missing', 'n/a'],
['checkout', 10],
]);
expect(
prepareTopListRows([table]).rows.map((row) => [row.label, row.share]),
).toStrictEqual([
['payment', 0.6],
['auth', 0.3],
['checkout', 0.1],
['missing', null],
]);
});
it.each([
{ scenario: 'any value is negative', values: [8, -4] },
{ scenario: 'the total is zero', values: [0, 0] },
])('gives no shares when $scenario', ({ values }) => {
const table = serviceTable(
values.map((value, index) => [`s${index}`, value]),
);
expect(
prepareTopListRows([table]).rows.map((row) => row.share),
).toStrictEqual([null, null]);
});
it.each([
{ legend: '', expected: 'count()' },
{ legend: '{{service.name}}', expected: 'A' },
])(
'names the value $expected when the legend is "$legend"',
({ legend, expected }) => {
const table = serviceTable([['auth', 1]], {
legend,
columns: [groupColumn('service.name'), valueColumn(legend || 'count()')],
});
expect(prepareTopListRows([table]).valueName).toBe(expected);
},
);
it('parses numeric strings', () => {
const table = serviceTable([
['a', '12'],
['b', ' '],
]);
expect(summarize(table)).toStrictEqual([
['a', 12, 1],
['b', null, 0],
]);
});
it('labels a missing group value as empty for both null (traces/logs) and "" (metrics)', () => {
const table = serviceTable([
[null, 2],
['', 1],
]);
const { rows } = prepareTopListRows([table]);
expect(rows.map((row) => [row.label, row.isEmptyLabel])).toStrictEqual([
[EMPTY_LABEL, true],
[EMPTY_LABEL, true],
]);
expect(new Set(rows.map((row) => row.key)).size).toBe(2);
});
it('joins several group values, marking only the missing ones', () => {
const table: PanelTable = {
queryName: 'A',
legend: '',
columns: [groupColumn('http.route'), groupColumn('region'), valueColumn()],
rows: [
{
data: { 'http.route': 'GET /orders', region: 'us-east-1', 'count()': 3 },
},
{ data: { 'http.route': 'GET /cart', region: null, 'count()': 1 } },
],
};
expect(summarize(table).map(([label]) => label)).toStrictEqual([
'GET /orders · us-east-1',
`GET /cart · ${EMPTY_LABEL}`,
]);
});
it('fills a legend template, rendering a key the row lacks as empty', () => {
const table = serviceTable([['checkout', 1]], {
legend: '{{service.name}} ({{region}})',
});
expect(summarize(table)[0][0]).toBe('checkout ()');
});
it('labels a legend that fills to blank as empty', () => {
const table = serviceTable([['checkout', 1]], { legend: ' {{region}} ' });
const [row] = prepareTopListRows([table]).rows;
expect(row.label).toBe(EMPTY_LABEL);
expect(row.isEmptyLabel).toBe(true);
});
it('keys rows by their group values, so a reordered refetch keeps each key on its row', () => {
const keysByService = (rows: [unknown, unknown][]): Record<string, string> =>
Object.fromEntries(
prepareTopListRows([serviceTable(rows)]).rows.map((row) => [
row.label,
row.key,
]),
);
expect(
keysByService([
['auth', 1],
['payment', 2],
]),
).toStrictEqual(
keysByService([
['payment', 2],
['auth', 1],
]),
);
});
it('keeps rows distinct when a legend without variables gives them all one label', () => {
const table = serviceTable(
[
['a', 2],
['b', 1],
],
{ legend: 'requests' },
);
const { rows } = prepareTopListRows([table]);
expect(rows.map((row) => row.label)).toStrictEqual(['requests', 'requests']);
expect(new Set(rows.map((row) => row.key)).size).toBe(2);
});
it('labels a query without a group-by by its name', () => {
const table: PanelTable = {
queryName: 'A',
legend: '',
columns: [valueColumn()],
rows: [{ data: { 'count()': 42 } }],
};
const data = prepareTopListRows([table]);
expect(data.labelColumnNames).toStrictEqual([]);
expect(data.rows.map((row) => [row.label, row.value])).toStrictEqual([
['A', 42],
]);
});
it('ranks by the first value column and reports the rest as ignored', () => {
const table: PanelTable = {
queryName: 'A',
legend: '',
columns: [groupColumn('host'), valueColumn('p99'), valueColumn('p50')],
rows: [
{ data: { host: 'a', p99: 1, p50: 9 } },
{ data: { host: 'b', p99: 2, p50: 1 } },
],
};
const data = prepareTopListRows([table]);
expect(data.rows.map((row) => [row.label, row.value])).toStrictEqual([
['b', 2],
['a', 1],
]);
expect(data.ignoredValueColumns).toStrictEqual(['p50']);
});
it('carries the query and group values for drilldown filters', () => {
const table = serviceTable([
['checkout', 1],
['', 2],
[null, 3],
]);
const { rows } = prepareTopListRows([table]);
expect(rows.map((row) => [row.queryName, row.labels])).toStrictEqual([
['A', {}],
['A', { 'service.name': '' }],
['A', { 'service.name': 'checkout' }],
]);
});
it('returns no rows when no table has a value column', () => {
expect(prepareTopListRows([])).toStrictEqual({
rows: [],
labelColumnNames: [],
valueColumnName: '',
valueName: '',
ignoredValueColumns: [],
ignoredResults: [],
orderedByGroupKey: null,
});
expect(
prepareTopListRows([
{ queryName: 'A', legend: '', columns: [groupColumn('x')], rows: [] },
]).rows,
).toStrictEqual([]);
});
});

View File

@@ -0,0 +1,25 @@
import type { PanelTable } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import { prepareTopListRows } from '../prepareData';
describe('prepareTopListRows with an unlimited SQL result', () => {
it('ranks more rows than a function call can take as arguments', () => {
const count = 200_000;
const table: PanelTable = {
queryName: 'A',
legend: '',
columns: [
{ name: 'host', id: 'host', queryName: 'A', isValueColumn: false },
{ name: 'hits', id: 'hits', queryName: 'A', isValueColumn: true },
],
rows: Array.from({ length: count }, (_, index) => ({
data: { host: `host-${index}`, hits: index + 1 },
})),
};
const { rows } = prepareTopListRows([table]);
expect(rows).toHaveLength(count);
expect(rows[0]).toMatchObject({ label: `host-${count - 1}`, ratio: 1 });
});
});

View File

@@ -0,0 +1,110 @@
import type { TopListRow } from '../../types';
import {
formatShare,
getRowHeight,
getTooltipContent,
truncateMiddle,
} from '../rowDisplay';
// Each case: rows that fit at a density, given a 1px gap and 12px of list padding.
describe('getRowHeight', () => {
it.each([
{ count: 10, height: 10 * 32 + 9 + 12, expected: 32 },
{ count: 10, height: 10 * 32 + 9 + 11, expected: 28 },
{ count: 10, height: 10 * 28 + 9 + 12, expected: 28 },
{ count: 10, height: 10 * 28 + 9 + 11, expected: 24 },
{ count: 200, height: 400, expected: 24 },
])(
'uses $expected px rows for $count rows in $height px',
({ count, height, expected }) => {
expect(getRowHeight(count, height)).toBe(expected);
},
);
it('falls back to the default height before the panel is measured', () => {
expect(getRowHeight(10, 0)).toBe(28);
});
});
describe('formatShare', () => {
it.each([
{ share: 0.5, expected: '50%' },
{ share: 0.12345, expected: '12%' },
{ share: 0.0995, expected: '10%' },
{ share: 0.0456, expected: '4.6%' },
{ share: 0.0004, expected: '<0.1%' },
{ share: 0, expected: '0%' },
{ share: 1, expected: '100%' },
{ share: null, expected: '—' },
])('formats $share as $expected', ({ share, expected }) => {
expect(formatShare(share)).toBe(expected);
});
});
describe('truncateMiddle', () => {
const byLength = (text: string): number => text.length;
it('keeps a label that fits', () => {
expect(truncateMiddle('checkout', 8, byLength)).toBe('checkout');
});
it('keeps both ends of a label that does not', () => {
expect(truncateMiddle('recommendationservice', 9, byLength)).toBe(
'reco…vice',
);
});
it('leaves only the ellipsis when nothing else fits', () => {
expect(truncateMiddle('checkout', 1, byLength)).toBe('…');
});
});
describe('getTooltipContent', () => {
const row = (overrides: Partial<TopListRow> = {}): TopListRow => ({
key: 'A-0',
label: 'checkout',
isEmptyLabel: false,
value: 1500,
rawValue: 1500,
ratio: 1,
share: 0.25,
queryName: 'A',
labels: { 'service.name': 'checkout' },
...overrides,
});
const options = {
valueName: 'p99(duration_nano)',
unit: 'ms',
showShare: true,
};
it('names the value and its share', () => {
expect(getTooltipContent(row(), options).rows).toStrictEqual([
{ key: 'value', label: 'p99(duration_nano)', value: '1.5 s' },
{ key: 'share', label: 'Share of listed total', value: '25%' },
]);
});
it('leaves the share out when the panel hides it or the row has none', () => {
expect(
getTooltipContent(row(), { ...options, showShare: false }).rows,
).toHaveLength(1);
expect(getTooltipContent(row({ share: null }), options).rows).toHaveLength(1);
});
it('lists the group values only when the label is not one already', () => {
expect(getTooltipContent(row(), options).mutedRows).toStrictEqual([]);
expect(
getTooltipContent(
row({
label: 'checkout · eu',
labels: { 'service.name': 'checkout', region: 'eu' },
}),
options,
).mutedRows,
).toStrictEqual([
{ key: 'service.name', label: 'service.name', value: 'checkout' },
{ key: 'region', label: 'region', value: 'eu' },
]);
});
});

View File

@@ -0,0 +1,95 @@
import {
Querybuildertypesv5QueryEnvelopeClickHouseSQLDTOType,
type Querybuildertypesv5ColumnDescriptorDTO,
type Querybuildertypesv5QueryRangeRequestDTO,
} from 'api/generated/services/sigNoz.schemas';
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import {
groupColumn as group,
requestWith,
scalarResponse,
topListPanel,
valueColumn as aggregation,
} from '../../__tests__/fixtures';
import { getTopListDataWarning } from '../warnings';
const panel = topListPanel();
function dataWith(
columns: Querybuildertypesv5ColumnDescriptorDTO[],
rows: unknown[][],
legend = '',
requestPayload?: Querybuildertypesv5QueryRangeRequestDTO,
): PanelQueryData {
return {
response: scalarResponse([{ queryName: 'A', columns, data: rows }]),
requestPayload,
legendMap: legend ? { A: legend } : {},
};
}
describe('getTopListDataWarning', () => {
it('stays quiet for a grouped single-value result', () => {
const data = dataWith(
[group('service.name'), aggregation('__result')],
[
['checkout', 2],
['auth', 1],
],
);
expect(getTopListDataWarning(panel, data)).toBeNull();
});
it('stays quiet when there are no rows', () => {
expect(getTopListDataWarning(panel, dataWith([], []))).toBeNull();
});
it('warns when the query has no group by', () => {
const data = dataWith([aggregation('__result')], [[42]]);
expect(getTopListDataWarning(panel, data)?.messages).toStrictEqual([
'The query has no group by, so the list shows a single total. Add a group by to rank its groups.',
]);
});
it('names the value columns the ranking ignores', () => {
const data = dataWith(
[
group('host'),
aggregation('p99'),
aggregation('p50', 1),
aggregation('p90', 2),
],
[['a', 1, 2, 3]],
'',
// ClickHouse value columns keep their SQL alias as their name.
requestWith([
{
type: Querybuildertypesv5QueryEnvelopeClickHouseSQLDTOType.clickhouse_sql,
spec: { name: 'A', query: 'SELECT 1' },
},
]),
);
expect(getTopListDataWarning(panel, data)?.messages).toStrictEqual([
'The list ranks the first value column only; "p50", "p90" are not shown.',
]);
});
it('warns when every row shares one label', () => {
const data = dataWith(
[group('service.name'), aggregation('__result')],
[
['checkout', 2],
['auth', 1],
],
'requests',
);
expect(getTopListDataWarning(panel, data)?.messages).toStrictEqual([
'Every row has the same label. Use {{group-by key}} variables in the legend to tell rows apart.',
]);
});
});

View File

@@ -0,0 +1,68 @@
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import type { PanelOfKind } from '../../../types/rendererProps';
import { resolveDecimalPrecision } from '../../../utils/chartAppearance/resolvers';
import { LABEL_NAME_SEPARATOR, prepareTopListData } from './prepareData';
import type { TopListRow } from '../types';
import { formatRowValue, formatShare } from './rowDisplay';
const RANK_HEADER = 'Rank';
const LABEL_HEADER = 'Label';
const VALUE_HEADER = 'Value';
const SHARE_HEADER = 'Share';
interface CsvColumn {
header: string;
cell: (row: TopListRow, index: number) => string;
}
/** Suffixes repeated headers (`Share`, `Share (2)`) so no column overwrites another. */
function uniqueHeaders(headers: string[]): string[] {
const seen = new Set<string>();
return headers.map((header) => {
let unique = header;
for (let n = 2; seen.has(unique); n += 1) {
unique = `${header} (${n})`;
}
seen.add(unique);
return unique;
});
}
/** The list as shown: rows in ranked order with their rank, label, formatted value and share. */
export function getTopListCsvRows(
panel: PanelOfKind<'signoz/TopListPanel'>,
data: PanelQueryData,
): Record<string, string>[] {
const { formatting, appearance } = panel.spec.plugin.spec;
const { rows, labelColumnNames, valueName } = prepareTopListData(data);
const precision = resolveDecimalPrecision(formatting?.decimalPrecision);
const columns: CsvColumn[] = [
{
header: labelColumnNames.join(LABEL_NAME_SEPARATOR) || LABEL_HEADER,
cell: (row) => row.label,
},
{
header: valueName || VALUE_HEADER,
cell: (row) => formatRowValue(row, formatting?.unit, precision),
},
];
if (appearance?.showRank) {
columns.unshift({
header: RANK_HEADER,
cell: (_, index) => String(index + 1),
});
}
if (appearance?.showShare) {
columns.push({ header: SHARE_HEADER, cell: (row) => formatShare(row.share) });
}
const headers = uniqueHeaders(columns.map(({ header }) => header));
return rows.map((row, index) =>
Object.fromEntries(
columns.map(({ cell }, column) => [headers[column], cell(row, index)]),
),
);
}

View File

@@ -0,0 +1,216 @@
import { prepareScalarTables } from 'pages/DashboardPage/DashboardContainer/queryV5/prepareScalarTables';
import type {
PanelQueryData,
PanelTable,
PanelTableColumn,
PanelTableRow,
} from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import { getScalarResults } from 'pages/DashboardPage/DashboardContainer/queryV5/v5ResponseData';
import {
describeValue,
getQueryOrder,
getRankedOrder,
type SortDirection,
} from './querySpec';
import type { TopListData, TopListRow } from '../types';
export const EMPTY_LABEL = '(empty)';
const LABEL_SEPARATOR = ' · ';
/** Joins the group-by keys heading the label column. */
export const LABEL_NAME_SEPARATOR = ', ';
const LEGEND_VARIABLE = /\{\{\s*([^}]+?)\s*\}\}/g;
const EMPTY_DATA: TopListData = {
rows: [],
labelColumnNames: [],
valueColumnName: '',
valueName: '',
ignoredValueColumns: [],
ignoredResults: [],
orderedByGroupKey: null,
};
/** A missing group value is `null` for traces/logs and `""` for metrics. */
function isMissing(value: unknown): boolean {
return value == null || value === '';
}
/** Finite numbers only: the server sends NaN/±Inf as "NaN"/"Inf"/"-Inf" and a missing value as "n/a". */
function toFiniteNumber(value: unknown): number | null {
if (typeof value === 'number') {
return Number.isFinite(value) ? value : null;
}
if (typeof value === 'string' && value.trim() !== '') {
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : null;
}
return null;
}
function toGroupValue(value: unknown): string {
return typeof value === 'object'
? JSON.stringify(value)
: String(value as string | number | boolean);
}
function getCell(row: PanelTableRow, column: PanelTableColumn): unknown {
return row.data[column.id || column.name];
}
function resolveLabel(
labelColumns: PanelTableColumn[],
row: PanelTableRow,
labels: Record<string, string>,
table: PanelTable,
): Pick<TopListRow, 'label' | 'isEmptyLabel'> {
if (table.legend) {
// Unlike `getLabelName`, a key the row doesn't carry renders empty, not "undefined".
const label = table.legend.replace(
LEGEND_VARIABLE,
(_, key: string) => labels[key] ?? '',
);
return label.trim()
? { label, isEmptyLabel: false }
: { label: EMPTY_LABEL, isEmptyLabel: true };
}
if (labelColumns.length === 0) {
return { label: table.queryName, isEmptyLabel: false };
}
const parts = labelColumns.map((column) => getCell(row, column));
if (parts.every(isMissing)) {
return { label: EMPTY_LABEL, isEmptyLabel: true };
}
return {
label: parts
.map((part) => (isMissing(part) ? EMPTY_LABEL : toGroupValue(part)))
.join(LABEL_SEPARATOR),
isEmptyLabel: false,
};
}
/** By value in the query's direction; non-numeric values last; ties by label so the order is stable across refreshes. */
function compareRows(direction: SortDirection) {
return (a: TopListRow, b: TopListRow): number => {
if (a.value === null || b.value === null) {
if (a.value === b.value) {
return a.label.localeCompare(b.label);
}
return a.value === null ? 1 : -1;
}
const byValue = direction === 'asc' ? a.value - b.value : b.value - a.value;
return byValue || a.label.localeCompare(b.label);
};
}
/** Tables in builder order; the response lists them in no particular order. */
function orderTables(tables: PanelTable[], queryOrder: string[]): PanelTable[] {
const position = (table: PanelTable): number => {
const index = queryOrder.indexOf(table.queryName);
return index === -1 ? queryOrder.length : index;
};
return [...tables].sort((a, b) => position(a) - position(b));
}
const hasValueColumn = (table: PanelTable): boolean =>
table.columns.some((column) => column.isValueColumn);
/**
* Ranks the first value column of the first table that has one. The server already
* orders and limits, but its order isn't stable on ties, so the rows are sorted again here.
* A query ordered by a group key still lists by value: its rows are the first N groups.
*/
export function prepareTopListRows(
tables: PanelTable[],
direction: SortDirection = 'desc',
): TopListData {
const [table, ...otherTables] = tables.filter(hasValueColumn);
if (!table) {
return EMPTY_DATA;
}
const [valueColumn, ...ignoredColumns] = table.columns.filter(
(column) => column.isValueColumn,
);
const labelColumns = table.columns.filter((column) => !column.isValueColumn);
const keyCounts = new Map<string, number>();
const rows = table.rows.map((row): TopListRow => {
const labels: Record<string, string> = {};
labelColumns.forEach((column) => {
const value = getCell(row, column);
if (value != null) {
labels[column.name] = toGroupValue(value);
}
});
const groupKey = `${table.queryName}-${JSON.stringify(
labelColumns.map((column) => getCell(row, column) ?? null),
)}`;
const repeats = keyCounts.get(groupKey) ?? 0;
keyCounts.set(groupKey, repeats + 1);
const rawValue = getCell(row, valueColumn);
return {
key: repeats ? `${groupKey}-${repeats}` : groupKey,
...resolveLabel(labelColumns, row, labels, table),
value: toFiniteNumber(rawValue),
rawValue,
ratio: 0,
share: null,
queryName: valueColumn.queryName,
labels,
};
});
const values = rows
.map((row) => row.value)
.filter((value): value is number => value !== null);
const max = values.reduce((largest, value) => Math.max(largest, value), 0);
const total = values.some((value) => value < 0)
? 0
: values.reduce((sum, value) => sum + value, 0);
rows.forEach((row) => {
row.ratio =
max > 0 && row.value !== null && row.value > 0 ? row.value / max : 0;
row.share = total > 0 && row.value !== null ? row.value / total : null;
});
return {
rows: rows.sort(compareRows(direction)),
labelColumnNames: labelColumns.map((column) => column.name),
valueColumnName: valueColumn.name,
// A lone aggregation's column takes the legend, which labels rows here, not values.
valueName:
table.legend && valueColumn.name === table.legend
? valueColumn.queryName
: valueColumn.name,
ignoredValueColumns: ignoredColumns.map((column) => column.name),
ignoredResults: otherTables.map((other) => other.queryName),
orderedByGroupKey: null,
};
}
/** Ranks the first enabled query or formula, in builder order, in its order direction. */
export function prepareTopListData(data: PanelQueryData): TopListData {
const tables = prepareScalarTables({
results: getScalarResults(data.response),
legendMap: data.legendMap ?? {},
requestPayload: data.requestPayload,
});
const ordered = orderTables(tables, getQueryOrder(data.requestPayload));
const { direction, groupKey } = getRankedOrder(
data.requestPayload,
ordered.find(hasValueColumn)?.queryName,
);
const prepared = prepareTopListRows(ordered, direction);
const rankedQuery = prepared.rows[0]?.queryName;
// A bare query name ("A") says nothing about the value; the query spec can.
const valueName =
rankedQuery && prepared.valueName === rankedQuery
? (describeValue(data.requestPayload, rankedQuery) ?? rankedQuery)
: prepared.valueName;
return { ...prepared, valueName, orderedByGroupKey: groupKey };
}

View File

@@ -0,0 +1,138 @@
import {
Querybuildertypesv5QueryEnvelopeBuilderAIDTOType,
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
Querybuildertypesv5QueryEnvelopeFormulaDTOType,
Querybuildertypesv5QueryEnvelopeTraceOperatorDTOType,
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal as MetricSignal,
type Querybuildertypesv5BuilderQuerySpecDTO,
type Querybuildertypesv5QueryBuilderFormulaDTO,
type Querybuildertypesv5QueryBuilderTraceOperatorDTO,
type Querybuildertypesv5QueryEnvelopeDTO,
type Querybuildertypesv5QueryRangeRequestDTO,
} from 'api/generated/services/sigNoz.schemas';
export type SortDirection = 'asc' | 'desc';
export function findQueryEnvelope(
requestPayload: Querybuildertypesv5QueryRangeRequestDTO | undefined,
queryName: string | undefined,
): Querybuildertypesv5QueryEnvelopeDTO | undefined {
return requestPayload?.compositeQuery?.queries?.find(
(envelope) => envelope.spec?.name === queryName,
);
}
type RankedSpec =
| Querybuildertypesv5BuilderQuerySpecDTO
| Querybuildertypesv5QueryBuilderFormulaDTO
| Querybuildertypesv5QueryBuilderTraceOperatorDTO;
/** Builder queries, formulas and trace operators; PromQL and ClickHouse SQL have no spec to read. */
function findQuerySpec(
requestPayload: Querybuildertypesv5QueryRangeRequestDTO | undefined,
queryName: string | undefined,
): RankedSpec | undefined {
const envelope = findQueryEnvelope(requestPayload, queryName);
switch (envelope?.type) {
case Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query:
case Querybuildertypesv5QueryEnvelopeBuilderAIDTOType.builder_ai_query:
case Querybuildertypesv5QueryEnvelopeFormulaDTOType.builder_formula:
case Querybuildertypesv5QueryEnvelopeTraceOperatorDTOType.builder_trace_operator:
return envelope.spec;
default:
return undefined;
}
}
const isMetricSpec = (
spec: RankedSpec,
): spec is Extract<RankedSpec, { signal: MetricSignal }> =>
'signal' in spec && spec.signal === MetricSignal.metrics;
const AGGREGATION_FUNCTION = /^\s*([a-z_]\w*)\s*\(/i;
/**
* The ranked aggregation's function, lowercased: `p99` for `p99(duration_nano)`, the space
* aggregation for a metric. Null for formulas and ClickHouse SQL, which have none to read.
*/
export function getRankedAggregationFunction(
requestPayload: Querybuildertypesv5QueryRangeRequestDTO | undefined,
queryName: string,
): string | null {
const spec = findQuerySpec(requestPayload, queryName);
if (!spec || !('aggregations' in spec)) {
return null;
}
const name = isMetricSpec(spec)
? spec.aggregations?.[0]?.spaceAggregation
: spec.aggregations?.[0]?.expression?.match(AGGREGATION_FUNCTION)?.[1];
return name ? name.toLowerCase() : null;
}
/** The ranked aggregation as the query writes it: its alias, expression or formula. */
export function describeValue(
requestPayload: Querybuildertypesv5QueryRangeRequestDTO | undefined,
queryName: string,
): string | null {
const spec = findQuerySpec(requestPayload, queryName);
if (!spec) {
return null;
}
if (isMetricSpec(spec)) {
const [aggregation] = spec.aggregations ?? [];
if (!aggregation?.metricName) {
return null;
}
return aggregation.spaceAggregation
? `${aggregation.spaceAggregation}(${aggregation.metricName})`
: aggregation.metricName;
}
if ('aggregations' in spec) {
const [aggregation] = spec.aggregations ?? [];
if (aggregation?.alias || aggregation?.expression) {
return aggregation.alias || aggregation.expression || null;
}
}
return ('expression' in spec && spec.expression) || null;
}
interface RankedOrder {
direction: SortDirection;
groupKey: string | null;
}
/**
* How the ranked query orders its rows. The server orders by value, descending, when
* no order is set; ordering by a group-by key returns the first N groups by that key.
*/
export function getRankedOrder(
requestPayload: Querybuildertypesv5QueryRangeRequestDTO | undefined,
queryName: string | undefined,
): RankedOrder {
const spec = findQuerySpec(requestPayload, queryName);
const [order] = spec?.order ?? [];
const keyName = order?.key?.name;
if (!keyName) {
return { direction: 'desc', groupKey: null };
}
if (
spec &&
'groupBy' in spec &&
spec.groupBy?.some((key) => key.name === keyName)
) {
return { direction: 'desc', groupKey: keyName };
}
return {
direction: order.direction === 'asc' ? 'asc' : 'desc',
groupKey: null,
};
}
/** The request's queries and formulas, in builder order. */
export function getQueryOrder(
requestPayload: Querybuildertypesv5QueryRangeRequestDTO | undefined,
): string[] {
return (requestPayload?.compositeQuery?.queries ?? [])
.map((envelope) => envelope.spec?.name)
.filter((name): name is string => Boolean(name));
}

View File

@@ -0,0 +1,207 @@
import type { PrecisionOption } from 'components/Graph/types';
import type { TooltipCardRow } from 'lib/uPlotV2/components/Tooltip/components/TooltipCard/TooltipCard';
import type { PanelThreshold } from '../../../types/threshold';
import { resolveActiveThreshold } from '../../../utils/evaluateThresholds';
import { formatPanelValue } from '../../../utils/formatPanelValue';
import {
DEFAULT_ROW_HEIGHT,
LIST_PADDING_Y,
ROW_GAP,
ROW_HEIGHTS,
} from '../constants';
import type { TopListRow } from '../types';
export const ACCENT_COLOR = 'var(--bg-robin-500)';
const NO_VALUE = '—';
export interface RowColors {
barColor?: string;
valueColor?: string;
}
/**
* A matching threshold recolours the bar (`background` format) or the value (`text`).
* Bars no threshold recolours take `barColor`.
*/
export function resolveRowColors(
value: number | null,
thresholds: PanelThreshold[],
unit?: string,
barColor?: string,
): RowColors {
const base = { barColor };
if (value === null || thresholds.length === 0) {
return base;
}
const { threshold } = resolveActiveThreshold(thresholds, value, unit);
if (!threshold) {
return base;
}
return threshold.format === 'background'
? { barColor: threshold.color }
: { ...base, valueColor: threshold.color };
}
/** Non-numeric cells ("NaN", "n/a") are shown as the server sent them. */
export function formatRowValue(
row: TopListRow,
unit?: string,
precision?: PrecisionOption,
): string {
if (row.value !== null) {
return formatPanelValue(row.value, unit, precision);
}
if (typeof row.rawValue === 'string' && row.rawValue !== '') {
return row.rawValue;
}
return NO_VALUE;
}
/** Under 10% to one decimal, whole percents above; a nonzero share never reads as 0%. */
export function formatShare(share: number | null): string {
if (share === null) {
return NO_VALUE;
}
const percent = share * 100;
if (percent > 0 && percent < 0.1) {
return '<0.1%';
}
return `${percent < 10 ? Number(percent.toFixed(1)) : Math.round(percent)}%`;
}
interface TooltipContentOptions {
valueName: string;
unit?: string;
precision?: PrecisionOption;
showShare: boolean;
}
/**
* The value and, when shown, the share; then the group values behind the label, unless
* the label is the lone group value already.
*/
export function getTooltipContent(
row: TopListRow,
{ valueName, unit, precision, showShare }: TooltipContentOptions,
): { rows: TooltipCardRow[]; mutedRows: TooltipCardRow[] } {
const rows: TooltipCardRow[] = [
{
key: 'value',
label: valueName,
value: formatRowValue(row, unit, precision),
},
];
if (showShare && row.share !== null) {
rows.push({
key: 'share',
label: 'Share of listed total',
value: formatShare(row.share),
});
}
const groups = Object.entries(row.labels);
const isLabelTheGroup = groups.length === 1 && groups[0][1] === row.label;
return {
rows,
mutedRows: isLabelTheGroup
? []
: groups.map(([key, value]) => ({ key, label: key, value })),
};
}
const ELLIPSIS = '…';
/**
* Cuts the middle out of `text` so it fits `maxWidth`, keeping both ends: with
* multi-key labels and paths, the tail often tells rows apart.
*/
export function truncateMiddle(
text: string,
maxWidth: number,
measure: (value: string) => number,
): string {
if (measure(text) <= maxWidth) {
return text;
}
const fit = (kept: number): string =>
text.slice(0, Math.ceil(kept / 2)) +
ELLIPSIS +
text.slice(text.length - Math.floor(kept / 2));
let low = 0;
let high = text.length - 1;
while (low < high) {
const mid = Math.ceil((low + high) / 2);
if (measure(fit(mid)) <= maxWidth) {
low = mid;
} else {
high = mid - 1;
}
}
return fit(low);
}
/** The row a navigation key moves focus to, or null when the key isn't one or the move leaves the list. */
export function getNavigationTarget(
index: number,
key: string,
count: number,
): number | null {
const targets: Record<string, number> = {
ArrowDown: index + 1,
ArrowUp: index - 1,
Home: 0,
End: count - 1,
};
const target = targets[key];
return target === undefined || target < 0 || target >= count ? null : target;
}
const longest = (values: string[]): string =>
values.reduce(
(widest, value) => (value.length > widest.length ? value : widest),
'',
);
/**
* The widest formatted value across all rows. The list renders only the rows in view,
* so a hidden row carrying it keeps the value column from resizing as rows scroll in
* and out.
*/
export function getWidestValue(
rows: TopListRow[],
unit?: string,
precision?: PrecisionOption,
): string {
return longest(rows.map((row) => formatRowValue(row, unit, precision)));
}
/** The widest share across all rows, for the same reason as `getWidestValue`. */
export function getWidestShare(rows: TopListRow[]): string {
return longest(rows.map((row) => formatShare(row.share)));
}
/** The roomiest row height at which every row fits; compact when none does. */
export function getRowHeight(count: number, availableHeight: number): number {
if (availableHeight <= 0) {
return DEFAULT_ROW_HEIGHT;
}
const fits = (rowHeight: number): boolean =>
count * rowHeight + Math.max(count - 1, 0) * ROW_GAP + LIST_PADDING_Y <=
availableHeight;
return ROW_HEIGHTS.find(fits) ?? ROW_HEIGHTS[ROW_HEIGHTS.length - 1];
}
/** Grid columns in display order: rank, the bar with its label, share, then value. */
export function getGridColumns(showRank: boolean, showShare: boolean): string {
return [
showRank && 'max-content',
'minmax(0, 1fr)',
showShare && 'max-content',
'max-content',
]
.filter(Boolean)
.join(' ');
}

View File

@@ -0,0 +1,140 @@
import {
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
Querybuildertypesv5QueryEnvelopeFormulaDTOType,
type Querybuildertypesv5QueryEnvelopeBuilderDTO,
type Querybuildertypesv5QueryRangeRequestDTO,
} from 'api/generated/services/sigNoz.schemas';
import type { PanelStatusDetail } from 'pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelStatus/types';
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import type { PanelOfKind } from '../../../types/rendererProps';
import { prepareTopListData } from './prepareData';
import { findQueryEnvelope, getRankedAggregationFunction } from './querySpec';
import type { TopListData } from '../types';
/** Aggregations whose group values don't add up to a meaningful total. */
const NON_ADDITIVE_FUNCTION = /^(avg|min|max|median|p\d+|quantile)/;
const quoteAll = (names: string[]): string =>
names.map((name) => `"${name}"`).join(', ');
const verbFor = (names: string[]): string =>
names.length === 1 ? 'is' : 'are';
/**
* Builder queries with a limit that the ranked formula reads. Each input is cut to its
* own top N before the formula joins them, so the formula only sees groups that made
* every input's cut.
*/
function getLimitedFormulaInputs(
requestPayload: Querybuildertypesv5QueryRangeRequestDTO | undefined,
rankedQuery: string,
): string[] {
const ranked = findQueryEnvelope(requestPayload, rankedQuery);
if (
ranked?.type !==
Querybuildertypesv5QueryEnvelopeFormulaDTOType.builder_formula
) {
return [];
}
const expression = ranked.spec?.expression ?? '';
return (requestPayload?.compositeQuery?.queries ?? [])
.filter(
(envelope): envelope is Querybuildertypesv5QueryEnvelopeBuilderDTO =>
envelope.type ===
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
)
.filter((envelope) => (envelope.spec?.limit ?? 0) > 0)
.map((envelope) => envelope.spec?.name)
.filter(
(name): name is string =>
Boolean(name) && new RegExp(`\\b${name}\\b`).test(expression),
);
}
function collectIssues(
{
rows,
labelColumnNames,
ignoredValueColumns,
ignoredResults,
orderedByGroupKey,
}: TopListData,
limitedFormulaInputs: string[],
): string[] {
const issues: string[] = [];
if (ignoredResults.length > 0) {
issues.push(
`The list ranks "${rows[0].queryName}" only; ${quoteAll(ignoredResults)} ${verbFor(ignoredResults)} not shown. Disable the queries you don't want to rank.`,
);
}
if (limitedFormulaInputs.length > 0) {
issues.push(
`${quoteAll(limitedFormulaInputs)} ${verbFor(limitedFormulaInputs)} limited before the formula combines them, so the formula only sees groups in every input's top N. Set the limit on the formula instead.`,
);
}
if (orderedByGroupKey) {
issues.push(
`The query orders by "${orderedByGroupKey}", so the list shows the first groups by that key rather than the top values. Order by the value instead.`,
);
}
if (labelColumnNames.length === 0) {
issues.push(
'The query has no group by, so the list shows a single total. Add a group by to rank its groups.',
);
}
if (ignoredValueColumns.length > 0) {
issues.push(
`The list ranks the first value column only; ${quoteAll(ignoredValueColumns)} ${verbFor(ignoredValueColumns)} not shown.`,
);
}
if (rows.length > 1 && rows.every((row) => row.label === rows[0].label)) {
issues.push(
'Every row has the same label. Use {{group-by key}} variables in the legend to tell rows apart.',
);
}
return issues;
}
/** Share of total sums the rows, which says nothing for averages, percentiles, min or max. */
function getShareIssue(
{ rows, valueName }: TopListData,
requestPayload: Querybuildertypesv5QueryRangeRequestDTO | undefined,
): string | null {
const aggregation = getRankedAggregationFunction(
requestPayload,
rows[0].queryName,
);
if (!aggregation || !NON_ADDITIVE_FUNCTION.test(aggregation)) {
return null;
}
return `Share of total adds up "${valueName}" across rows, which isn't meaningful for averages, percentiles, minimums or maximums. Turn it off in Appearance, or rank a count or sum.`;
}
export function getTopListDataWarning(
panel: PanelOfKind<'signoz/TopListPanel'>,
data: PanelQueryData,
): PanelStatusDetail | null {
const topList = prepareTopListData(data);
if (topList.rows.length === 0) {
return null;
}
const shareIssue = panel.spec.plugin.spec.appearance?.showShare
? getShareIssue(topList, data.requestPayload)
: null;
const issues = [
...collectIssues(
topList,
getLimitedFormulaInputs(data.requestPayload, topList.rows[0].queryName),
),
...(shareIssue ? [shareIssue] : []),
];
if (issues.length === 0) {
return null;
}
return {
message: 'This list may not rank what you expect.',
messages: issues,
};
}

View File

@@ -7,6 +7,7 @@ import { definition as PieChart } from './kinds/PieChartPanel/definition';
import { definition as ScatterPlot } from './kinds/ScatterPlotPanel/definition';
import { definition as TimeSeries } from './kinds/TimeSeriesPanel/definition';
import { definition as GeoMap } from './kinds/GeoMapPanel/definition';
import { definition as TopList } from './kinds/TopListPanel/definition';
import { definition as Table } from './kinds/TablePanel/definition';
import { definition as List } from './kinds/ListPanel/definition';
import { definition as Text } from './kinds/TextPanel/definition';
@@ -29,6 +30,7 @@ export const PANELS: PanelRegistry = {
[PieChart.kind]: PieChart,
[ScatterPlot.kind]: ScatterPlot,
[GeoMap.kind]: GeoMap,
[TopList.kind]: TopList,
[Histogram.kind]: Histogram,
[Heatmap.kind]: Heatmap,
[List.kind]: List,

View File

@@ -37,6 +37,7 @@ export type PanelInteractionMap = Record<PanelKind, object> & {
'signoz/HeatmapPanel': { onDragSelect?: DragSelect };
'signoz/TablePanel': { onClick?: (event: DrilldownClickPayload) => void };
'signoz/PieChartPanel': { onClick?: (event: DrilldownClickPayload) => void };
'signoz/TopListPanel': { onClick?: (event: DrilldownClickPayload) => void };
'signoz/NumberPanel': { onClick?: (event: DrilldownClickPayload) => void };
'signoz/ScatterPlotPanel': {
onClick?: (event: DrilldownClickPayload) => void;

View File

@@ -26,6 +26,7 @@ export const PANEL_KIND_TO_PANEL_TYPE: Record<PanelKind, PANEL_TYPES> = {
'signoz/ListPanel': PANEL_TYPES.LIST,
'signoz/HeatmapPanel': PANEL_TYPES.HEATMAP,
'signoz/GeoMapPanel': PANEL_TYPES.GEO_MAP,
'signoz/TopListPanel': PANEL_TYPES.TOP_LIST,
'signoz/TextPanel': PANEL_TYPES.TEXT,
'signoz/ScatterPlotPanel': PANEL_TYPES.SCATTER,
};

View File

@@ -28,6 +28,7 @@ import type {
DashboardtypesTextPresentationDTO,
DashboardtypesThresholdWithLabelDTO,
DashboardtypesTimePreferenceDTO,
DashboardtypesTopListAppearanceDTO,
TelemetrytypesTelemetryFieldKeyDTO,
} from 'api/generated/services/sigNoz.schemas';
import type { LegendSeriesResolver } from '../utils/legendSeries';
@@ -79,6 +80,8 @@ export enum SectionKind {
ScatterAxes = 'scatterAxes',
/** Geo Map's placement: what a row is, its columns, the area, the layer and the value columns. */
Location = 'location',
/** Top List's row display, for a kind with no chart to style. */
Appearance = 'appearance',
}
/**
@@ -169,6 +172,7 @@ export interface SectionSpecMap {
[SectionKind.Dimensions]: DashboardtypesScatterPlotDimensionsDTO; // spec.plugin.spec.dimensions (Scatter Plot)
[SectionKind.ScatterAxes]: DashboardtypesScatterPlotAxesDTO; // spec.plugin.spec.axes (Scatter Plot)
[SectionKind.Location]: GeoMapPlacementSlice; // spec.plugin.spec.location + .map (Geo Map)
[SectionKind.Appearance]: DashboardtypesTopListAppearanceDTO; // spec.plugin.spec.appearance (Top List)
}
/**
@@ -234,6 +238,11 @@ export interface SectionControls {
// Editor discriminator (not a spec field): which threshold variant a kind edits.
// axis → a `label` threshold picks the axis it marks (Scatter Plot).
[SectionKind.Thresholds]: { variant?: ThresholdVariant; axis?: boolean };
[SectionKind.Appearance]: {
showRank?: boolean;
showShare?: boolean;
barColor?: boolean;
};
}
export type ControlledSectionKind = keyof SectionControls;
@@ -284,6 +293,7 @@ export const SECTION_METADATA = {
[SectionKind.Dimensions]: { title: 'Dimensions', icon: Crosshair },
[SectionKind.ScatterAxes]: { title: 'Axes', icon: Scale3D },
[SectionKind.Location]: { title: 'Location', icon: MapPin },
[SectionKind.Appearance]: { title: 'Appearance', icon: Palette },
} as const satisfies Record<SectionKind, SectionMetadata>;
/**

View File

@@ -13,6 +13,7 @@ import {
TelemetrytypesSignalDTO,
} from 'api/generated/services/sigNoz.schemas';
import { DEFAULT_BAR_COLOR } from '../../../PanelEditor/ConfigPane/sections/AppearanceSection/barColorOptions';
import { defaultColumnsForSignal } from '../../../PanelEditor/ListColumnsEditor/selectFields';
import { sections as areaSections } from '../../kinds/AreaChartPanel/sections';
import { sections as geoMapSections } from '../../kinds/GeoMapPanel/sections';
@@ -342,6 +343,33 @@ describe('buildPluginSpec', () => {
});
});
describe('appearance seed', () => {
const sections: SectionConfig[] = [
{
kind: SectionKind.Appearance,
controls: { showRank: true, showShare: true, barColor: true },
},
];
it('carries the toggles and bar color across a switch between kinds that declare them', () => {
const oldSpec = oldSpecWith({
appearance: { showRank: true, showShare: false, barColor: '#00C853' },
});
expect(buildPluginSpec(sections, { oldSpec }).appearance).toStrictEqual({
barColor: '#00C853',
showRank: true,
showShare: false,
});
});
it('seeds only the default bar color for a new panel, where unset toggles read as off', () => {
expect(buildPluginSpec(sections)).toStrictEqual({
appearance: { barColor: DEFAULT_BAR_COLOR },
});
});
});
describe('chartAppearance seed', () => {
it('seeds only the declared defaulting controls', () => {
const sections: SectionConfig[] = [

View File

@@ -29,6 +29,7 @@ import {
type SectionSpecMap,
ThresholdVariant,
} from '../types/sections';
import { DEFAULT_BAR_COLOR } from '../../PanelEditor/ConfigPane/sections/AppearanceSection/barColorOptions';
import { getTableColumnKeys } from './getTableColumnKeys';
/** Cross-section of the per-kind spec union; assigned to `plugin.spec` (unknown) at the boundary. */
@@ -37,6 +38,7 @@ export interface SeededPluginSpec {
axes?: SectionSpecMap[SectionKind.Axes];
legend?: SectionSpecMap[SectionKind.Legend];
chartAppearance?: SectionSpecMap[SectionKind.ChartAppearance];
appearance?: SectionSpecMap[SectionKind.Appearance];
formatting?: Pick<
PanelFormattingSlice,
'unit' | 'decimalPrecision' | 'columnUnits'
@@ -218,6 +220,23 @@ function seedMapMarks(
}
const SECTION_SEEDS: SectionSeeds = {
[SectionKind.Appearance]: {
specKey: 'appearance',
// Carries the toggles the target kind declares; unset reads as off.
seed: (
controls,
{ oldPluginSpec },
): SectionSpecMap[SectionKind.Appearance] => {
const old = oldPluginSpec?.appearance;
return {
barColor: (controls.barColor && old?.barColor) || DEFAULT_BAR_COLOR,
...(controls.showRank &&
old?.showRank !== undefined && { showRank: old.showRank }),
...(controls.showShare &&
old?.showShare !== undefined && { showShare: old.showShare }),
};
},
},
[SectionKind.TextLayout]: {
specKey: 'presentation',
// Explicit alignment defaults (not the API's implicit ones) so the controls

View File

@@ -53,6 +53,11 @@ const PANEL_TYPE_META: Record<PanelKind, PanelTypeMeta> = {
description: 'Values by country, state or coordinates',
isNew: true,
},
'signoz/TopListPanel': {
group: 'compare',
description: 'Groups ranked by a single value',
isNew: true,
},
'signoz/HistogramPanel': {
group: 'distributions',
description: 'Distribution of values into buckets',

View File

@@ -11,6 +11,8 @@ const AREA_FILL = { fill: 'var(--bg-robin-500)', fillOpacity: 0.22 };
const RING_TRACK = { stroke: 'var(--l3-background)' };
const RING_PRIMARY = { stroke: 'var(--bg-robin-500)' };
const RING_SECONDARY = { stroke: 'var(--bg-robin-400)', strokeOpacity: 0.55 };
const RING_TRACK_FILL = { fill: 'var(--l3-background)' };
const BAR_FILL = { fill: 'var(--bg-robin-500)' };
const DOT_FILL = { fill: 'var(--bg-robin-500)', fillOpacity: 0.55 };
/** `[cx, cy, r]`: a loose up-and-right cloud with one large outlier. */
@@ -56,6 +58,8 @@ const HEATMAP_CELLS = [
[0.4, 0.85, 0.7, 0.2],
[0.3, 0.65, 0.9, 0.45],
];
// Bar lengths (% of the track) for the top-list sketch, longest first.
const TOP_LIST_BARS = [100, 76, 54, 34];
const TEXT_ROWS = [45, 100, 92, 64].map((width, i) => [
{ ...(i === 0 ? HEAD : CELL), width },
]);
@@ -102,6 +106,30 @@ export const PANEL_TYPE_PREVIEWS: Record<PanelKind, JSX.Element> = {
))}
</svg>
),
'signoz/TopListPanel': (
<svg viewBox="0 0 120 44" preserveAspectRatio="none" className={styles.svg}>
{TOP_LIST_BARS.map((width, row) => (
<g key={width}>
<rect
x={0}
y={row * 11 + 2}
width={120}
height={7}
rx={1.5}
style={RING_TRACK_FILL}
/>
<rect
x={0}
y={row * 11 + 2}
width={(width / 100) * 120}
height={7}
rx={1.5}
style={BAR_FILL}
/>
</g>
))}
</svg>
),
'signoz/HistogramPanel': (
<PreviewBars
heights={[14, 26, 52, 88, 100, 70, 40, 20, 10]}

View File

@@ -3,6 +3,7 @@ import logEvent from 'api/common/logEvent';
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
import { DashboardDetailEvents } from 'pages/DashboardPage/constants/events';
import { getTableCsvRows } from 'pages/DashboardPage/DashboardContainer/Panels/kinds/TablePanel/tableCsv';
import { getTopListCsvRows } from 'pages/DashboardPage/DashboardContainer/Panels/kinds/TopListPanel/utils/csv';
import { toPanelType } from 'pages/DashboardPage/DashboardContainer/Panels/types/panelKind';
import type { PanelOfKind } from 'pages/DashboardPage/DashboardContainer/Panels/types/rendererProps';
import { downloadCsv } from 'pages/DashboardPage/DashboardContainer/Panels/utils/downloadCsv';
@@ -15,10 +16,9 @@ interface UseDownloadPanelCsvArgs {
data: PanelQueryData;
/**
* Whether the kind's definition declares CSV as a downloadable format
* (`actions.download.csv`). Only kinds drawn from a joined scalar table
* (Table, Scatter Plot, Geo Map) carry tabular data, so this is the same gate the
* menu uses — kept here so the callback stays a no-op when invoked for a kind that
* can't produce CSV.
* (`actions.download.csv`). Only Table, Scatter Plot, Geo Map and Top List carry
* tabular data, so this is the same gate the menu uses — kept here so the callback
* stays a no-op when invoked for a kind that can't produce CSV.
*/
canDownloadCsv: boolean;
}
@@ -38,12 +38,15 @@ export function useDownloadPanelCsv({
if (!canDownloadCsv) {
return;
}
const rows = getTableCsvRows(
panel as PanelOfKind<
'signoz/TablePanel' | 'signoz/ScatterPlotPanel' | 'signoz/GeoMapPanel'
>,
data,
);
const rows =
panel.spec.plugin.kind === 'signoz/TopListPanel'
? getTopListCsvRows(panel as PanelOfKind<'signoz/TopListPanel'>, data)
: getTableCsvRows(
panel as PanelOfKind<
'signoz/TablePanel' | 'signoz/ScatterPlotPanel' | 'signoz/GeoMapPanel'
>,
data,
);
if (rows.length === 0) {
return;
}

View File

@@ -19,7 +19,10 @@ import {
} from 'api/generated/services/sigNoz.schemas';
import type { PanelQueryCapabilities } from '../Panels/types/panelCapabilities';
import { isBuilderEnvelope } from 'lib/query/builderEnvelope';
import {
isBuilderEnvelope,
isLoneBuilderQuery,
} from 'lib/query/builderEnvelope';
// Narrow view over the envelope spec variants. Orval erases envelope `spec` to `unknown`, so
// shared fields are read through this view with a localized cast at the envelope boundary.
@@ -221,13 +224,11 @@ function withDefaultRowLimit(
envelopes: Querybuildertypesv5QueryEnvelopeDTO[],
limit: number,
): Querybuildertypesv5QueryEnvelopeDTO[] {
if (!isLoneBuilderQuery(envelopes)) {
return envelopes;
}
const [envelope] = envelopes;
if (
envelopes.length !== 1 ||
envelope.type !==
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query ||
envelope.spec?.limit
) {
if (envelope.spec?.limit) {
return envelopes;
}
return [

View File

@@ -108,6 +108,7 @@ export function panelTypeToRequestType(
case PANEL_TYPES.VALUE:
case PANEL_TYPES.SCATTER:
case PANEL_TYPES.GEO_MAP:
case PANEL_TYPES.TOP_LIST:
return Querybuildertypesv5RequestTypeDTO.scalar;
case PANEL_TYPES.LIST:
return Querybuildertypesv5RequestTypeDTO.raw;

View File

@@ -4,11 +4,14 @@
*/
import { rest } from 'msw';
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
import ROUTES from 'constants/routes';
import { buildDashboardReadPermission } from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';
import { buildRoutePath } from 'lib/router/buildRoutePath';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
import { grantsAll } from '@/storybook/access/access';
import { choiceControl, toggleControl } from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import {
@@ -19,6 +22,7 @@ import {
listMetricsResponse,
metricMetadataResponse,
} from '@/storybook/msw/__story_mockdata__/metrics';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
NEW_PANEL_ID,
@@ -32,6 +36,8 @@ import {
import {
currentDashboardDocument,
PANEL_IDS,
type PanelId,
panelQueryShape,
patchDashboardDocument,
seedDashboardDocument,
STORY_DASHBOARD_ID,
@@ -213,6 +219,55 @@ export const panelEditorMocks = defineStoryMocks({
},
});
export type PanelEditorArgs = PageStoryArgs<typeof panelEditorMocks>;
const SAVED_TIME_SERIES: readonly PanelId[] = ['request-rate', 'error-rate'];
const NEW_PANEL_KINDS_WITHOUT_CLICKHOUSE: readonly NewPanelKind[] = [
'list',
'text',
];
const NEW_PANEL_KINDS_WITH_SPAN_GAPS: readonly NewPanelKind[] = [
'time-series',
'area-chart',
];
/**
* The page mounts on `read`. A check that fails rather than denies still
* renders it.
*/
export const showsEditor = (args: PanelEditorArgs): boolean =>
args.authzState === 'error' ||
grantsAll(args, buildDashboardReadPermission(STORY_DASHBOARD_ID));
/** The list and text kinds offer no ClickHouse query mode. */
export const hasClickHouseTab = (args: PanelEditorArgs): boolean => {
if (!showsEditor(args)) {
return false;
}
if (args.panel === NEW_PANEL_ID) {
return !NEW_PANEL_KINDS_WITHOUT_CLICKHOUSE.includes(args.newPanelKind);
}
return (
panelQueryShape(args.panel).requestType !==
Querybuildertypesv5RequestTypeDTO.raw
);
};
/** Only the time series and area kinds offer "When data is missing". */
export const hasDisconnectValues = (args: PanelEditorArgs): boolean => {
if (!showsEditor(args)) {
return false;
}
return args.panel === NEW_PANEL_ID
? NEW_PANEL_KINDS_WITH_SPAN_GAPS.includes(args.newPanelKind)
: SAVED_TIME_SERIES.includes(args.panel);
};
export const savePanel = async (): Promise<void> => {
const save = await screen.findByTestId(
'panel-editor-v2-save',

View File

@@ -8,6 +8,7 @@ import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { panelEditorMocks, savePanel } from './PanelEditorPage.stories.mocks';
import { openClickHouseQuery } from './__story_mockdata__/panelEditor.play';
import PanelEditorPage from '../PanelEditorPage';
@@ -63,6 +64,11 @@ const expandConfigSections: Story['play'] = async ({ canvasElement }) => {
*/
export const Default: Story = {};
/** The ClickHouse query tab, including its info callout. */
export const ClickHouseQuery: Story = {
play: openClickHouseQuery,
};
/** The create route, seeding an unsaved panel of the chosen kind. */
export const NewPanel: Story = {
args: { panel: 'new' },
@@ -83,6 +89,21 @@ export const PieChartPanel: Story = {
args: { panel: 'traffic-share' },
};
/** A new area chart: the time series options with the area filled. */
export const AreaChartPanel: Story = {
args: { panel: 'new', newPanelKind: 'area-chart' },
};
/** A new histogram, where the display options are its buckets. */
export const HistogramPanel: Story = {
args: { panel: 'new', newPanelKind: 'histogram' },
};
/** A new text panel: a markdown body in place of the query builder. */
export const TextPanel: Story = {
args: { panel: 'new', newPanelKind: 'text' },
};
/** A list panel, where the config pane is the column editor. */
export const ListPanel: Story = {
args: { panel: 'recent-logs' },

View File

@@ -0,0 +1,54 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { screen, userEvent, within } from 'storybook/test';
import {
expandSection,
hasClickHouseTab,
hasDisconnectValues,
type PanelEditorArgs,
pickSegment,
} from '../PanelEditorPage.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: PanelEditorArgs;
}
export const openClickHouseQuery = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!hasClickHouseTab(args)) {
return;
}
await userEvent.click(
await within(canvasElement).findByText('ClickHouse Query', undefined, {
timeout: 15000,
}),
);
await screen.findByText(/ClickHouse query agent skill/i, undefined, {
timeout: 15000,
});
};
export const enterInvalidDisconnectThreshold = async ({
args,
}: PlayContext): Promise<void> => {
if (!hasDisconnectValues(args)) {
return;
}
await expandSection('Chart appearance');
await screen.findByTestId('panel-editor-v2-line-style');
await pickSegment('panel-editor-v2-span-gaps', 'threshold');
const input = await screen.findByTestId('panel-editor-v2-span-gaps-value');
await userEvent.clear(input);
await userEvent.type(input, '5x');
await screen.findByText(/enter a valid duration/i);
};

View File

@@ -13,6 +13,7 @@ import {
panelEditorMocks,
pickSegment,
} from '../PanelEditorPage.stories.mocks';
import { enterInvalidDisconnectThreshold } from '../__story_mockdata__/panelEditor.play';
import PanelEditorPage from '../../PanelEditorPage';
@@ -105,6 +106,11 @@ export const ChartAppearance: Story = {
},
};
/** Disconnect-values in threshold mode, with an invalid duration showing the inline error. */
export const ChartAppearanceDisconnectThreshold: Story = {
play: enterInvalidDisconnectThreshold,
};
/** Dashed lines under a gradient fill, with the points drawn. */
export const ChartAppearanceDashedGradient: Story = {
play: async (context) => {

View File

@@ -8,9 +8,16 @@ import ROUTES from 'constants/routes';
import { buildRoutePath } from 'lib/router/buildRoutePath';
import type { GetPublicDashboard200 } from 'api/generated/services/sigNoz.schemas';
import { useDashboardPreferencesStore } from 'hooks/dashboard/useDashboardPreference';
import {
buildDashboardDeletePermission,
buildDashboardReadPermission,
buildDashboardUpdatePermission,
} from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';
import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
import { grantsAll } from '@/storybook/access/access';
import {
choiceControl,
countControl,
@@ -23,6 +30,7 @@ import {
fieldValuesResponse,
} from '@/storybook/msw/__story_mockdata__/fields';
import { queryRangeV5ScalarResponse } from '@/storybook/msw/__story_mockdata__/queryRange';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
currentDashboardDocument,
@@ -33,6 +41,7 @@ import {
STORY_DASHBOARD_ID,
VARIABLE_KINDS,
type DashboardArgs,
type PanelId,
type VariableKind,
} from './__story_mockdata__/dashboard';
import { publicDashboardMeta } from './__story_mockdata__/publicDashboard';
@@ -370,6 +379,42 @@ export const dashboardMocks = defineStoryMocks({
},
});
export type DashboardPageArgs = PageStoryArgs<typeof dashboardMocks>;
const SEARCHABLE_PANELS: readonly PanelId[] = ['top-endpoints', 'recent-logs'];
/**
* The page mounts on `read`. A check that fails rather than denies still
* renders it.
*/
export const showsDashboard = (args: DashboardPageArgs): boolean =>
!args.notFound &&
(args.authzState === 'error' ||
grantsAll(args, buildDashboardReadPermission(STORY_DASHBOARD_ID)));
/** A menu row whose check errors stays enabled; a lock disables it otherwise. */
const rowEnabled = (
args: DashboardPageArgs,
...checks: BrandedPermission[]
): boolean =>
showsDashboard(args) &&
(args.authzState === 'error' || (!args.locked && grantsAll(args, ...checks)));
export const hasPanelSearch = (args: DashboardPageArgs): boolean =>
showsDashboard(args) &&
PANEL_IDS.slice(0, args.panels).some((id) => SEARCHABLE_PANELS.includes(id));
export const canDeleteDashboard = (args: DashboardPageArgs): boolean =>
rowEnabled(args, buildDashboardDeletePermission(STORY_DASHBOARD_ID));
export const canEditSections = (args: DashboardPageArgs): boolean =>
args.sectioned &&
rowEnabled(
args,
buildDashboardReadPermission(STORY_DASHBOARD_ID),
buildDashboardUpdatePermission(STORY_DASHBOARD_ID),
);
/**
* One panel's query answered with a warning beside its value, so its header
* carries the status indicator while the rest of the dashboard is untouched.

View File

@@ -22,6 +22,11 @@ import {
tooltipRoute,
warnedPanelQueryHandler,
} from './DashboardPage.stories.mocks';
import {
expandPanelSearch,
openDeleteDashboardDialog,
openRenameSectionDialog,
} from './__story_mockdata__/dashboard.play';
import { TOOLTIP_PANEL_NAME } from './__story_mockdata__/tooltipDashboard';
import DashboardPage from '../DashboardPage';
@@ -191,6 +196,11 @@ export const TooltipsInViewPanelModal: Story = {
},
};
/** A list or table panel's search field, expanded and filled. */
export const PanelSearchExpanded: Story = {
play: expandPanelSearch,
};
/**
* The dashboard's own Actions menu, open: rename, clone, lock, full screen and
* delete, the menu the toolbar's Actions button carries.
@@ -243,6 +253,16 @@ export const SectionActionsMenu: Story = {
},
};
/** Delete dashboard, the confirm dialog the Actions menu opens. */
export const DeleteDashboardDialog: Story = {
play: openDeleteDashboardDialog,
};
/** Rename section, the title dialog a section menu opens. */
export const RenameSectionDialog: Story = {
play: openRenameSectionDialog,
};
const openNewPanelPicker = async (
canvasElement: HTMLElement,
): Promise<void> => {

View File

@@ -0,0 +1,75 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { screen, userEvent, waitFor, within } from 'storybook/test';
import {
canDeleteDashboard,
canEditSections,
clickSectionAction,
type DashboardPageArgs,
hasPanelSearch,
openActionsMenu,
} from '../DashboardPage.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: DashboardPageArgs;
}
export const expandPanelSearch = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!hasPanelSearch(args)) {
return;
}
// Both the table and the log list render a search trigger; expand the first.
const [trigger] = await within(canvasElement).findAllByTestId(
'panel-header-search-trigger',
{},
{ timeout: 15000 },
);
await userEvent.click(trigger);
const input = await screen.findByTestId('panel-header-search-input');
await userEvent.type(input, 'error');
};
export const openDeleteDashboardDialog = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!canDeleteDashboard(args)) {
return;
}
await openActionsMenu(canvasElement);
// The row stays inert until its authz checks resolve, so one click can
// land too early; keep clicking until the confirm dialog is up.
await waitFor(
async () => {
const item = screen.queryByTestId('dashboard-action-delete');
if (item) {
await userEvent.click(item);
}
screen.getByText('This action cannot be undone.');
},
{ timeout: 10000 },
);
};
export const openRenameSectionDialog = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!canEditSections(args)) {
return;
}
await clickSectionAction(canvasElement, 'Rename section');
await screen.findByRole('dialog', { name: /rename section/i });
};

Some files were not shown because too many files have changed in this diff Show More